rollup.js 893 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632
  1. /*
  2. @license
  3. Rollup.js v4.41.0
  4. Sun, 18 May 2025 05:33:01 GMT - commit 0928185cd544907dab472754634ddf988452aae6
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const parseAst_js = require('./parseAst.js');
  10. const process$1 = require('node:process');
  11. const path = require('node:path');
  12. const require$$0 = require('path');
  13. const native_js = require('../native.js');
  14. const node_perf_hooks = require('node:perf_hooks');
  15. const promises = require('node:fs/promises');
  16. var version = "4.41.0";
  17. function ensureArray$1(items) {
  18. if (Array.isArray(items)) {
  19. return items.filter(Boolean);
  20. }
  21. if (items) {
  22. return [items];
  23. }
  24. return [];
  25. }
  26. var BuildPhase;
  27. (function (BuildPhase) {
  28. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  29. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  30. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  31. })(BuildPhase || (BuildPhase = {}));
  32. let textEncoder;
  33. const getHash64 = input => native_js.xxhashBase64Url(ensureBuffer(input));
  34. const getHash36 = input => native_js.xxhashBase36(ensureBuffer(input));
  35. const getHash16 = input => native_js.xxhashBase16(ensureBuffer(input));
  36. const hasherByType = {
  37. base36: getHash36,
  38. base64: getHash64,
  39. hex: getHash16
  40. };
  41. function ensureBuffer(input) {
  42. if (typeof input === 'string') {
  43. if (typeof Buffer === 'undefined') {
  44. textEncoder ??= new TextEncoder();
  45. return textEncoder.encode(input);
  46. }
  47. return Buffer.from(input);
  48. }
  49. return input;
  50. }
  51. function getOrCreate(map, key, init) {
  52. const existing = map.get(key);
  53. if (existing !== undefined) {
  54. return existing;
  55. }
  56. const value = init();
  57. map.set(key, value);
  58. return value;
  59. }
  60. function getNewSet() {
  61. return new Set();
  62. }
  63. function getNewArray() {
  64. return [];
  65. }
  66. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  67. const base = 64;
  68. function toBase64(value) {
  69. let outString = '';
  70. do {
  71. const currentDigit = value % base;
  72. value = (value / base) | 0;
  73. outString = chars$1[currentDigit] + outString;
  74. } while (value !== 0);
  75. return outString;
  76. }
  77. // Four random characters from the private use area to minimize risk of
  78. // conflicts
  79. const hashPlaceholderLeft = '!~{';
  80. const hashPlaceholderRight = '}~';
  81. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  82. // This is the size of a 128-bits xxhash with base64url encoding
  83. const MAX_HASH_SIZE = 21;
  84. const DEFAULT_HASH_SIZE = 8;
  85. const getHashPlaceholderGenerator = () => {
  86. let nextIndex = 0;
  87. return (optionName, hashSize) => {
  88. if (hashSize > MAX_HASH_SIZE) {
  89. return parseAst_js.error(parseAst_js.logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  90. }
  91. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  92. if (placeholder.length > hashSize) {
  93. return parseAst_js.error(parseAst_js.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.`));
  94. }
  95. return placeholder;
  96. };
  97. };
  98. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  99. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  100. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  101. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  102. const containedPlaceholders = new Set();
  103. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  104. if (placeholders.has(placeholder)) {
  105. containedPlaceholders.add(placeholder);
  106. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  107. }
  108. return placeholder;
  109. });
  110. return { containedPlaceholders, transformedCode };
  111. };
  112. const lowercaseBundleKeys = Symbol('bundleKeys');
  113. const FILE_PLACEHOLDER = {
  114. type: 'placeholder'
  115. };
  116. const getOutputBundle = (outputBundleBase) => {
  117. const reservedLowercaseBundleKeys = new Set();
  118. return new Proxy(outputBundleBase, {
  119. deleteProperty(target, key) {
  120. if (typeof key === 'string') {
  121. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  122. }
  123. return Reflect.deleteProperty(target, key);
  124. },
  125. get(target, key) {
  126. if (key === lowercaseBundleKeys) {
  127. return reservedLowercaseBundleKeys;
  128. }
  129. return Reflect.get(target, key);
  130. },
  131. set(target, key, value) {
  132. if (typeof key === 'string') {
  133. reservedLowercaseBundleKeys.add(key.toLowerCase());
  134. }
  135. return Reflect.set(target, key, value);
  136. }
  137. });
  138. };
  139. const removeUnreferencedAssets = (outputBundle) => {
  140. const unreferencedAssets = new Set();
  141. const bundleEntries = Object.values(outputBundle);
  142. for (const asset of bundleEntries) {
  143. if (asset.type === 'asset' && asset.needsCodeReference) {
  144. unreferencedAssets.add(asset.fileName);
  145. }
  146. }
  147. for (const chunk of bundleEntries) {
  148. if (chunk.type === 'chunk') {
  149. for (const referencedFile of chunk.referencedFiles) {
  150. if (unreferencedAssets.has(referencedFile)) {
  151. unreferencedAssets.delete(referencedFile);
  152. }
  153. }
  154. }
  155. }
  156. for (const file of unreferencedAssets) {
  157. delete outputBundle[file];
  158. }
  159. };
  160. function renderNamePattern(pattern, patternName, replacements) {
  161. if (parseAst_js.isPathFragment(pattern))
  162. return parseAst_js.error(parseAst_js.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.`));
  163. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  164. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  165. return parseAst_js.error(parseAst_js.logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  166. }
  167. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  168. if (parseAst_js.isPathFragment(replacement))
  169. return parseAst_js.error(parseAst_js.logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  170. return replacement;
  171. });
  172. }
  173. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  174. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  175. return name;
  176. const extension = path.extname(name);
  177. name = name.slice(0, Math.max(0, name.length - extension.length));
  178. let uniqueName, uniqueIndex = 1;
  179. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  180. ;
  181. return uniqueName;
  182. }
  183. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  184. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  185. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  186. ? outputOptions.assetFileNames({
  187. // Additionally, this should be non-enumerable in the next major
  188. get name() {
  189. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
  190. return name;
  191. },
  192. names,
  193. // Additionally, this should be non-enumerable in the next major
  194. get originalFileName() {
  195. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
  196. return originalFileName;
  197. },
  198. originalFileNames,
  199. source,
  200. type: 'asset'
  201. })
  202. : outputOptions.assetFileNames, 'output.assetFileNames', {
  203. ext: () => path.extname(emittedName).slice(1),
  204. extname: () => path.extname(emittedName),
  205. hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
  206. name: () => emittedName.slice(0, Math.max(0, emittedName.length - path.extname(emittedName).length))
  207. }), bundle);
  208. }
  209. function reserveFileNameInBundle(fileName, { bundle }, log) {
  210. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  211. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logFileNameConflict(fileName));
  212. }
  213. else {
  214. bundle[fileName] = FILE_PLACEHOLDER;
  215. }
  216. }
  217. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  218. function hasValidType(emittedFile) {
  219. return Boolean(emittedFile &&
  220. emittedFileTypes.has(emittedFile.type));
  221. }
  222. function hasValidName(emittedFile) {
  223. const validatedName = emittedFile.fileName || emittedFile.name;
  224. return !validatedName || (typeof validatedName === 'string' && !parseAst_js.isPathFragment(validatedName));
  225. }
  226. function getValidSource(source, emittedFile, fileReferenceId) {
  227. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  228. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  229. return parseAst_js.error(parseAst_js.logFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  230. }
  231. return source;
  232. }
  233. function getAssetFileName(file, referenceId) {
  234. if (typeof file.fileName !== 'string') {
  235. return parseAst_js.error(parseAst_js.logAssetNotFinalisedForFileName(file.name || referenceId));
  236. }
  237. return file.fileName;
  238. }
  239. function getChunkFileName(file, facadeChunkByModule) {
  240. if (file.fileName) {
  241. return file.fileName;
  242. }
  243. if (facadeChunkByModule) {
  244. return facadeChunkByModule.get(file.module).getFileName();
  245. }
  246. return parseAst_js.error(parseAst_js.logChunkNotGeneratedForFileName(file.fileName || file.name));
  247. }
  248. class FileEmitter {
  249. constructor(graph, options, baseFileEmitter) {
  250. this.graph = graph;
  251. this.options = options;
  252. this.facadeChunkByModule = null;
  253. this.nextIdBase = 1;
  254. this.output = null;
  255. this.outputFileEmitters = [];
  256. this.emitFile = (emittedFile) => {
  257. if (!hasValidType(emittedFile)) {
  258. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  259. }
  260. if (emittedFile.type === 'prebuilt-chunk') {
  261. return this.emitPrebuiltChunk(emittedFile);
  262. }
  263. if (!hasValidName(emittedFile)) {
  264. return parseAst_js.error(parseAst_js.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}".`));
  265. }
  266. if (emittedFile.type === 'chunk') {
  267. return this.emitChunk(emittedFile);
  268. }
  269. return this.emitAsset(emittedFile);
  270. };
  271. this.finaliseAssets = () => {
  272. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  273. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  274. return parseAst_js.error(parseAst_js.logNoAssetSourceSet(emittedFile.name || referenceId));
  275. }
  276. };
  277. this.getFileName = (fileReferenceId) => {
  278. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  279. if (!emittedFile)
  280. return parseAst_js.error(parseAst_js.logFileReferenceIdNotFoundForFilename(fileReferenceId));
  281. if (emittedFile.type === 'chunk') {
  282. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  283. }
  284. if (emittedFile.type === 'prebuilt-chunk') {
  285. return emittedFile.fileName;
  286. }
  287. return getAssetFileName(emittedFile, fileReferenceId);
  288. };
  289. this.setAssetSource = (referenceId, requestedSource) => {
  290. const consumedFile = this.filesByReferenceId.get(referenceId);
  291. if (!consumedFile)
  292. return parseAst_js.error(parseAst_js.logAssetReferenceIdNotFoundForSetSource(referenceId));
  293. if (consumedFile.type !== 'asset') {
  294. return parseAst_js.error(parseAst_js.logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  295. }
  296. if (consumedFile.source !== undefined) {
  297. return parseAst_js.error(parseAst_js.logAssetSourceAlreadySet(consumedFile.name || referenceId));
  298. }
  299. const source = getValidSource(requestedSource, consumedFile, referenceId);
  300. if (this.output) {
  301. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  302. }
  303. else {
  304. consumedFile.source = source;
  305. for (const emitter of this.outputFileEmitters) {
  306. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  307. }
  308. }
  309. };
  310. this.setChunkInformation = (facadeChunkByModule) => {
  311. this.facadeChunkByModule = facadeChunkByModule;
  312. };
  313. this.setOutputBundle = (bundle, outputOptions) => {
  314. const getHash = hasherByType[outputOptions.hashCharacters];
  315. const output = (this.output = {
  316. bundle,
  317. fileNamesBySourceHash: new Map(),
  318. getHash,
  319. outputOptions
  320. });
  321. for (const emittedFile of this.filesByReferenceId.values()) {
  322. if (emittedFile.fileName) {
  323. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  324. }
  325. }
  326. const consumedAssetsByHash = new Map();
  327. for (const consumedFile of this.filesByReferenceId.values()) {
  328. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  329. if (consumedFile.fileName) {
  330. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  331. }
  332. else {
  333. const sourceHash = getHash(consumedFile.source);
  334. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  335. }
  336. }
  337. else if (consumedFile.type === 'prebuilt-chunk') {
  338. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  339. }
  340. }
  341. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  342. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  343. }
  344. };
  345. this.filesByReferenceId = baseFileEmitter
  346. ? new Map(baseFileEmitter.filesByReferenceId)
  347. : new Map();
  348. baseFileEmitter?.addOutputFileEmitter(this);
  349. }
  350. addOutputFileEmitter(outputFileEmitter) {
  351. this.outputFileEmitters.push(outputFileEmitter);
  352. }
  353. assignReferenceId(file, idBase) {
  354. let referenceId = idBase;
  355. do {
  356. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  357. } while (this.filesByReferenceId.has(referenceId) ||
  358. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  359. file.referenceId = referenceId;
  360. this.filesByReferenceId.set(referenceId, file);
  361. for (const { filesByReferenceId } of this.outputFileEmitters) {
  362. filesByReferenceId.set(referenceId, file);
  363. }
  364. return referenceId;
  365. }
  366. createPrebuiltChunk(prebuiltChunk) {
  367. return {
  368. code: prebuiltChunk.code,
  369. dynamicImports: [],
  370. exports: prebuiltChunk.exports || [],
  371. facadeModuleId: null,
  372. fileName: prebuiltChunk.fileName,
  373. implicitlyLoadedBefore: [],
  374. importedBindings: {},
  375. imports: [],
  376. isDynamicEntry: false,
  377. isEntry: false,
  378. isImplicitEntry: false,
  379. map: prebuiltChunk.map || null,
  380. moduleIds: [],
  381. modules: {},
  382. name: prebuiltChunk.fileName,
  383. preliminaryFileName: prebuiltChunk.fileName,
  384. referencedFiles: [],
  385. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  386. type: 'chunk'
  387. };
  388. }
  389. emitAsset(emittedAsset) {
  390. const source = emittedAsset.source === undefined
  391. ? undefined
  392. : getValidSource(emittedAsset.source, emittedAsset, null);
  393. const originalFileName = emittedAsset.originalFileName || null;
  394. if (typeof originalFileName === 'string') {
  395. this.graph.watchFiles[originalFileName] = true;
  396. }
  397. const consumedAsset = {
  398. fileName: emittedAsset.fileName,
  399. name: emittedAsset.name,
  400. needsCodeReference: !!emittedAsset.needsCodeReference,
  401. originalFileName,
  402. referenceId: '',
  403. source,
  404. type: 'asset'
  405. };
  406. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  407. if (this.output) {
  408. this.emitAssetWithReferenceId(consumedAsset, this.output);
  409. }
  410. else {
  411. for (const fileEmitter of this.outputFileEmitters) {
  412. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  413. }
  414. }
  415. return referenceId;
  416. }
  417. emitAssetWithReferenceId(consumedAsset, output) {
  418. const { fileName, source } = consumedAsset;
  419. if (fileName) {
  420. reserveFileNameInBundle(fileName, output, this.options.onLog);
  421. }
  422. if (source !== undefined) {
  423. this.finalizeAdditionalAsset(consumedAsset, source, output);
  424. }
  425. }
  426. emitChunk(emittedChunk) {
  427. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  428. return parseAst_js.error(parseAst_js.logInvalidRollupPhaseForChunkEmission());
  429. }
  430. if (typeof emittedChunk.id !== 'string') {
  431. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  432. }
  433. const consumedChunk = {
  434. fileName: emittedChunk.fileName,
  435. module: null,
  436. name: emittedChunk.name || emittedChunk.id,
  437. referenceId: '',
  438. type: 'chunk'
  439. };
  440. this.graph.moduleLoader
  441. .emitChunk(emittedChunk)
  442. .then(module => (consumedChunk.module = module))
  443. .catch(() => {
  444. // Avoid unhandled Promise rejection as the error will be thrown later
  445. // once module loading has finished
  446. });
  447. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  448. }
  449. emitPrebuiltChunk(emitPrebuiltChunk) {
  450. if (typeof emitPrebuiltChunk.code !== 'string') {
  451. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  452. }
  453. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  454. parseAst_js.isPathFragment(emitPrebuiltChunk.fileName)) {
  455. return parseAst_js.error(parseAst_js.logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  456. }
  457. const consumedPrebuiltChunk = {
  458. code: emitPrebuiltChunk.code,
  459. exports: emitPrebuiltChunk.exports,
  460. fileName: emitPrebuiltChunk.fileName,
  461. map: emitPrebuiltChunk.map,
  462. referenceId: '',
  463. type: 'prebuilt-chunk'
  464. };
  465. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  466. if (this.output) {
  467. this.output.bundle[consumedPrebuiltChunk.fileName] =
  468. this.createPrebuiltChunk(consumedPrebuiltChunk);
  469. }
  470. return referenceId;
  471. }
  472. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  473. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  474. // Deduplicate assets if an explicit fileName is not provided
  475. if (!fileName) {
  476. const sourceHash = getHash(source);
  477. fileName = fileNamesBySourceHash.get(sourceHash);
  478. if (!fileName) {
  479. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  480. fileNamesBySourceHash.set(sourceHash, fileName);
  481. }
  482. }
  483. // We must not modify the original assets to avoid interaction between outputs
  484. const assetWithFileName = { ...consumedFile, fileName, source };
  485. this.filesByReferenceId.set(referenceId, assetWithFileName);
  486. const existingAsset = bundle[fileName];
  487. if (existingAsset?.type === 'asset') {
  488. existingAsset.needsCodeReference &&= needsCodeReference;
  489. if (name) {
  490. existingAsset.names.push(name);
  491. }
  492. if (originalFileName) {
  493. existingAsset.originalFileNames.push(originalFileName);
  494. }
  495. }
  496. else {
  497. const { options } = this;
  498. bundle[fileName] = {
  499. fileName,
  500. get name() {
  501. // Additionally, this should be non-enumerable in the next major
  502. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  503. return name;
  504. },
  505. names: name ? [name] : [],
  506. needsCodeReference,
  507. get originalFileName() {
  508. // Additionally, this should be non-enumerable in the next major
  509. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  510. return originalFileName;
  511. },
  512. originalFileNames: originalFileName ? [originalFileName] : [],
  513. source,
  514. type: 'asset'
  515. };
  516. }
  517. }
  518. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  519. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  520. let fileName = '';
  521. let usedConsumedFile;
  522. let needsCodeReference = true;
  523. for (const consumedFile of consumedFiles) {
  524. needsCodeReference &&= consumedFile.needsCodeReference;
  525. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  526. if (!fileName ||
  527. assetFileName.length < fileName.length ||
  528. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  529. fileName = assetFileName;
  530. usedConsumedFile = consumedFile;
  531. }
  532. }
  533. fileNamesBySourceHash.set(sourceHash, fileName);
  534. for (const consumedFile of consumedFiles) {
  535. // We must not modify the original assets to avoid interaction between outputs
  536. const assetWithFileName = { ...consumedFile, fileName };
  537. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  538. }
  539. const { options } = this;
  540. bundle[fileName] = {
  541. fileName,
  542. get name() {
  543. // Additionally, this should be non-enumerable in the next major
  544. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  545. return usedConsumedFile.name;
  546. },
  547. names,
  548. needsCodeReference,
  549. get originalFileName() {
  550. // Additionally, this should be non-enumerable in the next major
  551. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  552. return usedConsumedFile.originalFileName;
  553. },
  554. originalFileNames,
  555. source: usedConsumedFile.source,
  556. type: 'asset'
  557. };
  558. }
  559. }
  560. function getNamesFromAssets(consumedFiles) {
  561. const names = [];
  562. const originalFileNames = [];
  563. for (const { name, originalFileName } of consumedFiles) {
  564. if (typeof name === 'string') {
  565. names.push(name);
  566. }
  567. if (originalFileName) {
  568. originalFileNames.push(originalFileName);
  569. }
  570. }
  571. originalFileNames.sort();
  572. // Sort by length first and then alphabetically so that the order is stable
  573. // and the shortest names come first
  574. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  575. return { names, originalFileNames };
  576. }
  577. const doNothing = () => { };
  578. async function asyncFlatten(array) {
  579. do {
  580. array = (await Promise.all(array)).flat(Infinity);
  581. } while (array.some((v) => v?.then));
  582. return array;
  583. }
  584. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  585. const { onwarn, onLog } = config;
  586. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  587. if (onLog) {
  588. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  589. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  590. if (level === parseAst_js.LOGLEVEL_ERROR) {
  591. return parseAst_js.error(normalizeLog(handledLog));
  592. }
  593. if (parseAst_js.logLevelPriority[level] >= minimalPriority) {
  594. defaultOnLog(level, normalizeLog(handledLog));
  595. }
  596. });
  597. }
  598. return defaultOnLog;
  599. };
  600. const getDefaultOnLog = (printLog, onwarn) => onwarn
  601. ? (level, log) => {
  602. if (level === parseAst_js.LOGLEVEL_WARN) {
  603. onwarn(addLogToString(log), warning => printLog(parseAst_js.LOGLEVEL_WARN, normalizeLog(warning)));
  604. }
  605. else {
  606. printLog(level, log);
  607. }
  608. }
  609. : printLog;
  610. const addLogToString = (log) => {
  611. Object.defineProperty(log, 'toString', {
  612. value: () => log.message,
  613. writable: true
  614. });
  615. return log;
  616. };
  617. const normalizeLog = (log) => typeof log === 'string'
  618. ? { message: log }
  619. : typeof log === 'function'
  620. ? normalizeLog(log())
  621. : log;
  622. const defaultPrintLog = (level, { message }) => {
  623. switch (level) {
  624. case parseAst_js.LOGLEVEL_WARN: {
  625. return console.warn(message);
  626. }
  627. case parseAst_js.LOGLEVEL_DEBUG: {
  628. return console.debug(message);
  629. }
  630. default: {
  631. return console.info(message);
  632. }
  633. }
  634. };
  635. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  636. const validOptionSet = new Set(validOptions);
  637. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  638. if (unknownOptions.length > 0) {
  639. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  640. }
  641. }
  642. const treeshakePresets = {
  643. recommended: {
  644. annotations: true,
  645. correctVarValueBeforeDeclaration: false,
  646. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  647. moduleSideEffects: () => true,
  648. propertyReadSideEffects: true,
  649. tryCatchDeoptimization: true,
  650. unknownGlobalSideEffects: false
  651. },
  652. safest: {
  653. annotations: true,
  654. correctVarValueBeforeDeclaration: true,
  655. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  656. moduleSideEffects: () => true,
  657. propertyReadSideEffects: true,
  658. tryCatchDeoptimization: true,
  659. unknownGlobalSideEffects: true
  660. },
  661. smallest: {
  662. annotations: true,
  663. correctVarValueBeforeDeclaration: false,
  664. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  665. moduleSideEffects: () => false,
  666. propertyReadSideEffects: false,
  667. tryCatchDeoptimization: false,
  668. unknownGlobalSideEffects: false
  669. }
  670. };
  671. const jsxPresets = {
  672. preserve: {
  673. factory: null,
  674. fragment: null,
  675. importSource: null,
  676. mode: 'preserve'
  677. },
  678. 'preserve-react': {
  679. factory: 'React.createElement',
  680. fragment: 'React.Fragment',
  681. importSource: 'react',
  682. mode: 'preserve'
  683. },
  684. react: {
  685. factory: 'React.createElement',
  686. fragment: 'React.Fragment',
  687. importSource: 'react',
  688. mode: 'classic'
  689. },
  690. 'react-jsx': {
  691. factory: 'React.createElement',
  692. importSource: 'react',
  693. jsxImportSource: 'react/jsx-runtime',
  694. mode: 'automatic'
  695. }
  696. };
  697. const generatedCodePresets = {
  698. es2015: {
  699. arrowFunctions: true,
  700. constBindings: true,
  701. objectShorthand: true,
  702. reservedNamesAsProps: true,
  703. symbols: true
  704. },
  705. es5: {
  706. arrowFunctions: false,
  707. constBindings: false,
  708. objectShorthand: false,
  709. reservedNamesAsProps: true,
  710. symbols: false
  711. }
  712. };
  713. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  714. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  715. if (typeof value === 'string') {
  716. const preset = presets[value];
  717. if (preset) {
  718. return preset;
  719. }
  720. parseAst_js.error(parseAst_js.logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${parseAst_js.printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  721. }
  722. return objectifyOption(value);
  723. };
  724. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  725. const presetName = value?.preset;
  726. if (presetName) {
  727. const preset = presets[presetName];
  728. if (preset) {
  729. return { ...preset, ...value };
  730. }
  731. else {
  732. parseAst_js.error(parseAst_js.logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${parseAst_js.printQuotedStringList(Object.keys(presets))}`, presetName));
  733. }
  734. }
  735. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  736. };
  737. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  738. function getLogHandler(level, code, logger, pluginName, logLevel) {
  739. if (parseAst_js.logLevelPriority[level] < parseAst_js.logLevelPriority[logLevel]) {
  740. return doNothing;
  741. }
  742. return (log, pos) => {
  743. if (pos != null) {
  744. logger(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidLogPosition(pluginName));
  745. }
  746. log = normalizeLog(log);
  747. if (log.code && !log.pluginCode) {
  748. log.pluginCode = log.code;
  749. }
  750. log.code = code;
  751. log.plugin = pluginName;
  752. logger(level, log);
  753. };
  754. }
  755. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  756. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  757. function createPluginCache(cache) {
  758. return {
  759. delete(id) {
  760. return delete cache[id];
  761. },
  762. get(id) {
  763. const item = cache[id];
  764. if (!item)
  765. return;
  766. item[0] = 0;
  767. return item[1];
  768. },
  769. has(id) {
  770. const item = cache[id];
  771. if (!item)
  772. return false;
  773. item[0] = 0;
  774. return true;
  775. },
  776. set(id, value) {
  777. cache[id] = [0, value];
  778. }
  779. };
  780. }
  781. function getTrackedPluginCache(pluginCache, onUse) {
  782. return {
  783. delete(id) {
  784. onUse();
  785. return pluginCache.delete(id);
  786. },
  787. get(id) {
  788. onUse();
  789. return pluginCache.get(id);
  790. },
  791. has(id) {
  792. onUse();
  793. return pluginCache.has(id);
  794. },
  795. set(id, value) {
  796. onUse();
  797. return pluginCache.set(id, value);
  798. }
  799. };
  800. }
  801. const NO_CACHE = {
  802. delete() {
  803. return false;
  804. },
  805. get() {
  806. return undefined;
  807. },
  808. has() {
  809. return false;
  810. },
  811. set() { }
  812. };
  813. function uncacheablePluginError(pluginName) {
  814. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  815. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  816. return parseAst_js.error(parseAst_js.logAnonymousPluginCache());
  817. }
  818. return parseAst_js.error(parseAst_js.logDuplicatePluginName(pluginName));
  819. }
  820. function getCacheForUncacheablePlugin(pluginName) {
  821. return {
  822. delete() {
  823. return uncacheablePluginError(pluginName);
  824. },
  825. get() {
  826. return uncacheablePluginError(pluginName);
  827. },
  828. has() {
  829. return uncacheablePluginError(pluginName);
  830. },
  831. set() {
  832. return uncacheablePluginError(pluginName);
  833. }
  834. };
  835. }
  836. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  837. const { logLevel, onLog } = options;
  838. let cacheable = true;
  839. if (typeof plugin.cacheKey !== 'string') {
  840. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  841. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  842. existingPluginNames.has(plugin.name)) {
  843. cacheable = false;
  844. }
  845. else {
  846. existingPluginNames.add(plugin.name);
  847. }
  848. }
  849. let cacheInstance;
  850. if (!pluginCache) {
  851. cacheInstance = NO_CACHE;
  852. }
  853. else if (cacheable) {
  854. const cacheKey = plugin.cacheKey || plugin.name;
  855. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  856. }
  857. else {
  858. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  859. }
  860. return {
  861. addWatchFile(id) {
  862. graph.watchFiles[id] = true;
  863. },
  864. cache: cacheInstance,
  865. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  866. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  867. error(error_) {
  868. return parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), plugin.name));
  869. },
  870. getFileName: fileEmitter.getFileName,
  871. getModuleIds: () => graph.modulesById.keys(),
  872. getModuleInfo: graph.getModuleInfo,
  873. getWatchFiles: () => Object.keys(graph.watchFiles),
  874. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  875. load(resolvedId) {
  876. return graph.moduleLoader.preloadModule(resolvedId);
  877. },
  878. meta: {
  879. rollupVersion: version,
  880. watchMode: graph.watchMode
  881. },
  882. parse: parseAst_js.parseAst,
  883. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) {
  884. skipSelf ??= true;
  885. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  886. },
  887. setAssetSource: fileEmitter.setAssetSource,
  888. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  889. };
  890. }
  891. function getDefaultExportFromCjs (x) {
  892. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  893. }
  894. function getAugmentedNamespace(n) {
  895. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  896. var f = n.default;
  897. if (typeof f == "function") {
  898. var a = function a () {
  899. if (this instanceof a) {
  900. return Reflect.construct(f, arguments, this.constructor);
  901. }
  902. return f.apply(this, arguments);
  903. };
  904. a.prototype = f.prototype;
  905. } else a = {};
  906. Object.defineProperty(a, '__esModule', {value: true});
  907. Object.keys(n).forEach(function (k) {
  908. var d = Object.getOwnPropertyDescriptor(n, k);
  909. Object.defineProperty(a, k, d.get ? d : {
  910. enumerable: true,
  911. get: function () {
  912. return n[k];
  913. }
  914. });
  915. });
  916. return a;
  917. }
  918. var utils = {};
  919. var constants;
  920. var hasRequiredConstants;
  921. function requireConstants () {
  922. if (hasRequiredConstants) return constants;
  923. hasRequiredConstants = 1;
  924. const WIN_SLASH = '\\\\/';
  925. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  926. /**
  927. * Posix glob regex
  928. */
  929. const DOT_LITERAL = '\\.';
  930. const PLUS_LITERAL = '\\+';
  931. const QMARK_LITERAL = '\\?';
  932. const SLASH_LITERAL = '\\/';
  933. const ONE_CHAR = '(?=.)';
  934. const QMARK = '[^/]';
  935. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  936. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  937. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  938. const NO_DOT = `(?!${DOT_LITERAL})`;
  939. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  940. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  941. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  942. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  943. const STAR = `${QMARK}*?`;
  944. const SEP = '/';
  945. const POSIX_CHARS = {
  946. DOT_LITERAL,
  947. PLUS_LITERAL,
  948. QMARK_LITERAL,
  949. SLASH_LITERAL,
  950. ONE_CHAR,
  951. QMARK,
  952. END_ANCHOR,
  953. DOTS_SLASH,
  954. NO_DOT,
  955. NO_DOTS,
  956. NO_DOT_SLASH,
  957. NO_DOTS_SLASH,
  958. QMARK_NO_DOT,
  959. STAR,
  960. START_ANCHOR,
  961. SEP
  962. };
  963. /**
  964. * Windows glob regex
  965. */
  966. const WINDOWS_CHARS = {
  967. ...POSIX_CHARS,
  968. SLASH_LITERAL: `[${WIN_SLASH}]`,
  969. QMARK: WIN_NO_SLASH,
  970. STAR: `${WIN_NO_SLASH}*?`,
  971. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  972. NO_DOT: `(?!${DOT_LITERAL})`,
  973. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  974. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  975. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  976. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  977. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  978. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  979. SEP: '\\'
  980. };
  981. /**
  982. * POSIX Bracket Regex
  983. */
  984. const POSIX_REGEX_SOURCE = {
  985. alnum: 'a-zA-Z0-9',
  986. alpha: 'a-zA-Z',
  987. ascii: '\\x00-\\x7F',
  988. blank: ' \\t',
  989. cntrl: '\\x00-\\x1F\\x7F',
  990. digit: '0-9',
  991. graph: '\\x21-\\x7E',
  992. lower: 'a-z',
  993. print: '\\x20-\\x7E ',
  994. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  995. space: ' \\t\\r\\n\\v\\f',
  996. upper: 'A-Z',
  997. word: 'A-Za-z0-9_',
  998. xdigit: 'A-Fa-f0-9'
  999. };
  1000. constants = {
  1001. MAX_LENGTH: 1024 * 64,
  1002. POSIX_REGEX_SOURCE,
  1003. // regular expressions
  1004. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1005. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1006. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1007. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1008. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1009. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1010. // Replace globs with equivalent patterns to reduce parsing time.
  1011. REPLACEMENTS: {
  1012. '***': '*',
  1013. '**/**': '**',
  1014. '**/**/**': '**'
  1015. },
  1016. // Digits
  1017. CHAR_0: 48, /* 0 */
  1018. CHAR_9: 57, /* 9 */
  1019. // Alphabet chars.
  1020. CHAR_UPPERCASE_A: 65, /* A */
  1021. CHAR_LOWERCASE_A: 97, /* a */
  1022. CHAR_UPPERCASE_Z: 90, /* Z */
  1023. CHAR_LOWERCASE_Z: 122, /* z */
  1024. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1025. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1026. CHAR_ASTERISK: 42, /* * */
  1027. // Non-alphabetic chars.
  1028. CHAR_AMPERSAND: 38, /* & */
  1029. CHAR_AT: 64, /* @ */
  1030. CHAR_BACKWARD_SLASH: 92, /* \ */
  1031. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1032. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1033. CHAR_COLON: 58, /* : */
  1034. CHAR_COMMA: 44, /* , */
  1035. CHAR_DOT: 46, /* . */
  1036. CHAR_DOUBLE_QUOTE: 34, /* " */
  1037. CHAR_EQUAL: 61, /* = */
  1038. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1039. CHAR_FORM_FEED: 12, /* \f */
  1040. CHAR_FORWARD_SLASH: 47, /* / */
  1041. CHAR_GRAVE_ACCENT: 96, /* ` */
  1042. CHAR_HASH: 35, /* # */
  1043. CHAR_HYPHEN_MINUS: 45, /* - */
  1044. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1045. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1046. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1047. CHAR_LINE_FEED: 10, /* \n */
  1048. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1049. CHAR_PERCENT: 37, /* % */
  1050. CHAR_PLUS: 43, /* + */
  1051. CHAR_QUESTION_MARK: 63, /* ? */
  1052. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1053. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1054. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1055. CHAR_SEMICOLON: 59, /* ; */
  1056. CHAR_SINGLE_QUOTE: 39, /* ' */
  1057. CHAR_SPACE: 32, /* */
  1058. CHAR_TAB: 9, /* \t */
  1059. CHAR_UNDERSCORE: 95, /* _ */
  1060. CHAR_VERTICAL_LINE: 124, /* | */
  1061. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1062. /**
  1063. * Create EXTGLOB_CHARS
  1064. */
  1065. extglobChars(chars) {
  1066. return {
  1067. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1068. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1069. '+': { type: 'plus', open: '(?:', close: ')+' },
  1070. '*': { type: 'star', open: '(?:', close: ')*' },
  1071. '@': { type: 'at', open: '(?:', close: ')' }
  1072. };
  1073. },
  1074. /**
  1075. * Create GLOB_CHARS
  1076. */
  1077. globChars(win32) {
  1078. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1079. }
  1080. };
  1081. return constants;
  1082. }
  1083. /*global navigator*/
  1084. var hasRequiredUtils;
  1085. function requireUtils () {
  1086. if (hasRequiredUtils) return utils;
  1087. hasRequiredUtils = 1;
  1088. (function (exports) {
  1089. const {
  1090. REGEX_BACKSLASH,
  1091. REGEX_REMOVE_BACKSLASH,
  1092. REGEX_SPECIAL_CHARS,
  1093. REGEX_SPECIAL_CHARS_GLOBAL
  1094. } = /*@__PURE__*/ requireConstants();
  1095. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1096. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1097. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1098. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1099. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1100. exports.isWindows = () => {
  1101. if (typeof navigator !== 'undefined' && navigator.platform) {
  1102. const platform = navigator.platform.toLowerCase();
  1103. return platform === 'win32' || platform === 'windows';
  1104. }
  1105. if (typeof process !== 'undefined' && process.platform) {
  1106. return process.platform === 'win32';
  1107. }
  1108. return false;
  1109. };
  1110. exports.removeBackslashes = str => {
  1111. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1112. return match === '\\' ? '' : match;
  1113. });
  1114. };
  1115. exports.escapeLast = (input, char, lastIdx) => {
  1116. const idx = input.lastIndexOf(char, lastIdx);
  1117. if (idx === -1) return input;
  1118. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1119. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1120. };
  1121. exports.removePrefix = (input, state = {}) => {
  1122. let output = input;
  1123. if (output.startsWith('./')) {
  1124. output = output.slice(2);
  1125. state.prefix = './';
  1126. }
  1127. return output;
  1128. };
  1129. exports.wrapOutput = (input, state = {}, options = {}) => {
  1130. const prepend = options.contains ? '' : '^';
  1131. const append = options.contains ? '' : '$';
  1132. let output = `${prepend}(?:${input})${append}`;
  1133. if (state.negated === true) {
  1134. output = `(?:^(?!${output}).*$)`;
  1135. }
  1136. return output;
  1137. };
  1138. exports.basename = (path, { windows } = {}) => {
  1139. const segs = path.split(windows ? /[\\/]/ : '/');
  1140. const last = segs[segs.length - 1];
  1141. if (last === '') {
  1142. return segs[segs.length - 2];
  1143. }
  1144. return last;
  1145. };
  1146. } (utils));
  1147. return utils;
  1148. }
  1149. var scan_1;
  1150. var hasRequiredScan;
  1151. function requireScan () {
  1152. if (hasRequiredScan) return scan_1;
  1153. hasRequiredScan = 1;
  1154. const utils = /*@__PURE__*/ requireUtils();
  1155. const {
  1156. CHAR_ASTERISK, /* * */
  1157. CHAR_AT, /* @ */
  1158. CHAR_BACKWARD_SLASH, /* \ */
  1159. CHAR_COMMA, /* , */
  1160. CHAR_DOT, /* . */
  1161. CHAR_EXCLAMATION_MARK, /* ! */
  1162. CHAR_FORWARD_SLASH, /* / */
  1163. CHAR_LEFT_CURLY_BRACE, /* { */
  1164. CHAR_LEFT_PARENTHESES, /* ( */
  1165. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1166. CHAR_PLUS, /* + */
  1167. CHAR_QUESTION_MARK, /* ? */
  1168. CHAR_RIGHT_CURLY_BRACE, /* } */
  1169. CHAR_RIGHT_PARENTHESES, /* ) */
  1170. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1171. } = /*@__PURE__*/ requireConstants();
  1172. const isPathSeparator = code => {
  1173. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1174. };
  1175. const depth = token => {
  1176. if (token.isPrefix !== true) {
  1177. token.depth = token.isGlobstar ? Infinity : 1;
  1178. }
  1179. };
  1180. /**
  1181. * Quickly scans a glob pattern and returns an object with a handful of
  1182. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1183. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1184. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1185. *
  1186. * ```js
  1187. * const pm = require('picomatch');
  1188. * console.log(pm.scan('foo/bar/*.js'));
  1189. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1190. * ```
  1191. * @param {String} `str`
  1192. * @param {Object} `options`
  1193. * @return {Object} Returns an object with tokens and regex source string.
  1194. * @api public
  1195. */
  1196. const scan = (input, options) => {
  1197. const opts = options || {};
  1198. const length = input.length - 1;
  1199. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1200. const slashes = [];
  1201. const tokens = [];
  1202. const parts = [];
  1203. let str = input;
  1204. let index = -1;
  1205. let start = 0;
  1206. let lastIndex = 0;
  1207. let isBrace = false;
  1208. let isBracket = false;
  1209. let isGlob = false;
  1210. let isExtglob = false;
  1211. let isGlobstar = false;
  1212. let braceEscaped = false;
  1213. let backslashes = false;
  1214. let negated = false;
  1215. let negatedExtglob = false;
  1216. let finished = false;
  1217. let braces = 0;
  1218. let prev;
  1219. let code;
  1220. let token = { value: '', depth: 0, isGlob: false };
  1221. const eos = () => index >= length;
  1222. const peek = () => str.charCodeAt(index + 1);
  1223. const advance = () => {
  1224. prev = code;
  1225. return str.charCodeAt(++index);
  1226. };
  1227. while (index < length) {
  1228. code = advance();
  1229. let next;
  1230. if (code === CHAR_BACKWARD_SLASH) {
  1231. backslashes = token.backslashes = true;
  1232. code = advance();
  1233. if (code === CHAR_LEFT_CURLY_BRACE) {
  1234. braceEscaped = true;
  1235. }
  1236. continue;
  1237. }
  1238. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1239. braces++;
  1240. while (eos() !== true && (code = advance())) {
  1241. if (code === CHAR_BACKWARD_SLASH) {
  1242. backslashes = token.backslashes = true;
  1243. advance();
  1244. continue;
  1245. }
  1246. if (code === CHAR_LEFT_CURLY_BRACE) {
  1247. braces++;
  1248. continue;
  1249. }
  1250. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1251. isBrace = token.isBrace = true;
  1252. isGlob = token.isGlob = true;
  1253. finished = true;
  1254. if (scanToEnd === true) {
  1255. continue;
  1256. }
  1257. break;
  1258. }
  1259. if (braceEscaped !== true && code === CHAR_COMMA) {
  1260. isBrace = token.isBrace = true;
  1261. isGlob = token.isGlob = true;
  1262. finished = true;
  1263. if (scanToEnd === true) {
  1264. continue;
  1265. }
  1266. break;
  1267. }
  1268. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1269. braces--;
  1270. if (braces === 0) {
  1271. braceEscaped = false;
  1272. isBrace = token.isBrace = true;
  1273. finished = true;
  1274. break;
  1275. }
  1276. }
  1277. }
  1278. if (scanToEnd === true) {
  1279. continue;
  1280. }
  1281. break;
  1282. }
  1283. if (code === CHAR_FORWARD_SLASH) {
  1284. slashes.push(index);
  1285. tokens.push(token);
  1286. token = { value: '', depth: 0, isGlob: false };
  1287. if (finished === true) continue;
  1288. if (prev === CHAR_DOT && index === (start + 1)) {
  1289. start += 2;
  1290. continue;
  1291. }
  1292. lastIndex = index + 1;
  1293. continue;
  1294. }
  1295. if (opts.noext !== true) {
  1296. const isExtglobChar = code === CHAR_PLUS
  1297. || code === CHAR_AT
  1298. || code === CHAR_ASTERISK
  1299. || code === CHAR_QUESTION_MARK
  1300. || code === CHAR_EXCLAMATION_MARK;
  1301. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1302. isGlob = token.isGlob = true;
  1303. isExtglob = token.isExtglob = true;
  1304. finished = true;
  1305. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1306. negatedExtglob = true;
  1307. }
  1308. if (scanToEnd === true) {
  1309. while (eos() !== true && (code = advance())) {
  1310. if (code === CHAR_BACKWARD_SLASH) {
  1311. backslashes = token.backslashes = true;
  1312. code = advance();
  1313. continue;
  1314. }
  1315. if (code === CHAR_RIGHT_PARENTHESES) {
  1316. isGlob = token.isGlob = true;
  1317. finished = true;
  1318. break;
  1319. }
  1320. }
  1321. continue;
  1322. }
  1323. break;
  1324. }
  1325. }
  1326. if (code === CHAR_ASTERISK) {
  1327. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1328. isGlob = token.isGlob = true;
  1329. finished = true;
  1330. if (scanToEnd === true) {
  1331. continue;
  1332. }
  1333. break;
  1334. }
  1335. if (code === CHAR_QUESTION_MARK) {
  1336. isGlob = token.isGlob = true;
  1337. finished = true;
  1338. if (scanToEnd === true) {
  1339. continue;
  1340. }
  1341. break;
  1342. }
  1343. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1344. while (eos() !== true && (next = advance())) {
  1345. if (next === CHAR_BACKWARD_SLASH) {
  1346. backslashes = token.backslashes = true;
  1347. advance();
  1348. continue;
  1349. }
  1350. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1351. isBracket = token.isBracket = true;
  1352. isGlob = token.isGlob = true;
  1353. finished = true;
  1354. break;
  1355. }
  1356. }
  1357. if (scanToEnd === true) {
  1358. continue;
  1359. }
  1360. break;
  1361. }
  1362. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1363. negated = token.negated = true;
  1364. start++;
  1365. continue;
  1366. }
  1367. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1368. isGlob = token.isGlob = true;
  1369. if (scanToEnd === true) {
  1370. while (eos() !== true && (code = advance())) {
  1371. if (code === CHAR_LEFT_PARENTHESES) {
  1372. backslashes = token.backslashes = true;
  1373. code = advance();
  1374. continue;
  1375. }
  1376. if (code === CHAR_RIGHT_PARENTHESES) {
  1377. finished = true;
  1378. break;
  1379. }
  1380. }
  1381. continue;
  1382. }
  1383. break;
  1384. }
  1385. if (isGlob === true) {
  1386. finished = true;
  1387. if (scanToEnd === true) {
  1388. continue;
  1389. }
  1390. break;
  1391. }
  1392. }
  1393. if (opts.noext === true) {
  1394. isExtglob = false;
  1395. isGlob = false;
  1396. }
  1397. let base = str;
  1398. let prefix = '';
  1399. let glob = '';
  1400. if (start > 0) {
  1401. prefix = str.slice(0, start);
  1402. str = str.slice(start);
  1403. lastIndex -= start;
  1404. }
  1405. if (base && isGlob === true && lastIndex > 0) {
  1406. base = str.slice(0, lastIndex);
  1407. glob = str.slice(lastIndex);
  1408. } else if (isGlob === true) {
  1409. base = '';
  1410. glob = str;
  1411. } else {
  1412. base = str;
  1413. }
  1414. if (base && base !== '' && base !== '/' && base !== str) {
  1415. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1416. base = base.slice(0, -1);
  1417. }
  1418. }
  1419. if (opts.unescape === true) {
  1420. if (glob) glob = utils.removeBackslashes(glob);
  1421. if (base && backslashes === true) {
  1422. base = utils.removeBackslashes(base);
  1423. }
  1424. }
  1425. const state = {
  1426. prefix,
  1427. input,
  1428. start,
  1429. base,
  1430. glob,
  1431. isBrace,
  1432. isBracket,
  1433. isGlob,
  1434. isExtglob,
  1435. isGlobstar,
  1436. negated,
  1437. negatedExtglob
  1438. };
  1439. if (opts.tokens === true) {
  1440. state.maxDepth = 0;
  1441. if (!isPathSeparator(code)) {
  1442. tokens.push(token);
  1443. }
  1444. state.tokens = tokens;
  1445. }
  1446. if (opts.parts === true || opts.tokens === true) {
  1447. let prevIndex;
  1448. for (let idx = 0; idx < slashes.length; idx++) {
  1449. const n = prevIndex ? prevIndex + 1 : start;
  1450. const i = slashes[idx];
  1451. const value = input.slice(n, i);
  1452. if (opts.tokens) {
  1453. if (idx === 0 && start !== 0) {
  1454. tokens[idx].isPrefix = true;
  1455. tokens[idx].value = prefix;
  1456. } else {
  1457. tokens[idx].value = value;
  1458. }
  1459. depth(tokens[idx]);
  1460. state.maxDepth += tokens[idx].depth;
  1461. }
  1462. if (idx !== 0 || value !== '') {
  1463. parts.push(value);
  1464. }
  1465. prevIndex = i;
  1466. }
  1467. if (prevIndex && prevIndex + 1 < input.length) {
  1468. const value = input.slice(prevIndex + 1);
  1469. parts.push(value);
  1470. if (opts.tokens) {
  1471. tokens[tokens.length - 1].value = value;
  1472. depth(tokens[tokens.length - 1]);
  1473. state.maxDepth += tokens[tokens.length - 1].depth;
  1474. }
  1475. }
  1476. state.slashes = slashes;
  1477. state.parts = parts;
  1478. }
  1479. return state;
  1480. };
  1481. scan_1 = scan;
  1482. return scan_1;
  1483. }
  1484. var parse_1;
  1485. var hasRequiredParse;
  1486. function requireParse () {
  1487. if (hasRequiredParse) return parse_1;
  1488. hasRequiredParse = 1;
  1489. const constants = /*@__PURE__*/ requireConstants();
  1490. const utils = /*@__PURE__*/ requireUtils();
  1491. /**
  1492. * Constants
  1493. */
  1494. const {
  1495. MAX_LENGTH,
  1496. POSIX_REGEX_SOURCE,
  1497. REGEX_NON_SPECIAL_CHARS,
  1498. REGEX_SPECIAL_CHARS_BACKREF,
  1499. REPLACEMENTS
  1500. } = constants;
  1501. /**
  1502. * Helpers
  1503. */
  1504. const expandRange = (args, options) => {
  1505. if (typeof options.expandRange === 'function') {
  1506. return options.expandRange(...args, options);
  1507. }
  1508. args.sort();
  1509. const value = `[${args.join('-')}]`;
  1510. return value;
  1511. };
  1512. /**
  1513. * Create the message for a syntax error
  1514. */
  1515. const syntaxError = (type, char) => {
  1516. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1517. };
  1518. /**
  1519. * Parse the given input string.
  1520. * @param {String} input
  1521. * @param {Object} options
  1522. * @return {Object}
  1523. */
  1524. const parse = (input, options) => {
  1525. if (typeof input !== 'string') {
  1526. throw new TypeError('Expected a string');
  1527. }
  1528. input = REPLACEMENTS[input] || input;
  1529. const opts = { ...options };
  1530. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1531. let len = input.length;
  1532. if (len > max) {
  1533. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1534. }
  1535. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1536. const tokens = [bos];
  1537. const capture = opts.capture ? '' : '?:';
  1538. // create constants based on platform, for windows or posix
  1539. const PLATFORM_CHARS = constants.globChars(opts.windows);
  1540. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  1541. const {
  1542. DOT_LITERAL,
  1543. PLUS_LITERAL,
  1544. SLASH_LITERAL,
  1545. ONE_CHAR,
  1546. DOTS_SLASH,
  1547. NO_DOT,
  1548. NO_DOT_SLASH,
  1549. NO_DOTS_SLASH,
  1550. QMARK,
  1551. QMARK_NO_DOT,
  1552. STAR,
  1553. START_ANCHOR
  1554. } = PLATFORM_CHARS;
  1555. const globstar = opts => {
  1556. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1557. };
  1558. const nodot = opts.dot ? '' : NO_DOT;
  1559. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1560. let star = opts.bash === true ? globstar(opts) : STAR;
  1561. if (opts.capture) {
  1562. star = `(${star})`;
  1563. }
  1564. // minimatch options support
  1565. if (typeof opts.noext === 'boolean') {
  1566. opts.noextglob = opts.noext;
  1567. }
  1568. const state = {
  1569. input,
  1570. index: -1,
  1571. start: 0,
  1572. dot: opts.dot === true,
  1573. consumed: '',
  1574. output: '',
  1575. prefix: '',
  1576. backtrack: false,
  1577. negated: false,
  1578. brackets: 0,
  1579. braces: 0,
  1580. parens: 0,
  1581. quotes: 0,
  1582. globstar: false,
  1583. tokens
  1584. };
  1585. input = utils.removePrefix(input, state);
  1586. len = input.length;
  1587. const extglobs = [];
  1588. const braces = [];
  1589. const stack = [];
  1590. let prev = bos;
  1591. let value;
  1592. /**
  1593. * Tokenizing helpers
  1594. */
  1595. const eos = () => state.index === len - 1;
  1596. const peek = state.peek = (n = 1) => input[state.index + n];
  1597. const advance = state.advance = () => input[++state.index] || '';
  1598. const remaining = () => input.slice(state.index + 1);
  1599. const consume = (value = '', num = 0) => {
  1600. state.consumed += value;
  1601. state.index += num;
  1602. };
  1603. const append = token => {
  1604. state.output += token.output != null ? token.output : token.value;
  1605. consume(token.value);
  1606. };
  1607. const negate = () => {
  1608. let count = 1;
  1609. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1610. advance();
  1611. state.start++;
  1612. count++;
  1613. }
  1614. if (count % 2 === 0) {
  1615. return false;
  1616. }
  1617. state.negated = true;
  1618. state.start++;
  1619. return true;
  1620. };
  1621. const increment = type => {
  1622. state[type]++;
  1623. stack.push(type);
  1624. };
  1625. const decrement = type => {
  1626. state[type]--;
  1627. stack.pop();
  1628. };
  1629. /**
  1630. * Push tokens onto the tokens array. This helper speeds up
  1631. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1632. * and 2) helping us avoid creating extra tokens when consecutive
  1633. * characters are plain text. This improves performance and simplifies
  1634. * lookbehinds.
  1635. */
  1636. const push = tok => {
  1637. if (prev.type === 'globstar') {
  1638. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1639. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1640. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1641. state.output = state.output.slice(0, -prev.output.length);
  1642. prev.type = 'star';
  1643. prev.value = '*';
  1644. prev.output = star;
  1645. state.output += prev.output;
  1646. }
  1647. }
  1648. if (extglobs.length && tok.type !== 'paren') {
  1649. extglobs[extglobs.length - 1].inner += tok.value;
  1650. }
  1651. if (tok.value || tok.output) append(tok);
  1652. if (prev && prev.type === 'text' && tok.type === 'text') {
  1653. prev.output = (prev.output || prev.value) + tok.value;
  1654. prev.value += tok.value;
  1655. return;
  1656. }
  1657. tok.prev = prev;
  1658. tokens.push(tok);
  1659. prev = tok;
  1660. };
  1661. const extglobOpen = (type, value) => {
  1662. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1663. token.prev = prev;
  1664. token.parens = state.parens;
  1665. token.output = state.output;
  1666. const output = (opts.capture ? '(' : '') + token.open;
  1667. increment('parens');
  1668. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1669. push({ type: 'paren', extglob: true, value: advance(), output });
  1670. extglobs.push(token);
  1671. };
  1672. const extglobClose = token => {
  1673. let output = token.close + (opts.capture ? ')' : '');
  1674. let rest;
  1675. if (token.type === 'negate') {
  1676. let extglobStar = star;
  1677. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1678. extglobStar = globstar(opts);
  1679. }
  1680. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1681. output = token.close = `)$))${extglobStar}`;
  1682. }
  1683. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1684. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1685. // In this case, we need to parse the string and use it in the output of the original pattern.
  1686. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1687. //
  1688. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1689. const expression = parse(rest, { ...options, fastpaths: false }).output;
  1690. output = token.close = `)${expression})${extglobStar})`;
  1691. }
  1692. if (token.prev.type === 'bos') {
  1693. state.negatedExtglob = true;
  1694. }
  1695. }
  1696. push({ type: 'paren', extglob: true, value, output });
  1697. decrement('parens');
  1698. };
  1699. /**
  1700. * Fast paths
  1701. */
  1702. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1703. let backslashes = false;
  1704. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1705. if (first === '\\') {
  1706. backslashes = true;
  1707. return m;
  1708. }
  1709. if (first === '?') {
  1710. if (esc) {
  1711. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1712. }
  1713. if (index === 0) {
  1714. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1715. }
  1716. return QMARK.repeat(chars.length);
  1717. }
  1718. if (first === '.') {
  1719. return DOT_LITERAL.repeat(chars.length);
  1720. }
  1721. if (first === '*') {
  1722. if (esc) {
  1723. return esc + first + (rest ? star : '');
  1724. }
  1725. return star;
  1726. }
  1727. return esc ? m : `\\${m}`;
  1728. });
  1729. if (backslashes === true) {
  1730. if (opts.unescape === true) {
  1731. output = output.replace(/\\/g, '');
  1732. } else {
  1733. output = output.replace(/\\+/g, m => {
  1734. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1735. });
  1736. }
  1737. }
  1738. if (output === input && opts.contains === true) {
  1739. state.output = input;
  1740. return state;
  1741. }
  1742. state.output = utils.wrapOutput(output, state, options);
  1743. return state;
  1744. }
  1745. /**
  1746. * Tokenize input until we reach end-of-string
  1747. */
  1748. while (!eos()) {
  1749. value = advance();
  1750. if (value === '\u0000') {
  1751. continue;
  1752. }
  1753. /**
  1754. * Escaped characters
  1755. */
  1756. if (value === '\\') {
  1757. const next = peek();
  1758. if (next === '/' && opts.bash !== true) {
  1759. continue;
  1760. }
  1761. if (next === '.' || next === ';') {
  1762. continue;
  1763. }
  1764. if (!next) {
  1765. value += '\\';
  1766. push({ type: 'text', value });
  1767. continue;
  1768. }
  1769. // collapse slashes to reduce potential for exploits
  1770. const match = /^\\+/.exec(remaining());
  1771. let slashes = 0;
  1772. if (match && match[0].length > 2) {
  1773. slashes = match[0].length;
  1774. state.index += slashes;
  1775. if (slashes % 2 !== 0) {
  1776. value += '\\';
  1777. }
  1778. }
  1779. if (opts.unescape === true) {
  1780. value = advance();
  1781. } else {
  1782. value += advance();
  1783. }
  1784. if (state.brackets === 0) {
  1785. push({ type: 'text', value });
  1786. continue;
  1787. }
  1788. }
  1789. /**
  1790. * If we're inside a regex character class, continue
  1791. * until we reach the closing bracket.
  1792. */
  1793. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1794. if (opts.posix !== false && value === ':') {
  1795. const inner = prev.value.slice(1);
  1796. if (inner.includes('[')) {
  1797. prev.posix = true;
  1798. if (inner.includes(':')) {
  1799. const idx = prev.value.lastIndexOf('[');
  1800. const pre = prev.value.slice(0, idx);
  1801. const rest = prev.value.slice(idx + 2);
  1802. const posix = POSIX_REGEX_SOURCE[rest];
  1803. if (posix) {
  1804. prev.value = pre + posix;
  1805. state.backtrack = true;
  1806. advance();
  1807. if (!bos.output && tokens.indexOf(prev) === 1) {
  1808. bos.output = ONE_CHAR;
  1809. }
  1810. continue;
  1811. }
  1812. }
  1813. }
  1814. }
  1815. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1816. value = `\\${value}`;
  1817. }
  1818. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1819. value = `\\${value}`;
  1820. }
  1821. if (opts.posix === true && value === '!' && prev.value === '[') {
  1822. value = '^';
  1823. }
  1824. prev.value += value;
  1825. append({ value });
  1826. continue;
  1827. }
  1828. /**
  1829. * If we're inside a quoted string, continue
  1830. * until we reach the closing double quote.
  1831. */
  1832. if (state.quotes === 1 && value !== '"') {
  1833. value = utils.escapeRegex(value);
  1834. prev.value += value;
  1835. append({ value });
  1836. continue;
  1837. }
  1838. /**
  1839. * Double quotes
  1840. */
  1841. if (value === '"') {
  1842. state.quotes = state.quotes === 1 ? 0 : 1;
  1843. if (opts.keepQuotes === true) {
  1844. push({ type: 'text', value });
  1845. }
  1846. continue;
  1847. }
  1848. /**
  1849. * Parentheses
  1850. */
  1851. if (value === '(') {
  1852. increment('parens');
  1853. push({ type: 'paren', value });
  1854. continue;
  1855. }
  1856. if (value === ')') {
  1857. if (state.parens === 0 && opts.strictBrackets === true) {
  1858. throw new SyntaxError(syntaxError('opening', '('));
  1859. }
  1860. const extglob = extglobs[extglobs.length - 1];
  1861. if (extglob && state.parens === extglob.parens + 1) {
  1862. extglobClose(extglobs.pop());
  1863. continue;
  1864. }
  1865. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1866. decrement('parens');
  1867. continue;
  1868. }
  1869. /**
  1870. * Square brackets
  1871. */
  1872. if (value === '[') {
  1873. if (opts.nobracket === true || !remaining().includes(']')) {
  1874. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1875. throw new SyntaxError(syntaxError('closing', ']'));
  1876. }
  1877. value = `\\${value}`;
  1878. } else {
  1879. increment('brackets');
  1880. }
  1881. push({ type: 'bracket', value });
  1882. continue;
  1883. }
  1884. if (value === ']') {
  1885. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1886. push({ type: 'text', value, output: `\\${value}` });
  1887. continue;
  1888. }
  1889. if (state.brackets === 0) {
  1890. if (opts.strictBrackets === true) {
  1891. throw new SyntaxError(syntaxError('opening', '['));
  1892. }
  1893. push({ type: 'text', value, output: `\\${value}` });
  1894. continue;
  1895. }
  1896. decrement('brackets');
  1897. const prevValue = prev.value.slice(1);
  1898. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1899. value = `/${value}`;
  1900. }
  1901. prev.value += value;
  1902. append({ value });
  1903. // when literal brackets are explicitly disabled
  1904. // assume we should match with a regex character class
  1905. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  1906. continue;
  1907. }
  1908. const escaped = utils.escapeRegex(prev.value);
  1909. state.output = state.output.slice(0, -prev.value.length);
  1910. // when literal brackets are explicitly enabled
  1911. // assume we should escape the brackets to match literal characters
  1912. if (opts.literalBrackets === true) {
  1913. state.output += escaped;
  1914. prev.value = escaped;
  1915. continue;
  1916. }
  1917. // when the user specifies nothing, try to match both
  1918. prev.value = `(${capture}${escaped}|${prev.value})`;
  1919. state.output += prev.value;
  1920. continue;
  1921. }
  1922. /**
  1923. * Braces
  1924. */
  1925. if (value === '{' && opts.nobrace !== true) {
  1926. increment('braces');
  1927. const open = {
  1928. type: 'brace',
  1929. value,
  1930. output: '(',
  1931. outputIndex: state.output.length,
  1932. tokensIndex: state.tokens.length
  1933. };
  1934. braces.push(open);
  1935. push(open);
  1936. continue;
  1937. }
  1938. if (value === '}') {
  1939. const brace = braces[braces.length - 1];
  1940. if (opts.nobrace === true || !brace) {
  1941. push({ type: 'text', value, output: value });
  1942. continue;
  1943. }
  1944. let output = ')';
  1945. if (brace.dots === true) {
  1946. const arr = tokens.slice();
  1947. const range = [];
  1948. for (let i = arr.length - 1; i >= 0; i--) {
  1949. tokens.pop();
  1950. if (arr[i].type === 'brace') {
  1951. break;
  1952. }
  1953. if (arr[i].type !== 'dots') {
  1954. range.unshift(arr[i].value);
  1955. }
  1956. }
  1957. output = expandRange(range, opts);
  1958. state.backtrack = true;
  1959. }
  1960. if (brace.comma !== true && brace.dots !== true) {
  1961. const out = state.output.slice(0, brace.outputIndex);
  1962. const toks = state.tokens.slice(brace.tokensIndex);
  1963. brace.value = brace.output = '\\{';
  1964. value = output = '\\}';
  1965. state.output = out;
  1966. for (const t of toks) {
  1967. state.output += (t.output || t.value);
  1968. }
  1969. }
  1970. push({ type: 'brace', value, output });
  1971. decrement('braces');
  1972. braces.pop();
  1973. continue;
  1974. }
  1975. /**
  1976. * Pipes
  1977. */
  1978. if (value === '|') {
  1979. if (extglobs.length > 0) {
  1980. extglobs[extglobs.length - 1].conditions++;
  1981. }
  1982. push({ type: 'text', value });
  1983. continue;
  1984. }
  1985. /**
  1986. * Commas
  1987. */
  1988. if (value === ',') {
  1989. let output = value;
  1990. const brace = braces[braces.length - 1];
  1991. if (brace && stack[stack.length - 1] === 'braces') {
  1992. brace.comma = true;
  1993. output = '|';
  1994. }
  1995. push({ type: 'comma', value, output });
  1996. continue;
  1997. }
  1998. /**
  1999. * Slashes
  2000. */
  2001. if (value === '/') {
  2002. // if the beginning of the glob is "./", advance the start
  2003. // to the current index, and don't add the "./" characters
  2004. // to the state. This greatly simplifies lookbehinds when
  2005. // checking for BOS characters like "!" and "." (not "./")
  2006. if (prev.type === 'dot' && state.index === state.start + 1) {
  2007. state.start = state.index + 1;
  2008. state.consumed = '';
  2009. state.output = '';
  2010. tokens.pop();
  2011. prev = bos; // reset "prev" to the first token
  2012. continue;
  2013. }
  2014. push({ type: 'slash', value, output: SLASH_LITERAL });
  2015. continue;
  2016. }
  2017. /**
  2018. * Dots
  2019. */
  2020. if (value === '.') {
  2021. if (state.braces > 0 && prev.type === 'dot') {
  2022. if (prev.value === '.') prev.output = DOT_LITERAL;
  2023. const brace = braces[braces.length - 1];
  2024. prev.type = 'dots';
  2025. prev.output += value;
  2026. prev.value += value;
  2027. brace.dots = true;
  2028. continue;
  2029. }
  2030. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2031. push({ type: 'text', value, output: DOT_LITERAL });
  2032. continue;
  2033. }
  2034. push({ type: 'dot', value, output: DOT_LITERAL });
  2035. continue;
  2036. }
  2037. /**
  2038. * Question marks
  2039. */
  2040. if (value === '?') {
  2041. const isGroup = prev && prev.value === '(';
  2042. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2043. extglobOpen('qmark', value);
  2044. continue;
  2045. }
  2046. if (prev && prev.type === 'paren') {
  2047. const next = peek();
  2048. let output = value;
  2049. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2050. output = `\\${value}`;
  2051. }
  2052. push({ type: 'text', value, output });
  2053. continue;
  2054. }
  2055. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2056. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2057. continue;
  2058. }
  2059. push({ type: 'qmark', value, output: QMARK });
  2060. continue;
  2061. }
  2062. /**
  2063. * Exclamation
  2064. */
  2065. if (value === '!') {
  2066. if (opts.noextglob !== true && peek() === '(') {
  2067. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2068. extglobOpen('negate', value);
  2069. continue;
  2070. }
  2071. }
  2072. if (opts.nonegate !== true && state.index === 0) {
  2073. negate();
  2074. continue;
  2075. }
  2076. }
  2077. /**
  2078. * Plus
  2079. */
  2080. if (value === '+') {
  2081. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2082. extglobOpen('plus', value);
  2083. continue;
  2084. }
  2085. if ((prev && prev.value === '(') || opts.regex === false) {
  2086. push({ type: 'plus', value, output: PLUS_LITERAL });
  2087. continue;
  2088. }
  2089. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2090. push({ type: 'plus', value });
  2091. continue;
  2092. }
  2093. push({ type: 'plus', value: PLUS_LITERAL });
  2094. continue;
  2095. }
  2096. /**
  2097. * Plain text
  2098. */
  2099. if (value === '@') {
  2100. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2101. push({ type: 'at', extglob: true, value, output: '' });
  2102. continue;
  2103. }
  2104. push({ type: 'text', value });
  2105. continue;
  2106. }
  2107. /**
  2108. * Plain text
  2109. */
  2110. if (value !== '*') {
  2111. if (value === '$' || value === '^') {
  2112. value = `\\${value}`;
  2113. }
  2114. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2115. if (match) {
  2116. value += match[0];
  2117. state.index += match[0].length;
  2118. }
  2119. push({ type: 'text', value });
  2120. continue;
  2121. }
  2122. /**
  2123. * Stars
  2124. */
  2125. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2126. prev.type = 'star';
  2127. prev.star = true;
  2128. prev.value += value;
  2129. prev.output = star;
  2130. state.backtrack = true;
  2131. state.globstar = true;
  2132. consume(value);
  2133. continue;
  2134. }
  2135. let rest = remaining();
  2136. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2137. extglobOpen('star', value);
  2138. continue;
  2139. }
  2140. if (prev.type === 'star') {
  2141. if (opts.noglobstar === true) {
  2142. consume(value);
  2143. continue;
  2144. }
  2145. const prior = prev.prev;
  2146. const before = prior.prev;
  2147. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2148. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2149. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2150. push({ type: 'star', value, output: '' });
  2151. continue;
  2152. }
  2153. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2154. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2155. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2156. push({ type: 'star', value, output: '' });
  2157. continue;
  2158. }
  2159. // strip consecutive `/**/`
  2160. while (rest.slice(0, 3) === '/**') {
  2161. const after = input[state.index + 4];
  2162. if (after && after !== '/') {
  2163. break;
  2164. }
  2165. rest = rest.slice(3);
  2166. consume('/**', 3);
  2167. }
  2168. if (prior.type === 'bos' && eos()) {
  2169. prev.type = 'globstar';
  2170. prev.value += value;
  2171. prev.output = globstar(opts);
  2172. state.output = prev.output;
  2173. state.globstar = true;
  2174. consume(value);
  2175. continue;
  2176. }
  2177. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2178. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2179. prior.output = `(?:${prior.output}`;
  2180. prev.type = 'globstar';
  2181. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2182. prev.value += value;
  2183. state.globstar = true;
  2184. state.output += prior.output + prev.output;
  2185. consume(value);
  2186. continue;
  2187. }
  2188. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2189. const end = rest[1] !== void 0 ? '|$' : '';
  2190. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2191. prior.output = `(?:${prior.output}`;
  2192. prev.type = 'globstar';
  2193. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2194. prev.value += value;
  2195. state.output += prior.output + prev.output;
  2196. state.globstar = true;
  2197. consume(value + advance());
  2198. push({ type: 'slash', value: '/', output: '' });
  2199. continue;
  2200. }
  2201. if (prior.type === 'bos' && rest[0] === '/') {
  2202. prev.type = 'globstar';
  2203. prev.value += value;
  2204. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2205. state.output = prev.output;
  2206. state.globstar = true;
  2207. consume(value + advance());
  2208. push({ type: 'slash', value: '/', output: '' });
  2209. continue;
  2210. }
  2211. // remove single star from output
  2212. state.output = state.output.slice(0, -prev.output.length);
  2213. // reset previous token to globstar
  2214. prev.type = 'globstar';
  2215. prev.output = globstar(opts);
  2216. prev.value += value;
  2217. // reset output with globstar
  2218. state.output += prev.output;
  2219. state.globstar = true;
  2220. consume(value);
  2221. continue;
  2222. }
  2223. const token = { type: 'star', value, output: star };
  2224. if (opts.bash === true) {
  2225. token.output = '.*?';
  2226. if (prev.type === 'bos' || prev.type === 'slash') {
  2227. token.output = nodot + token.output;
  2228. }
  2229. push(token);
  2230. continue;
  2231. }
  2232. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2233. token.output = value;
  2234. push(token);
  2235. continue;
  2236. }
  2237. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2238. if (prev.type === 'dot') {
  2239. state.output += NO_DOT_SLASH;
  2240. prev.output += NO_DOT_SLASH;
  2241. } else if (opts.dot === true) {
  2242. state.output += NO_DOTS_SLASH;
  2243. prev.output += NO_DOTS_SLASH;
  2244. } else {
  2245. state.output += nodot;
  2246. prev.output += nodot;
  2247. }
  2248. if (peek() !== '*') {
  2249. state.output += ONE_CHAR;
  2250. prev.output += ONE_CHAR;
  2251. }
  2252. }
  2253. push(token);
  2254. }
  2255. while (state.brackets > 0) {
  2256. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2257. state.output = utils.escapeLast(state.output, '[');
  2258. decrement('brackets');
  2259. }
  2260. while (state.parens > 0) {
  2261. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2262. state.output = utils.escapeLast(state.output, '(');
  2263. decrement('parens');
  2264. }
  2265. while (state.braces > 0) {
  2266. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2267. state.output = utils.escapeLast(state.output, '{');
  2268. decrement('braces');
  2269. }
  2270. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2271. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2272. }
  2273. // rebuild the output if we had to backtrack at any point
  2274. if (state.backtrack === true) {
  2275. state.output = '';
  2276. for (const token of state.tokens) {
  2277. state.output += token.output != null ? token.output : token.value;
  2278. if (token.suffix) {
  2279. state.output += token.suffix;
  2280. }
  2281. }
  2282. }
  2283. return state;
  2284. };
  2285. /**
  2286. * Fast paths for creating regular expressions for common glob patterns.
  2287. * This can significantly speed up processing and has very little downside
  2288. * impact when none of the fast paths match.
  2289. */
  2290. parse.fastpaths = (input, options) => {
  2291. const opts = { ...options };
  2292. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2293. const len = input.length;
  2294. if (len > max) {
  2295. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2296. }
  2297. input = REPLACEMENTS[input] || input;
  2298. // create constants based on platform, for windows or posix
  2299. const {
  2300. DOT_LITERAL,
  2301. SLASH_LITERAL,
  2302. ONE_CHAR,
  2303. DOTS_SLASH,
  2304. NO_DOT,
  2305. NO_DOTS,
  2306. NO_DOTS_SLASH,
  2307. STAR,
  2308. START_ANCHOR
  2309. } = constants.globChars(opts.windows);
  2310. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2311. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2312. const capture = opts.capture ? '' : '?:';
  2313. const state = { negated: false, prefix: '' };
  2314. let star = opts.bash === true ? '.*?' : STAR;
  2315. if (opts.capture) {
  2316. star = `(${star})`;
  2317. }
  2318. const globstar = opts => {
  2319. if (opts.noglobstar === true) return star;
  2320. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2321. };
  2322. const create = str => {
  2323. switch (str) {
  2324. case '*':
  2325. return `${nodot}${ONE_CHAR}${star}`;
  2326. case '.*':
  2327. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2328. case '*.*':
  2329. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2330. case '*/*':
  2331. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2332. case '**':
  2333. return nodot + globstar(opts);
  2334. case '**/*':
  2335. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2336. case '**/*.*':
  2337. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2338. case '**/.*':
  2339. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2340. default: {
  2341. const match = /^(.*?)\.(\w+)$/.exec(str);
  2342. if (!match) return;
  2343. const source = create(match[1]);
  2344. if (!source) return;
  2345. return source + DOT_LITERAL + match[2];
  2346. }
  2347. }
  2348. };
  2349. const output = utils.removePrefix(input, state);
  2350. let source = create(output);
  2351. if (source && opts.strictSlashes !== true) {
  2352. source += `${SLASH_LITERAL}?`;
  2353. }
  2354. return source;
  2355. };
  2356. parse_1 = parse;
  2357. return parse_1;
  2358. }
  2359. var picomatch_1$1;
  2360. var hasRequiredPicomatch$1;
  2361. function requirePicomatch$1 () {
  2362. if (hasRequiredPicomatch$1) return picomatch_1$1;
  2363. hasRequiredPicomatch$1 = 1;
  2364. const scan = /*@__PURE__*/ requireScan();
  2365. const parse = /*@__PURE__*/ requireParse();
  2366. const utils = /*@__PURE__*/ requireUtils();
  2367. const constants = /*@__PURE__*/ requireConstants();
  2368. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  2369. /**
  2370. * Creates a matcher function from one or more glob patterns. The
  2371. * returned function takes a string to match as its first argument,
  2372. * and returns true if the string is a match. The returned matcher
  2373. * function also takes a boolean as the second argument that, when true,
  2374. * returns an object with additional information.
  2375. *
  2376. * ```js
  2377. * const picomatch = require('picomatch');
  2378. * // picomatch(glob[, options]);
  2379. *
  2380. * const isMatch = picomatch('*.!(*a)');
  2381. * console.log(isMatch('a.a')); //=> false
  2382. * console.log(isMatch('a.b')); //=> true
  2383. * ```
  2384. * @name picomatch
  2385. * @param {String|Array} `globs` One or more glob patterns.
  2386. * @param {Object=} `options`
  2387. * @return {Function=} Returns a matcher function.
  2388. * @api public
  2389. */
  2390. const picomatch = (glob, options, returnState = false) => {
  2391. if (Array.isArray(glob)) {
  2392. const fns = glob.map(input => picomatch(input, options, returnState));
  2393. const arrayMatcher = str => {
  2394. for (const isMatch of fns) {
  2395. const state = isMatch(str);
  2396. if (state) return state;
  2397. }
  2398. return false;
  2399. };
  2400. return arrayMatcher;
  2401. }
  2402. const isState = isObject(glob) && glob.tokens && glob.input;
  2403. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2404. throw new TypeError('Expected pattern to be a non-empty string');
  2405. }
  2406. const opts = options || {};
  2407. const posix = opts.windows;
  2408. const regex = isState
  2409. ? picomatch.compileRe(glob, options)
  2410. : picomatch.makeRe(glob, options, false, true);
  2411. const state = regex.state;
  2412. delete regex.state;
  2413. let isIgnored = () => false;
  2414. if (opts.ignore) {
  2415. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2416. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  2417. }
  2418. const matcher = (input, returnObject = false) => {
  2419. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  2420. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2421. if (typeof opts.onResult === 'function') {
  2422. opts.onResult(result);
  2423. }
  2424. if (isMatch === false) {
  2425. result.isMatch = false;
  2426. return returnObject ? result : false;
  2427. }
  2428. if (isIgnored(input)) {
  2429. if (typeof opts.onIgnore === 'function') {
  2430. opts.onIgnore(result);
  2431. }
  2432. result.isMatch = false;
  2433. return returnObject ? result : false;
  2434. }
  2435. if (typeof opts.onMatch === 'function') {
  2436. opts.onMatch(result);
  2437. }
  2438. return returnObject ? result : true;
  2439. };
  2440. if (returnState) {
  2441. matcher.state = state;
  2442. }
  2443. return matcher;
  2444. };
  2445. /**
  2446. * Test `input` with the given `regex`. This is used by the main
  2447. * `picomatch()` function to test the input string.
  2448. *
  2449. * ```js
  2450. * const picomatch = require('picomatch');
  2451. * // picomatch.test(input, regex[, options]);
  2452. *
  2453. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2454. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2455. * ```
  2456. * @param {String} `input` String to test.
  2457. * @param {RegExp} `regex`
  2458. * @return {Object} Returns an object with matching info.
  2459. * @api public
  2460. */
  2461. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  2462. if (typeof input !== 'string') {
  2463. throw new TypeError('Expected input to be a string');
  2464. }
  2465. if (input === '') {
  2466. return { isMatch: false, output: '' };
  2467. }
  2468. const opts = options || {};
  2469. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  2470. let match = input === glob;
  2471. let output = (match && format) ? format(input) : input;
  2472. if (match === false) {
  2473. output = format ? format(input) : input;
  2474. match = output === glob;
  2475. }
  2476. if (match === false || opts.capture === true) {
  2477. if (opts.matchBase === true || opts.basename === true) {
  2478. match = picomatch.matchBase(input, regex, options, posix);
  2479. } else {
  2480. match = regex.exec(output);
  2481. }
  2482. }
  2483. return { isMatch: Boolean(match), match, output };
  2484. };
  2485. /**
  2486. * Match the basename of a filepath.
  2487. *
  2488. * ```js
  2489. * const picomatch = require('picomatch');
  2490. * // picomatch.matchBase(input, glob[, options]);
  2491. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2492. * ```
  2493. * @param {String} `input` String to test.
  2494. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2495. * @return {Boolean}
  2496. * @api public
  2497. */
  2498. picomatch.matchBase = (input, glob, options) => {
  2499. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  2500. return regex.test(utils.basename(input));
  2501. };
  2502. /**
  2503. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2504. *
  2505. * ```js
  2506. * const picomatch = require('picomatch');
  2507. * // picomatch.isMatch(string, patterns[, options]);
  2508. *
  2509. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2510. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2511. * ```
  2512. * @param {String|Array} str The string to test.
  2513. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2514. * @param {Object} [options] See available [options](#options).
  2515. * @return {Boolean} Returns true if any patterns match `str`
  2516. * @api public
  2517. */
  2518. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  2519. /**
  2520. * Parse a glob pattern to create the source string for a regular
  2521. * expression.
  2522. *
  2523. * ```js
  2524. * const picomatch = require('picomatch');
  2525. * const result = picomatch.parse(pattern[, options]);
  2526. * ```
  2527. * @param {String} `pattern`
  2528. * @param {Object} `options`
  2529. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2530. * @api public
  2531. */
  2532. picomatch.parse = (pattern, options) => {
  2533. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  2534. return parse(pattern, { ...options, fastpaths: false });
  2535. };
  2536. /**
  2537. * Scan a glob pattern to separate the pattern into segments.
  2538. *
  2539. * ```js
  2540. * const picomatch = require('picomatch');
  2541. * // picomatch.scan(input[, options]);
  2542. *
  2543. * const result = picomatch.scan('!./foo/*.js');
  2544. * console.log(result);
  2545. * { prefix: '!./',
  2546. * input: '!./foo/*.js',
  2547. * start: 3,
  2548. * base: 'foo',
  2549. * glob: '*.js',
  2550. * isBrace: false,
  2551. * isBracket: false,
  2552. * isGlob: true,
  2553. * isExtglob: false,
  2554. * isGlobstar: false,
  2555. * negated: true }
  2556. * ```
  2557. * @param {String} `input` Glob pattern to scan.
  2558. * @param {Object} `options`
  2559. * @return {Object} Returns an object with
  2560. * @api public
  2561. */
  2562. picomatch.scan = (input, options) => scan(input, options);
  2563. /**
  2564. * Compile a regular expression from the `state` object returned by the
  2565. * [parse()](#parse) method.
  2566. *
  2567. * @param {Object} `state`
  2568. * @param {Object} `options`
  2569. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2570. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2571. * @return {RegExp}
  2572. * @api public
  2573. */
  2574. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2575. if (returnOutput === true) {
  2576. return state.output;
  2577. }
  2578. const opts = options || {};
  2579. const prepend = opts.contains ? '' : '^';
  2580. const append = opts.contains ? '' : '$';
  2581. let source = `${prepend}(?:${state.output})${append}`;
  2582. if (state && state.negated === true) {
  2583. source = `^(?!${source}).*$`;
  2584. }
  2585. const regex = picomatch.toRegex(source, options);
  2586. if (returnState === true) {
  2587. regex.state = state;
  2588. }
  2589. return regex;
  2590. };
  2591. /**
  2592. * Create a regular expression from a parsed glob pattern.
  2593. *
  2594. * ```js
  2595. * const picomatch = require('picomatch');
  2596. * const state = picomatch.parse('*.js');
  2597. * // picomatch.compileRe(state[, options]);
  2598. *
  2599. * console.log(picomatch.compileRe(state));
  2600. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2601. * ```
  2602. * @param {String} `state` The object returned from the `.parse` method.
  2603. * @param {Object} `options`
  2604. * @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.
  2605. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2606. * @return {RegExp} Returns a regex created from the given pattern.
  2607. * @api public
  2608. */
  2609. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2610. if (!input || typeof input !== 'string') {
  2611. throw new TypeError('Expected a non-empty string');
  2612. }
  2613. let parsed = { negated: false, fastpaths: true };
  2614. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2615. parsed.output = parse.fastpaths(input, options);
  2616. }
  2617. if (!parsed.output) {
  2618. parsed = parse(input, options);
  2619. }
  2620. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  2621. };
  2622. /**
  2623. * Create a regular expression from the given regex source string.
  2624. *
  2625. * ```js
  2626. * const picomatch = require('picomatch');
  2627. * // picomatch.toRegex(source[, options]);
  2628. *
  2629. * const { output } = picomatch.parse('*.js');
  2630. * console.log(picomatch.toRegex(output));
  2631. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2632. * ```
  2633. * @param {String} `source` Regular expression source string.
  2634. * @param {Object} `options`
  2635. * @return {RegExp}
  2636. * @api public
  2637. */
  2638. picomatch.toRegex = (source, options) => {
  2639. try {
  2640. const opts = options || {};
  2641. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2642. } catch (err) {
  2643. if (options && options.debug === true) throw err;
  2644. return /$^/;
  2645. }
  2646. };
  2647. /**
  2648. * Picomatch constants.
  2649. * @return {Object}
  2650. */
  2651. picomatch.constants = constants;
  2652. /**
  2653. * Expose "picomatch"
  2654. */
  2655. picomatch_1$1 = picomatch;
  2656. return picomatch_1$1;
  2657. }
  2658. var picomatch_1;
  2659. var hasRequiredPicomatch;
  2660. function requirePicomatch () {
  2661. if (hasRequiredPicomatch) return picomatch_1;
  2662. hasRequiredPicomatch = 1;
  2663. const pico = /*@__PURE__*/ requirePicomatch$1();
  2664. const utils = /*@__PURE__*/ requireUtils();
  2665. function picomatch(glob, options, returnState = false) {
  2666. // default to os.platform()
  2667. if (options && (options.windows === null || options.windows === undefined)) {
  2668. // don't mutate the original options object
  2669. options = { ...options, windows: utils.isWindows() };
  2670. }
  2671. return pico(glob, options, returnState);
  2672. }
  2673. Object.assign(picomatch, pico);
  2674. picomatch_1 = picomatch;
  2675. return picomatch_1;
  2676. }
  2677. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  2678. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  2679. function getMatcherString$1(glob, cwd) {
  2680. if (glob.startsWith('**') || parseAst_js.isAbsolute(glob)) {
  2681. return parseAst_js.normalize(glob);
  2682. }
  2683. const resolved = path.resolve(cwd, glob);
  2684. return parseAst_js.normalize(resolved);
  2685. }
  2686. function patternToIdFilter(pattern) {
  2687. if (pattern instanceof RegExp) {
  2688. return (id) => {
  2689. const normalizedId = parseAst_js.normalize(id);
  2690. const result = pattern.test(normalizedId);
  2691. pattern.lastIndex = 0;
  2692. return result;
  2693. };
  2694. }
  2695. const cwd = process.cwd();
  2696. const glob = getMatcherString$1(pattern, cwd);
  2697. const matcher = pm(glob, { dot: true });
  2698. return (id) => {
  2699. const normalizedId = parseAst_js.normalize(id);
  2700. return matcher(normalizedId);
  2701. };
  2702. }
  2703. function patternToCodeFilter(pattern) {
  2704. if (pattern instanceof RegExp) {
  2705. return (code) => {
  2706. const result = pattern.test(code);
  2707. pattern.lastIndex = 0;
  2708. return result;
  2709. };
  2710. }
  2711. return (code) => code.includes(pattern);
  2712. }
  2713. function createFilter$1(exclude, include) {
  2714. if (!exclude && !include) {
  2715. return;
  2716. }
  2717. return input => {
  2718. if (exclude?.some(filter => filter(input))) {
  2719. return false;
  2720. }
  2721. if (include?.some(filter => filter(input))) {
  2722. return true;
  2723. }
  2724. return !(include && include.length > 0);
  2725. };
  2726. }
  2727. function normalizeFilter(filter) {
  2728. if (typeof filter === 'string' || filter instanceof RegExp) {
  2729. return {
  2730. include: [filter]
  2731. };
  2732. }
  2733. if (Array.isArray(filter)) {
  2734. return {
  2735. include: filter
  2736. };
  2737. }
  2738. return {
  2739. exclude: filter.exclude ? ensureArray$1(filter.exclude) : undefined,
  2740. include: filter.include ? ensureArray$1(filter.include) : undefined
  2741. };
  2742. }
  2743. function createIdFilter(filter) {
  2744. if (!filter)
  2745. return;
  2746. const { exclude, include } = normalizeFilter(filter);
  2747. const excludeFilter = exclude?.map(patternToIdFilter);
  2748. const includeFilter = include?.map(patternToIdFilter);
  2749. return createFilter$1(excludeFilter, includeFilter);
  2750. }
  2751. function createCodeFilter(filter) {
  2752. if (!filter)
  2753. return;
  2754. const { exclude, include } = normalizeFilter(filter);
  2755. const excludeFilter = exclude?.map(patternToCodeFilter);
  2756. const includeFilter = include?.map(patternToCodeFilter);
  2757. return createFilter$1(excludeFilter, includeFilter);
  2758. }
  2759. function createFilterForId(filter) {
  2760. const filterFunction = createIdFilter(filter);
  2761. return filterFunction ? id => !!filterFunction(id) : undefined;
  2762. }
  2763. function createFilterForTransform(idFilter, codeFilter) {
  2764. if (!idFilter && !codeFilter)
  2765. return;
  2766. const idFilterFunction = createIdFilter(idFilter);
  2767. const codeFilterFunction = createCodeFilter(codeFilter);
  2768. return (id, code) => {
  2769. let fallback = true;
  2770. if (idFilterFunction) {
  2771. fallback &&= idFilterFunction(id);
  2772. }
  2773. if (!fallback) {
  2774. return false;
  2775. }
  2776. if (codeFilterFunction) {
  2777. fallback &&= codeFilterFunction(code);
  2778. }
  2779. return fallback;
  2780. };
  2781. }
  2782. // This will make sure no input hook is omitted
  2783. const inputHookNames = {
  2784. buildEnd: 1,
  2785. buildStart: 1,
  2786. closeBundle: 1,
  2787. closeWatcher: 1,
  2788. load: 1,
  2789. moduleParsed: 1,
  2790. onLog: 1,
  2791. options: 1,
  2792. resolveDynamicImport: 1,
  2793. resolveId: 1,
  2794. shouldTransformCachedModule: 1,
  2795. transform: 1,
  2796. watchChange: 1
  2797. };
  2798. const inputHooks = Object.keys(inputHookNames);
  2799. class PluginDriver {
  2800. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  2801. this.graph = graph;
  2802. this.options = options;
  2803. this.pluginCache = pluginCache;
  2804. this.sortedPlugins = new Map();
  2805. this.unfulfilledActions = new Set();
  2806. this.compiledPluginFilters = {
  2807. idOnlyFilter: new WeakMap(),
  2808. transformFilter: new WeakMap()
  2809. };
  2810. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  2811. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  2812. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  2813. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  2814. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  2815. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  2816. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  2817. const existingPluginNames = new Set();
  2818. this.pluginContexts = new Map(this.plugins.map(plugin => [
  2819. plugin,
  2820. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  2821. ]));
  2822. if (basePluginDriver) {
  2823. for (const plugin of userPlugins) {
  2824. for (const hook of inputHooks) {
  2825. if (hook in plugin) {
  2826. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInputHookInOutputPlugin(plugin.name, hook));
  2827. }
  2828. }
  2829. }
  2830. }
  2831. }
  2832. createOutputPluginDriver(plugins) {
  2833. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  2834. }
  2835. getUnfulfilledHookActions() {
  2836. return this.unfulfilledActions;
  2837. }
  2838. // chains, first non-null result stops and returns
  2839. hookFirst(hookName, parameters, replaceContext, skipped) {
  2840. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  2841. }
  2842. // chains, first non-null result stops and returns result and last plugin
  2843. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  2844. for (const plugin of this.getSortedPlugins(hookName)) {
  2845. if (skipped?.has(plugin))
  2846. continue;
  2847. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  2848. if (result != null)
  2849. return [result, plugin];
  2850. }
  2851. return null;
  2852. }
  2853. // chains synchronously, first non-null result stops and returns
  2854. hookFirstSync(hookName, parameters, replaceContext) {
  2855. for (const plugin of this.getSortedPlugins(hookName)) {
  2856. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2857. if (result != null)
  2858. return result;
  2859. }
  2860. return null;
  2861. }
  2862. // parallel, ignores returns
  2863. async hookParallel(hookName, parameters, replaceContext) {
  2864. const parallelPromises = [];
  2865. for (const plugin of this.getSortedPlugins(hookName)) {
  2866. if (plugin[hookName].sequential) {
  2867. await Promise.all(parallelPromises);
  2868. parallelPromises.length = 0;
  2869. await this.runHook(hookName, parameters, plugin, replaceContext);
  2870. }
  2871. else {
  2872. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  2873. }
  2874. }
  2875. await Promise.all(parallelPromises);
  2876. }
  2877. // chains, reduces returned value, handling the reduced value as the first hook argument
  2878. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  2879. let promise = Promise.resolve(argument0);
  2880. for (const plugin of this.getSortedPlugins(hookName)) {
  2881. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  2882. }
  2883. return promise;
  2884. }
  2885. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  2886. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  2887. for (const plugin of this.getSortedPlugins(hookName)) {
  2888. const parameters = [argument0, ...rest];
  2889. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2890. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  2891. }
  2892. return argument0;
  2893. }
  2894. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  2895. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  2896. const results = [];
  2897. const parallelResults = [];
  2898. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  2899. if (plugin[hookName].sequential) {
  2900. results.push(...(await Promise.all(parallelResults)));
  2901. parallelResults.length = 0;
  2902. results.push(await this.runHook(hookName, parameters, plugin));
  2903. }
  2904. else {
  2905. parallelResults.push(this.runHook(hookName, parameters, plugin));
  2906. }
  2907. }
  2908. results.push(...(await Promise.all(parallelResults)));
  2909. return results.reduce(reducer, await initialValue);
  2910. }
  2911. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  2912. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  2913. let accumulator = initialValue;
  2914. for (const plugin of this.getSortedPlugins(hookName)) {
  2915. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2916. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  2917. }
  2918. return accumulator;
  2919. }
  2920. // chains, ignores returns
  2921. hookSeq(hookName, parameters, replaceContext) {
  2922. let promise = Promise.resolve();
  2923. for (const plugin of this.getSortedPlugins(hookName)) {
  2924. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  2925. }
  2926. return promise.then(noReturn);
  2927. }
  2928. getSortedPlugins(hookName, validateHandler) {
  2929. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  2930. }
  2931. // Implementation signature
  2932. runHook(hookName, parameters, plugin, replaceContext) {
  2933. // We always filter for plugins that support the hook before running it
  2934. const hook = plugin[hookName];
  2935. const handler = typeof hook === 'object' ? hook.handler : hook;
  2936. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  2937. if (hookName === 'transform') {
  2938. const filter = hook.filter;
  2939. const hookParameters = parameters;
  2940. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  2941. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  2942. return Promise.resolve();
  2943. }
  2944. }
  2945. else if (hookName === 'resolveId' || hookName === 'load') {
  2946. const filter = hook.filter;
  2947. const hookParameters = parameters;
  2948. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  2949. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  2950. return Promise.resolve();
  2951. }
  2952. }
  2953. }
  2954. let context = this.pluginContexts.get(plugin);
  2955. if (replaceContext) {
  2956. context = replaceContext(context, plugin);
  2957. }
  2958. let action = null;
  2959. return Promise.resolve()
  2960. .then(() => {
  2961. if (typeof handler !== 'function') {
  2962. return handler;
  2963. }
  2964. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  2965. const hookResult = handler.apply(context, parameters);
  2966. if (!hookResult?.then) {
  2967. // short circuit for non-thenables and non-Promises
  2968. return hookResult;
  2969. }
  2970. // Track pending hook actions to properly error out when
  2971. // unfulfilled promises cause rollup to abruptly and confusingly
  2972. // exit with a successful 0 return code but without producing any
  2973. // output, errors or warnings.
  2974. action = [plugin.name, hookName, parameters];
  2975. this.unfulfilledActions.add(action);
  2976. // Although it would be more elegant to just return hookResult here
  2977. // and put the .then() handler just above the .catch() handler below,
  2978. // doing so would subtly change the defacto async event dispatch order
  2979. // which at least one test and some plugins in the wild may depend on.
  2980. return Promise.resolve(hookResult).then(result => {
  2981. // action was fulfilled
  2982. this.unfulfilledActions.delete(action);
  2983. return result;
  2984. });
  2985. })
  2986. .catch(error_ => {
  2987. if (action !== null) {
  2988. // action considered to be fulfilled since error being handled
  2989. this.unfulfilledActions.delete(action);
  2990. }
  2991. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  2992. });
  2993. }
  2994. /**
  2995. * Run a sync plugin hook and return the result.
  2996. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  2997. * @param args Arguments passed to the plugin hook.
  2998. * @param plugin The acutal plugin
  2999. * @param replaceContext When passed, the plugin context can be overridden.
  3000. */
  3001. runHookSync(hookName, parameters, plugin, replaceContext) {
  3002. const hook = plugin[hookName];
  3003. const handler = typeof hook === 'object' ? hook.handler : hook;
  3004. let context = this.pluginContexts.get(plugin);
  3005. if (replaceContext) {
  3006. context = replaceContext(context, plugin);
  3007. }
  3008. try {
  3009. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  3010. return handler.apply(context, parameters);
  3011. }
  3012. catch (error_) {
  3013. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  3014. }
  3015. }
  3016. }
  3017. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  3018. const pre = [];
  3019. const normal = [];
  3020. const post = [];
  3021. for (const plugin of plugins) {
  3022. const hook = plugin[hookName];
  3023. if (hook) {
  3024. if (typeof hook === 'object') {
  3025. validateHandler(hook.handler, hookName, plugin);
  3026. if (hook.order === 'pre') {
  3027. pre.push(plugin);
  3028. continue;
  3029. }
  3030. if (hook.order === 'post') {
  3031. post.push(plugin);
  3032. continue;
  3033. }
  3034. }
  3035. else {
  3036. validateHandler(hook, hookName, plugin);
  3037. }
  3038. normal.push(plugin);
  3039. }
  3040. }
  3041. return [...pre, ...normal, ...post];
  3042. }
  3043. function validateFunctionPluginHandler(handler, hookName, plugin) {
  3044. if (typeof handler !== 'function') {
  3045. parseAst_js.error(parseAst_js.logInvalidFunctionPluginHook(hookName, plugin.name));
  3046. }
  3047. }
  3048. function validateAddonPluginHandler(handler, hookName, plugin) {
  3049. if (typeof handler !== 'string' && typeof handler !== 'function') {
  3050. return parseAst_js.error(parseAst_js.logInvalidAddonPluginHook(hookName, plugin.name));
  3051. }
  3052. }
  3053. function noReturn() { }
  3054. function getLogger(plugins, onLog, watchMode, logLevel) {
  3055. plugins = getSortedValidatedPlugins('onLog', plugins);
  3056. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  3057. const logger = (level, log, skipped = parseAst_js.EMPTY_SET) => {
  3058. parseAst_js.augmentLogMessage(log);
  3059. const logPriority = parseAst_js.logLevelPriority[level];
  3060. if (logPriority < minimalPriority) {
  3061. return;
  3062. }
  3063. for (const plugin of plugins) {
  3064. if (skipped.has(plugin))
  3065. continue;
  3066. const { onLog: pluginOnLog } = plugin;
  3067. const getLogHandler = (level) => {
  3068. if (parseAst_js.logLevelPriority[level] < minimalPriority) {
  3069. return doNothing;
  3070. }
  3071. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  3072. };
  3073. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  3074. if (handler.call({
  3075. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG),
  3076. error: (log) => parseAst_js.error(normalizeLog(log)),
  3077. info: getLogHandler(parseAst_js.LOGLEVEL_INFO),
  3078. meta: { rollupVersion: version, watchMode },
  3079. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN)
  3080. }, level, log) === false) {
  3081. return;
  3082. }
  3083. }
  3084. onLog(level, log);
  3085. };
  3086. return logger;
  3087. }
  3088. const commandAliases = {
  3089. c: 'config',
  3090. d: 'dir',
  3091. e: 'external',
  3092. f: 'format',
  3093. g: 'globals',
  3094. h: 'help',
  3095. i: 'input',
  3096. m: 'sourcemap',
  3097. n: 'name',
  3098. o: 'file',
  3099. p: 'plugin',
  3100. v: 'version',
  3101. w: 'watch'
  3102. };
  3103. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  3104. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  3105. const command = getCommandOptions(rawCommandOptions);
  3106. const plugins = await normalizePluginOption(config.plugins);
  3107. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  3108. const onLog = getOnLog(config, logLevel, printLog);
  3109. const log = getLogger(plugins, onLog, watchMode, logLevel);
  3110. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  3111. if (command.output) {
  3112. Object.assign(command, command.output);
  3113. }
  3114. const outputOptionsArray = ensureArray$1(config.output);
  3115. if (outputOptionsArray.length === 0)
  3116. outputOptionsArray.push({});
  3117. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  3118. warnUnknownOptions(command, [
  3119. ...Object.keys(inputOptions),
  3120. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  3121. ...Object.keys(commandAliases),
  3122. 'bundleConfigAsCjs',
  3123. 'config',
  3124. 'configImportAttributesKey',
  3125. 'configPlugin',
  3126. 'environment',
  3127. 'failAfterWarnings',
  3128. 'filterLogs',
  3129. 'forceExit',
  3130. 'plugin',
  3131. 'silent',
  3132. 'stdin',
  3133. 'waitForBundleInput'
  3134. ], 'CLI flags', log, /^_$|output$|config/);
  3135. inputOptions.output = outputOptions;
  3136. return inputOptions;
  3137. }
  3138. function getCommandOptions(rawCommandOptions) {
  3139. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  3140. ? rawCommandOptions.external.split(',')
  3141. : [];
  3142. return {
  3143. ...rawCommandOptions,
  3144. external,
  3145. globals: typeof rawCommandOptions.globals === 'string'
  3146. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  3147. const [id, variableName] = globalDefinition.split(':');
  3148. globals[id] = variableName;
  3149. if (!external.includes(id)) {
  3150. external.push(id);
  3151. }
  3152. return globals;
  3153. }, Object.create(null))
  3154. : undefined
  3155. };
  3156. }
  3157. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  3158. const getOption = (name) => overrides[name] ?? config[name];
  3159. const inputOptions = {
  3160. cache: config.cache,
  3161. context: getOption('context'),
  3162. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  3163. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  3164. external: getExternal(config, overrides),
  3165. input: getOption('input') || [],
  3166. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ')),
  3167. logLevel: getOption('logLevel'),
  3168. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  3169. maxParallelFileOps: getOption('maxParallelFileOps'),
  3170. moduleContext: getOption('moduleContext'),
  3171. onLog,
  3172. onwarn: undefined,
  3173. perf: getOption('perf'),
  3174. plugins,
  3175. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  3176. preserveSymlinks: getOption('preserveSymlinks'),
  3177. shimMissingExports: getOption('shimMissingExports'),
  3178. strictDeprecations: getOption('strictDeprecations'),
  3179. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ')),
  3180. watch: getWatch(config, overrides)
  3181. };
  3182. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  3183. return inputOptions;
  3184. }
  3185. const getExternal = (config, overrides) => {
  3186. const configExternal = config.external;
  3187. return typeof configExternal === 'function'
  3188. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  3189. : [...ensureArray$1(configExternal), ...overrides.external];
  3190. };
  3191. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  3192. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  3193. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  3194. if (commandOption !== undefined) {
  3195. return commandOption && { ...configOption, ...commandOption };
  3196. }
  3197. return configOption;
  3198. };
  3199. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  3200. const isWatchEnabled = (optionValue) => {
  3201. if (Array.isArray(optionValue)) {
  3202. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  3203. }
  3204. return optionValue === true;
  3205. };
  3206. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  3207. if (!optionValue) {
  3208. return optionValue;
  3209. }
  3210. if (Array.isArray(optionValue)) {
  3211. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  3212. }
  3213. return objectifyValue(optionValue);
  3214. };
  3215. async function mergeOutputOptions(config, overrides, log) {
  3216. const getOption = (name) => overrides[name] ?? config[name];
  3217. const outputOptions = {
  3218. amd: getObjectOption(config, overrides, 'amd'),
  3219. assetFileNames: getOption('assetFileNames'),
  3220. banner: getOption('banner'),
  3221. chunkFileNames: getOption('chunkFileNames'),
  3222. compact: getOption('compact'),
  3223. dir: getOption('dir'),
  3224. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  3225. entryFileNames: getOption('entryFileNames'),
  3226. esModule: getOption('esModule'),
  3227. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  3228. exports: getOption('exports'),
  3229. extend: getOption('extend'),
  3230. externalImportAssertions: getOption('externalImportAssertions'),
  3231. externalImportAttributes: getOption('externalImportAttributes'),
  3232. externalLiveBindings: getOption('externalLiveBindings'),
  3233. file: getOption('file'),
  3234. footer: getOption('footer'),
  3235. format: getOption('format'),
  3236. freeze: getOption('freeze'),
  3237. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '')),
  3238. globals: getOption('globals'),
  3239. hashCharacters: getOption('hashCharacters'),
  3240. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  3241. importAttributesKey: getOption('importAttributesKey'),
  3242. indent: getOption('indent'),
  3243. inlineDynamicImports: getOption('inlineDynamicImports'),
  3244. interop: getOption('interop'),
  3245. intro: getOption('intro'),
  3246. manualChunks: getOption('manualChunks'),
  3247. minifyInternalExports: getOption('minifyInternalExports'),
  3248. name: getOption('name'),
  3249. noConflict: getOption('noConflict'),
  3250. outro: getOption('outro'),
  3251. paths: getOption('paths'),
  3252. plugins: await normalizePluginOption(config.plugins),
  3253. preserveModules: getOption('preserveModules'),
  3254. preserveModulesRoot: getOption('preserveModulesRoot'),
  3255. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  3256. sanitizeFileName: getOption('sanitizeFileName'),
  3257. sourcemap: getOption('sourcemap'),
  3258. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  3259. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  3260. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  3261. sourcemapFile: getOption('sourcemapFile'),
  3262. sourcemapFileNames: getOption('sourcemapFileNames'),
  3263. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  3264. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  3265. strict: getOption('strict'),
  3266. systemNullSetters: getOption('systemNullSetters'),
  3267. validate: getOption('validate'),
  3268. virtualDirname: getOption('virtualDirname')
  3269. };
  3270. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  3271. return outputOptions;
  3272. }
  3273. var picocolors = {exports: {}};
  3274. var hasRequiredPicocolors;
  3275. function requirePicocolors () {
  3276. if (hasRequiredPicocolors) return picocolors.exports;
  3277. hasRequiredPicocolors = 1;
  3278. let p = process || {}, argv = p.argv || [], env = p.env || {};
  3279. let isColorSupported =
  3280. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  3281. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  3282. let formatter = (open, close, replace = open) =>
  3283. input => {
  3284. let string = "" + input, index = string.indexOf(close, open.length);
  3285. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  3286. };
  3287. let replaceClose = (string, close, replace, index) => {
  3288. let result = "", cursor = 0;
  3289. do {
  3290. result += string.substring(cursor, index) + replace;
  3291. cursor = index + close.length;
  3292. index = string.indexOf(close, cursor);
  3293. } while (~index)
  3294. return result + string.substring(cursor)
  3295. };
  3296. let createColors = (enabled = isColorSupported) => {
  3297. let f = enabled ? formatter : () => String;
  3298. return {
  3299. isColorSupported: enabled,
  3300. reset: f("\x1b[0m", "\x1b[0m"),
  3301. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  3302. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  3303. italic: f("\x1b[3m", "\x1b[23m"),
  3304. underline: f("\x1b[4m", "\x1b[24m"),
  3305. inverse: f("\x1b[7m", "\x1b[27m"),
  3306. hidden: f("\x1b[8m", "\x1b[28m"),
  3307. strikethrough: f("\x1b[9m", "\x1b[29m"),
  3308. black: f("\x1b[30m", "\x1b[39m"),
  3309. red: f("\x1b[31m", "\x1b[39m"),
  3310. green: f("\x1b[32m", "\x1b[39m"),
  3311. yellow: f("\x1b[33m", "\x1b[39m"),
  3312. blue: f("\x1b[34m", "\x1b[39m"),
  3313. magenta: f("\x1b[35m", "\x1b[39m"),
  3314. cyan: f("\x1b[36m", "\x1b[39m"),
  3315. white: f("\x1b[37m", "\x1b[39m"),
  3316. gray: f("\x1b[90m", "\x1b[39m"),
  3317. bgBlack: f("\x1b[40m", "\x1b[49m"),
  3318. bgRed: f("\x1b[41m", "\x1b[49m"),
  3319. bgGreen: f("\x1b[42m", "\x1b[49m"),
  3320. bgYellow: f("\x1b[43m", "\x1b[49m"),
  3321. bgBlue: f("\x1b[44m", "\x1b[49m"),
  3322. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  3323. bgCyan: f("\x1b[46m", "\x1b[49m"),
  3324. bgWhite: f("\x1b[47m", "\x1b[49m"),
  3325. blackBright: f("\x1b[90m", "\x1b[39m"),
  3326. redBright: f("\x1b[91m", "\x1b[39m"),
  3327. greenBright: f("\x1b[92m", "\x1b[39m"),
  3328. yellowBright: f("\x1b[93m", "\x1b[39m"),
  3329. blueBright: f("\x1b[94m", "\x1b[39m"),
  3330. magentaBright: f("\x1b[95m", "\x1b[39m"),
  3331. cyanBright: f("\x1b[96m", "\x1b[39m"),
  3332. whiteBright: f("\x1b[97m", "\x1b[39m"),
  3333. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  3334. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  3335. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  3336. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  3337. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  3338. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  3339. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  3340. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  3341. }
  3342. };
  3343. picocolors.exports = createColors();
  3344. picocolors.exports.createColors = createColors;
  3345. return picocolors.exports;
  3346. }
  3347. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  3348. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  3349. // @see https://no-color.org
  3350. // @see https://www.npmjs.com/package/chalk
  3351. const { bold, cyan, dim, gray, green, red, underline, yellow } = pc.createColors(process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR);
  3352. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  3353. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  3354. function handleError(error, recover = false) {
  3355. const name = error.name || error.cause?.name;
  3356. const nameSection = name ? `${name}: ` : '';
  3357. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  3358. const message = `${pluginSection}${nameSection}${error.message}`;
  3359. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  3360. if (error.url) {
  3361. outputLines.push(cyan(error.url));
  3362. }
  3363. if (error.loc) {
  3364. outputLines.push(`${parseAst_js.relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  3365. }
  3366. else if (error.id) {
  3367. outputLines.push(parseAst_js.relativeId(error.id));
  3368. }
  3369. if (error.frame) {
  3370. outputLines.push(dim(error.frame));
  3371. }
  3372. if (error.stack) {
  3373. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  3374. }
  3375. // ES2022: Error.prototype.cause is optional
  3376. if (error.cause) {
  3377. let cause = error.cause;
  3378. const causeErrorLines = [];
  3379. let indent = '';
  3380. while (cause) {
  3381. indent += ' ';
  3382. const message = cause.stack || cause;
  3383. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  3384. cause = cause.cause;
  3385. }
  3386. outputLines.push(dim(causeErrorLines.join('\n')));
  3387. }
  3388. outputLines.push('', '');
  3389. stderr(outputLines.join('\n'));
  3390. if (!recover)
  3391. process$1.exit(1);
  3392. }
  3393. const comma = ','.charCodeAt(0);
  3394. const semicolon = ';'.charCodeAt(0);
  3395. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  3396. const intToChar = new Uint8Array(64); // 64 possible chars.
  3397. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  3398. for (let i = 0; i < chars.length; i++) {
  3399. const c = chars.charCodeAt(i);
  3400. intToChar[i] = c;
  3401. charToInt[c] = i;
  3402. }
  3403. function decodeInteger(reader, relative) {
  3404. let value = 0;
  3405. let shift = 0;
  3406. let integer = 0;
  3407. do {
  3408. const c = reader.next();
  3409. integer = charToInt[c];
  3410. value |= (integer & 31) << shift;
  3411. shift += 5;
  3412. } while (integer & 32);
  3413. const shouldNegate = value & 1;
  3414. value >>>= 1;
  3415. if (shouldNegate) {
  3416. value = -2147483648 | -value;
  3417. }
  3418. return relative + value;
  3419. }
  3420. function encodeInteger(builder, num, relative) {
  3421. let delta = num - relative;
  3422. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  3423. do {
  3424. let clamped = delta & 0b011111;
  3425. delta >>>= 5;
  3426. if (delta > 0)
  3427. clamped |= 0b100000;
  3428. builder.write(intToChar[clamped]);
  3429. } while (delta > 0);
  3430. return num;
  3431. }
  3432. function hasMoreVlq(reader, max) {
  3433. if (reader.pos >= max)
  3434. return false;
  3435. return reader.peek() !== comma;
  3436. }
  3437. const bufLength = 1024 * 16;
  3438. // Provide a fallback for older environments.
  3439. const td = typeof TextDecoder !== 'undefined'
  3440. ? /* #__PURE__ */ new TextDecoder()
  3441. : typeof Buffer !== 'undefined'
  3442. ? {
  3443. decode(buf) {
  3444. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  3445. return out.toString();
  3446. },
  3447. }
  3448. : {
  3449. decode(buf) {
  3450. let out = '';
  3451. for (let i = 0; i < buf.length; i++) {
  3452. out += String.fromCharCode(buf[i]);
  3453. }
  3454. return out;
  3455. },
  3456. };
  3457. class StringWriter {
  3458. constructor() {
  3459. this.pos = 0;
  3460. this.out = '';
  3461. this.buffer = new Uint8Array(bufLength);
  3462. }
  3463. write(v) {
  3464. const { buffer } = this;
  3465. buffer[this.pos++] = v;
  3466. if (this.pos === bufLength) {
  3467. this.out += td.decode(buffer);
  3468. this.pos = 0;
  3469. }
  3470. }
  3471. flush() {
  3472. const { buffer, out, pos } = this;
  3473. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  3474. }
  3475. }
  3476. class StringReader {
  3477. constructor(buffer) {
  3478. this.pos = 0;
  3479. this.buffer = buffer;
  3480. }
  3481. next() {
  3482. return this.buffer.charCodeAt(this.pos++);
  3483. }
  3484. peek() {
  3485. return this.buffer.charCodeAt(this.pos);
  3486. }
  3487. indexOf(char) {
  3488. const { buffer, pos } = this;
  3489. const idx = buffer.indexOf(char, pos);
  3490. return idx === -1 ? buffer.length : idx;
  3491. }
  3492. }
  3493. function decode(mappings) {
  3494. const { length } = mappings;
  3495. const reader = new StringReader(mappings);
  3496. const decoded = [];
  3497. let genColumn = 0;
  3498. let sourcesIndex = 0;
  3499. let sourceLine = 0;
  3500. let sourceColumn = 0;
  3501. let namesIndex = 0;
  3502. do {
  3503. const semi = reader.indexOf(';');
  3504. const line = [];
  3505. let sorted = true;
  3506. let lastCol = 0;
  3507. genColumn = 0;
  3508. while (reader.pos < semi) {
  3509. let seg;
  3510. genColumn = decodeInteger(reader, genColumn);
  3511. if (genColumn < lastCol)
  3512. sorted = false;
  3513. lastCol = genColumn;
  3514. if (hasMoreVlq(reader, semi)) {
  3515. sourcesIndex = decodeInteger(reader, sourcesIndex);
  3516. sourceLine = decodeInteger(reader, sourceLine);
  3517. sourceColumn = decodeInteger(reader, sourceColumn);
  3518. if (hasMoreVlq(reader, semi)) {
  3519. namesIndex = decodeInteger(reader, namesIndex);
  3520. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  3521. }
  3522. else {
  3523. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  3524. }
  3525. }
  3526. else {
  3527. seg = [genColumn];
  3528. }
  3529. line.push(seg);
  3530. reader.pos++;
  3531. }
  3532. if (!sorted)
  3533. sort(line);
  3534. decoded.push(line);
  3535. reader.pos = semi + 1;
  3536. } while (reader.pos <= length);
  3537. return decoded;
  3538. }
  3539. function sort(line) {
  3540. line.sort(sortComparator);
  3541. }
  3542. function sortComparator(a, b) {
  3543. return a[0] - b[0];
  3544. }
  3545. function encode(decoded) {
  3546. const writer = new StringWriter();
  3547. let sourcesIndex = 0;
  3548. let sourceLine = 0;
  3549. let sourceColumn = 0;
  3550. let namesIndex = 0;
  3551. for (let i = 0; i < decoded.length; i++) {
  3552. const line = decoded[i];
  3553. if (i > 0)
  3554. writer.write(semicolon);
  3555. if (line.length === 0)
  3556. continue;
  3557. let genColumn = 0;
  3558. for (let j = 0; j < line.length; j++) {
  3559. const segment = line[j];
  3560. if (j > 0)
  3561. writer.write(comma);
  3562. genColumn = encodeInteger(writer, segment[0], genColumn);
  3563. if (segment.length === 1)
  3564. continue;
  3565. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  3566. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  3567. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  3568. if (segment.length === 4)
  3569. continue;
  3570. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  3571. }
  3572. }
  3573. return writer.flush();
  3574. }
  3575. class BitSet {
  3576. constructor(arg) {
  3577. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3578. }
  3579. add(n) {
  3580. this.bits[n >> 5] |= 1 << (n & 31);
  3581. }
  3582. has(n) {
  3583. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  3584. }
  3585. }
  3586. let Chunk$1 = class Chunk {
  3587. constructor(start, end, content) {
  3588. this.start = start;
  3589. this.end = end;
  3590. this.original = content;
  3591. this.intro = '';
  3592. this.outro = '';
  3593. this.content = content;
  3594. this.storeName = false;
  3595. this.edited = false;
  3596. {
  3597. this.previous = null;
  3598. this.next = null;
  3599. }
  3600. }
  3601. appendLeft(content) {
  3602. this.outro += content;
  3603. }
  3604. appendRight(content) {
  3605. this.intro = this.intro + content;
  3606. }
  3607. clone() {
  3608. const chunk = new Chunk(this.start, this.end, this.original);
  3609. chunk.intro = this.intro;
  3610. chunk.outro = this.outro;
  3611. chunk.content = this.content;
  3612. chunk.storeName = this.storeName;
  3613. chunk.edited = this.edited;
  3614. return chunk;
  3615. }
  3616. contains(index) {
  3617. return this.start < index && index < this.end;
  3618. }
  3619. eachNext(fn) {
  3620. let chunk = this;
  3621. while (chunk) {
  3622. fn(chunk);
  3623. chunk = chunk.next;
  3624. }
  3625. }
  3626. eachPrevious(fn) {
  3627. let chunk = this;
  3628. while (chunk) {
  3629. fn(chunk);
  3630. chunk = chunk.previous;
  3631. }
  3632. }
  3633. edit(content, storeName, contentOnly) {
  3634. this.content = content;
  3635. if (!contentOnly) {
  3636. this.intro = '';
  3637. this.outro = '';
  3638. }
  3639. this.storeName = storeName;
  3640. this.edited = true;
  3641. return this;
  3642. }
  3643. prependLeft(content) {
  3644. this.outro = content + this.outro;
  3645. }
  3646. prependRight(content) {
  3647. this.intro = content + this.intro;
  3648. }
  3649. reset() {
  3650. this.intro = '';
  3651. this.outro = '';
  3652. if (this.edited) {
  3653. this.content = this.original;
  3654. this.storeName = false;
  3655. this.edited = false;
  3656. }
  3657. }
  3658. split(index) {
  3659. const sliceIndex = index - this.start;
  3660. const originalBefore = this.original.slice(0, sliceIndex);
  3661. const originalAfter = this.original.slice(sliceIndex);
  3662. this.original = originalBefore;
  3663. const newChunk = new Chunk(index, this.end, originalAfter);
  3664. newChunk.outro = this.outro;
  3665. this.outro = '';
  3666. this.end = index;
  3667. if (this.edited) {
  3668. // after split we should save the edit content record into the correct chunk
  3669. // to make sure sourcemap correct
  3670. // For example:
  3671. // ' test'.trim()
  3672. // split -> ' ' + 'test'
  3673. // ✔️ edit -> '' + 'test'
  3674. // ✖️ edit -> 'test' + ''
  3675. // TODO is this block necessary?...
  3676. newChunk.edit('', false);
  3677. this.content = '';
  3678. } else {
  3679. this.content = originalBefore;
  3680. }
  3681. newChunk.next = this.next;
  3682. if (newChunk.next) newChunk.next.previous = newChunk;
  3683. newChunk.previous = this;
  3684. this.next = newChunk;
  3685. return newChunk;
  3686. }
  3687. toString() {
  3688. return this.intro + this.content + this.outro;
  3689. }
  3690. trimEnd(rx) {
  3691. this.outro = this.outro.replace(rx, '');
  3692. if (this.outro.length) return true;
  3693. const trimmed = this.content.replace(rx, '');
  3694. if (trimmed.length) {
  3695. if (trimmed !== this.content) {
  3696. this.split(this.start + trimmed.length).edit('', undefined, true);
  3697. if (this.edited) {
  3698. // save the change, if it has been edited
  3699. this.edit(trimmed, this.storeName, true);
  3700. }
  3701. }
  3702. return true;
  3703. } else {
  3704. this.edit('', undefined, true);
  3705. this.intro = this.intro.replace(rx, '');
  3706. if (this.intro.length) return true;
  3707. }
  3708. }
  3709. trimStart(rx) {
  3710. this.intro = this.intro.replace(rx, '');
  3711. if (this.intro.length) return true;
  3712. const trimmed = this.content.replace(rx, '');
  3713. if (trimmed.length) {
  3714. if (trimmed !== this.content) {
  3715. const newChunk = this.split(this.end - trimmed.length);
  3716. if (this.edited) {
  3717. // save the change, if it has been edited
  3718. newChunk.edit(trimmed, this.storeName, true);
  3719. }
  3720. this.edit('', undefined, true);
  3721. }
  3722. return true;
  3723. } else {
  3724. this.edit('', undefined, true);
  3725. this.outro = this.outro.replace(rx, '');
  3726. if (this.outro.length) return true;
  3727. }
  3728. }
  3729. };
  3730. function getBtoa() {
  3731. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  3732. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  3733. } else if (typeof Buffer === 'function') {
  3734. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  3735. } else {
  3736. return () => {
  3737. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  3738. };
  3739. }
  3740. }
  3741. const btoa = /*#__PURE__*/ getBtoa();
  3742. class SourceMap {
  3743. constructor(properties) {
  3744. this.version = 3;
  3745. this.file = properties.file;
  3746. this.sources = properties.sources;
  3747. this.sourcesContent = properties.sourcesContent;
  3748. this.names = properties.names;
  3749. this.mappings = encode(properties.mappings);
  3750. if (typeof properties.x_google_ignoreList !== 'undefined') {
  3751. this.x_google_ignoreList = properties.x_google_ignoreList;
  3752. }
  3753. if (typeof properties.debugId !== 'undefined') {
  3754. this.debugId = properties.debugId;
  3755. }
  3756. }
  3757. toString() {
  3758. return JSON.stringify(this);
  3759. }
  3760. toUrl() {
  3761. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  3762. }
  3763. }
  3764. function guessIndent(code) {
  3765. const lines = code.split('\n');
  3766. const tabbed = lines.filter((line) => /^\t+/.test(line));
  3767. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  3768. if (tabbed.length === 0 && spaced.length === 0) {
  3769. return null;
  3770. }
  3771. // More lines tabbed than spaced? Assume tabs, and
  3772. // default to tabs in the case of a tie (or nothing
  3773. // to go on)
  3774. if (tabbed.length >= spaced.length) {
  3775. return '\t';
  3776. }
  3777. // Otherwise, we need to guess the multiple
  3778. const min = spaced.reduce((previous, current) => {
  3779. const numSpaces = /^ +/.exec(current)[0].length;
  3780. return Math.min(numSpaces, previous);
  3781. }, Infinity);
  3782. return new Array(min + 1).join(' ');
  3783. }
  3784. function getRelativePath(from, to) {
  3785. const fromParts = from.split(/[/\\]/);
  3786. const toParts = to.split(/[/\\]/);
  3787. fromParts.pop(); // get dirname
  3788. while (fromParts[0] === toParts[0]) {
  3789. fromParts.shift();
  3790. toParts.shift();
  3791. }
  3792. if (fromParts.length) {
  3793. let i = fromParts.length;
  3794. while (i--) fromParts[i] = '..';
  3795. }
  3796. return fromParts.concat(toParts).join('/');
  3797. }
  3798. const toString = Object.prototype.toString;
  3799. function isObject(thing) {
  3800. return toString.call(thing) === '[object Object]';
  3801. }
  3802. function getLocator(source) {
  3803. const originalLines = source.split('\n');
  3804. const lineOffsets = [];
  3805. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  3806. lineOffsets.push(pos);
  3807. pos += originalLines[i].length + 1;
  3808. }
  3809. return function locate(index) {
  3810. let i = 0;
  3811. let j = lineOffsets.length;
  3812. while (i < j) {
  3813. const m = (i + j) >> 1;
  3814. if (index < lineOffsets[m]) {
  3815. j = m;
  3816. } else {
  3817. i = m + 1;
  3818. }
  3819. }
  3820. const line = i - 1;
  3821. const column = index - lineOffsets[line];
  3822. return { line, column };
  3823. };
  3824. }
  3825. const wordRegex = /\w/;
  3826. class Mappings {
  3827. constructor(hires) {
  3828. this.hires = hires;
  3829. this.generatedCodeLine = 0;
  3830. this.generatedCodeColumn = 0;
  3831. this.raw = [];
  3832. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  3833. this.pending = null;
  3834. }
  3835. addEdit(sourceIndex, content, loc, nameIndex) {
  3836. if (content.length) {
  3837. const contentLengthMinusOne = content.length - 1;
  3838. let contentLineEnd = content.indexOf('\n', 0);
  3839. let previousContentLineEnd = -1;
  3840. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  3841. // else code afterwards would fill one line too many
  3842. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  3843. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3844. if (nameIndex >= 0) {
  3845. segment.push(nameIndex);
  3846. }
  3847. this.rawSegments.push(segment);
  3848. this.generatedCodeLine += 1;
  3849. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3850. this.generatedCodeColumn = 0;
  3851. previousContentLineEnd = contentLineEnd;
  3852. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  3853. }
  3854. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3855. if (nameIndex >= 0) {
  3856. segment.push(nameIndex);
  3857. }
  3858. this.rawSegments.push(segment);
  3859. this.advance(content.slice(previousContentLineEnd + 1));
  3860. } else if (this.pending) {
  3861. this.rawSegments.push(this.pending);
  3862. this.advance(content);
  3863. }
  3864. this.pending = null;
  3865. }
  3866. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  3867. let originalCharIndex = chunk.start;
  3868. let first = true;
  3869. // when iterating each char, check if it's in a word boundary
  3870. let charInHiresBoundary = false;
  3871. while (originalCharIndex < chunk.end) {
  3872. if (original[originalCharIndex] === '\n') {
  3873. loc.line += 1;
  3874. loc.column = 0;
  3875. this.generatedCodeLine += 1;
  3876. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3877. this.generatedCodeColumn = 0;
  3878. first = true;
  3879. charInHiresBoundary = false;
  3880. } else {
  3881. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  3882. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3883. if (this.hires === 'boundary') {
  3884. // in hires "boundary", group segments per word boundary than per char
  3885. if (wordRegex.test(original[originalCharIndex])) {
  3886. // for first char in the boundary found, start the boundary by pushing a segment
  3887. if (!charInHiresBoundary) {
  3888. this.rawSegments.push(segment);
  3889. charInHiresBoundary = true;
  3890. }
  3891. } else {
  3892. // for non-word char, end the boundary by pushing a segment
  3893. this.rawSegments.push(segment);
  3894. charInHiresBoundary = false;
  3895. }
  3896. } else {
  3897. this.rawSegments.push(segment);
  3898. }
  3899. }
  3900. loc.column += 1;
  3901. this.generatedCodeColumn += 1;
  3902. first = false;
  3903. }
  3904. originalCharIndex += 1;
  3905. }
  3906. this.pending = null;
  3907. }
  3908. advance(str) {
  3909. if (!str) return;
  3910. const lines = str.split('\n');
  3911. if (lines.length > 1) {
  3912. for (let i = 0; i < lines.length - 1; i++) {
  3913. this.generatedCodeLine++;
  3914. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3915. }
  3916. this.generatedCodeColumn = 0;
  3917. }
  3918. this.generatedCodeColumn += lines[lines.length - 1].length;
  3919. }
  3920. }
  3921. const n = '\n';
  3922. const warned = {
  3923. insertLeft: false,
  3924. insertRight: false,
  3925. storeName: false,
  3926. };
  3927. class MagicString {
  3928. constructor(string, options = {}) {
  3929. const chunk = new Chunk$1(0, string.length, string);
  3930. Object.defineProperties(this, {
  3931. original: { writable: true, value: string },
  3932. outro: { writable: true, value: '' },
  3933. intro: { writable: true, value: '' },
  3934. firstChunk: { writable: true, value: chunk },
  3935. lastChunk: { writable: true, value: chunk },
  3936. lastSearchedChunk: { writable: true, value: chunk },
  3937. byStart: { writable: true, value: {} },
  3938. byEnd: { writable: true, value: {} },
  3939. filename: { writable: true, value: options.filename },
  3940. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  3941. sourcemapLocations: { writable: true, value: new BitSet() },
  3942. storedNames: { writable: true, value: {} },
  3943. indentStr: { writable: true, value: undefined },
  3944. ignoreList: { writable: true, value: options.ignoreList },
  3945. offset: { writable: true, value: options.offset || 0 },
  3946. });
  3947. this.byStart[0] = chunk;
  3948. this.byEnd[string.length] = chunk;
  3949. }
  3950. addSourcemapLocation(char) {
  3951. this.sourcemapLocations.add(char);
  3952. }
  3953. append(content) {
  3954. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  3955. this.outro += content;
  3956. return this;
  3957. }
  3958. appendLeft(index, content) {
  3959. index = index + this.offset;
  3960. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3961. this._split(index);
  3962. const chunk = this.byEnd[index];
  3963. if (chunk) {
  3964. chunk.appendLeft(content);
  3965. } else {
  3966. this.intro += content;
  3967. }
  3968. return this;
  3969. }
  3970. appendRight(index, content) {
  3971. index = index + this.offset;
  3972. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3973. this._split(index);
  3974. const chunk = this.byStart[index];
  3975. if (chunk) {
  3976. chunk.appendRight(content);
  3977. } else {
  3978. this.outro += content;
  3979. }
  3980. return this;
  3981. }
  3982. clone() {
  3983. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  3984. let originalChunk = this.firstChunk;
  3985. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  3986. while (originalChunk) {
  3987. cloned.byStart[clonedChunk.start] = clonedChunk;
  3988. cloned.byEnd[clonedChunk.end] = clonedChunk;
  3989. const nextOriginalChunk = originalChunk.next;
  3990. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  3991. if (nextClonedChunk) {
  3992. clonedChunk.next = nextClonedChunk;
  3993. nextClonedChunk.previous = clonedChunk;
  3994. clonedChunk = nextClonedChunk;
  3995. }
  3996. originalChunk = nextOriginalChunk;
  3997. }
  3998. cloned.lastChunk = clonedChunk;
  3999. if (this.indentExclusionRanges) {
  4000. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4001. }
  4002. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4003. cloned.intro = this.intro;
  4004. cloned.outro = this.outro;
  4005. return cloned;
  4006. }
  4007. generateDecodedMap(options) {
  4008. options = options || {};
  4009. const sourceIndex = 0;
  4010. const names = Object.keys(this.storedNames);
  4011. const mappings = new Mappings(options.hires);
  4012. const locate = getLocator(this.original);
  4013. if (this.intro) {
  4014. mappings.advance(this.intro);
  4015. }
  4016. this.firstChunk.eachNext((chunk) => {
  4017. const loc = locate(chunk.start);
  4018. if (chunk.intro.length) mappings.advance(chunk.intro);
  4019. if (chunk.edited) {
  4020. mappings.addEdit(
  4021. sourceIndex,
  4022. chunk.content,
  4023. loc,
  4024. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4025. );
  4026. } else {
  4027. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  4028. }
  4029. if (chunk.outro.length) mappings.advance(chunk.outro);
  4030. });
  4031. return {
  4032. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4033. sources: [
  4034. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  4035. ],
  4036. sourcesContent: options.includeContent ? [this.original] : undefined,
  4037. names,
  4038. mappings: mappings.raw,
  4039. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  4040. };
  4041. }
  4042. generateMap(options) {
  4043. return new SourceMap(this.generateDecodedMap(options));
  4044. }
  4045. _ensureindentStr() {
  4046. if (this.indentStr === undefined) {
  4047. this.indentStr = guessIndent(this.original);
  4048. }
  4049. }
  4050. _getRawIndentString() {
  4051. this._ensureindentStr();
  4052. return this.indentStr;
  4053. }
  4054. getIndentString() {
  4055. this._ensureindentStr();
  4056. return this.indentStr === null ? '\t' : this.indentStr;
  4057. }
  4058. indent(indentStr, options) {
  4059. const pattern = /^[^\r\n]/gm;
  4060. if (isObject(indentStr)) {
  4061. options = indentStr;
  4062. indentStr = undefined;
  4063. }
  4064. if (indentStr === undefined) {
  4065. this._ensureindentStr();
  4066. indentStr = this.indentStr || '\t';
  4067. }
  4068. if (indentStr === '') return this; // noop
  4069. options = options || {};
  4070. // Process exclusion ranges
  4071. const isExcluded = {};
  4072. if (options.exclude) {
  4073. const exclusions =
  4074. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  4075. exclusions.forEach((exclusion) => {
  4076. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  4077. isExcluded[i] = true;
  4078. }
  4079. });
  4080. }
  4081. let shouldIndentNextCharacter = options.indentStart !== false;
  4082. const replacer = (match) => {
  4083. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4084. shouldIndentNextCharacter = true;
  4085. return match;
  4086. };
  4087. this.intro = this.intro.replace(pattern, replacer);
  4088. let charIndex = 0;
  4089. let chunk = this.firstChunk;
  4090. while (chunk) {
  4091. const end = chunk.end;
  4092. if (chunk.edited) {
  4093. if (!isExcluded[charIndex]) {
  4094. chunk.content = chunk.content.replace(pattern, replacer);
  4095. if (chunk.content.length) {
  4096. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  4097. }
  4098. }
  4099. } else {
  4100. charIndex = chunk.start;
  4101. while (charIndex < end) {
  4102. if (!isExcluded[charIndex]) {
  4103. const char = this.original[charIndex];
  4104. if (char === '\n') {
  4105. shouldIndentNextCharacter = true;
  4106. } else if (char !== '\r' && shouldIndentNextCharacter) {
  4107. shouldIndentNextCharacter = false;
  4108. if (charIndex === chunk.start) {
  4109. chunk.prependRight(indentStr);
  4110. } else {
  4111. this._splitChunk(chunk, charIndex);
  4112. chunk = chunk.next;
  4113. chunk.prependRight(indentStr);
  4114. }
  4115. }
  4116. }
  4117. charIndex += 1;
  4118. }
  4119. }
  4120. charIndex = chunk.end;
  4121. chunk = chunk.next;
  4122. }
  4123. this.outro = this.outro.replace(pattern, replacer);
  4124. return this;
  4125. }
  4126. insert() {
  4127. throw new Error(
  4128. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  4129. );
  4130. }
  4131. insertLeft(index, content) {
  4132. if (!warned.insertLeft) {
  4133. console.warn(
  4134. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  4135. );
  4136. warned.insertLeft = true;
  4137. }
  4138. return this.appendLeft(index, content);
  4139. }
  4140. insertRight(index, content) {
  4141. if (!warned.insertRight) {
  4142. console.warn(
  4143. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  4144. );
  4145. warned.insertRight = true;
  4146. }
  4147. return this.prependRight(index, content);
  4148. }
  4149. move(start, end, index) {
  4150. start = start + this.offset;
  4151. end = end + this.offset;
  4152. index = index + this.offset;
  4153. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  4154. this._split(start);
  4155. this._split(end);
  4156. this._split(index);
  4157. const first = this.byStart[start];
  4158. const last = this.byEnd[end];
  4159. const oldLeft = first.previous;
  4160. const oldRight = last.next;
  4161. const newRight = this.byStart[index];
  4162. if (!newRight && last === this.lastChunk) return this;
  4163. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4164. if (oldLeft) oldLeft.next = oldRight;
  4165. if (oldRight) oldRight.previous = oldLeft;
  4166. if (newLeft) newLeft.next = first;
  4167. if (newRight) newRight.previous = last;
  4168. if (!first.previous) this.firstChunk = last.next;
  4169. if (!last.next) {
  4170. this.lastChunk = first.previous;
  4171. this.lastChunk.next = null;
  4172. }
  4173. first.previous = newLeft;
  4174. last.next = newRight || null;
  4175. if (!newLeft) this.firstChunk = first;
  4176. if (!newRight) this.lastChunk = last;
  4177. return this;
  4178. }
  4179. overwrite(start, end, content, options) {
  4180. options = options || {};
  4181. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  4182. }
  4183. update(start, end, content, options) {
  4184. start = start + this.offset;
  4185. end = end + this.offset;
  4186. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  4187. if (this.original.length !== 0) {
  4188. while (start < 0) start += this.original.length;
  4189. while (end < 0) end += this.original.length;
  4190. }
  4191. if (end > this.original.length) throw new Error('end is out of bounds');
  4192. if (start === end)
  4193. throw new Error(
  4194. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  4195. );
  4196. this._split(start);
  4197. this._split(end);
  4198. if (options === true) {
  4199. if (!warned.storeName) {
  4200. console.warn(
  4201. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  4202. );
  4203. warned.storeName = true;
  4204. }
  4205. options = { storeName: true };
  4206. }
  4207. const storeName = options !== undefined ? options.storeName : false;
  4208. const overwrite = options !== undefined ? options.overwrite : false;
  4209. if (storeName) {
  4210. const original = this.original.slice(start, end);
  4211. Object.defineProperty(this.storedNames, original, {
  4212. writable: true,
  4213. value: true,
  4214. enumerable: true,
  4215. });
  4216. }
  4217. const first = this.byStart[start];
  4218. const last = this.byEnd[end];
  4219. if (first) {
  4220. let chunk = first;
  4221. while (chunk !== last) {
  4222. if (chunk.next !== this.byStart[chunk.end]) {
  4223. throw new Error('Cannot overwrite across a split point');
  4224. }
  4225. chunk = chunk.next;
  4226. chunk.edit('', false);
  4227. }
  4228. first.edit(content, storeName, !overwrite);
  4229. } else {
  4230. // must be inserting at the end
  4231. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  4232. // TODO last chunk in the array may not be the last chunk, if it's moved...
  4233. last.next = newChunk;
  4234. newChunk.previous = last;
  4235. }
  4236. return this;
  4237. }
  4238. prepend(content) {
  4239. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  4240. this.intro = content + this.intro;
  4241. return this;
  4242. }
  4243. prependLeft(index, content) {
  4244. index = index + this.offset;
  4245. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4246. this._split(index);
  4247. const chunk = this.byEnd[index];
  4248. if (chunk) {
  4249. chunk.prependLeft(content);
  4250. } else {
  4251. this.intro = content + this.intro;
  4252. }
  4253. return this;
  4254. }
  4255. prependRight(index, content) {
  4256. index = index + this.offset;
  4257. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4258. this._split(index);
  4259. const chunk = this.byStart[index];
  4260. if (chunk) {
  4261. chunk.prependRight(content);
  4262. } else {
  4263. this.outro = content + this.outro;
  4264. }
  4265. return this;
  4266. }
  4267. remove(start, end) {
  4268. start = start + this.offset;
  4269. end = end + this.offset;
  4270. if (this.original.length !== 0) {
  4271. while (start < 0) start += this.original.length;
  4272. while (end < 0) end += this.original.length;
  4273. }
  4274. if (start === end) return this;
  4275. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4276. if (start > end) throw new Error('end must be greater than start');
  4277. this._split(start);
  4278. this._split(end);
  4279. let chunk = this.byStart[start];
  4280. while (chunk) {
  4281. chunk.intro = '';
  4282. chunk.outro = '';
  4283. chunk.edit('');
  4284. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4285. }
  4286. return this;
  4287. }
  4288. reset(start, end) {
  4289. start = start + this.offset;
  4290. end = end + this.offset;
  4291. if (this.original.length !== 0) {
  4292. while (start < 0) start += this.original.length;
  4293. while (end < 0) end += this.original.length;
  4294. }
  4295. if (start === end) return this;
  4296. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4297. if (start > end) throw new Error('end must be greater than start');
  4298. this._split(start);
  4299. this._split(end);
  4300. let chunk = this.byStart[start];
  4301. while (chunk) {
  4302. chunk.reset();
  4303. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4304. }
  4305. return this;
  4306. }
  4307. lastChar() {
  4308. if (this.outro.length) return this.outro[this.outro.length - 1];
  4309. let chunk = this.lastChunk;
  4310. do {
  4311. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4312. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4313. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4314. } while ((chunk = chunk.previous));
  4315. if (this.intro.length) return this.intro[this.intro.length - 1];
  4316. return '';
  4317. }
  4318. lastLine() {
  4319. let lineIndex = this.outro.lastIndexOf(n);
  4320. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4321. let lineStr = this.outro;
  4322. let chunk = this.lastChunk;
  4323. do {
  4324. if (chunk.outro.length > 0) {
  4325. lineIndex = chunk.outro.lastIndexOf(n);
  4326. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4327. lineStr = chunk.outro + lineStr;
  4328. }
  4329. if (chunk.content.length > 0) {
  4330. lineIndex = chunk.content.lastIndexOf(n);
  4331. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4332. lineStr = chunk.content + lineStr;
  4333. }
  4334. if (chunk.intro.length > 0) {
  4335. lineIndex = chunk.intro.lastIndexOf(n);
  4336. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4337. lineStr = chunk.intro + lineStr;
  4338. }
  4339. } while ((chunk = chunk.previous));
  4340. lineIndex = this.intro.lastIndexOf(n);
  4341. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4342. return this.intro + lineStr;
  4343. }
  4344. slice(start = 0, end = this.original.length - this.offset) {
  4345. start = start + this.offset;
  4346. end = end + this.offset;
  4347. if (this.original.length !== 0) {
  4348. while (start < 0) start += this.original.length;
  4349. while (end < 0) end += this.original.length;
  4350. }
  4351. let result = '';
  4352. // find start chunk
  4353. let chunk = this.firstChunk;
  4354. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4355. // found end chunk before start
  4356. if (chunk.start < end && chunk.end >= end) {
  4357. return result;
  4358. }
  4359. chunk = chunk.next;
  4360. }
  4361. if (chunk && chunk.edited && chunk.start !== start)
  4362. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4363. const startChunk = chunk;
  4364. while (chunk) {
  4365. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  4366. result += chunk.intro;
  4367. }
  4368. const containsEnd = chunk.start < end && chunk.end >= end;
  4369. if (containsEnd && chunk.edited && chunk.end !== end)
  4370. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4371. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4372. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4373. result += chunk.content.slice(sliceStart, sliceEnd);
  4374. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  4375. result += chunk.outro;
  4376. }
  4377. if (containsEnd) {
  4378. break;
  4379. }
  4380. chunk = chunk.next;
  4381. }
  4382. return result;
  4383. }
  4384. // TODO deprecate this? not really very useful
  4385. snip(start, end) {
  4386. const clone = this.clone();
  4387. clone.remove(0, start);
  4388. clone.remove(end, clone.original.length);
  4389. return clone;
  4390. }
  4391. _split(index) {
  4392. if (this.byStart[index] || this.byEnd[index]) return;
  4393. let chunk = this.lastSearchedChunk;
  4394. const searchForward = index > chunk.end;
  4395. while (chunk) {
  4396. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4397. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4398. }
  4399. }
  4400. _splitChunk(chunk, index) {
  4401. if (chunk.edited && chunk.content.length) {
  4402. // zero-length edited chunks are a special case (overlapping replacements)
  4403. const loc = getLocator(this.original)(index);
  4404. throw new Error(
  4405. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  4406. );
  4407. }
  4408. const newChunk = chunk.split(index);
  4409. this.byEnd[index] = chunk;
  4410. this.byStart[index] = newChunk;
  4411. this.byEnd[newChunk.end] = newChunk;
  4412. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4413. this.lastSearchedChunk = chunk;
  4414. return true;
  4415. }
  4416. toString() {
  4417. let str = this.intro;
  4418. let chunk = this.firstChunk;
  4419. while (chunk) {
  4420. str += chunk.toString();
  4421. chunk = chunk.next;
  4422. }
  4423. return str + this.outro;
  4424. }
  4425. isEmpty() {
  4426. let chunk = this.firstChunk;
  4427. do {
  4428. if (
  4429. (chunk.intro.length && chunk.intro.trim()) ||
  4430. (chunk.content.length && chunk.content.trim()) ||
  4431. (chunk.outro.length && chunk.outro.trim())
  4432. )
  4433. return false;
  4434. } while ((chunk = chunk.next));
  4435. return true;
  4436. }
  4437. length() {
  4438. let chunk = this.firstChunk;
  4439. let length = 0;
  4440. do {
  4441. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4442. } while ((chunk = chunk.next));
  4443. return length;
  4444. }
  4445. trimLines() {
  4446. return this.trim('[\\r\\n]');
  4447. }
  4448. trim(charType) {
  4449. return this.trimStart(charType).trimEnd(charType);
  4450. }
  4451. trimEndAborted(charType) {
  4452. const rx = new RegExp((charType || '\\s') + '+$');
  4453. this.outro = this.outro.replace(rx, '');
  4454. if (this.outro.length) return true;
  4455. let chunk = this.lastChunk;
  4456. do {
  4457. const end = chunk.end;
  4458. const aborted = chunk.trimEnd(rx);
  4459. // if chunk was trimmed, we have a new lastChunk
  4460. if (chunk.end !== end) {
  4461. if (this.lastChunk === chunk) {
  4462. this.lastChunk = chunk.next;
  4463. }
  4464. this.byEnd[chunk.end] = chunk;
  4465. this.byStart[chunk.next.start] = chunk.next;
  4466. this.byEnd[chunk.next.end] = chunk.next;
  4467. }
  4468. if (aborted) return true;
  4469. chunk = chunk.previous;
  4470. } while (chunk);
  4471. return false;
  4472. }
  4473. trimEnd(charType) {
  4474. this.trimEndAborted(charType);
  4475. return this;
  4476. }
  4477. trimStartAborted(charType) {
  4478. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4479. this.intro = this.intro.replace(rx, '');
  4480. if (this.intro.length) return true;
  4481. let chunk = this.firstChunk;
  4482. do {
  4483. const end = chunk.end;
  4484. const aborted = chunk.trimStart(rx);
  4485. if (chunk.end !== end) {
  4486. // special case...
  4487. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4488. this.byEnd[chunk.end] = chunk;
  4489. this.byStart[chunk.next.start] = chunk.next;
  4490. this.byEnd[chunk.next.end] = chunk.next;
  4491. }
  4492. if (aborted) return true;
  4493. chunk = chunk.next;
  4494. } while (chunk);
  4495. return false;
  4496. }
  4497. trimStart(charType) {
  4498. this.trimStartAborted(charType);
  4499. return this;
  4500. }
  4501. hasChanged() {
  4502. return this.original !== this.toString();
  4503. }
  4504. _replaceRegexp(searchValue, replacement) {
  4505. function getReplacement(match, str) {
  4506. if (typeof replacement === 'string') {
  4507. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4508. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  4509. if (i === '$') return '$';
  4510. if (i === '&') return match[0];
  4511. const num = +i;
  4512. if (num < match.length) return match[+i];
  4513. return `$${i}`;
  4514. });
  4515. } else {
  4516. return replacement(...match, match.index, str, match.groups);
  4517. }
  4518. }
  4519. function matchAll(re, str) {
  4520. let match;
  4521. const matches = [];
  4522. while ((match = re.exec(str))) {
  4523. matches.push(match);
  4524. }
  4525. return matches;
  4526. }
  4527. if (searchValue.global) {
  4528. const matches = matchAll(searchValue, this.original);
  4529. matches.forEach((match) => {
  4530. if (match.index != null) {
  4531. const replacement = getReplacement(match, this.original);
  4532. if (replacement !== match[0]) {
  4533. this.overwrite(match.index, match.index + match[0].length, replacement);
  4534. }
  4535. }
  4536. });
  4537. } else {
  4538. const match = this.original.match(searchValue);
  4539. if (match && match.index != null) {
  4540. const replacement = getReplacement(match, this.original);
  4541. if (replacement !== match[0]) {
  4542. this.overwrite(match.index, match.index + match[0].length, replacement);
  4543. }
  4544. }
  4545. }
  4546. return this;
  4547. }
  4548. _replaceString(string, replacement) {
  4549. const { original } = this;
  4550. const index = original.indexOf(string);
  4551. if (index !== -1) {
  4552. this.overwrite(index, index + string.length, replacement);
  4553. }
  4554. return this;
  4555. }
  4556. replace(searchValue, replacement) {
  4557. if (typeof searchValue === 'string') {
  4558. return this._replaceString(searchValue, replacement);
  4559. }
  4560. return this._replaceRegexp(searchValue, replacement);
  4561. }
  4562. _replaceAllString(string, replacement) {
  4563. const { original } = this;
  4564. const stringLength = string.length;
  4565. for (
  4566. let index = original.indexOf(string);
  4567. index !== -1;
  4568. index = original.indexOf(string, index + stringLength)
  4569. ) {
  4570. const previous = original.slice(index, index + stringLength);
  4571. if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
  4572. }
  4573. return this;
  4574. }
  4575. replaceAll(searchValue, replacement) {
  4576. if (typeof searchValue === 'string') {
  4577. return this._replaceAllString(searchValue, replacement);
  4578. }
  4579. if (!searchValue.global) {
  4580. throw new TypeError(
  4581. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  4582. );
  4583. }
  4584. return this._replaceRegexp(searchValue, replacement);
  4585. }
  4586. }
  4587. const hasOwnProp = Object.prototype.hasOwnProperty;
  4588. let Bundle$1 = class Bundle {
  4589. constructor(options = {}) {
  4590. this.intro = options.intro || '';
  4591. this.separator = options.separator !== undefined ? options.separator : '\n';
  4592. this.sources = [];
  4593. this.uniqueSources = [];
  4594. this.uniqueSourceIndexByFilename = {};
  4595. }
  4596. addSource(source) {
  4597. if (source instanceof MagicString) {
  4598. return this.addSource({
  4599. content: source,
  4600. filename: source.filename,
  4601. separator: this.separator,
  4602. });
  4603. }
  4604. if (!isObject(source) || !source.content) {
  4605. throw new Error(
  4606. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  4607. );
  4608. }
  4609. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  4610. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  4611. });
  4612. if (source.separator === undefined) {
  4613. // TODO there's a bunch of this sort of thing, needs cleaning up
  4614. source.separator = this.separator;
  4615. }
  4616. if (source.filename) {
  4617. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  4618. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  4619. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  4620. } else {
  4621. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  4622. if (source.content.original !== uniqueSource.content) {
  4623. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  4624. }
  4625. }
  4626. }
  4627. this.sources.push(source);
  4628. return this;
  4629. }
  4630. append(str, options) {
  4631. this.addSource({
  4632. content: new MagicString(str),
  4633. separator: (options && options.separator) || '',
  4634. });
  4635. return this;
  4636. }
  4637. clone() {
  4638. const bundle = new Bundle({
  4639. intro: this.intro,
  4640. separator: this.separator,
  4641. });
  4642. this.sources.forEach((source) => {
  4643. bundle.addSource({
  4644. filename: source.filename,
  4645. content: source.content.clone(),
  4646. separator: source.separator,
  4647. });
  4648. });
  4649. return bundle;
  4650. }
  4651. generateDecodedMap(options = {}) {
  4652. const names = [];
  4653. let x_google_ignoreList = undefined;
  4654. this.sources.forEach((source) => {
  4655. Object.keys(source.content.storedNames).forEach((name) => {
  4656. if (!~names.indexOf(name)) names.push(name);
  4657. });
  4658. });
  4659. const mappings = new Mappings(options.hires);
  4660. if (this.intro) {
  4661. mappings.advance(this.intro);
  4662. }
  4663. this.sources.forEach((source, i) => {
  4664. if (i > 0) {
  4665. mappings.advance(this.separator);
  4666. }
  4667. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  4668. const magicString = source.content;
  4669. const locate = getLocator(magicString.original);
  4670. if (magicString.intro) {
  4671. mappings.advance(magicString.intro);
  4672. }
  4673. magicString.firstChunk.eachNext((chunk) => {
  4674. const loc = locate(chunk.start);
  4675. if (chunk.intro.length) mappings.advance(chunk.intro);
  4676. if (source.filename) {
  4677. if (chunk.edited) {
  4678. mappings.addEdit(
  4679. sourceIndex,
  4680. chunk.content,
  4681. loc,
  4682. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4683. );
  4684. } else {
  4685. mappings.addUneditedChunk(
  4686. sourceIndex,
  4687. chunk,
  4688. magicString.original,
  4689. loc,
  4690. magicString.sourcemapLocations,
  4691. );
  4692. }
  4693. } else {
  4694. mappings.advance(chunk.content);
  4695. }
  4696. if (chunk.outro.length) mappings.advance(chunk.outro);
  4697. });
  4698. if (magicString.outro) {
  4699. mappings.advance(magicString.outro);
  4700. }
  4701. if (source.ignoreList && sourceIndex !== -1) {
  4702. if (x_google_ignoreList === undefined) {
  4703. x_google_ignoreList = [];
  4704. }
  4705. x_google_ignoreList.push(sourceIndex);
  4706. }
  4707. });
  4708. return {
  4709. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4710. sources: this.uniqueSources.map((source) => {
  4711. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  4712. }),
  4713. sourcesContent: this.uniqueSources.map((source) => {
  4714. return options.includeContent ? source.content : null;
  4715. }),
  4716. names,
  4717. mappings: mappings.raw,
  4718. x_google_ignoreList,
  4719. };
  4720. }
  4721. generateMap(options) {
  4722. return new SourceMap(this.generateDecodedMap(options));
  4723. }
  4724. getIndentString() {
  4725. const indentStringCounts = {};
  4726. this.sources.forEach((source) => {
  4727. const indentStr = source.content._getRawIndentString();
  4728. if (indentStr === null) return;
  4729. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  4730. indentStringCounts[indentStr] += 1;
  4731. });
  4732. return (
  4733. Object.keys(indentStringCounts).sort((a, b) => {
  4734. return indentStringCounts[a] - indentStringCounts[b];
  4735. })[0] || '\t'
  4736. );
  4737. }
  4738. indent(indentStr) {
  4739. if (!arguments.length) {
  4740. indentStr = this.getIndentString();
  4741. }
  4742. if (indentStr === '') return this; // noop
  4743. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  4744. this.sources.forEach((source, i) => {
  4745. const separator = source.separator !== undefined ? source.separator : this.separator;
  4746. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  4747. source.content.indent(indentStr, {
  4748. exclude: source.indentExclusionRanges,
  4749. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  4750. });
  4751. trailingNewline = source.content.lastChar() === '\n';
  4752. });
  4753. if (this.intro) {
  4754. this.intro =
  4755. indentStr +
  4756. this.intro.replace(/^[^\n]/gm, (match, index) => {
  4757. return index > 0 ? indentStr + match : match;
  4758. });
  4759. }
  4760. return this;
  4761. }
  4762. prepend(str) {
  4763. this.intro = str + this.intro;
  4764. return this;
  4765. }
  4766. toString() {
  4767. const body = this.sources
  4768. .map((source, i) => {
  4769. const separator = source.separator !== undefined ? source.separator : this.separator;
  4770. const str = (i > 0 ? separator : '') + source.content.toString();
  4771. return str;
  4772. })
  4773. .join('');
  4774. return this.intro + body;
  4775. }
  4776. isEmpty() {
  4777. if (this.intro.length && this.intro.trim()) return false;
  4778. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  4779. return true;
  4780. }
  4781. length() {
  4782. return this.sources.reduce(
  4783. (length, source) => length + source.content.length(),
  4784. this.intro.length,
  4785. );
  4786. }
  4787. trimLines() {
  4788. return this.trim('[\\r\\n]');
  4789. }
  4790. trim(charType) {
  4791. return this.trimStart(charType).trimEnd(charType);
  4792. }
  4793. trimStart(charType) {
  4794. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4795. this.intro = this.intro.replace(rx, '');
  4796. if (!this.intro) {
  4797. let source;
  4798. let i = 0;
  4799. do {
  4800. source = this.sources[i++];
  4801. if (!source) {
  4802. break;
  4803. }
  4804. } while (!source.content.trimStartAborted(charType));
  4805. }
  4806. return this;
  4807. }
  4808. trimEnd(charType) {
  4809. const rx = new RegExp((charType || '\\s') + '+$');
  4810. let source;
  4811. let i = this.sources.length - 1;
  4812. do {
  4813. source = this.sources[i--];
  4814. if (!source) {
  4815. this.intro = this.intro.replace(rx, '');
  4816. break;
  4817. }
  4818. } while (!source.content.trimEndAborted(charType));
  4819. return this;
  4820. }
  4821. };
  4822. function treeshakeNode(node, code, start, end) {
  4823. code.remove(start, end);
  4824. node.removeAnnotations(code);
  4825. }
  4826. const NO_SEMICOLON = { isNoStatement: true };
  4827. // This assumes there are only white-space and comments between start and the string we are looking for
  4828. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  4829. let searchPos, charCodeAfterSlash;
  4830. searchPos = code.indexOf(searchString, start);
  4831. while (true) {
  4832. start = code.indexOf('/', start);
  4833. if (start === -1 || start >= searchPos)
  4834. return searchPos;
  4835. charCodeAfterSlash = code.charCodeAt(++start);
  4836. ++start;
  4837. // With our assumption, '/' always starts a comment. Determine comment type:
  4838. start =
  4839. charCodeAfterSlash === 47 /*"/"*/
  4840. ? code.indexOf('\n', start) + 1
  4841. : code.indexOf('*/', start) + 2;
  4842. if (start > searchPos) {
  4843. searchPos = code.indexOf(searchString, start);
  4844. }
  4845. }
  4846. }
  4847. const NON_WHITESPACE = /\S/g;
  4848. function findNonWhiteSpace(code, index) {
  4849. NON_WHITESPACE.lastIndex = index;
  4850. const result = NON_WHITESPACE.exec(code);
  4851. return result.index;
  4852. }
  4853. const WHITESPACE = /\s/;
  4854. function findLastWhiteSpaceReverse(code, start, end) {
  4855. while (true) {
  4856. if (start >= end) {
  4857. return end;
  4858. }
  4859. if (WHITESPACE.test(code[end - 1])) {
  4860. end--;
  4861. }
  4862. else {
  4863. return end;
  4864. }
  4865. }
  4866. }
  4867. // This assumes "code" only contains white-space and comments
  4868. // Returns position of line-comment if applicable
  4869. function findFirstLineBreakOutsideComment(code) {
  4870. let lineBreakPos, charCodeAfterSlash, start = 0;
  4871. lineBreakPos = code.indexOf('\n', start);
  4872. while (true) {
  4873. start = code.indexOf('/', start);
  4874. if (start === -1 || start > lineBreakPos)
  4875. return [lineBreakPos, lineBreakPos + 1];
  4876. // With our assumption, '/' always starts a comment. Determine comment type:
  4877. charCodeAfterSlash = code.charCodeAt(start + 1);
  4878. if (charCodeAfterSlash === 47 /*"/"*/)
  4879. return [start, lineBreakPos + 1];
  4880. start = code.indexOf('*/', start + 2) + 2;
  4881. if (start > lineBreakPos) {
  4882. lineBreakPos = code.indexOf('\n', start);
  4883. }
  4884. }
  4885. }
  4886. function renderStatementList(statements, code, start, end, options) {
  4887. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  4888. let nextNode = statements[0];
  4889. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  4890. if (nextNodeNeedsBoundaries) {
  4891. nextNodeStart =
  4892. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  4893. }
  4894. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  4895. currentNode = nextNode;
  4896. currentNodeStart = nextNodeStart;
  4897. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  4898. nextNode = statements[nextIndex];
  4899. nextNodeNeedsBoundaries =
  4900. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  4901. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  4902. nextNodeStart =
  4903. currentNode.end +
  4904. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  4905. if (currentNode.included) {
  4906. if (currentNodeNeedsBoundaries) {
  4907. currentNode.render(code, options, {
  4908. end: nextNodeStart,
  4909. start: currentNodeStart
  4910. });
  4911. }
  4912. else {
  4913. currentNode.render(code, options);
  4914. }
  4915. }
  4916. else {
  4917. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  4918. }
  4919. }
  4920. else {
  4921. currentNode.render(code, options);
  4922. }
  4923. }
  4924. }
  4925. // This assumes that the first character is not part of the first node
  4926. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  4927. const splitUpNodes = [];
  4928. let node, nextNodeStart, contentEnd, char;
  4929. let separator = start - 1;
  4930. for (const nextNode of nodes) {
  4931. if (node !== undefined) {
  4932. separator =
  4933. node.end +
  4934. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  4935. }
  4936. nextNodeStart = contentEnd =
  4937. separator +
  4938. 1 +
  4939. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  4940. while (((char = code.original.charCodeAt(nextNodeStart)),
  4941. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  4942. nextNodeStart++;
  4943. if (node !== undefined) {
  4944. splitUpNodes.push({
  4945. contentEnd,
  4946. end: nextNodeStart,
  4947. node,
  4948. separator,
  4949. start
  4950. });
  4951. }
  4952. node = nextNode;
  4953. start = nextNodeStart;
  4954. }
  4955. splitUpNodes.push({
  4956. contentEnd: end,
  4957. end,
  4958. node: node,
  4959. separator: null,
  4960. start
  4961. });
  4962. return splitUpNodes;
  4963. }
  4964. // This assumes there are only white-space and comments between start and end
  4965. function removeLineBreaks(code, start, end) {
  4966. while (true) {
  4967. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  4968. if (removeStart === -1) {
  4969. break;
  4970. }
  4971. code.remove(start + removeStart, (start += removeEnd));
  4972. }
  4973. }
  4974. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  4975. if (exportedVariables.length === 1 &&
  4976. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  4977. const variable = exportedVariables[0];
  4978. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  4979. }
  4980. else {
  4981. const fields = [];
  4982. for (const variable of exportedVariables) {
  4983. for (const exportName of exportNamesByVariable.get(variable)) {
  4984. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  4985. }
  4986. }
  4987. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  4988. }
  4989. }
  4990. // This is only invoked if there is exactly one export name
  4991. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  4992. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  4993. code.appendLeft(expressionEnd, ')');
  4994. }
  4995. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  4996. const { _, getDirectReturnIifeLeft } = options.snippets;
  4997. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  4998. code.appendLeft(expressionEnd, ')');
  4999. }
  5000. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  5001. const { _, getPropertyAccess } = options.snippets;
  5002. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  5003. if (needsParens) {
  5004. code.prependRight(expressionStart, '(');
  5005. code.appendLeft(expressionEnd, ')');
  5006. }
  5007. }
  5008. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  5009. const { _ } = options.snippets;
  5010. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  5011. if (needsParens) {
  5012. code.prependRight(expressionStart, '(');
  5013. code.appendLeft(expressionEnd, ')');
  5014. }
  5015. }
  5016. const UnknownKey = Symbol('Unknown Key');
  5017. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  5018. const UnknownInteger = Symbol('Unknown Integer');
  5019. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  5020. const EMPTY_PATH = [];
  5021. const UNKNOWN_PATH = [UnknownKey];
  5022. // For deoptimizations, this means we are modifying an unknown property but did
  5023. // not lose track of the object or are creating a setter/getter;
  5024. // For assignment effects it means we do not check for setter/getter effects
  5025. // but only if something is mutated that is included, which is relevant for
  5026. // Object.defineProperty
  5027. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  5028. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  5029. const EntitiesKey = Symbol('Entities');
  5030. class EntityPathTracker {
  5031. constructor() {
  5032. this.entityPaths = Object.create(null, {
  5033. [EntitiesKey]: { value: new Set() }
  5034. });
  5035. }
  5036. trackEntityAtPathAndGetIfTracked(path, entity) {
  5037. const trackedEntities = this.getEntities(path);
  5038. if (trackedEntities.has(entity))
  5039. return true;
  5040. trackedEntities.add(entity);
  5041. return false;
  5042. }
  5043. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  5044. const trackedEntities = this.getEntities(path);
  5045. if (trackedEntities.has(entity))
  5046. return returnIfTracked;
  5047. trackedEntities.add(entity);
  5048. const result = onUntracked();
  5049. trackedEntities.delete(entity);
  5050. return result;
  5051. }
  5052. getEntities(path) {
  5053. let currentPaths = this.entityPaths;
  5054. for (const pathSegment of path) {
  5055. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5056. [EntitiesKey]: { value: new Set() }
  5057. });
  5058. }
  5059. return currentPaths[EntitiesKey];
  5060. }
  5061. }
  5062. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  5063. class DiscriminatedPathTracker {
  5064. constructor() {
  5065. this.entityPaths = Object.create(null, {
  5066. [EntitiesKey]: { value: new Map() }
  5067. });
  5068. }
  5069. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  5070. let currentPaths = this.entityPaths;
  5071. for (const pathSegment of path) {
  5072. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5073. [EntitiesKey]: { value: new Map() }
  5074. });
  5075. }
  5076. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  5077. if (trackedEntities.has(entity))
  5078. return true;
  5079. trackedEntities.add(entity);
  5080. return false;
  5081. }
  5082. }
  5083. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: parseAst_js.EMPTY_OBJECT });
  5084. class IncludedFullPathTracker {
  5085. constructor() {
  5086. this.includedPaths = null;
  5087. }
  5088. includePathAndGetIfIncluded(path) {
  5089. let included = true;
  5090. let parent = this;
  5091. let parentSegment = 'includedPaths';
  5092. let currentPaths = (this.includedPaths ||=
  5093. ((included = false), Object.create(null)));
  5094. for (const pathSegment of path) {
  5095. // This means from here, all paths are included
  5096. if (currentPaths[UnknownKey]) {
  5097. return true;
  5098. }
  5099. // Including UnknownKey automatically includes all nested paths.
  5100. // From above, we know that UnknownKey is not included yet.
  5101. if (typeof pathSegment === 'symbol') {
  5102. // Hopefully, this saves some memory over just setting
  5103. // currentPaths[UnknownKey] = EMPTY_OBJECT
  5104. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  5105. return false;
  5106. }
  5107. parent = currentPaths;
  5108. parentSegment = pathSegment;
  5109. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  5110. }
  5111. return included;
  5112. }
  5113. }
  5114. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  5115. [UnknownKey]: true
  5116. });
  5117. class IncludedTopLevelPathTracker {
  5118. constructor() {
  5119. this.includedPaths = null;
  5120. }
  5121. includePathAndGetIfIncluded(path) {
  5122. let included = true;
  5123. const includedPaths = (this.includedPaths ||=
  5124. ((included = false), Object.create(null)));
  5125. if (includedPaths[UnknownKey]) {
  5126. return true;
  5127. }
  5128. const [firstPathSegment, secondPathSegment] = path;
  5129. if (!firstPathSegment) {
  5130. return included;
  5131. }
  5132. if (typeof firstPathSegment === 'symbol') {
  5133. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  5134. return false;
  5135. }
  5136. if (secondPathSegment) {
  5137. if (includedPaths[firstPathSegment] === UnknownKey) {
  5138. return true;
  5139. }
  5140. includedPaths[firstPathSegment] = UnknownKey;
  5141. return false;
  5142. }
  5143. if (includedPaths[firstPathSegment]) {
  5144. return true;
  5145. }
  5146. includedPaths[firstPathSegment] = true;
  5147. return false;
  5148. }
  5149. includeAllPaths(entity, context, basePath) {
  5150. const { includedPaths } = this;
  5151. if (includedPaths) {
  5152. if (includedPaths[UnknownKey]) {
  5153. entity.includePath([...basePath, UnknownKey], context);
  5154. }
  5155. else {
  5156. const inclusionEntries = Object.entries(includedPaths);
  5157. if (inclusionEntries.length === 0) {
  5158. entity.includePath(basePath, context);
  5159. }
  5160. else {
  5161. for (const [key, value] of inclusionEntries) {
  5162. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  5163. }
  5164. }
  5165. }
  5166. }
  5167. }
  5168. }
  5169. /** @import { Node } from 'estree' */
  5170. /**
  5171. * @param {Node} node
  5172. * @param {Node} parent
  5173. * @returns {boolean}
  5174. */
  5175. function is_reference(node, parent) {
  5176. if (node.type === 'MemberExpression') {
  5177. return !node.computed && is_reference(node.object, node);
  5178. }
  5179. if (node.type !== 'Identifier') return false;
  5180. switch (parent?.type) {
  5181. // disregard `bar` in `foo.bar`
  5182. case 'MemberExpression':
  5183. return parent.computed || node === parent.object;
  5184. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5185. case 'MethodDefinition':
  5186. return parent.computed;
  5187. // disregard the `meta` in `import.meta`
  5188. case 'MetaProperty':
  5189. return parent.meta === node;
  5190. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5191. case 'PropertyDefinition':
  5192. return parent.computed || node === parent.value;
  5193. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5194. case 'Property':
  5195. return parent.computed || node === parent.value;
  5196. // disregard the `bar` in `export { foo as bar }` or
  5197. // the foo in `import { foo as bar }`
  5198. case 'ExportSpecifier':
  5199. case 'ImportSpecifier':
  5200. return node === parent.local;
  5201. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5202. case 'LabeledStatement':
  5203. case 'BreakStatement':
  5204. case 'ContinueStatement':
  5205. return false;
  5206. default:
  5207. return true;
  5208. }
  5209. }
  5210. function createInclusionContext() {
  5211. return {
  5212. brokenFlow: false,
  5213. hasBreak: false,
  5214. hasContinue: false,
  5215. includedCallArguments: new Set(),
  5216. includedLabels: new Set()
  5217. };
  5218. }
  5219. function createHasEffectsContext() {
  5220. return {
  5221. accessed: new EntityPathTracker(),
  5222. assigned: new EntityPathTracker(),
  5223. brokenFlow: false,
  5224. called: new DiscriminatedPathTracker(),
  5225. hasBreak: false,
  5226. hasContinue: false,
  5227. ignore: {
  5228. breaks: false,
  5229. continues: false,
  5230. labels: new Set(),
  5231. returnYield: false,
  5232. this: false
  5233. },
  5234. includedLabels: new Set(),
  5235. instantiated: new DiscriminatedPathTracker(),
  5236. replacedVariableInits: new Map()
  5237. };
  5238. }
  5239. function isFlagSet(flags, flag) {
  5240. return (flags & flag) !== 0;
  5241. }
  5242. function setFlag(flags, flag, value) {
  5243. return (flags & ~flag) | (-value & flag);
  5244. }
  5245. const UnknownValue = Symbol('Unknown Value');
  5246. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  5247. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  5248. class ExpressionEntity {
  5249. constructor() {
  5250. this.flags = 0;
  5251. }
  5252. get included() {
  5253. return isFlagSet(this.flags, 1 /* Flag.included */);
  5254. }
  5255. set included(value) {
  5256. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  5257. }
  5258. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  5259. deoptimizeInteraction(interaction);
  5260. }
  5261. deoptimizePath(_path) { }
  5262. /**
  5263. * If possible it returns a stringifyable literal value for this node that
  5264. * can be used for inlining or comparing values. Otherwise, it should return
  5265. * UnknownValue.
  5266. */
  5267. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  5268. return UnknownValue;
  5269. }
  5270. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  5271. return UNKNOWN_RETURN_EXPRESSION;
  5272. }
  5273. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  5274. return true;
  5275. }
  5276. include(context, _includeChildrenRecursively, _options) {
  5277. if (!this.included)
  5278. this.includeNode(context);
  5279. }
  5280. includeNode(_context) {
  5281. this.included = true;
  5282. }
  5283. includePath(_path, context) {
  5284. if (!this.included)
  5285. this.includeNode(context);
  5286. }
  5287. /* We are both including and including an unknown path here as the former
  5288. * ensures that nested nodes are included while the latter ensures that all
  5289. * paths of the expression are included.
  5290. * */
  5291. includeCallArguments(interaction, context) {
  5292. includeInteraction(interaction, context);
  5293. }
  5294. shouldBeIncluded(_context) {
  5295. return true;
  5296. }
  5297. }
  5298. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  5299. })();
  5300. const UNKNOWN_RETURN_EXPRESSION = [
  5301. UNKNOWN_EXPRESSION,
  5302. false
  5303. ];
  5304. const deoptimizeInteraction = (interaction) => {
  5305. for (const argument of interaction.args) {
  5306. argument?.deoptimizePath(UNKNOWN_PATH);
  5307. }
  5308. };
  5309. const includeInteraction = (interaction, context) => {
  5310. // We do not re-include the "this" argument as we expect this is already
  5311. // re-included at the call site
  5312. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  5313. includeInteractionWithoutThis(interaction, context);
  5314. };
  5315. const includeInteractionWithoutThis = ({ args }, context) => {
  5316. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5317. const argument = args[argumentIndex];
  5318. if (argument) {
  5319. argument.includePath(UNKNOWN_PATH, context);
  5320. argument.include(context, false);
  5321. }
  5322. }
  5323. };
  5324. const INTERACTION_ACCESSED = 0;
  5325. const INTERACTION_ASSIGNED = 1;
  5326. const INTERACTION_CALLED = 2;
  5327. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  5328. args: [null],
  5329. type: INTERACTION_ACCESSED
  5330. };
  5331. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  5332. args: [null, UNKNOWN_EXPRESSION],
  5333. type: INTERACTION_ASSIGNED
  5334. };
  5335. // While this is technically a call without arguments, we can compare against
  5336. // this reference in places where precise values or this argument would make a
  5337. // difference
  5338. const NODE_INTERACTION_UNKNOWN_CALL = {
  5339. args: [null],
  5340. type: INTERACTION_CALLED,
  5341. withNew: false
  5342. };
  5343. const PureFunctionKey = Symbol('PureFunction');
  5344. const getPureFunctions = ({ treeshake }) => {
  5345. const pureFunctions = Object.create(null);
  5346. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  5347. let currentFunctions = pureFunctions;
  5348. for (const pathSegment of functionName.split('.')) {
  5349. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  5350. }
  5351. currentFunctions[PureFunctionKey] = true;
  5352. }
  5353. return pureFunctions;
  5354. };
  5355. class Variable extends ExpressionEntity {
  5356. markReassigned() {
  5357. this.isReassigned = true;
  5358. }
  5359. constructor(name) {
  5360. super();
  5361. this.name = name;
  5362. this.alwaysRendered = false;
  5363. this.forbiddenNames = null;
  5364. this.globalName = null;
  5365. this.initReached = false;
  5366. this.isId = false;
  5367. this.kind = null;
  5368. this.renderBaseName = null;
  5369. this.renderName = null;
  5370. this.isReassigned = false;
  5371. this.onlyFunctionCallUsed = true;
  5372. }
  5373. /**
  5374. * Binds identifiers that reference this variable to this variable.
  5375. * Necessary to be able to change variable names.
  5376. */
  5377. addReference(_identifier) { }
  5378. /**
  5379. * Check if the identifier variable is only used as function call
  5380. * @returns true if the variable is only used as function call
  5381. */
  5382. getOnlyFunctionCallUsed() {
  5383. return this.onlyFunctionCallUsed;
  5384. }
  5385. /**
  5386. * Collect the places where the identifier variable is used
  5387. * @param usedPlace Where the variable is used
  5388. */
  5389. addUsedPlace(usedPlace) {
  5390. const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
  5391. usedPlace.parent.callee === usedPlace;
  5392. if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
  5393. this.onlyFunctionCallUsed = false;
  5394. }
  5395. }
  5396. /**
  5397. * Prevent this variable from being renamed to this name to avoid name
  5398. * collisions
  5399. */
  5400. forbidName(name) {
  5401. (this.forbiddenNames ||= new Set()).add(name);
  5402. }
  5403. getBaseVariableName() {
  5404. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  5405. this.renderBaseName ||
  5406. this.renderName ||
  5407. this.name);
  5408. }
  5409. getName(getPropertyAccess, useOriginalName) {
  5410. if (this.globalName) {
  5411. return this.globalName;
  5412. }
  5413. if (useOriginalName?.(this)) {
  5414. return this.name;
  5415. }
  5416. if (this.renderedLikeHoisted) {
  5417. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  5418. }
  5419. const name = this.renderName || this.name;
  5420. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  5421. }
  5422. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  5423. return type !== INTERACTION_ACCESSED || path.length > 0;
  5424. }
  5425. /**
  5426. * Marks this variable as being part of the bundle, which is usually the case
  5427. * when one of its identifiers becomes part of the bundle. Returns true if it
  5428. * has not been included previously. Once a variable is included, it should
  5429. * take care all its declarations are included.
  5430. */
  5431. includePath(path, context) {
  5432. this.included = true;
  5433. this.renderedLikeHoisted?.includePath(path, context);
  5434. }
  5435. /**
  5436. * Links the rendered name of this variable to another variable and includes
  5437. * this variable if the other variable is included.
  5438. */
  5439. renderLikeHoisted(variable) {
  5440. this.renderedLikeHoisted = variable;
  5441. }
  5442. markCalledFromTryStatement() { }
  5443. setRenderNames(baseName, name) {
  5444. this.renderBaseName = baseName;
  5445. this.renderName = name;
  5446. }
  5447. }
  5448. class ExternalVariable extends Variable {
  5449. constructor(module, name) {
  5450. super(name);
  5451. this.referenced = false;
  5452. this.module = module;
  5453. this.isNamespace = name === '*';
  5454. }
  5455. addReference(identifier) {
  5456. this.referenced = true;
  5457. if (this.name === 'default' || this.name === '*') {
  5458. this.module.suggestName(identifier.name);
  5459. }
  5460. }
  5461. hasEffectsOnInteractionAtPath(path, { type }) {
  5462. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  5463. }
  5464. includePath(path, context) {
  5465. super.includePath(path, context);
  5466. this.module.used = true;
  5467. }
  5468. }
  5469. function cacheObjectGetters(object, getterProperties) {
  5470. for (const property of getterProperties) {
  5471. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  5472. Object.defineProperty(object, property, {
  5473. get() {
  5474. const value = propertyGetter.call(object);
  5475. // This replaces the getter with a fixed value for subsequent calls
  5476. Object.defineProperty(object, property, { value });
  5477. return value;
  5478. }
  5479. });
  5480. }
  5481. }
  5482. const RESERVED_NAMES = new Set([
  5483. 'await',
  5484. 'break',
  5485. 'case',
  5486. 'catch',
  5487. 'class',
  5488. 'const',
  5489. 'continue',
  5490. 'debugger',
  5491. 'default',
  5492. 'delete',
  5493. 'do',
  5494. 'else',
  5495. 'enum',
  5496. 'eval',
  5497. 'export',
  5498. 'extends',
  5499. 'false',
  5500. 'finally',
  5501. 'for',
  5502. 'function',
  5503. 'if',
  5504. 'implements',
  5505. 'import',
  5506. 'in',
  5507. 'instanceof',
  5508. 'interface',
  5509. 'let',
  5510. 'NaN',
  5511. 'new',
  5512. 'null',
  5513. 'package',
  5514. 'private',
  5515. 'protected',
  5516. 'public',
  5517. 'return',
  5518. 'static',
  5519. 'super',
  5520. 'switch',
  5521. 'this',
  5522. 'throw',
  5523. 'true',
  5524. 'try',
  5525. 'typeof',
  5526. 'undefined',
  5527. 'var',
  5528. 'void',
  5529. 'while',
  5530. 'with',
  5531. 'yield'
  5532. ]);
  5533. const illegalCharacters = /[^\w$]/g;
  5534. const startsWithDigit = (value) => /\d/.test(value[0]);
  5535. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  5536. function isLegal(value) {
  5537. if (needsEscape(value)) {
  5538. return false;
  5539. }
  5540. return !illegalCharacters.test(value);
  5541. }
  5542. function makeLegal(value) {
  5543. value = value
  5544. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  5545. .replace(illegalCharacters, '_');
  5546. if (needsEscape(value))
  5547. value = `_${value}`;
  5548. return value || '_';
  5549. }
  5550. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  5551. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  5552. function stringifyObjectKeyIfNeeded(key) {
  5553. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5554. return key === '__proto__' ? '["__proto__"]' : key;
  5555. }
  5556. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  5557. return key;
  5558. }
  5559. return JSON.stringify(key);
  5560. }
  5561. function stringifyIdentifierIfNeeded(key) {
  5562. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5563. return key;
  5564. }
  5565. return JSON.stringify(key);
  5566. }
  5567. class ExternalModule {
  5568. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  5569. this.options = options;
  5570. this.id = id;
  5571. this.renormalizeRenderPath = renormalizeRenderPath;
  5572. this.dynamicImporters = [];
  5573. this.execIndex = Infinity;
  5574. this.exportedVariables = new Map();
  5575. this.importers = [];
  5576. this.reexported = false;
  5577. this.used = false;
  5578. this.declarations = new Map();
  5579. this.mostCommonSuggestion = 0;
  5580. this.nameSuggestions = new Map();
  5581. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  5582. const { importers, dynamicImporters } = this;
  5583. this.info = {
  5584. ast: null,
  5585. attributes,
  5586. code: null,
  5587. dynamicallyImportedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5588. dynamicallyImportedIds: parseAst_js.EMPTY_ARRAY,
  5589. get dynamicImporters() {
  5590. return dynamicImporters.sort();
  5591. },
  5592. exportedBindings: null,
  5593. exports: null,
  5594. hasDefaultExport: null,
  5595. id,
  5596. implicitlyLoadedAfterOneOf: parseAst_js.EMPTY_ARRAY,
  5597. implicitlyLoadedBefore: parseAst_js.EMPTY_ARRAY,
  5598. importedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5599. importedIds: parseAst_js.EMPTY_ARRAY,
  5600. get importers() {
  5601. return importers.sort();
  5602. },
  5603. isEntry: false,
  5604. isExternal: true,
  5605. isIncluded: null,
  5606. meta,
  5607. moduleSideEffects,
  5608. syntheticNamedExports: false
  5609. };
  5610. }
  5611. cacheInfoGetters() {
  5612. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  5613. }
  5614. getVariableForExportName(name) {
  5615. const declaration = this.declarations.get(name);
  5616. if (declaration)
  5617. return [declaration];
  5618. const externalVariable = new ExternalVariable(this, name);
  5619. this.declarations.set(name, externalVariable);
  5620. this.exportedVariables.set(externalVariable, name);
  5621. return [externalVariable];
  5622. }
  5623. suggestName(name) {
  5624. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  5625. this.nameSuggestions.set(name, value);
  5626. if (value > this.mostCommonSuggestion) {
  5627. this.mostCommonSuggestion = value;
  5628. this.suggestedVariableName = name;
  5629. }
  5630. }
  5631. warnUnusedImports() {
  5632. const unused = [...this.declarations]
  5633. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  5634. .map(([name]) => name);
  5635. if (unused.length === 0)
  5636. return;
  5637. const importersSet = new Set();
  5638. for (const name of unused) {
  5639. for (const importer of this.declarations.get(name).module.importers) {
  5640. importersSet.add(importer);
  5641. }
  5642. }
  5643. const importersArray = [...importersSet];
  5644. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnusedExternalImports(this.id, unused, importersArray));
  5645. }
  5646. }
  5647. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  5648. baseModule.isExecuted = true;
  5649. const modules = [baseModule];
  5650. const visitedModules = new Set();
  5651. for (const module of modules) {
  5652. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  5653. if (!(dependency instanceof ExternalModule) &&
  5654. !dependency.isExecuted &&
  5655. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  5656. !visitedModules.has(dependency.id)) {
  5657. dependency.isExecuted = true;
  5658. visitedModules.add(dependency.id);
  5659. modules.push(dependency);
  5660. }
  5661. }
  5662. }
  5663. }
  5664. // This file is generated by scripts/generate-child-node-keys.js.
  5665. // Do not edit this file directly.
  5666. const childNodeKeys = {
  5667. ArrayExpression: ['elements'],
  5668. ArrayPattern: ['elements'],
  5669. ArrowFunctionExpression: ['params', 'body'],
  5670. AssignmentExpression: ['left', 'right'],
  5671. AssignmentPattern: ['left', 'right'],
  5672. AwaitExpression: ['argument'],
  5673. BinaryExpression: ['left', 'right'],
  5674. BlockStatement: ['body'],
  5675. BreakStatement: ['label'],
  5676. CallExpression: ['callee', 'arguments'],
  5677. CatchClause: ['param', 'body'],
  5678. ChainExpression: ['expression'],
  5679. ClassBody: ['body'],
  5680. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  5681. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  5682. ConditionalExpression: ['test', 'consequent', 'alternate'],
  5683. ContinueStatement: ['label'],
  5684. DebuggerStatement: [],
  5685. Decorator: ['expression'],
  5686. DoWhileStatement: ['body', 'test'],
  5687. EmptyStatement: [],
  5688. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  5689. ExportDefaultDeclaration: ['declaration'],
  5690. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  5691. ExportSpecifier: ['local', 'exported'],
  5692. ExpressionStatement: ['expression'],
  5693. ForInStatement: ['left', 'right', 'body'],
  5694. ForOfStatement: ['left', 'right', 'body'],
  5695. ForStatement: ['init', 'test', 'update', 'body'],
  5696. FunctionDeclaration: ['id', 'params', 'body'],
  5697. FunctionExpression: ['id', 'params', 'body'],
  5698. Identifier: [],
  5699. IfStatement: ['test', 'consequent', 'alternate'],
  5700. ImportAttribute: ['key', 'value'],
  5701. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  5702. ImportDefaultSpecifier: ['local'],
  5703. ImportExpression: ['source', 'options'],
  5704. ImportNamespaceSpecifier: ['local'],
  5705. ImportSpecifier: ['imported', 'local'],
  5706. JSXAttribute: ['name', 'value'],
  5707. JSXClosingElement: ['name'],
  5708. JSXClosingFragment: [],
  5709. JSXElement: ['openingElement', 'children', 'closingElement'],
  5710. JSXEmptyExpression: [],
  5711. JSXExpressionContainer: ['expression'],
  5712. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  5713. JSXIdentifier: [],
  5714. JSXMemberExpression: ['object', 'property'],
  5715. JSXNamespacedName: ['namespace', 'name'],
  5716. JSXOpeningElement: ['name', 'attributes'],
  5717. JSXOpeningFragment: [],
  5718. JSXSpreadAttribute: ['argument'],
  5719. JSXSpreadChild: ['expression'],
  5720. JSXText: [],
  5721. LabeledStatement: ['label', 'body'],
  5722. Literal: [],
  5723. LogicalExpression: ['left', 'right'],
  5724. MemberExpression: ['object', 'property'],
  5725. MetaProperty: ['meta', 'property'],
  5726. MethodDefinition: ['decorators', 'key', 'value'],
  5727. NewExpression: ['callee', 'arguments'],
  5728. ObjectExpression: ['properties'],
  5729. ObjectPattern: ['properties'],
  5730. PanicError: [],
  5731. ParseError: [],
  5732. PrivateIdentifier: [],
  5733. Program: ['body'],
  5734. Property: ['key', 'value'],
  5735. PropertyDefinition: ['decorators', 'key', 'value'],
  5736. RestElement: ['argument'],
  5737. ReturnStatement: ['argument'],
  5738. SequenceExpression: ['expressions'],
  5739. SpreadElement: ['argument'],
  5740. StaticBlock: ['body'],
  5741. Super: [],
  5742. SwitchCase: ['test', 'consequent'],
  5743. SwitchStatement: ['discriminant', 'cases'],
  5744. TaggedTemplateExpression: ['tag', 'quasi'],
  5745. TemplateElement: [],
  5746. TemplateLiteral: ['quasis', 'expressions'],
  5747. ThisExpression: [],
  5748. ThrowStatement: ['argument'],
  5749. TryStatement: ['block', 'handler', 'finalizer'],
  5750. UnaryExpression: ['argument'],
  5751. UpdateExpression: ['argument'],
  5752. VariableDeclaration: ['declarations'],
  5753. VariableDeclarator: ['id', 'init'],
  5754. WhileStatement: ['test', 'body'],
  5755. YieldExpression: ['argument']
  5756. };
  5757. const INCLUDE_PARAMETERS = 'variables';
  5758. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  5759. class NodeBase extends ExpressionEntity {
  5760. /**
  5761. * Nodes can apply custom deoptimizations once they become part of the
  5762. * executed code. To do this, they must initialize this as false, implement
  5763. * applyDeoptimizations and call this from include and hasEffects if they have
  5764. * custom handlers
  5765. */
  5766. get deoptimized() {
  5767. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  5768. }
  5769. set deoptimized(value) {
  5770. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  5771. }
  5772. constructor(parent, parentScope) {
  5773. super();
  5774. this.parent = parent;
  5775. this.scope = parentScope;
  5776. this.createScope(parentScope);
  5777. }
  5778. addExportedVariables(_variables, _exportNamesByVariable) { }
  5779. /**
  5780. * Override this to bind assignments to variables and do any initialisations
  5781. * that require the scopes to be populated with variables.
  5782. */
  5783. bind() {
  5784. for (const key of childNodeKeys[this.type]) {
  5785. const value = this[key];
  5786. if (Array.isArray(value)) {
  5787. for (const child of value) {
  5788. child?.bind();
  5789. }
  5790. }
  5791. else if (value) {
  5792. value.bind();
  5793. }
  5794. }
  5795. }
  5796. /**
  5797. * Override if this node should receive a different scope than the parent
  5798. * scope.
  5799. */
  5800. createScope(parentScope) {
  5801. this.scope = parentScope;
  5802. }
  5803. hasEffects(context) {
  5804. if (!this.deoptimized)
  5805. this.applyDeoptimizations();
  5806. for (const key of childNodeKeys[this.type]) {
  5807. const value = this[key];
  5808. if (value === null)
  5809. continue;
  5810. if (Array.isArray(value)) {
  5811. for (const child of value) {
  5812. if (child?.hasEffects(context))
  5813. return true;
  5814. }
  5815. }
  5816. else if (value.hasEffects(context))
  5817. return true;
  5818. }
  5819. return false;
  5820. }
  5821. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  5822. return (this.hasEffects(context) ||
  5823. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  5824. }
  5825. include(context, includeChildrenRecursively, _options) {
  5826. if (!this.included)
  5827. this.includeNode(context);
  5828. for (const key of childNodeKeys[this.type]) {
  5829. const value = this[key];
  5830. if (value === null)
  5831. continue;
  5832. if (Array.isArray(value)) {
  5833. for (const child of value) {
  5834. child?.include(context, includeChildrenRecursively);
  5835. }
  5836. }
  5837. else {
  5838. value.include(context, includeChildrenRecursively);
  5839. }
  5840. }
  5841. }
  5842. includeNode(context) {
  5843. this.included = true;
  5844. if (!this.deoptimized)
  5845. this.applyDeoptimizations();
  5846. for (const key of childNodeKeys[this.type]) {
  5847. const value = this[key];
  5848. if (value === null)
  5849. continue;
  5850. if (Array.isArray(value)) {
  5851. for (const child of value) {
  5852. child?.includePath(UNKNOWN_PATH, context);
  5853. }
  5854. }
  5855. else {
  5856. value.includePath(UNKNOWN_PATH, context);
  5857. }
  5858. }
  5859. }
  5860. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  5861. this.include(context, includeChildrenRecursively);
  5862. }
  5863. /**
  5864. * Override to perform special initialisation steps after the scope is
  5865. * initialised
  5866. */
  5867. initialise() {
  5868. this.scope.context.magicString.addSourcemapLocation(this.start);
  5869. this.scope.context.magicString.addSourcemapLocation(this.end);
  5870. }
  5871. parseNode(esTreeNode) {
  5872. for (const [key, value] of Object.entries(esTreeNode)) {
  5873. // Skip properties defined on the class already.
  5874. // This way, we can override this function to add custom initialisation and then call super.parseNode
  5875. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  5876. // in bitfields. Those are still assigned from the value in the esTreeNode.
  5877. if (this.hasOwnProperty(key))
  5878. continue;
  5879. if (key.charCodeAt(0) === 95 /* _ */) {
  5880. if (key === parseAst_js.ANNOTATION_KEY) {
  5881. this.annotations = value;
  5882. }
  5883. else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
  5884. this.invalidAnnotations = value;
  5885. }
  5886. }
  5887. else if (typeof value !== 'object' || value === null) {
  5888. this[key] = value;
  5889. }
  5890. else if (Array.isArray(value)) {
  5891. this[key] = new Array(value.length);
  5892. let index = 0;
  5893. for (const child of value) {
  5894. this[key][index++] =
  5895. child === null
  5896. ? null
  5897. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  5898. }
  5899. }
  5900. else {
  5901. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  5902. }
  5903. }
  5904. // extend child keys for unknown node types
  5905. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  5906. this.initialise();
  5907. return this;
  5908. }
  5909. removeAnnotations(code) {
  5910. if (this.annotations) {
  5911. for (const annotation of this.annotations) {
  5912. code.remove(annotation.start, annotation.end);
  5913. }
  5914. }
  5915. }
  5916. render(code, options) {
  5917. for (const key of childNodeKeys[this.type]) {
  5918. const value = this[key];
  5919. if (value === null)
  5920. continue;
  5921. if (Array.isArray(value)) {
  5922. for (const child of value) {
  5923. child?.render(code, options);
  5924. }
  5925. }
  5926. else {
  5927. value.render(code, options);
  5928. }
  5929. }
  5930. }
  5931. setAssignedValue(value) {
  5932. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  5933. }
  5934. shouldBeIncluded(context) {
  5935. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  5936. }
  5937. /**
  5938. * Just deoptimize everything by default so that when e.g. we do not track
  5939. * something properly, it is deoptimized.
  5940. * @protected
  5941. */
  5942. applyDeoptimizations() {
  5943. this.deoptimized = true;
  5944. for (const key of childNodeKeys[this.type]) {
  5945. const value = this[key];
  5946. if (value === null)
  5947. continue;
  5948. if (Array.isArray(value)) {
  5949. for (const child of value) {
  5950. child?.deoptimizePath(UNKNOWN_PATH);
  5951. }
  5952. }
  5953. else {
  5954. value.deoptimizePath(UNKNOWN_PATH);
  5955. }
  5956. }
  5957. this.scope.context.requestTreeshakingPass();
  5958. }
  5959. }
  5960. function createChildNodeKeysForNode(esTreeNode) {
  5961. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  5962. }
  5963. function onlyIncludeSelf() {
  5964. this.included = true;
  5965. if (!this.deoptimized)
  5966. this.applyDeoptimizations();
  5967. }
  5968. function onlyIncludeSelfNoDeoptimize() {
  5969. this.included = true;
  5970. }
  5971. function doNotDeoptimize() {
  5972. this.deoptimized = true;
  5973. }
  5974. function isObjectExpressionNode(node) {
  5975. return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
  5976. }
  5977. function isPropertyNode(node) {
  5978. return node instanceof NodeBase && node.type === parseAst_js.Property;
  5979. }
  5980. function isArrowFunctionExpressionNode(node) {
  5981. return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
  5982. }
  5983. function isCallExpressionNode(node) {
  5984. return node instanceof NodeBase && node.type === parseAst_js.CallExpression;
  5985. }
  5986. function isMemberExpressionNode(node) {
  5987. return node instanceof NodeBase && node.type === parseAst_js.MemberExpression;
  5988. }
  5989. function isImportExpressionNode(node) {
  5990. return node instanceof NodeBase && node.type === parseAst_js.ImportExpression;
  5991. }
  5992. function isAwaitExpressionNode(node) {
  5993. return node instanceof NodeBase && node.type === parseAst_js.AwaitExpression;
  5994. }
  5995. function isIdentifierNode(node) {
  5996. return node instanceof NodeBase && node.type === parseAst_js.Identifier;
  5997. }
  5998. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  5999. return Object.create(inheritedDescriptions, memberDescriptions);
  6000. }
  6001. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  6002. getLiteralValueAtPath(path) {
  6003. return path.length > 0 ? UnknownValue : undefined;
  6004. }
  6005. })();
  6006. const returnsUnknown = {
  6007. value: {
  6008. hasEffectsWhenCalled: null,
  6009. returns: UNKNOWN_EXPRESSION
  6010. }
  6011. };
  6012. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  6013. getReturnExpressionWhenCalledAtPath(path) {
  6014. if (path.length === 1) {
  6015. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  6016. }
  6017. return UNKNOWN_RETURN_EXPRESSION;
  6018. }
  6019. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6020. if (interaction.type === INTERACTION_ACCESSED) {
  6021. return path.length > 1;
  6022. }
  6023. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6024. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  6025. }
  6026. return true;
  6027. }
  6028. })();
  6029. const returnsBoolean = {
  6030. value: {
  6031. hasEffectsWhenCalled: null,
  6032. returns: UNKNOWN_LITERAL_BOOLEAN
  6033. }
  6034. };
  6035. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  6036. getReturnExpressionWhenCalledAtPath(path) {
  6037. if (path.length === 1) {
  6038. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  6039. }
  6040. return UNKNOWN_RETURN_EXPRESSION;
  6041. }
  6042. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6043. if (interaction.type === INTERACTION_ACCESSED) {
  6044. return path.length > 1;
  6045. }
  6046. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6047. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  6048. }
  6049. return true;
  6050. }
  6051. })();
  6052. const returnsNumber = {
  6053. value: {
  6054. hasEffectsWhenCalled: null,
  6055. returns: UNKNOWN_LITERAL_NUMBER
  6056. }
  6057. };
  6058. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  6059. getReturnExpressionWhenCalledAtPath(path) {
  6060. if (path.length === 1) {
  6061. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  6062. }
  6063. return UNKNOWN_RETURN_EXPRESSION;
  6064. }
  6065. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6066. if (interaction.type === INTERACTION_ACCESSED) {
  6067. return path.length > 1;
  6068. }
  6069. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6070. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  6071. }
  6072. return true;
  6073. }
  6074. })();
  6075. const returnsString = {
  6076. value: {
  6077. hasEffectsWhenCalled: null,
  6078. returns: UNKNOWN_LITERAL_STRING
  6079. }
  6080. };
  6081. const stringReplace = {
  6082. value: {
  6083. hasEffectsWhenCalled({ args }, context) {
  6084. const argument1 = args[2];
  6085. return (args.length < 3 ||
  6086. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  6087. deoptimizeCache() { }
  6088. }) === 'symbol' &&
  6089. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  6090. },
  6091. returns: UNKNOWN_LITERAL_STRING
  6092. }
  6093. };
  6094. const objectMembers = assembleMemberDescriptions({
  6095. hasOwnProperty: returnsBoolean,
  6096. isPrototypeOf: returnsBoolean,
  6097. propertyIsEnumerable: returnsBoolean,
  6098. toLocaleString: returnsString,
  6099. toString: returnsString,
  6100. valueOf: returnsUnknown
  6101. });
  6102. const literalBooleanMembers = assembleMemberDescriptions({
  6103. valueOf: returnsBoolean
  6104. }, objectMembers);
  6105. const literalNumberMembers = assembleMemberDescriptions({
  6106. toExponential: returnsString,
  6107. toFixed: returnsString,
  6108. toLocaleString: returnsString,
  6109. toPrecision: returnsString,
  6110. valueOf: returnsNumber
  6111. }, objectMembers);
  6112. /**
  6113. * RegExp are stateful when they have the global or sticky flags set.
  6114. * But if we actually don't use them, the side effect does not matter.
  6115. * the check logic in `hasEffectsOnInteractionAtPath`.
  6116. */
  6117. const literalRegExpMembers = assembleMemberDescriptions({
  6118. exec: returnsUnknown,
  6119. test: returnsBoolean
  6120. }, objectMembers);
  6121. const literalStringMembers = assembleMemberDescriptions({
  6122. anchor: returnsString,
  6123. at: returnsUnknown,
  6124. big: returnsString,
  6125. blink: returnsString,
  6126. bold: returnsString,
  6127. charAt: returnsString,
  6128. charCodeAt: returnsNumber,
  6129. codePointAt: returnsUnknown,
  6130. concat: returnsString,
  6131. endsWith: returnsBoolean,
  6132. fixed: returnsString,
  6133. fontcolor: returnsString,
  6134. fontsize: returnsString,
  6135. includes: returnsBoolean,
  6136. indexOf: returnsNumber,
  6137. italics: returnsString,
  6138. lastIndexOf: returnsNumber,
  6139. link: returnsString,
  6140. localeCompare: returnsNumber,
  6141. match: returnsUnknown,
  6142. matchAll: returnsUnknown,
  6143. normalize: returnsString,
  6144. padEnd: returnsString,
  6145. padStart: returnsString,
  6146. repeat: returnsString,
  6147. replace: stringReplace,
  6148. replaceAll: stringReplace,
  6149. search: returnsNumber,
  6150. slice: returnsString,
  6151. small: returnsString,
  6152. split: returnsUnknown,
  6153. startsWith: returnsBoolean,
  6154. strike: returnsString,
  6155. sub: returnsString,
  6156. substr: returnsString,
  6157. substring: returnsString,
  6158. sup: returnsString,
  6159. toLocaleLowerCase: returnsString,
  6160. toLocaleUpperCase: returnsString,
  6161. toLowerCase: returnsString,
  6162. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  6163. toUpperCase: returnsString,
  6164. trim: returnsString,
  6165. trimEnd: returnsString,
  6166. trimLeft: returnsString,
  6167. trimRight: returnsString,
  6168. trimStart: returnsString,
  6169. valueOf: returnsString
  6170. }, objectMembers);
  6171. function getLiteralMembersForValue(value) {
  6172. if (value instanceof RegExp) {
  6173. return literalRegExpMembers;
  6174. }
  6175. switch (typeof value) {
  6176. case 'boolean': {
  6177. return literalBooleanMembers;
  6178. }
  6179. case 'number': {
  6180. return literalNumberMembers;
  6181. }
  6182. case 'string': {
  6183. return literalStringMembers;
  6184. }
  6185. }
  6186. return Object.create(null);
  6187. }
  6188. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  6189. if (typeof memberName !== 'string' || !members[memberName]) {
  6190. return true;
  6191. }
  6192. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  6193. }
  6194. function getMemberReturnExpressionWhenCalled(members, memberName) {
  6195. if (typeof memberName !== 'string' || !members[memberName])
  6196. return UNKNOWN_RETURN_EXPRESSION;
  6197. return [members[memberName].returns, false];
  6198. }
  6199. class Method extends ExpressionEntity {
  6200. constructor(description) {
  6201. super();
  6202. this.description = description;
  6203. }
  6204. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  6205. if (type === INTERACTION_CALLED && path.length === 0) {
  6206. if (this.description.mutatesSelfAsArray) {
  6207. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6208. }
  6209. if (this.description.mutatesArgs) {
  6210. for (let index = 1; index < args.length; index++) {
  6211. args[index].deoptimizePath(UNKNOWN_PATH);
  6212. }
  6213. }
  6214. }
  6215. }
  6216. getReturnExpressionWhenCalledAtPath(path, { args }) {
  6217. if (path.length > 0) {
  6218. return UNKNOWN_RETURN_EXPRESSION;
  6219. }
  6220. return [
  6221. this.description.returnsPrimitive ||
  6222. (this.description.returns === 'self'
  6223. ? args[0] || UNKNOWN_EXPRESSION
  6224. : this.description.returns()),
  6225. false
  6226. ];
  6227. }
  6228. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  6229. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  6230. return true;
  6231. }
  6232. if (type === INTERACTION_CALLED) {
  6233. if (this.description.mutatesSelfAsArray === true &&
  6234. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  6235. return true;
  6236. }
  6237. if (this.description.callsArgs) {
  6238. for (const argumentIndex of this.description.callsArgs) {
  6239. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  6240. return true;
  6241. }
  6242. }
  6243. }
  6244. }
  6245. return false;
  6246. }
  6247. }
  6248. const METHOD_RETURNS_BOOLEAN = [
  6249. new Method({
  6250. callsArgs: null,
  6251. mutatesArgs: false,
  6252. mutatesSelfAsArray: false,
  6253. returns: null,
  6254. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6255. })
  6256. ];
  6257. const METHOD_RETURNS_STRING = [
  6258. new Method({
  6259. callsArgs: null,
  6260. mutatesArgs: false,
  6261. mutatesSelfAsArray: false,
  6262. returns: null,
  6263. returnsPrimitive: UNKNOWN_LITERAL_STRING
  6264. })
  6265. ];
  6266. const METHOD_RETURNS_NUMBER = [
  6267. new Method({
  6268. callsArgs: null,
  6269. mutatesArgs: false,
  6270. mutatesSelfAsArray: false,
  6271. returns: null,
  6272. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6273. })
  6274. ];
  6275. const METHOD_RETURNS_UNKNOWN = [
  6276. new Method({
  6277. callsArgs: null,
  6278. mutatesArgs: false,
  6279. mutatesSelfAsArray: false,
  6280. returns: null,
  6281. returnsPrimitive: UNKNOWN_EXPRESSION
  6282. })
  6283. ];
  6284. const INTEGER_REG_EXP = /^\d+$/;
  6285. class ObjectEntity extends ExpressionEntity {
  6286. get hasLostTrack() {
  6287. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  6288. }
  6289. set hasLostTrack(value) {
  6290. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  6291. }
  6292. get hasUnknownDeoptimizedInteger() {
  6293. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  6294. }
  6295. set hasUnknownDeoptimizedInteger(value) {
  6296. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  6297. }
  6298. get hasUnknownDeoptimizedProperty() {
  6299. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  6300. }
  6301. set hasUnknownDeoptimizedProperty(value) {
  6302. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  6303. }
  6304. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  6305. // and we assume there are no setters or getters
  6306. constructor(properties, prototypeExpression, immutable = false) {
  6307. super();
  6308. this.prototypeExpression = prototypeExpression;
  6309. this.immutable = immutable;
  6310. this.additionalExpressionsToBeDeoptimized = new Set();
  6311. this.allProperties = [];
  6312. this.deoptimizedPaths = Object.create(null);
  6313. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  6314. this.gettersByKey = Object.create(null);
  6315. this.propertiesAndGettersByKey = Object.create(null);
  6316. this.propertiesAndSettersByKey = Object.create(null);
  6317. this.settersByKey = Object.create(null);
  6318. this.unknownIntegerProps = [];
  6319. this.unmatchableGetters = [];
  6320. this.unmatchablePropertiesAndGetters = [];
  6321. this.unmatchablePropertiesAndSetters = [];
  6322. this.unmatchableSetters = [];
  6323. if (Array.isArray(properties)) {
  6324. this.buildPropertyMaps(properties);
  6325. }
  6326. else {
  6327. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  6328. for (const propertiesForKey of Object.values(properties)) {
  6329. this.allProperties.push(...propertiesForKey);
  6330. }
  6331. }
  6332. }
  6333. deoptimizeAllProperties(noAccessors) {
  6334. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  6335. if (noAccessors) {
  6336. this.hasUnknownDeoptimizedProperty = true;
  6337. }
  6338. else {
  6339. this.hasLostTrack = true;
  6340. }
  6341. if (isDeoptimized) {
  6342. return;
  6343. }
  6344. for (const properties of [
  6345. ...Object.values(this.propertiesAndGettersByKey),
  6346. ...Object.values(this.settersByKey)
  6347. ]) {
  6348. for (const property of properties) {
  6349. property.deoptimizePath(UNKNOWN_PATH);
  6350. }
  6351. }
  6352. // While the prototype itself cannot be mutated, each property can
  6353. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  6354. this.deoptimizeCachedEntities();
  6355. }
  6356. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6357. const [key, ...subPath] = path;
  6358. const { args, type } = interaction;
  6359. if (this.hasLostTrack ||
  6360. // single paths that are deoptimized will not become getters or setters
  6361. ((type === INTERACTION_CALLED || path.length > 1) &&
  6362. (this.hasUnknownDeoptimizedProperty ||
  6363. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  6364. deoptimizeInteraction(interaction);
  6365. return;
  6366. }
  6367. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  6368. ? [
  6369. this.propertiesAndGettersByKey,
  6370. this.propertiesAndGettersByKey,
  6371. this.unmatchablePropertiesAndGetters
  6372. ]
  6373. : type === INTERACTION_ACCESSED
  6374. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6375. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6376. if (typeof key === 'string') {
  6377. if (propertiesForExactMatchByKey[key]) {
  6378. const properties = relevantPropertiesByKey[key];
  6379. if (properties) {
  6380. for (const property of properties) {
  6381. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6382. }
  6383. }
  6384. if (!this.immutable) {
  6385. for (const argument of args) {
  6386. if (argument) {
  6387. this.additionalExpressionsToBeDeoptimized.add(argument);
  6388. }
  6389. }
  6390. }
  6391. return;
  6392. }
  6393. for (const property of relevantUnmatchableProperties) {
  6394. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6395. }
  6396. if (INTEGER_REG_EXP.test(key)) {
  6397. for (const property of this.unknownIntegerProps) {
  6398. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6399. }
  6400. }
  6401. }
  6402. else {
  6403. for (const properties of [
  6404. ...Object.values(relevantPropertiesByKey),
  6405. relevantUnmatchableProperties
  6406. ]) {
  6407. for (const property of properties) {
  6408. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6409. }
  6410. }
  6411. for (const property of this.unknownIntegerProps) {
  6412. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6413. }
  6414. }
  6415. if (!this.immutable) {
  6416. for (const argument of args) {
  6417. if (argument) {
  6418. this.additionalExpressionsToBeDeoptimized.add(argument);
  6419. }
  6420. }
  6421. }
  6422. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6423. }
  6424. deoptimizeIntegerProperties() {
  6425. if (this.hasLostTrack ||
  6426. this.hasUnknownDeoptimizedProperty ||
  6427. this.hasUnknownDeoptimizedInteger) {
  6428. return;
  6429. }
  6430. this.hasUnknownDeoptimizedInteger = true;
  6431. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  6432. if (INTEGER_REG_EXP.test(key)) {
  6433. for (const property of propertiesAndGetters) {
  6434. property.deoptimizePath(UNKNOWN_PATH);
  6435. }
  6436. }
  6437. }
  6438. this.deoptimizeCachedIntegerEntities();
  6439. }
  6440. // Assumption: If only a specific path is deoptimized, no accessors are created
  6441. deoptimizePath(path) {
  6442. if (this.hasLostTrack || this.immutable) {
  6443. return;
  6444. }
  6445. const key = path[0];
  6446. if (path.length === 1) {
  6447. if (key === UnknownInteger) {
  6448. return this.deoptimizeIntegerProperties();
  6449. }
  6450. else if (typeof key !== 'string') {
  6451. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  6452. }
  6453. if (!this.deoptimizedPaths[key]) {
  6454. this.deoptimizedPaths[key] = true;
  6455. // we only deoptimizeCache exact matches as in all other cases,
  6456. // we do not return a literal value or return expression
  6457. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  6458. if (expressionsToBeDeoptimized) {
  6459. for (const expression of expressionsToBeDeoptimized) {
  6460. expression.deoptimizeCache();
  6461. }
  6462. }
  6463. }
  6464. }
  6465. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  6466. for (const property of typeof key === 'string'
  6467. ? [
  6468. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  6469. ...(this.settersByKey[key] || this.unmatchableSetters)
  6470. ]
  6471. : this.allProperties) {
  6472. property.deoptimizePath(subPath);
  6473. }
  6474. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  6475. }
  6476. getLiteralValueAtPath(path, recursionTracker, origin) {
  6477. if (path.length === 0) {
  6478. // This should actually be "UnknownTruthyValue". However, this currently
  6479. // causes an issue with TypeScript enums in files with moduleSideEffects:
  6480. // false because we cannot properly track whether a "var" has been
  6481. // initialized. This should be reverted once we can properly track this.
  6482. // return UnknownTruthyValue;
  6483. return UnknownValue;
  6484. }
  6485. const key = path[0];
  6486. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6487. if (expressionAtPath) {
  6488. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  6489. }
  6490. if (this.prototypeExpression) {
  6491. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6492. }
  6493. if (path.length === 1) {
  6494. return undefined;
  6495. }
  6496. return UnknownValue;
  6497. }
  6498. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6499. if (path.length === 0) {
  6500. return UNKNOWN_RETURN_EXPRESSION;
  6501. }
  6502. const [key, ...subPath] = path;
  6503. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6504. if (expressionAtPath) {
  6505. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  6506. }
  6507. if (this.prototypeExpression) {
  6508. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6509. }
  6510. return UNKNOWN_RETURN_EXPRESSION;
  6511. }
  6512. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6513. const [key, ...subPath] = path;
  6514. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  6515. const expressionAtPath = this.getMemberExpression(key);
  6516. if (expressionAtPath) {
  6517. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  6518. }
  6519. if (this.prototypeExpression) {
  6520. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6521. }
  6522. return true;
  6523. }
  6524. if (key === UnknownNonAccessorKey)
  6525. return false;
  6526. if (this.hasLostTrack)
  6527. return true;
  6528. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  6529. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6530. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6531. if (typeof key === 'string') {
  6532. if (propertiesAndAccessorsByKey[key]) {
  6533. const accessors = accessorsByKey[key];
  6534. if (accessors) {
  6535. for (const accessor of accessors) {
  6536. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6537. return true;
  6538. }
  6539. }
  6540. return false;
  6541. }
  6542. for (const accessor of unmatchableAccessors) {
  6543. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  6544. return true;
  6545. }
  6546. }
  6547. }
  6548. else {
  6549. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  6550. for (const accessor of accessors) {
  6551. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6552. return true;
  6553. }
  6554. }
  6555. }
  6556. if (this.prototypeExpression) {
  6557. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6558. }
  6559. return false;
  6560. }
  6561. include(context, includeChildrenRecursively) {
  6562. this.included = true;
  6563. for (const property of this.allProperties) {
  6564. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  6565. property.include(context, includeChildrenRecursively);
  6566. }
  6567. }
  6568. this.prototypeExpression?.include(context, includeChildrenRecursively);
  6569. }
  6570. includePath(path, context) {
  6571. this.included = true;
  6572. if (path.length === 0)
  6573. return;
  6574. const [key, ...subPath] = path;
  6575. const [includedMembers, includedPath] = typeof key === 'string'
  6576. ? [
  6577. new Set([
  6578. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  6579. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  6580. ]),
  6581. subPath
  6582. ]
  6583. : [this.allProperties, UNKNOWN_PATH];
  6584. for (const property of includedMembers) {
  6585. property.includePath(includedPath, context);
  6586. }
  6587. this.prototypeExpression?.includePath(path, context);
  6588. }
  6589. buildPropertyMaps(properties) {
  6590. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  6591. for (let index = properties.length - 1; index >= 0; index--) {
  6592. const { key, kind, property } = properties[index];
  6593. allProperties.push(property);
  6594. if (typeof key === 'string') {
  6595. if (kind === 'set') {
  6596. if (!propertiesAndSettersByKey[key]) {
  6597. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6598. settersByKey[key] = [property, ...unmatchableSetters];
  6599. }
  6600. }
  6601. else if (kind === 'get') {
  6602. if (!propertiesAndGettersByKey[key]) {
  6603. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6604. gettersByKey[key] = [property, ...unmatchableGetters];
  6605. }
  6606. }
  6607. else {
  6608. if (!propertiesAndSettersByKey[key]) {
  6609. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6610. }
  6611. if (!propertiesAndGettersByKey[key]) {
  6612. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6613. }
  6614. }
  6615. }
  6616. else {
  6617. if (key === UnknownInteger) {
  6618. unknownIntegerProps.push(property);
  6619. continue;
  6620. }
  6621. if (kind === 'set')
  6622. unmatchableSetters.push(property);
  6623. if (kind === 'get')
  6624. unmatchableGetters.push(property);
  6625. if (kind !== 'get')
  6626. unmatchablePropertiesAndSetters.push(property);
  6627. if (kind !== 'set')
  6628. unmatchablePropertiesAndGetters.push(property);
  6629. }
  6630. }
  6631. }
  6632. deoptimizeCachedEntities() {
  6633. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  6634. for (const expression of expressionsToBeDeoptimized) {
  6635. expression.deoptimizeCache();
  6636. }
  6637. }
  6638. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6639. expression.deoptimizePath(UNKNOWN_PATH);
  6640. }
  6641. }
  6642. deoptimizeCachedIntegerEntities() {
  6643. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  6644. if (INTEGER_REG_EXP.test(key)) {
  6645. for (const expression of expressionsToBeDeoptimized) {
  6646. expression.deoptimizeCache();
  6647. }
  6648. }
  6649. }
  6650. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6651. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6652. }
  6653. }
  6654. getMemberExpression(key) {
  6655. if (this.hasLostTrack ||
  6656. this.hasUnknownDeoptimizedProperty ||
  6657. typeof key !== 'string' ||
  6658. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  6659. this.deoptimizedPaths[key]) {
  6660. return UNKNOWN_EXPRESSION;
  6661. }
  6662. const properties = this.propertiesAndGettersByKey[key];
  6663. if (properties?.length === 1) {
  6664. return properties[0];
  6665. }
  6666. if (properties ||
  6667. this.unmatchablePropertiesAndGetters.length > 0 ||
  6668. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  6669. return UNKNOWN_EXPRESSION;
  6670. }
  6671. return null;
  6672. }
  6673. getMemberExpressionAndTrackDeopt(key, origin) {
  6674. if (typeof key !== 'string') {
  6675. return UNKNOWN_EXPRESSION;
  6676. }
  6677. const expression = this.getMemberExpression(key);
  6678. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  6679. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  6680. this.expressionsToBeDeoptimizedByKey[key] || []);
  6681. expressionsToBeDeoptimized.push(origin);
  6682. }
  6683. return expression;
  6684. }
  6685. }
  6686. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  6687. // This makes sure unknown properties are not handled as "undefined" but as
  6688. // "unknown" but without access side effects. An exception is done for numeric
  6689. // properties as we do not expect new builtin properties to be numbers, this
  6690. // will improve tree-shaking for out-of-bounds array properties
  6691. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  6692. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6693. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  6694. deoptimizeInteraction(interaction);
  6695. }
  6696. }
  6697. getLiteralValueAtPath(path) {
  6698. // We ignore number properties as we do not expect new properties to be
  6699. // numbers and also want to keep handling out-of-bound array elements as
  6700. // "undefined"
  6701. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  6702. }
  6703. hasEffectsOnInteractionAtPath(path, { type }) {
  6704. return path.length > 1 || type === INTERACTION_CALLED;
  6705. }
  6706. })();
  6707. const OBJECT_PROTOTYPE = new ObjectEntity({
  6708. __proto__: null,
  6709. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  6710. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  6711. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  6712. toLocaleString: METHOD_RETURNS_STRING,
  6713. toString: METHOD_RETURNS_STRING,
  6714. valueOf: METHOD_RETURNS_UNKNOWN
  6715. }, OBJECT_PROTOTYPE_FALLBACK, true);
  6716. const NEW_ARRAY_PROPERTIES = [
  6717. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  6718. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6719. ];
  6720. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  6721. new Method({
  6722. callsArgs: [0],
  6723. mutatesArgs: false,
  6724. mutatesSelfAsArray: 'deopt-only',
  6725. returns: null,
  6726. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6727. })
  6728. ];
  6729. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  6730. new Method({
  6731. callsArgs: [0],
  6732. mutatesArgs: false,
  6733. mutatesSelfAsArray: 'deopt-only',
  6734. returns: null,
  6735. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6736. })
  6737. ];
  6738. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  6739. new Method({
  6740. callsArgs: null,
  6741. mutatesArgs: false,
  6742. mutatesSelfAsArray: true,
  6743. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6744. returnsPrimitive: null
  6745. })
  6746. ];
  6747. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6748. new Method({
  6749. callsArgs: null,
  6750. mutatesArgs: false,
  6751. mutatesSelfAsArray: 'deopt-only',
  6752. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6753. returnsPrimitive: null
  6754. })
  6755. ];
  6756. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6757. new Method({
  6758. callsArgs: [0],
  6759. mutatesArgs: false,
  6760. mutatesSelfAsArray: 'deopt-only',
  6761. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6762. returnsPrimitive: null
  6763. })
  6764. ];
  6765. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  6766. new Method({
  6767. callsArgs: null,
  6768. mutatesArgs: true,
  6769. mutatesSelfAsArray: true,
  6770. returns: null,
  6771. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6772. })
  6773. ];
  6774. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  6775. new Method({
  6776. callsArgs: null,
  6777. mutatesArgs: false,
  6778. mutatesSelfAsArray: true,
  6779. returns: null,
  6780. returnsPrimitive: UNKNOWN_EXPRESSION
  6781. })
  6782. ];
  6783. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6784. new Method({
  6785. callsArgs: null,
  6786. mutatesArgs: false,
  6787. mutatesSelfAsArray: 'deopt-only',
  6788. returns: null,
  6789. returnsPrimitive: UNKNOWN_EXPRESSION
  6790. })
  6791. ];
  6792. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6793. new Method({
  6794. callsArgs: [0],
  6795. mutatesArgs: false,
  6796. mutatesSelfAsArray: 'deopt-only',
  6797. returns: null,
  6798. returnsPrimitive: UNKNOWN_EXPRESSION
  6799. })
  6800. ];
  6801. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  6802. new Method({
  6803. callsArgs: null,
  6804. mutatesArgs: false,
  6805. mutatesSelfAsArray: true,
  6806. returns: 'self',
  6807. returnsPrimitive: null
  6808. })
  6809. ];
  6810. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  6811. new Method({
  6812. callsArgs: [0],
  6813. mutatesArgs: false,
  6814. mutatesSelfAsArray: true,
  6815. returns: 'self',
  6816. returnsPrimitive: null
  6817. })
  6818. ];
  6819. const ARRAY_PROTOTYPE = new ObjectEntity({
  6820. __proto__: null,
  6821. // We assume that accessors have effects as we do not track the accessed value afterwards
  6822. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  6823. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6824. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  6825. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6826. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6827. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  6828. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6829. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6830. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6831. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6832. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6833. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6834. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6835. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6836. includes: METHOD_RETURNS_BOOLEAN,
  6837. indexOf: METHOD_RETURNS_NUMBER,
  6838. join: METHOD_RETURNS_STRING,
  6839. keys: METHOD_RETURNS_UNKNOWN,
  6840. lastIndexOf: METHOD_RETURNS_NUMBER,
  6841. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6842. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6843. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  6844. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6845. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6846. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  6847. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6848. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6849. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6850. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  6851. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  6852. toLocaleString: METHOD_RETURNS_STRING,
  6853. toString: METHOD_RETURNS_STRING,
  6854. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  6855. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  6856. }, OBJECT_PROTOTYPE, true);
  6857. class SpreadElement extends NodeBase {
  6858. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6859. if (path.length > 0) {
  6860. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  6861. }
  6862. }
  6863. hasEffects(context) {
  6864. if (!this.deoptimized)
  6865. this.applyDeoptimizations();
  6866. const { propertyReadSideEffects } = this.scope.context.options
  6867. .treeshake;
  6868. return (this.argument.hasEffects(context) ||
  6869. (propertyReadSideEffects &&
  6870. (propertyReadSideEffects === 'always' ||
  6871. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  6872. }
  6873. includeNode(context) {
  6874. this.included = true;
  6875. if (!this.deoptimized)
  6876. this.applyDeoptimizations();
  6877. this.argument.includePath(UNKNOWN_PATH, context);
  6878. }
  6879. applyDeoptimizations() {
  6880. this.deoptimized = true;
  6881. // Only properties of properties of the argument could become subject to reassignment
  6882. // This will also reassign the return values of iterators
  6883. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  6884. this.scope.context.requestTreeshakingPass();
  6885. }
  6886. }
  6887. class ArrayExpression extends NodeBase {
  6888. constructor() {
  6889. super(...arguments);
  6890. this.objectEntity = null;
  6891. }
  6892. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6893. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6894. }
  6895. deoptimizePath(path) {
  6896. this.getObjectEntity().deoptimizePath(path);
  6897. }
  6898. getLiteralValueAtPath(path, recursionTracker, origin) {
  6899. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6900. }
  6901. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6902. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6903. }
  6904. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6905. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6906. }
  6907. includeNode(context) {
  6908. this.included = true;
  6909. if (!this.deoptimized)
  6910. this.applyDeoptimizations();
  6911. for (const element of this.elements) {
  6912. if (element) {
  6913. element?.includePath(UNKNOWN_PATH, context);
  6914. }
  6915. }
  6916. }
  6917. applyDeoptimizations() {
  6918. this.deoptimized = true;
  6919. let hasSpread = false;
  6920. for (let index = 0; index < this.elements.length; index++) {
  6921. const element = this.elements[index];
  6922. if (element && (hasSpread || element instanceof SpreadElement)) {
  6923. hasSpread = true;
  6924. element.deoptimizePath(UNKNOWN_PATH);
  6925. }
  6926. }
  6927. this.scope.context.requestTreeshakingPass();
  6928. }
  6929. getObjectEntity() {
  6930. if (this.objectEntity !== null) {
  6931. return this.objectEntity;
  6932. }
  6933. const properties = [
  6934. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6935. ];
  6936. let hasSpread = false;
  6937. for (let index = 0; index < this.elements.length; index++) {
  6938. const element = this.elements[index];
  6939. if (hasSpread || element instanceof SpreadElement) {
  6940. if (element) {
  6941. hasSpread = true;
  6942. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  6943. }
  6944. }
  6945. else if (element) {
  6946. properties.push({ key: String(index), kind: 'init', property: element });
  6947. }
  6948. else {
  6949. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  6950. }
  6951. }
  6952. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  6953. }
  6954. }
  6955. /* eslint sort-keys: "off" */
  6956. const ValueProperties = Symbol('Value Properties');
  6957. const getUnknownValue = () => UnknownValue;
  6958. const returnFalse = () => false;
  6959. const returnTrue = () => true;
  6960. const PURE = {
  6961. deoptimizeArgumentsOnCall: doNothing,
  6962. getLiteralValue: getUnknownValue,
  6963. hasEffectsWhenCalled: returnFalse
  6964. };
  6965. const IMPURE = {
  6966. deoptimizeArgumentsOnCall: doNothing,
  6967. getLiteralValue: getUnknownValue,
  6968. hasEffectsWhenCalled: returnTrue
  6969. };
  6970. const PURE_WITH_ARRAY = {
  6971. deoptimizeArgumentsOnCall: doNothing,
  6972. getLiteralValue: getUnknownValue,
  6973. hasEffectsWhenCalled({ args }) {
  6974. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  6975. }
  6976. };
  6977. const GETTER_ACCESS = {
  6978. deoptimizeArgumentsOnCall: doNothing,
  6979. getLiteralValue: getUnknownValue,
  6980. hasEffectsWhenCalled({ args }, context) {
  6981. const [_thisArgument, firstArgument] = args;
  6982. return (!(firstArgument instanceof ExpressionEntity) ||
  6983. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6984. }
  6985. };
  6986. // We use shortened variables to reduce file size here
  6987. /* OBJECT */
  6988. const O = {
  6989. __proto__: null,
  6990. [ValueProperties]: IMPURE
  6991. };
  6992. /* PURE FUNCTION */
  6993. const PF = {
  6994. __proto__: null,
  6995. [ValueProperties]: PURE
  6996. };
  6997. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  6998. const PF_NO_GETTER = {
  6999. __proto__: null,
  7000. [ValueProperties]: GETTER_ACCESS
  7001. };
  7002. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  7003. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  7004. __proto__: null,
  7005. [ValueProperties]: {
  7006. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  7007. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  7008. },
  7009. getLiteralValue: getUnknownValue,
  7010. hasEffectsWhenCalled({ args }, context) {
  7011. return (args.length <= 1 ||
  7012. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  7013. }
  7014. }
  7015. };
  7016. /* CONSTRUCTOR */
  7017. const C = {
  7018. __proto__: null,
  7019. [ValueProperties]: IMPURE,
  7020. prototype: O
  7021. };
  7022. /* PURE CONSTRUCTOR */
  7023. const PC = {
  7024. __proto__: null,
  7025. [ValueProperties]: PURE,
  7026. prototype: O
  7027. };
  7028. const PC_WITH_ARRAY = {
  7029. __proto__: null,
  7030. [ValueProperties]: PURE_WITH_ARRAY,
  7031. prototype: O
  7032. };
  7033. const ARRAY_TYPE = {
  7034. __proto__: null,
  7035. [ValueProperties]: PURE,
  7036. from: O,
  7037. of: PF,
  7038. prototype: O
  7039. };
  7040. const INTL_MEMBER = {
  7041. __proto__: null,
  7042. [ValueProperties]: PURE,
  7043. supportedLocalesOf: PC
  7044. };
  7045. const knownGlobals = {
  7046. // Placeholders for global objects to avoid shape mutations
  7047. global: O,
  7048. globalThis: O,
  7049. self: O,
  7050. window: O,
  7051. // Common globals
  7052. __proto__: null,
  7053. [ValueProperties]: IMPURE,
  7054. Array: {
  7055. __proto__: null,
  7056. [ValueProperties]: IMPURE,
  7057. from: O,
  7058. isArray: PF,
  7059. of: PF,
  7060. prototype: O
  7061. },
  7062. ArrayBuffer: {
  7063. __proto__: null,
  7064. [ValueProperties]: PURE,
  7065. isView: PF,
  7066. prototype: O
  7067. },
  7068. AggregateError: PC_WITH_ARRAY,
  7069. Atomics: O,
  7070. BigInt: C,
  7071. BigInt64Array: C,
  7072. BigUint64Array: C,
  7073. Boolean: PC,
  7074. constructor: C,
  7075. DataView: PC,
  7076. Date: {
  7077. __proto__: null,
  7078. [ValueProperties]: PURE,
  7079. now: PF,
  7080. parse: PF,
  7081. prototype: O,
  7082. UTC: PF
  7083. },
  7084. decodeURI: PF,
  7085. decodeURIComponent: PF,
  7086. encodeURI: PF,
  7087. encodeURIComponent: PF,
  7088. Error: PC,
  7089. escape: PF,
  7090. eval: O,
  7091. EvalError: PC,
  7092. FinalizationRegistry: C,
  7093. Float32Array: ARRAY_TYPE,
  7094. Float64Array: ARRAY_TYPE,
  7095. Function: C,
  7096. hasOwnProperty: O,
  7097. Infinity: O,
  7098. Int16Array: ARRAY_TYPE,
  7099. Int32Array: ARRAY_TYPE,
  7100. Int8Array: ARRAY_TYPE,
  7101. isFinite: PF,
  7102. isNaN: PF,
  7103. isPrototypeOf: O,
  7104. JSON: O,
  7105. Map: PC_WITH_ARRAY,
  7106. Math: {
  7107. __proto__: null,
  7108. [ValueProperties]: IMPURE,
  7109. abs: PF,
  7110. acos: PF,
  7111. acosh: PF,
  7112. asin: PF,
  7113. asinh: PF,
  7114. atan: PF,
  7115. atan2: PF,
  7116. atanh: PF,
  7117. cbrt: PF,
  7118. ceil: PF,
  7119. clz32: PF,
  7120. cos: PF,
  7121. cosh: PF,
  7122. exp: PF,
  7123. expm1: PF,
  7124. floor: PF,
  7125. fround: PF,
  7126. hypot: PF,
  7127. imul: PF,
  7128. log: PF,
  7129. log10: PF,
  7130. log1p: PF,
  7131. log2: PF,
  7132. max: PF,
  7133. min: PF,
  7134. pow: PF,
  7135. random: PF,
  7136. round: PF,
  7137. sign: PF,
  7138. sin: PF,
  7139. sinh: PF,
  7140. sqrt: PF,
  7141. tan: PF,
  7142. tanh: PF,
  7143. trunc: PF
  7144. },
  7145. NaN: O,
  7146. Number: {
  7147. __proto__: null,
  7148. [ValueProperties]: PURE,
  7149. isFinite: PF,
  7150. isInteger: PF,
  7151. isNaN: PF,
  7152. isSafeInteger: PF,
  7153. parseFloat: PF,
  7154. parseInt: PF,
  7155. prototype: O
  7156. },
  7157. Object: {
  7158. __proto__: null,
  7159. [ValueProperties]: PURE,
  7160. create: PF,
  7161. // Technically those can throw in certain situations, but we ignore this as
  7162. // code that relies on this will hopefully wrap this in a try-catch, which
  7163. // deoptimizes everything anyway
  7164. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  7165. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  7166. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  7167. getOwnPropertyDescriptor: PF,
  7168. getOwnPropertyDescriptors: PF,
  7169. getOwnPropertyNames: PF,
  7170. getOwnPropertySymbols: PF,
  7171. getPrototypeOf: PF,
  7172. hasOwn: PF,
  7173. is: PF,
  7174. isExtensible: PF,
  7175. isFrozen: PF,
  7176. isSealed: PF,
  7177. keys: PF,
  7178. fromEntries: O,
  7179. entries: PF_NO_GETTER,
  7180. values: PF_NO_GETTER,
  7181. prototype: O
  7182. },
  7183. parseFloat: PF,
  7184. parseInt: PF,
  7185. Promise: {
  7186. __proto__: null,
  7187. [ValueProperties]: IMPURE,
  7188. all: O,
  7189. allSettled: O,
  7190. any: O,
  7191. prototype: O,
  7192. race: O,
  7193. reject: O,
  7194. resolve: O
  7195. },
  7196. propertyIsEnumerable: O,
  7197. Proxy: {
  7198. __proto__: null,
  7199. [ValueProperties]: {
  7200. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  7201. if (isObjectExpressionNode(parameter)) {
  7202. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  7203. if (!hasSpreadElement) {
  7204. for (const property of parameter.properties) {
  7205. property.deoptimizeArgumentsOnInteractionAtPath({
  7206. args: [null, target],
  7207. type: INTERACTION_CALLED,
  7208. withNew: false
  7209. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  7210. }
  7211. return;
  7212. }
  7213. }
  7214. target.deoptimizePath(UNKNOWN_PATH);
  7215. },
  7216. getLiteralValue: getUnknownValue,
  7217. hasEffectsWhenCalled: returnTrue
  7218. }
  7219. },
  7220. RangeError: PC,
  7221. ReferenceError: PC,
  7222. Reflect: O,
  7223. RegExp: PC,
  7224. Set: PC_WITH_ARRAY,
  7225. SharedArrayBuffer: C,
  7226. String: {
  7227. __proto__: null,
  7228. [ValueProperties]: PURE,
  7229. fromCharCode: PF,
  7230. fromCodePoint: PF,
  7231. prototype: O,
  7232. raw: PF
  7233. },
  7234. Symbol: {
  7235. __proto__: null,
  7236. [ValueProperties]: PURE,
  7237. for: PF,
  7238. keyFor: PF,
  7239. prototype: O,
  7240. toStringTag: {
  7241. __proto__: null,
  7242. [ValueProperties]: {
  7243. deoptimizeArgumentsOnCall: doNothing,
  7244. getLiteralValue() {
  7245. return SymbolToStringTag;
  7246. },
  7247. hasEffectsWhenCalled: returnTrue
  7248. }
  7249. }
  7250. },
  7251. SyntaxError: PC,
  7252. toLocaleString: O,
  7253. toString: O,
  7254. TypeError: PC,
  7255. Uint16Array: ARRAY_TYPE,
  7256. Uint32Array: ARRAY_TYPE,
  7257. Uint8Array: ARRAY_TYPE,
  7258. Uint8ClampedArray: ARRAY_TYPE,
  7259. // Technically, this is a global, but it needs special handling
  7260. // undefined: ?,
  7261. unescape: PF,
  7262. URIError: PC,
  7263. valueOf: O,
  7264. WeakMap: PC_WITH_ARRAY,
  7265. WeakRef: C,
  7266. WeakSet: PC_WITH_ARRAY,
  7267. // Additional globals shared by Node and Browser that are not strictly part of the language
  7268. clearInterval: C,
  7269. clearTimeout: C,
  7270. console: {
  7271. __proto__: null,
  7272. [ValueProperties]: IMPURE,
  7273. assert: C,
  7274. clear: C,
  7275. count: C,
  7276. countReset: C,
  7277. debug: C,
  7278. dir: C,
  7279. dirxml: C,
  7280. error: C,
  7281. exception: C,
  7282. group: C,
  7283. groupCollapsed: C,
  7284. groupEnd: C,
  7285. info: C,
  7286. log: C,
  7287. table: C,
  7288. time: C,
  7289. timeEnd: C,
  7290. timeLog: C,
  7291. trace: C,
  7292. warn: C
  7293. },
  7294. Intl: {
  7295. __proto__: null,
  7296. [ValueProperties]: IMPURE,
  7297. Collator: INTL_MEMBER,
  7298. DateTimeFormat: INTL_MEMBER,
  7299. DisplayNames: INTL_MEMBER,
  7300. ListFormat: INTL_MEMBER,
  7301. Locale: INTL_MEMBER,
  7302. NumberFormat: INTL_MEMBER,
  7303. PluralRules: INTL_MEMBER,
  7304. RelativeTimeFormat: INTL_MEMBER,
  7305. Segmenter: INTL_MEMBER
  7306. },
  7307. setInterval: C,
  7308. setTimeout: C,
  7309. TextDecoder: C,
  7310. TextEncoder: C,
  7311. URL: {
  7312. __proto__: null,
  7313. [ValueProperties]: IMPURE,
  7314. prototype: O,
  7315. canParse: PF
  7316. },
  7317. URLSearchParams: C,
  7318. // Browser specific globals
  7319. AbortController: C,
  7320. AbortSignal: C,
  7321. addEventListener: O,
  7322. alert: O,
  7323. AnalyserNode: C,
  7324. Animation: C,
  7325. AnimationEvent: C,
  7326. applicationCache: O,
  7327. ApplicationCache: C,
  7328. ApplicationCacheErrorEvent: C,
  7329. atob: O,
  7330. Attr: C,
  7331. Audio: C,
  7332. AudioBuffer: C,
  7333. AudioBufferSourceNode: C,
  7334. AudioContext: C,
  7335. AudioDestinationNode: C,
  7336. AudioListener: C,
  7337. AudioNode: C,
  7338. AudioParam: C,
  7339. AudioProcessingEvent: C,
  7340. AudioScheduledSourceNode: C,
  7341. AudioWorkletNode: C,
  7342. BarProp: C,
  7343. BaseAudioContext: C,
  7344. BatteryManager: C,
  7345. BeforeUnloadEvent: C,
  7346. BiquadFilterNode: C,
  7347. Blob: C,
  7348. BlobEvent: C,
  7349. blur: O,
  7350. BroadcastChannel: C,
  7351. btoa: O,
  7352. ByteLengthQueuingStrategy: C,
  7353. Cache: C,
  7354. caches: O,
  7355. CacheStorage: C,
  7356. cancelAnimationFrame: O,
  7357. cancelIdleCallback: O,
  7358. CanvasCaptureMediaStreamTrack: C,
  7359. CanvasGradient: C,
  7360. CanvasPattern: C,
  7361. CanvasRenderingContext2D: C,
  7362. ChannelMergerNode: C,
  7363. ChannelSplitterNode: C,
  7364. CharacterData: C,
  7365. clientInformation: O,
  7366. ClipboardEvent: C,
  7367. close: O,
  7368. closed: O,
  7369. CloseEvent: C,
  7370. Comment: C,
  7371. CompositionEvent: C,
  7372. confirm: O,
  7373. ConstantSourceNode: C,
  7374. ConvolverNode: C,
  7375. CountQueuingStrategy: C,
  7376. createImageBitmap: O,
  7377. Credential: C,
  7378. CredentialsContainer: C,
  7379. crypto: O,
  7380. Crypto: C,
  7381. CryptoKey: C,
  7382. CSS: C,
  7383. CSSConditionRule: C,
  7384. CSSFontFaceRule: C,
  7385. CSSGroupingRule: C,
  7386. CSSImportRule: C,
  7387. CSSKeyframeRule: C,
  7388. CSSKeyframesRule: C,
  7389. CSSMediaRule: C,
  7390. CSSNamespaceRule: C,
  7391. CSSPageRule: C,
  7392. CSSRule: C,
  7393. CSSRuleList: C,
  7394. CSSStyleDeclaration: C,
  7395. CSSStyleRule: C,
  7396. CSSStyleSheet: C,
  7397. CSSSupportsRule: C,
  7398. CustomElementRegistry: C,
  7399. customElements: O,
  7400. CustomEvent: {
  7401. __proto__: null,
  7402. [ValueProperties]: {
  7403. deoptimizeArgumentsOnCall({ args }) {
  7404. args[2]?.deoptimizePath(['detail']);
  7405. },
  7406. getLiteralValue: getUnknownValue,
  7407. hasEffectsWhenCalled: returnFalse
  7408. },
  7409. prototype: O
  7410. },
  7411. DataTransfer: C,
  7412. DataTransferItem: C,
  7413. DataTransferItemList: C,
  7414. defaultstatus: O,
  7415. defaultStatus: O,
  7416. DelayNode: C,
  7417. DeviceMotionEvent: C,
  7418. DeviceOrientationEvent: C,
  7419. devicePixelRatio: O,
  7420. dispatchEvent: O,
  7421. document: O,
  7422. Document: C,
  7423. DocumentFragment: C,
  7424. DocumentType: C,
  7425. DOMError: C,
  7426. DOMException: C,
  7427. DOMImplementation: C,
  7428. DOMMatrix: C,
  7429. DOMMatrixReadOnly: C,
  7430. DOMParser: C,
  7431. DOMPoint: C,
  7432. DOMPointReadOnly: C,
  7433. DOMQuad: C,
  7434. DOMRect: C,
  7435. DOMRectReadOnly: C,
  7436. DOMStringList: C,
  7437. DOMStringMap: C,
  7438. DOMTokenList: C,
  7439. DragEvent: C,
  7440. DynamicsCompressorNode: C,
  7441. Element: C,
  7442. ErrorEvent: C,
  7443. Event: C,
  7444. EventSource: C,
  7445. EventTarget: C,
  7446. external: O,
  7447. fetch: O,
  7448. File: C,
  7449. FileList: C,
  7450. FileReader: C,
  7451. find: O,
  7452. focus: O,
  7453. FocusEvent: C,
  7454. FontFace: C,
  7455. FontFaceSetLoadEvent: C,
  7456. FormData: C,
  7457. frames: O,
  7458. GainNode: C,
  7459. Gamepad: C,
  7460. GamepadButton: C,
  7461. GamepadEvent: C,
  7462. getComputedStyle: O,
  7463. getSelection: O,
  7464. HashChangeEvent: C,
  7465. Headers: C,
  7466. history: O,
  7467. History: C,
  7468. HTMLAllCollection: C,
  7469. HTMLAnchorElement: C,
  7470. HTMLAreaElement: C,
  7471. HTMLAudioElement: C,
  7472. HTMLBaseElement: C,
  7473. HTMLBodyElement: C,
  7474. HTMLBRElement: C,
  7475. HTMLButtonElement: C,
  7476. HTMLCanvasElement: C,
  7477. HTMLCollection: C,
  7478. HTMLContentElement: C,
  7479. HTMLDataElement: C,
  7480. HTMLDataListElement: C,
  7481. HTMLDetailsElement: C,
  7482. HTMLDialogElement: C,
  7483. HTMLDirectoryElement: C,
  7484. HTMLDivElement: C,
  7485. HTMLDListElement: C,
  7486. HTMLDocument: C,
  7487. HTMLElement: C,
  7488. HTMLEmbedElement: C,
  7489. HTMLFieldSetElement: C,
  7490. HTMLFontElement: C,
  7491. HTMLFormControlsCollection: C,
  7492. HTMLFormElement: C,
  7493. HTMLFrameElement: C,
  7494. HTMLFrameSetElement: C,
  7495. HTMLHeadElement: C,
  7496. HTMLHeadingElement: C,
  7497. HTMLHRElement: C,
  7498. HTMLHtmlElement: C,
  7499. HTMLIFrameElement: C,
  7500. HTMLImageElement: C,
  7501. HTMLInputElement: C,
  7502. HTMLLabelElement: C,
  7503. HTMLLegendElement: C,
  7504. HTMLLIElement: C,
  7505. HTMLLinkElement: C,
  7506. HTMLMapElement: C,
  7507. HTMLMarqueeElement: C,
  7508. HTMLMediaElement: C,
  7509. HTMLMenuElement: C,
  7510. HTMLMetaElement: C,
  7511. HTMLMeterElement: C,
  7512. HTMLModElement: C,
  7513. HTMLObjectElement: C,
  7514. HTMLOListElement: C,
  7515. HTMLOptGroupElement: C,
  7516. HTMLOptionElement: C,
  7517. HTMLOptionsCollection: C,
  7518. HTMLOutputElement: C,
  7519. HTMLParagraphElement: C,
  7520. HTMLParamElement: C,
  7521. HTMLPictureElement: C,
  7522. HTMLPreElement: C,
  7523. HTMLProgressElement: C,
  7524. HTMLQuoteElement: C,
  7525. HTMLScriptElement: C,
  7526. HTMLSelectElement: C,
  7527. HTMLShadowElement: C,
  7528. HTMLSlotElement: C,
  7529. HTMLSourceElement: C,
  7530. HTMLSpanElement: C,
  7531. HTMLStyleElement: C,
  7532. HTMLTableCaptionElement: C,
  7533. HTMLTableCellElement: C,
  7534. HTMLTableColElement: C,
  7535. HTMLTableElement: C,
  7536. HTMLTableRowElement: C,
  7537. HTMLTableSectionElement: C,
  7538. HTMLTemplateElement: C,
  7539. HTMLTextAreaElement: C,
  7540. HTMLTimeElement: C,
  7541. HTMLTitleElement: C,
  7542. HTMLTrackElement: C,
  7543. HTMLUListElement: C,
  7544. HTMLUnknownElement: C,
  7545. HTMLVideoElement: C,
  7546. IDBCursor: C,
  7547. IDBCursorWithValue: C,
  7548. IDBDatabase: C,
  7549. IDBFactory: C,
  7550. IDBIndex: C,
  7551. IDBKeyRange: C,
  7552. IDBObjectStore: C,
  7553. IDBOpenDBRequest: C,
  7554. IDBRequest: C,
  7555. IDBTransaction: C,
  7556. IDBVersionChangeEvent: C,
  7557. IdleDeadline: C,
  7558. IIRFilterNode: C,
  7559. Image: C,
  7560. ImageBitmap: C,
  7561. ImageBitmapRenderingContext: C,
  7562. ImageCapture: C,
  7563. ImageData: C,
  7564. indexedDB: O,
  7565. innerHeight: O,
  7566. innerWidth: O,
  7567. InputEvent: C,
  7568. IntersectionObserver: C,
  7569. IntersectionObserverEntry: C,
  7570. isSecureContext: O,
  7571. KeyboardEvent: C,
  7572. KeyframeEffect: C,
  7573. length: O,
  7574. localStorage: O,
  7575. location: O,
  7576. Location: C,
  7577. locationbar: O,
  7578. matchMedia: O,
  7579. MediaDeviceInfo: C,
  7580. MediaDevices: C,
  7581. MediaElementAudioSourceNode: C,
  7582. MediaEncryptedEvent: C,
  7583. MediaError: C,
  7584. MediaKeyMessageEvent: C,
  7585. MediaKeySession: C,
  7586. MediaKeyStatusMap: C,
  7587. MediaKeySystemAccess: C,
  7588. MediaList: C,
  7589. MediaQueryList: C,
  7590. MediaQueryListEvent: C,
  7591. MediaRecorder: C,
  7592. MediaSettingsRange: C,
  7593. MediaSource: C,
  7594. MediaStream: C,
  7595. MediaStreamAudioDestinationNode: C,
  7596. MediaStreamAudioSourceNode: C,
  7597. MediaStreamEvent: C,
  7598. MediaStreamTrack: C,
  7599. MediaStreamTrackEvent: C,
  7600. menubar: O,
  7601. MessageChannel: C,
  7602. MessageEvent: C,
  7603. MessagePort: C,
  7604. MIDIAccess: C,
  7605. MIDIConnectionEvent: C,
  7606. MIDIInput: C,
  7607. MIDIInputMap: C,
  7608. MIDIMessageEvent: C,
  7609. MIDIOutput: C,
  7610. MIDIOutputMap: C,
  7611. MIDIPort: C,
  7612. MimeType: C,
  7613. MimeTypeArray: C,
  7614. MouseEvent: C,
  7615. moveBy: O,
  7616. moveTo: O,
  7617. MutationEvent: C,
  7618. MutationObserver: C,
  7619. MutationRecord: C,
  7620. name: O,
  7621. NamedNodeMap: C,
  7622. NavigationPreloadManager: C,
  7623. navigator: O,
  7624. Navigator: C,
  7625. NetworkInformation: C,
  7626. Node: C,
  7627. NodeFilter: O,
  7628. NodeIterator: C,
  7629. NodeList: C,
  7630. Notification: C,
  7631. OfflineAudioCompletionEvent: C,
  7632. OfflineAudioContext: C,
  7633. offscreenBuffering: O,
  7634. OffscreenCanvas: C,
  7635. open: O,
  7636. openDatabase: O,
  7637. Option: C,
  7638. origin: O,
  7639. OscillatorNode: C,
  7640. outerHeight: O,
  7641. outerWidth: O,
  7642. PageTransitionEvent: C,
  7643. pageXOffset: O,
  7644. pageYOffset: O,
  7645. PannerNode: C,
  7646. parent: O,
  7647. Path2D: C,
  7648. PaymentAddress: C,
  7649. PaymentRequest: C,
  7650. PaymentRequestUpdateEvent: C,
  7651. PaymentResponse: C,
  7652. performance: O,
  7653. Performance: C,
  7654. PerformanceEntry: C,
  7655. PerformanceLongTaskTiming: C,
  7656. PerformanceMark: C,
  7657. PerformanceMeasure: C,
  7658. PerformanceNavigation: C,
  7659. PerformanceNavigationTiming: C,
  7660. PerformanceObserver: C,
  7661. PerformanceObserverEntryList: C,
  7662. PerformancePaintTiming: C,
  7663. PerformanceResourceTiming: C,
  7664. PerformanceTiming: C,
  7665. PeriodicWave: C,
  7666. Permissions: C,
  7667. PermissionStatus: C,
  7668. personalbar: O,
  7669. PhotoCapabilities: C,
  7670. Plugin: C,
  7671. PluginArray: C,
  7672. PointerEvent: C,
  7673. PopStateEvent: C,
  7674. postMessage: O,
  7675. Presentation: C,
  7676. PresentationAvailability: C,
  7677. PresentationConnection: C,
  7678. PresentationConnectionAvailableEvent: C,
  7679. PresentationConnectionCloseEvent: C,
  7680. PresentationConnectionList: C,
  7681. PresentationReceiver: C,
  7682. PresentationRequest: C,
  7683. print: O,
  7684. ProcessingInstruction: C,
  7685. ProgressEvent: C,
  7686. PromiseRejectionEvent: C,
  7687. prompt: O,
  7688. PushManager: C,
  7689. PushSubscription: C,
  7690. PushSubscriptionOptions: C,
  7691. queueMicrotask: O,
  7692. RadioNodeList: C,
  7693. Range: C,
  7694. ReadableStream: C,
  7695. RemotePlayback: C,
  7696. removeEventListener: O,
  7697. Request: C,
  7698. requestAnimationFrame: O,
  7699. requestIdleCallback: O,
  7700. resizeBy: O,
  7701. ResizeObserver: C,
  7702. ResizeObserverEntry: C,
  7703. resizeTo: O,
  7704. Response: C,
  7705. RTCCertificate: C,
  7706. RTCDataChannel: C,
  7707. RTCDataChannelEvent: C,
  7708. RTCDtlsTransport: C,
  7709. RTCIceCandidate: C,
  7710. RTCIceTransport: C,
  7711. RTCPeerConnection: C,
  7712. RTCPeerConnectionIceEvent: C,
  7713. RTCRtpReceiver: C,
  7714. RTCRtpSender: C,
  7715. RTCSctpTransport: C,
  7716. RTCSessionDescription: C,
  7717. RTCStatsReport: C,
  7718. RTCTrackEvent: C,
  7719. screen: O,
  7720. Screen: C,
  7721. screenLeft: O,
  7722. ScreenOrientation: C,
  7723. screenTop: O,
  7724. screenX: O,
  7725. screenY: O,
  7726. ScriptProcessorNode: C,
  7727. scroll: O,
  7728. scrollbars: O,
  7729. scrollBy: O,
  7730. scrollTo: O,
  7731. scrollX: O,
  7732. scrollY: O,
  7733. SecurityPolicyViolationEvent: C,
  7734. Selection: C,
  7735. ServiceWorker: C,
  7736. ServiceWorkerContainer: C,
  7737. ServiceWorkerRegistration: C,
  7738. sessionStorage: O,
  7739. ShadowRoot: C,
  7740. SharedWorker: C,
  7741. SourceBuffer: C,
  7742. SourceBufferList: C,
  7743. speechSynthesis: O,
  7744. SpeechSynthesisEvent: C,
  7745. SpeechSynthesisUtterance: C,
  7746. StaticRange: C,
  7747. status: O,
  7748. statusbar: O,
  7749. StereoPannerNode: C,
  7750. stop: O,
  7751. Storage: C,
  7752. StorageEvent: C,
  7753. StorageManager: C,
  7754. styleMedia: O,
  7755. StyleSheet: C,
  7756. StyleSheetList: C,
  7757. SubtleCrypto: C,
  7758. SVGAElement: C,
  7759. SVGAngle: C,
  7760. SVGAnimatedAngle: C,
  7761. SVGAnimatedBoolean: C,
  7762. SVGAnimatedEnumeration: C,
  7763. SVGAnimatedInteger: C,
  7764. SVGAnimatedLength: C,
  7765. SVGAnimatedLengthList: C,
  7766. SVGAnimatedNumber: C,
  7767. SVGAnimatedNumberList: C,
  7768. SVGAnimatedPreserveAspectRatio: C,
  7769. SVGAnimatedRect: C,
  7770. SVGAnimatedString: C,
  7771. SVGAnimatedTransformList: C,
  7772. SVGAnimateElement: C,
  7773. SVGAnimateMotionElement: C,
  7774. SVGAnimateTransformElement: C,
  7775. SVGAnimationElement: C,
  7776. SVGCircleElement: C,
  7777. SVGClipPathElement: C,
  7778. SVGComponentTransferFunctionElement: C,
  7779. SVGDefsElement: C,
  7780. SVGDescElement: C,
  7781. SVGDiscardElement: C,
  7782. SVGElement: C,
  7783. SVGEllipseElement: C,
  7784. SVGFEBlendElement: C,
  7785. SVGFEColorMatrixElement: C,
  7786. SVGFEComponentTransferElement: C,
  7787. SVGFECompositeElement: C,
  7788. SVGFEConvolveMatrixElement: C,
  7789. SVGFEDiffuseLightingElement: C,
  7790. SVGFEDisplacementMapElement: C,
  7791. SVGFEDistantLightElement: C,
  7792. SVGFEDropShadowElement: C,
  7793. SVGFEFloodElement: C,
  7794. SVGFEFuncAElement: C,
  7795. SVGFEFuncBElement: C,
  7796. SVGFEFuncGElement: C,
  7797. SVGFEFuncRElement: C,
  7798. SVGFEGaussianBlurElement: C,
  7799. SVGFEImageElement: C,
  7800. SVGFEMergeElement: C,
  7801. SVGFEMergeNodeElement: C,
  7802. SVGFEMorphologyElement: C,
  7803. SVGFEOffsetElement: C,
  7804. SVGFEPointLightElement: C,
  7805. SVGFESpecularLightingElement: C,
  7806. SVGFESpotLightElement: C,
  7807. SVGFETileElement: C,
  7808. SVGFETurbulenceElement: C,
  7809. SVGFilterElement: C,
  7810. SVGForeignObjectElement: C,
  7811. SVGGElement: C,
  7812. SVGGeometryElement: C,
  7813. SVGGradientElement: C,
  7814. SVGGraphicsElement: C,
  7815. SVGImageElement: C,
  7816. SVGLength: C,
  7817. SVGLengthList: C,
  7818. SVGLinearGradientElement: C,
  7819. SVGLineElement: C,
  7820. SVGMarkerElement: C,
  7821. SVGMaskElement: C,
  7822. SVGMatrix: C,
  7823. SVGMetadataElement: C,
  7824. SVGMPathElement: C,
  7825. SVGNumber: C,
  7826. SVGNumberList: C,
  7827. SVGPathElement: C,
  7828. SVGPatternElement: C,
  7829. SVGPoint: C,
  7830. SVGPointList: C,
  7831. SVGPolygonElement: C,
  7832. SVGPolylineElement: C,
  7833. SVGPreserveAspectRatio: C,
  7834. SVGRadialGradientElement: C,
  7835. SVGRect: C,
  7836. SVGRectElement: C,
  7837. SVGScriptElement: C,
  7838. SVGSetElement: C,
  7839. SVGStopElement: C,
  7840. SVGStringList: C,
  7841. SVGStyleElement: C,
  7842. SVGSVGElement: C,
  7843. SVGSwitchElement: C,
  7844. SVGSymbolElement: C,
  7845. SVGTextContentElement: C,
  7846. SVGTextElement: C,
  7847. SVGTextPathElement: C,
  7848. SVGTextPositioningElement: C,
  7849. SVGTitleElement: C,
  7850. SVGTransform: C,
  7851. SVGTransformList: C,
  7852. SVGTSpanElement: C,
  7853. SVGUnitTypes: C,
  7854. SVGUseElement: C,
  7855. SVGViewElement: C,
  7856. TaskAttributionTiming: C,
  7857. Text: C,
  7858. TextEvent: C,
  7859. TextMetrics: C,
  7860. TextTrack: C,
  7861. TextTrackCue: C,
  7862. TextTrackCueList: C,
  7863. TextTrackList: C,
  7864. TimeRanges: C,
  7865. toolbar: O,
  7866. top: O,
  7867. Touch: C,
  7868. TouchEvent: C,
  7869. TouchList: C,
  7870. TrackEvent: C,
  7871. TransitionEvent: C,
  7872. TreeWalker: C,
  7873. UIEvent: C,
  7874. ValidityState: C,
  7875. visualViewport: O,
  7876. VisualViewport: C,
  7877. VTTCue: C,
  7878. WaveShaperNode: C,
  7879. WebAssembly: O,
  7880. WebGL2RenderingContext: C,
  7881. WebGLActiveInfo: C,
  7882. WebGLBuffer: C,
  7883. WebGLContextEvent: C,
  7884. WebGLFramebuffer: C,
  7885. WebGLProgram: C,
  7886. WebGLQuery: C,
  7887. WebGLRenderbuffer: C,
  7888. WebGLRenderingContext: C,
  7889. WebGLSampler: C,
  7890. WebGLShader: C,
  7891. WebGLShaderPrecisionFormat: C,
  7892. WebGLSync: C,
  7893. WebGLTexture: C,
  7894. WebGLTransformFeedback: C,
  7895. WebGLUniformLocation: C,
  7896. WebGLVertexArrayObject: C,
  7897. WebSocket: C,
  7898. WheelEvent: C,
  7899. Window: C,
  7900. Worker: C,
  7901. WritableStream: C,
  7902. XMLDocument: C,
  7903. XMLHttpRequest: C,
  7904. XMLHttpRequestEventTarget: C,
  7905. XMLHttpRequestUpload: C,
  7906. XMLSerializer: C,
  7907. XPathEvaluator: C,
  7908. XPathExpression: C,
  7909. XPathResult: C,
  7910. XSLTProcessor: C
  7911. };
  7912. for (const global of ['window', 'global', 'self', 'globalThis']) {
  7913. knownGlobals[global] = knownGlobals;
  7914. }
  7915. function getGlobalAtPath(path) {
  7916. let currentGlobal = knownGlobals;
  7917. for (const pathSegment of path) {
  7918. if (typeof pathSegment !== 'string') {
  7919. return null;
  7920. }
  7921. currentGlobal = currentGlobal[pathSegment];
  7922. if (!currentGlobal) {
  7923. return null;
  7924. }
  7925. }
  7926. return currentGlobal[ValueProperties];
  7927. }
  7928. class GlobalVariable extends Variable {
  7929. constructor(name) {
  7930. super(name);
  7931. // Ensure we use live-bindings for globals as we do not know if they have
  7932. // been reassigned
  7933. this.markReassigned();
  7934. }
  7935. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7936. switch (interaction.type) {
  7937. // While there is no point in testing these cases as at the moment, they
  7938. // are also covered via other means, we keep them for completeness
  7939. case INTERACTION_ACCESSED:
  7940. case INTERACTION_ASSIGNED: {
  7941. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  7942. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7943. }
  7944. return;
  7945. }
  7946. case INTERACTION_CALLED: {
  7947. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7948. if (globalAtPath) {
  7949. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  7950. }
  7951. else {
  7952. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7953. }
  7954. return;
  7955. }
  7956. }
  7957. }
  7958. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  7959. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7960. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  7961. }
  7962. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7963. switch (interaction.type) {
  7964. case INTERACTION_ACCESSED: {
  7965. if (path.length === 0) {
  7966. // Technically, "undefined" is a global variable of sorts
  7967. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  7968. }
  7969. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  7970. }
  7971. case INTERACTION_ASSIGNED: {
  7972. return true;
  7973. }
  7974. case INTERACTION_CALLED: {
  7975. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7976. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  7977. }
  7978. }
  7979. }
  7980. }
  7981. // To avoid infinite recursions
  7982. const MAX_PATH_DEPTH = 6;
  7983. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  7984. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  7985. const limitConcatenatedPathDepth = (path1, path2) => {
  7986. const { length: length1 } = path1;
  7987. const { length: length2 } = path2;
  7988. return length1 === 0
  7989. ? path2
  7990. : length2 === 0
  7991. ? path1
  7992. : length1 + length2 > MAX_PATH_DEPTH
  7993. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  7994. : [...path1, ...path2];
  7995. };
  7996. class LocalVariable extends Variable {
  7997. constructor(name, declarator, init,
  7998. /** if this is non-empty, the actual init is this path of this.init */
  7999. initPath, context, kind) {
  8000. super(name);
  8001. this.init = init;
  8002. this.initPath = initPath;
  8003. this.kind = kind;
  8004. this.calledFromTryStatement = false;
  8005. this.additionalInitializers = null;
  8006. this.includedPathTracker = new IncludedFullPathTracker();
  8007. this.expressionsToBeDeoptimized = [];
  8008. this.declarations = declarator ? [declarator] : [];
  8009. this.deoptimizationTracker = context.deoptimizationTracker;
  8010. this.module = context.module;
  8011. }
  8012. addDeclaration(identifier, init) {
  8013. this.declarations.push(identifier);
  8014. this.markInitializersForDeoptimization().push(init);
  8015. }
  8016. consolidateInitializers() {
  8017. if (this.additionalInitializers) {
  8018. for (const initializer of this.additionalInitializers) {
  8019. initializer.deoptimizePath(UNKNOWN_PATH);
  8020. }
  8021. }
  8022. }
  8023. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8024. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8025. deoptimizeInteraction(interaction);
  8026. return;
  8027. }
  8028. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8029. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  8030. }, undefined);
  8031. }
  8032. deoptimizePath(path) {
  8033. if (this.isReassigned ||
  8034. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8035. return;
  8036. }
  8037. if (path.length === 0) {
  8038. this.markReassigned();
  8039. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  8040. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  8041. for (const expression of expressionsToBeDeoptimized) {
  8042. expression.deoptimizeCache();
  8043. }
  8044. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  8045. }
  8046. else {
  8047. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  8048. }
  8049. }
  8050. getLiteralValueAtPath(path, recursionTracker, origin) {
  8051. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8052. return UnknownValue;
  8053. }
  8054. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8055. this.expressionsToBeDeoptimized.push(origin);
  8056. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  8057. }, UnknownValue);
  8058. }
  8059. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8060. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8061. return UNKNOWN_RETURN_EXPRESSION;
  8062. }
  8063. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8064. this.expressionsToBeDeoptimized.push(origin);
  8065. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  8066. }, UNKNOWN_RETURN_EXPRESSION);
  8067. }
  8068. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8069. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8070. return true;
  8071. }
  8072. switch (interaction.type) {
  8073. case INTERACTION_ACCESSED: {
  8074. if (this.isReassigned)
  8075. return true;
  8076. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  8077. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8078. }
  8079. case INTERACTION_ASSIGNED: {
  8080. if (this.included)
  8081. return true;
  8082. if (path.length === 0)
  8083. return false;
  8084. if (this.isReassigned)
  8085. return true;
  8086. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  8087. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8088. }
  8089. case INTERACTION_CALLED: {
  8090. if (this.isReassigned)
  8091. return true;
  8092. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  8093. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8094. }
  8095. }
  8096. }
  8097. includePath(path, context) {
  8098. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  8099. this.module.scope.context.requestTreeshakingPass();
  8100. if (!this.included) {
  8101. // This will reduce the number of tree-shaking passes by eagerly
  8102. // including inits. By pushing this here instead of directly including
  8103. // we avoid deep call stacks.
  8104. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  8105. }
  8106. super.includePath(path, context);
  8107. for (const declaration of this.declarations) {
  8108. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  8109. if (!declaration.included)
  8110. declaration.include(context, false);
  8111. let node = declaration.parent;
  8112. while (!node.included) {
  8113. // We do not want to properly include parents in case they are part of a dead branch
  8114. // in which case .include() might pull in more dead code
  8115. node.includeNode(context);
  8116. if (node.type === parseAst_js.Program)
  8117. break;
  8118. node = node.parent;
  8119. }
  8120. /**
  8121. * import('foo').then(m => {
  8122. * console.log(m.foo)
  8123. * })
  8124. */
  8125. if (this.kind === 'parameter' &&
  8126. isArrowFunctionExpressionNode(declaration.parent) &&
  8127. isCallExpressionNode(declaration.parent.parent) &&
  8128. isMemberExpressionNode(declaration.parent.parent.callee) &&
  8129. isIdentifierNode(declaration.parent.parent.callee.property) &&
  8130. declaration.parent.parent.callee.property.name === 'then' &&
  8131. isImportExpressionNode(declaration.parent.parent.callee.object)) {
  8132. declaration.parent.parent.callee.object.includePath(path);
  8133. }
  8134. }
  8135. // We need to make sure we include the correct path of the init
  8136. if (path.length > 0) {
  8137. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  8138. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  8139. }
  8140. }
  8141. }
  8142. includeCallArguments(interaction, context) {
  8143. if (this.isReassigned ||
  8144. context.includedCallArguments.has(this.init) ||
  8145. // This can be removed again once we can include arguments when called at
  8146. // a specific path
  8147. this.initPath.length > 0) {
  8148. includeInteraction(interaction, context);
  8149. }
  8150. else {
  8151. context.includedCallArguments.add(this.init);
  8152. this.init.includeCallArguments(interaction, context);
  8153. context.includedCallArguments.delete(this.init);
  8154. }
  8155. }
  8156. markCalledFromTryStatement() {
  8157. this.calledFromTryStatement = true;
  8158. }
  8159. markInitializersForDeoptimization() {
  8160. if (this.additionalInitializers === null) {
  8161. this.additionalInitializers = [this.init];
  8162. this.init = UNKNOWN_EXPRESSION;
  8163. this.markReassigned();
  8164. }
  8165. return this.additionalInitializers;
  8166. }
  8167. }
  8168. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  8169. class IdentifierBase extends NodeBase {
  8170. constructor() {
  8171. super(...arguments);
  8172. this.variable = null;
  8173. this.isVariableReference = false;
  8174. }
  8175. get isTDZAccess() {
  8176. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  8177. return null;
  8178. }
  8179. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  8180. }
  8181. set isTDZAccess(value) {
  8182. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  8183. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  8184. }
  8185. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8186. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8187. }
  8188. deoptimizePath(path) {
  8189. if (path.length === 0 && !this.scope.contains(this.name)) {
  8190. this.disallowImportReassignment();
  8191. }
  8192. // We keep conditional chaining because an unknown Node could have an
  8193. // Identifier as property that might be deoptimized by default
  8194. this.variable?.deoptimizePath(path);
  8195. }
  8196. getLiteralValueAtPath(path, recursionTracker, origin) {
  8197. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  8198. }
  8199. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8200. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8201. return [expression, isPure || this.isPureFunction(path)];
  8202. }
  8203. hasEffects(context) {
  8204. if (!this.deoptimized)
  8205. this.applyDeoptimizations();
  8206. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  8207. return true;
  8208. }
  8209. return (this.scope.context.options.treeshake
  8210. .unknownGlobalSideEffects &&
  8211. this.variable instanceof GlobalVariable &&
  8212. !this.isPureFunction(EMPTY_PATH) &&
  8213. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8214. }
  8215. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8216. switch (interaction.type) {
  8217. case INTERACTION_ACCESSED: {
  8218. return (this.variable !== null &&
  8219. !this.isPureFunction(path) &&
  8220. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8221. }
  8222. case INTERACTION_ASSIGNED: {
  8223. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  8224. }
  8225. case INTERACTION_CALLED: {
  8226. return (!this.isPureFunction(path) &&
  8227. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8228. }
  8229. }
  8230. }
  8231. include(context, includeChildrenRecursively) {
  8232. if (!this.included)
  8233. this.includeNode(context);
  8234. if (includeChildrenRecursively) {
  8235. this.variable?.includePath(UNKNOWN_PATH, context);
  8236. }
  8237. }
  8238. includeNode(context) {
  8239. this.included = true;
  8240. if (!this.deoptimized)
  8241. this.applyDeoptimizations();
  8242. if (this.variable !== null) {
  8243. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8244. }
  8245. }
  8246. includePath(path, context) {
  8247. if (!this.included) {
  8248. this.included = true;
  8249. if (!this.deoptimized)
  8250. this.applyDeoptimizations();
  8251. if (this.variable !== null) {
  8252. this.scope.context.includeVariableInModule(this.variable, path, context);
  8253. }
  8254. }
  8255. else if (path.length > 0) {
  8256. this.variable?.includePath(path, context);
  8257. }
  8258. }
  8259. includeCallArguments(interaction, context) {
  8260. this.variable.includeCallArguments(interaction, context);
  8261. }
  8262. isPossibleTDZ() {
  8263. // return cached value to avoid issues with the next tree-shaking pass
  8264. const cachedTdzAccess = this.isTDZAccess;
  8265. if (cachedTdzAccess !== null)
  8266. return cachedTdzAccess;
  8267. if (!(this.variable instanceof LocalVariable &&
  8268. this.variable.kind &&
  8269. tdzVariableKinds.has(this.variable.kind) &&
  8270. // We ignore modules that did not receive a treeshaking pass yet as that
  8271. // causes many false positives due to circular dependencies or disabled
  8272. // moduleSideEffects.
  8273. this.variable.module.hasTreeShakingPassStarted)) {
  8274. return (this.isTDZAccess = false);
  8275. }
  8276. let decl_id;
  8277. if (this.variable.declarations &&
  8278. this.variable.declarations.length === 1 &&
  8279. (decl_id = this.variable.declarations[0]) &&
  8280. this.start < decl_id.start &&
  8281. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  8282. // a variable accessed before its declaration
  8283. // in the same function or at top level of module
  8284. return (this.isTDZAccess = true);
  8285. }
  8286. if (!this.variable.initReached) {
  8287. // Either a const/let TDZ violation or
  8288. // var use before declaration was encountered.
  8289. return (this.isTDZAccess = true);
  8290. }
  8291. return (this.isTDZAccess = false);
  8292. }
  8293. applyDeoptimizations() {
  8294. this.deoptimized = true;
  8295. if (this.variable instanceof LocalVariable) {
  8296. // When accessing a variable from a module without side effects, this
  8297. // means we use an export of that module and therefore need to potentially
  8298. // include it in the bundle.
  8299. if (!this.variable.module.isExecuted) {
  8300. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  8301. }
  8302. this.variable.consolidateInitializers();
  8303. this.scope.context.requestTreeshakingPass();
  8304. }
  8305. if (this.isVariableReference) {
  8306. this.variable.addUsedPlace(this);
  8307. this.scope.context.requestTreeshakingPass();
  8308. }
  8309. }
  8310. disallowImportReassignment() {
  8311. return this.scope.context.error(parseAst_js.logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  8312. }
  8313. getVariableRespectingTDZ() {
  8314. if (this.isPossibleTDZ()) {
  8315. return UNKNOWN_EXPRESSION;
  8316. }
  8317. return this.variable;
  8318. }
  8319. isPureFunction(path) {
  8320. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  8321. for (const segment of path) {
  8322. if (currentPureFunction) {
  8323. if (currentPureFunction[PureFunctionKey]) {
  8324. return true;
  8325. }
  8326. currentPureFunction = currentPureFunction[segment];
  8327. }
  8328. else {
  8329. return false;
  8330. }
  8331. }
  8332. return currentPureFunction?.[PureFunctionKey];
  8333. }
  8334. }
  8335. function closestParentFunctionOrProgram(node) {
  8336. while (node && !/^Program|Function/.test(node.type)) {
  8337. node = node.parent;
  8338. }
  8339. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  8340. return node;
  8341. }
  8342. class ObjectMember extends ExpressionEntity {
  8343. constructor(object, path) {
  8344. super();
  8345. this.object = object;
  8346. this.path = path;
  8347. }
  8348. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8349. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  8350. }
  8351. deoptimizePath(path) {
  8352. this.object.deoptimizePath([...this.path, ...path]);
  8353. }
  8354. getLiteralValueAtPath(path, recursionTracker, origin) {
  8355. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  8356. }
  8357. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8358. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  8359. }
  8360. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8361. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  8362. }
  8363. }
  8364. class Identifier extends IdentifierBase {
  8365. constructor() {
  8366. super(...arguments);
  8367. this.variable = null;
  8368. }
  8369. get isDestructuringDeoptimized() {
  8370. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  8371. }
  8372. set isDestructuringDeoptimized(value) {
  8373. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  8374. }
  8375. addExportedVariables(variables, exportNamesByVariable) {
  8376. if (exportNamesByVariable.has(this.variable)) {
  8377. variables.push(this.variable);
  8378. }
  8379. }
  8380. bind() {
  8381. if (!this.variable && is_reference(this, this.parent)) {
  8382. this.variable = this.scope.findVariable(this.name);
  8383. this.variable.addReference(this);
  8384. this.isVariableReference = true;
  8385. }
  8386. }
  8387. declare(kind, destructuredInitPath, init) {
  8388. let variable;
  8389. const { treeshake } = this.scope.context.options;
  8390. if (kind === 'parameter') {
  8391. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  8392. }
  8393. else {
  8394. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  8395. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  8396. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  8397. variable.markInitializersForDeoptimization();
  8398. }
  8399. }
  8400. return [(this.variable = variable)];
  8401. }
  8402. deoptimizeAssignment(destructuredInitPath, init) {
  8403. this.deoptimizePath(EMPTY_PATH);
  8404. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  8405. }
  8406. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  8407. return (destructuredInitPath.length > 0 &&
  8408. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8409. }
  8410. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  8411. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  8412. this.isDestructuringDeoptimized = true;
  8413. init.deoptimizeArgumentsOnInteractionAtPath({
  8414. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  8415. type: INTERACTION_ACCESSED
  8416. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  8417. }
  8418. const { propertyReadSideEffects } = this.scope.context.options
  8419. .treeshake;
  8420. if ((this.included ||=
  8421. destructuredInitPath.length > 0 &&
  8422. !context.brokenFlow &&
  8423. propertyReadSideEffects &&
  8424. (propertyReadSideEffects === 'always' ||
  8425. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  8426. if (this.variable && !this.variable.included) {
  8427. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8428. }
  8429. init.includePath(destructuredInitPath, context);
  8430. return true;
  8431. }
  8432. return false;
  8433. }
  8434. markDeclarationReached() {
  8435. this.variable.initReached = true;
  8436. }
  8437. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = parseAst_js.BLANK) {
  8438. if (this.variable) {
  8439. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  8440. if (name !== this.name) {
  8441. code.overwrite(this.start, this.end, name, {
  8442. contentOnly: true,
  8443. storeName: true
  8444. });
  8445. if (isShorthandProperty) {
  8446. code.prependRight(this.start, `${this.name}: `);
  8447. }
  8448. }
  8449. // In strict mode, any variable named "eval" must be the actual "eval" function
  8450. if (name === 'eval' &&
  8451. renderedParentType === parseAst_js.CallExpression &&
  8452. isCalleeOfRenderedParent) {
  8453. code.appendRight(this.start, '0, ');
  8454. }
  8455. }
  8456. }
  8457. }
  8458. function getSafeName(baseName, usedNames, forbiddenNames) {
  8459. let safeName = baseName;
  8460. let count = 1;
  8461. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  8462. safeName = `${baseName}$${toBase64(count++)}`;
  8463. }
  8464. usedNames.add(safeName);
  8465. return safeName;
  8466. }
  8467. class Scope {
  8468. constructor() {
  8469. this.children = [];
  8470. this.variables = new Map();
  8471. }
  8472. /*
  8473. Redeclaration rules:
  8474. - var can redeclare var
  8475. - in function scopes, function and var can redeclare function and var
  8476. - var is hoisted across scopes, function remains in the scope it is declared
  8477. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  8478. - function cannot redeclare catch scope parameters
  8479. - var can redeclare catch scope parameters in a way
  8480. - if the parameter is an identifier and not a pattern
  8481. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  8482. - const, let, class, and function except in the cases above cannot redeclare anything
  8483. */
  8484. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  8485. const name = identifier.name;
  8486. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  8487. if (existingVariable) {
  8488. if (kind === 'var' && existingVariable.kind === 'var') {
  8489. existingVariable.addDeclaration(identifier, init);
  8490. return existingVariable;
  8491. }
  8492. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  8493. }
  8494. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  8495. this.variables.set(name, newVariable);
  8496. return newVariable;
  8497. }
  8498. addHoistedVariable(name, variable) {
  8499. (this.hoistedVariables ||= new Map()).set(name, variable);
  8500. }
  8501. contains(name) {
  8502. return this.variables.has(name);
  8503. }
  8504. findVariable(_name) {
  8505. /* istanbul ignore next */
  8506. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  8507. }
  8508. }
  8509. class ChildScope extends Scope {
  8510. constructor(parent, context) {
  8511. super();
  8512. this.parent = parent;
  8513. this.context = context;
  8514. this.accessedOutsideVariables = new Map();
  8515. parent.children.push(this);
  8516. }
  8517. addAccessedDynamicImport(importExpression) {
  8518. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  8519. if (this.parent instanceof ChildScope) {
  8520. this.parent.addAccessedDynamicImport(importExpression);
  8521. }
  8522. }
  8523. addAccessedGlobals(globals, accessedGlobalsByScope) {
  8524. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  8525. for (const name of globals) {
  8526. accessedGlobals.add(name);
  8527. }
  8528. accessedGlobalsByScope.set(this, accessedGlobals);
  8529. if (this.parent instanceof ChildScope) {
  8530. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  8531. }
  8532. }
  8533. addNamespaceMemberAccess(name, variable) {
  8534. this.accessedOutsideVariables.set(name, variable);
  8535. this.parent.addNamespaceMemberAccess(name, variable);
  8536. }
  8537. addReturnExpression(expression) {
  8538. if (this.parent instanceof ChildScope) {
  8539. this.parent.addReturnExpression(expression);
  8540. }
  8541. }
  8542. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  8543. for (const variable of this.accessedOutsideVariables.values()) {
  8544. if (variable.included) {
  8545. usedNames.add(variable.getBaseVariableName());
  8546. if (format === 'system' && exportNamesByVariable.has(variable)) {
  8547. usedNames.add('exports');
  8548. }
  8549. }
  8550. }
  8551. const accessedGlobals = accessedGlobalsByScope.get(this);
  8552. if (accessedGlobals) {
  8553. for (const name of accessedGlobals) {
  8554. usedNames.add(name);
  8555. }
  8556. }
  8557. }
  8558. contains(name) {
  8559. return this.variables.has(name) || this.parent.contains(name);
  8560. }
  8561. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8562. const usedNames = new Set();
  8563. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  8564. if (this.accessedDynamicImports) {
  8565. for (const importExpression of this.accessedDynamicImports) {
  8566. if (importExpression.inlineNamespace) {
  8567. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  8568. }
  8569. }
  8570. }
  8571. for (const [name, variable] of this.variables) {
  8572. if (variable.included || variable.alwaysRendered) {
  8573. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  8574. }
  8575. }
  8576. for (const scope of this.children) {
  8577. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8578. }
  8579. }
  8580. findLexicalBoundary() {
  8581. return this.parent.findLexicalBoundary();
  8582. }
  8583. findGlobal(name) {
  8584. const variable = this.parent.findVariable(name);
  8585. this.accessedOutsideVariables.set(name, variable);
  8586. return variable;
  8587. }
  8588. findVariable(name) {
  8589. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8590. if (knownVariable) {
  8591. return knownVariable;
  8592. }
  8593. const variable = this.parent.findVariable(name);
  8594. this.accessedOutsideVariables.set(name, variable);
  8595. return variable;
  8596. }
  8597. }
  8598. function checkEffectForNodes(nodes, context) {
  8599. for (const node of nodes) {
  8600. if (node.hasEffects(context)) {
  8601. return true;
  8602. }
  8603. }
  8604. return false;
  8605. }
  8606. class MethodBase extends NodeBase {
  8607. constructor() {
  8608. super(...arguments);
  8609. this.accessedValue = null;
  8610. }
  8611. get computed() {
  8612. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  8613. }
  8614. set computed(value) {
  8615. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  8616. }
  8617. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8618. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8619. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8620. args: interaction.args,
  8621. type: INTERACTION_CALLED,
  8622. withNew: false
  8623. }, EMPTY_PATH, recursionTracker);
  8624. }
  8625. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8626. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8627. args: interaction.args,
  8628. type: INTERACTION_CALLED,
  8629. withNew: false
  8630. }, EMPTY_PATH, recursionTracker);
  8631. }
  8632. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8633. }
  8634. // As getter properties directly receive their values from fixed function
  8635. // expressions, there is no known situation where a getter is deoptimized.
  8636. deoptimizeCache() { }
  8637. deoptimizePath(path) {
  8638. this.getAccessedValue()[0].deoptimizePath(path);
  8639. }
  8640. getLiteralValueAtPath(path, recursionTracker, origin) {
  8641. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  8642. }
  8643. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8644. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8645. }
  8646. hasEffects(context) {
  8647. return this.key.hasEffects(context);
  8648. }
  8649. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8650. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8651. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8652. args: interaction.args,
  8653. type: INTERACTION_CALLED,
  8654. withNew: false
  8655. }, context);
  8656. }
  8657. // setters are only called for empty paths
  8658. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8659. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8660. args: interaction.args,
  8661. type: INTERACTION_CALLED,
  8662. withNew: false
  8663. }, context);
  8664. }
  8665. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  8666. }
  8667. getAccessedValue() {
  8668. if (this.accessedValue === null) {
  8669. if (this.kind === 'get') {
  8670. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  8671. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8672. }
  8673. else {
  8674. return (this.accessedValue = [this.value, false]);
  8675. }
  8676. }
  8677. return this.accessedValue;
  8678. }
  8679. }
  8680. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  8681. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  8682. class MethodDefinition extends MethodBase {
  8683. hasEffects(context) {
  8684. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  8685. }
  8686. }
  8687. class BlockScope extends ChildScope {
  8688. constructor(parent) {
  8689. super(parent, parent.context);
  8690. }
  8691. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  8692. if (kind === 'var') {
  8693. const name = identifier.name;
  8694. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  8695. if (existingVariable) {
  8696. if (existingVariable.kind === 'var' ||
  8697. (kind === 'var' && existingVariable.kind === 'parameter')) {
  8698. existingVariable.addDeclaration(identifier, init);
  8699. return existingVariable;
  8700. }
  8701. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  8702. }
  8703. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  8704. // Necessary to make sure the init is deoptimized for conditional declarations.
  8705. // We cannot call deoptimizePath here.
  8706. declaredVariable.markInitializersForDeoptimization();
  8707. // We add the variable to this and all parent scopes to reliably detect conflicts
  8708. this.addHoistedVariable(name, declaredVariable);
  8709. return declaredVariable;
  8710. }
  8711. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  8712. }
  8713. }
  8714. class StaticBlock extends NodeBase {
  8715. createScope(parentScope) {
  8716. this.scope = new BlockScope(parentScope);
  8717. }
  8718. hasEffects(context) {
  8719. for (const node of this.body) {
  8720. if (node.hasEffects(context))
  8721. return true;
  8722. }
  8723. return false;
  8724. }
  8725. include(context, includeChildrenRecursively) {
  8726. this.included = true;
  8727. for (const node of this.body) {
  8728. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8729. node.include(context, includeChildrenRecursively);
  8730. }
  8731. }
  8732. render(code, options) {
  8733. if (this.body.length > 0) {
  8734. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  8735. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  8736. }
  8737. else {
  8738. super.render(code, options);
  8739. }
  8740. }
  8741. }
  8742. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  8743. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  8744. function isStaticBlock(statement) {
  8745. return statement.type === parseAst_js.StaticBlock;
  8746. }
  8747. class ClassNode extends NodeBase {
  8748. constructor() {
  8749. super(...arguments);
  8750. this.objectEntity = null;
  8751. }
  8752. createScope(parentScope) {
  8753. this.scope = new ChildScope(parentScope, parentScope.context);
  8754. }
  8755. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8756. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8757. }
  8758. deoptimizeCache() {
  8759. this.getObjectEntity().deoptimizeAllProperties();
  8760. }
  8761. deoptimizePath(path) {
  8762. this.getObjectEntity().deoptimizePath(path);
  8763. }
  8764. getLiteralValueAtPath(path, recursionTracker, origin) {
  8765. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8766. }
  8767. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8768. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8769. }
  8770. hasEffects(context) {
  8771. if (!this.deoptimized)
  8772. this.applyDeoptimizations();
  8773. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  8774. this.id?.markDeclarationReached();
  8775. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  8776. }
  8777. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8778. return interaction.type === INTERACTION_CALLED && path.length === 0
  8779. ? !interaction.withNew ||
  8780. (this.classConstructor === null
  8781. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  8782. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8783. false
  8784. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8785. }
  8786. include(context, includeChildrenRecursively) {
  8787. if (!this.included)
  8788. this.includeNode(context);
  8789. this.superClass?.include(context, includeChildrenRecursively);
  8790. this.body.include(context, includeChildrenRecursively);
  8791. for (const decorator of this.decorators)
  8792. decorator.include(context, includeChildrenRecursively);
  8793. if (this.id) {
  8794. this.id.markDeclarationReached();
  8795. this.id.include(context, includeChildrenRecursively);
  8796. }
  8797. }
  8798. initialise() {
  8799. super.initialise();
  8800. this.id?.declare('class', EMPTY_PATH, this);
  8801. for (const method of this.body.body) {
  8802. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8803. this.classConstructor = method;
  8804. return;
  8805. }
  8806. }
  8807. this.classConstructor = null;
  8808. }
  8809. applyDeoptimizations() {
  8810. this.deoptimized = true;
  8811. for (const definition of this.body.body) {
  8812. if (!isStaticBlock(definition) &&
  8813. !(definition.static ||
  8814. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8815. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8816. definition.deoptimizePath(UNKNOWN_PATH);
  8817. }
  8818. }
  8819. this.scope.context.requestTreeshakingPass();
  8820. }
  8821. getObjectEntity() {
  8822. if (this.objectEntity !== null) {
  8823. return this.objectEntity;
  8824. }
  8825. const staticProperties = [];
  8826. const dynamicMethods = [];
  8827. for (const definition of this.body.body) {
  8828. if (isStaticBlock(definition))
  8829. continue;
  8830. const properties = definition.static ? staticProperties : dynamicMethods;
  8831. const definitionKind = definition.kind;
  8832. // Note that class fields do not end up on the prototype
  8833. if (properties === dynamicMethods && !definitionKind)
  8834. continue;
  8835. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8836. let key;
  8837. if (definition.computed) {
  8838. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8839. if (typeof keyValue === 'symbol') {
  8840. properties.push({ key: UnknownKey, kind, property: definition });
  8841. continue;
  8842. }
  8843. else {
  8844. key = String(keyValue);
  8845. }
  8846. }
  8847. else {
  8848. key =
  8849. definition.key instanceof Identifier
  8850. ? definition.key.name
  8851. : String(definition.key.value);
  8852. }
  8853. properties.push({ key, kind, property: definition });
  8854. }
  8855. staticProperties.unshift({
  8856. key: 'prototype',
  8857. kind: 'init',
  8858. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  8859. });
  8860. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8861. }
  8862. }
  8863. ClassNode.prototype.includeNode = onlyIncludeSelf;
  8864. class ClassDeclaration extends ClassNode {
  8865. initialise() {
  8866. super.initialise();
  8867. if (this.id !== null) {
  8868. this.id.variable.isId = true;
  8869. }
  8870. }
  8871. parseNode(esTreeNode) {
  8872. if (esTreeNode.id !== null) {
  8873. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  8874. }
  8875. return super.parseNode(esTreeNode);
  8876. }
  8877. render(code, options) {
  8878. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  8879. if (this.id) {
  8880. const { variable, name } = this.id;
  8881. if (format === 'system' && exportNamesByVariable.has(variable)) {
  8882. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  8883. }
  8884. const renderedVariable = variable.getName(getPropertyAccess);
  8885. if (renderedVariable !== name) {
  8886. this.decorators.map(decorator => decorator.render(code, options));
  8887. this.superClass?.render(code, options);
  8888. this.body.render(code, {
  8889. ...options,
  8890. useOriginalName: (_variable) => _variable === variable
  8891. });
  8892. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  8893. code.prependLeft(this.end, ';');
  8894. return;
  8895. }
  8896. }
  8897. super.render(code, options);
  8898. }
  8899. applyDeoptimizations() {
  8900. super.applyDeoptimizations();
  8901. const { id, scope } = this;
  8902. if (id) {
  8903. const { name, variable } = id;
  8904. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  8905. if (accessedVariable !== variable) {
  8906. accessedVariable.forbidName(name);
  8907. }
  8908. }
  8909. }
  8910. }
  8911. }
  8912. class ArgumentsVariable extends LocalVariable {
  8913. constructor(context) {
  8914. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  8915. }
  8916. addArgumentToBeDeoptimized(_argument) { }
  8917. // Only If there is at least one reference, then we need to track all
  8918. // arguments in order to be able to deoptimize them.
  8919. addReference() {
  8920. this.deoptimizedArguments = [];
  8921. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  8922. }
  8923. hasEffectsOnInteractionAtPath(path, { type }) {
  8924. return type !== INTERACTION_ACCESSED || path.length > 1;
  8925. }
  8926. includePath(path, context) {
  8927. super.includePath(path, context);
  8928. for (const argument of this.deoptimizedArguments) {
  8929. argument.deoptimizePath(UNKNOWN_PATH);
  8930. }
  8931. this.deoptimizedArguments.length = 0;
  8932. }
  8933. }
  8934. function addArgumentToBeDeoptimized(argument) {
  8935. if (this.included) {
  8936. argument.deoptimizePath(UNKNOWN_PATH);
  8937. }
  8938. else {
  8939. this.deoptimizedArguments?.push(argument);
  8940. }
  8941. }
  8942. const MAX_TRACKED_INTERACTIONS = 20;
  8943. const NO_INTERACTIONS = parseAst_js.EMPTY_ARRAY;
  8944. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  8945. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  8946. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  8947. class ParameterVariable extends LocalVariable {
  8948. constructor(name, declarator, argumentPath, context) {
  8949. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  8950. this.includedPathTracker = new IncludedTopLevelPathTracker();
  8951. this.argumentsToBeDeoptimized = new Set();
  8952. this.deoptimizationInteractions = [];
  8953. this.deoptimizations = new EntityPathTracker();
  8954. this.deoptimizedFields = new Set();
  8955. this.expressionsDependingOnKnownValue = [];
  8956. this.knownValue = null;
  8957. this.knownValueLiteral = UnknownValue;
  8958. }
  8959. addArgumentForDeoptimization(entity) {
  8960. this.updateKnownValue(entity);
  8961. if (entity === UNKNOWN_EXPRESSION) {
  8962. // As unknown expressions fully deoptimize all interactions, we can clear
  8963. // the interaction cache at this point provided we keep this optimization
  8964. // in mind when adding new interactions
  8965. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  8966. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  8967. for (const { interaction } of this.deoptimizationInteractions) {
  8968. deoptimizeInteraction(interaction);
  8969. }
  8970. this.deoptimizationInteractions = NO_INTERACTIONS;
  8971. }
  8972. }
  8973. else if (this.deoptimizedFields.has(UnknownKey)) {
  8974. // This means that we already deoptimized all interactions and no longer
  8975. // track them
  8976. entity.deoptimizePath([...this.initPath, UnknownKey]);
  8977. }
  8978. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  8979. this.argumentsToBeDeoptimized.add(entity);
  8980. for (const field of this.deoptimizedFields) {
  8981. entity.deoptimizePath([...this.initPath, field]);
  8982. }
  8983. for (const { interaction, path } of this.deoptimizationInteractions) {
  8984. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  8985. }
  8986. }
  8987. }
  8988. /** This says we should not make assumptions about the value of the parameter.
  8989. * This is different from deoptimization that will also cause argument values
  8990. * to be deoptimized. */
  8991. markReassigned() {
  8992. if (this.isReassigned) {
  8993. return;
  8994. }
  8995. super.markReassigned();
  8996. for (const expression of this.expressionsDependingOnKnownValue) {
  8997. expression.deoptimizeCache();
  8998. }
  8999. this.expressionsDependingOnKnownValue = parseAst_js.EMPTY_ARRAY;
  9000. }
  9001. deoptimizeCache() {
  9002. this.markReassigned();
  9003. }
  9004. /**
  9005. * Update the known value of the parameter variable.
  9006. * Must be called for every function call, so it can track all the arguments,
  9007. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  9008. * @param argument The argument of the function call
  9009. */
  9010. updateKnownValue(argument) {
  9011. if (this.isReassigned) {
  9012. return;
  9013. }
  9014. if (this.knownValue === null) {
  9015. this.knownValue = argument;
  9016. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  9017. return;
  9018. }
  9019. // the same literal or identifier, do nothing
  9020. if (this.knownValue === argument ||
  9021. (this.knownValue instanceof Identifier &&
  9022. argument instanceof Identifier &&
  9023. this.knownValue.variable === argument.variable)) {
  9024. return;
  9025. }
  9026. const { knownValueLiteral } = this;
  9027. if (typeof knownValueLiteral === 'symbol' ||
  9028. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  9029. knownValueLiteral) {
  9030. this.markReassigned();
  9031. }
  9032. }
  9033. /**
  9034. * This function freezes the known value of the parameter variable,
  9035. * so the optimization starts with a certain ExpressionEntity.
  9036. * The optimization can be undone by calling `markReassigned`.
  9037. * @returns the frozen value
  9038. */
  9039. getKnownValue() {
  9040. return this.knownValue || UNKNOWN_EXPRESSION;
  9041. }
  9042. getLiteralValueAtPath(path, recursionTracker, origin) {
  9043. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9044. return UnknownValue;
  9045. }
  9046. const knownValue = this.getKnownValue();
  9047. this.expressionsDependingOnKnownValue.push(origin);
  9048. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  9049. }
  9050. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9051. const { type } = interaction;
  9052. if (this.isReassigned ||
  9053. type === INTERACTION_ASSIGNED ||
  9054. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9055. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  9056. }
  9057. return (!(type === INTERACTION_CALLED
  9058. ? (interaction.withNew
  9059. ? context.instantiated
  9060. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  9061. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  9062. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  9063. }
  9064. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  9065. // For performance reasons, we fully deoptimize all deeper interactions
  9066. if (path.length >= 2 ||
  9067. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  9068. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  9069. (path.length === 1 &&
  9070. (this.deoptimizedFields.has(UnknownKey) ||
  9071. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  9072. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  9073. deoptimizeInteraction(interaction);
  9074. return;
  9075. }
  9076. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  9077. for (const entity of this.argumentsToBeDeoptimized) {
  9078. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  9079. }
  9080. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  9081. this.deoptimizationInteractions.push({
  9082. interaction,
  9083. path
  9084. });
  9085. }
  9086. }
  9087. }
  9088. deoptimizePath(path) {
  9089. if (path.length === 0) {
  9090. this.markReassigned();
  9091. return;
  9092. }
  9093. if (this.deoptimizedFields.has(UnknownKey)) {
  9094. return;
  9095. }
  9096. const key = path[0];
  9097. if (this.deoptimizedFields.has(key)) {
  9098. return;
  9099. }
  9100. this.deoptimizedFields.add(key);
  9101. for (const entity of this.argumentsToBeDeoptimized) {
  9102. // We do not need a recursion tracker here as we already track whether
  9103. // this field is deoptimized
  9104. entity.deoptimizePath([...this.initPath, key]);
  9105. }
  9106. if (key === UnknownKey) {
  9107. // save some memory
  9108. this.deoptimizationInteractions = NO_INTERACTIONS;
  9109. this.deoptimizations = EMPTY_PATH_TRACKER;
  9110. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  9111. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  9112. }
  9113. }
  9114. getReturnExpressionWhenCalledAtPath(path) {
  9115. // We deoptimize everything that is called as that will trivially deoptimize
  9116. // the corresponding return expressions as well and avoid badly performing
  9117. // and complicated alternatives
  9118. if (path.length === 0) {
  9119. this.deoptimizePath(UNKNOWN_PATH);
  9120. }
  9121. else if (!this.deoptimizedFields.has(path[0])) {
  9122. this.deoptimizePath([path[0]]);
  9123. }
  9124. return UNKNOWN_RETURN_EXPRESSION;
  9125. }
  9126. includeArgumentPaths(entity, context) {
  9127. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  9128. }
  9129. }
  9130. class ThisVariable extends ParameterVariable {
  9131. constructor(context) {
  9132. super('this', null, EMPTY_PATH, context);
  9133. }
  9134. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9135. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  9136. }
  9137. }
  9138. class CatchBodyScope extends ChildScope {
  9139. constructor(parent) {
  9140. super(parent, parent.context);
  9141. this.parent = parent;
  9142. }
  9143. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9144. if (kind === 'var') {
  9145. const name = identifier.name;
  9146. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9147. if (existingVariable) {
  9148. const existingKind = existingVariable.kind;
  9149. if (existingKind === 'parameter' &&
  9150. // If this is a destructured parameter, it is forbidden to redeclare
  9151. existingVariable.declarations[0].parent.type === parseAst_js.CatchClause) {
  9152. // If this is a var with the same name as the catch scope parameter,
  9153. // the assignment actually goes to the parameter and the var is
  9154. // hoisted without assignment. Locally, it is shadowed by the
  9155. // parameter
  9156. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  9157. // To avoid the need to rewrite the declaration, we link the variable
  9158. // names. If we ever implement a logic that splits initialization and
  9159. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  9160. // removed again.
  9161. // We do not need to check whether there already is a linked
  9162. // variable because then declaredVariable would be that linked
  9163. // variable.
  9164. existingVariable.renderLikeHoisted(declaredVariable);
  9165. this.addHoistedVariable(name, declaredVariable);
  9166. return declaredVariable;
  9167. }
  9168. if (existingKind === 'var') {
  9169. existingVariable.addDeclaration(identifier, init);
  9170. return existingVariable;
  9171. }
  9172. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9173. }
  9174. // We only add parameters to parameter scopes
  9175. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9176. // Necessary to make sure the init is deoptimized for conditional declarations.
  9177. // We cannot call deoptimizePath here.
  9178. declaredVariable.markInitializersForDeoptimization();
  9179. // We add the variable to this and all parent scopes to reliably detect conflicts
  9180. this.addHoistedVariable(name, declaredVariable);
  9181. return declaredVariable;
  9182. }
  9183. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9184. }
  9185. }
  9186. class FunctionBodyScope extends ChildScope {
  9187. constructor(parent) {
  9188. super(parent, parent.context);
  9189. }
  9190. // There is stuff that is only allowed in function scopes, i.e. functions can
  9191. // be redeclared, functions and var can redeclare each other
  9192. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9193. const name = identifier.name;
  9194. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9195. if (existingVariable) {
  9196. const existingKind = existingVariable.kind;
  9197. if ((kind === 'var' || kind === 'function') &&
  9198. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  9199. existingVariable.addDeclaration(identifier, init);
  9200. return existingVariable;
  9201. }
  9202. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9203. }
  9204. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  9205. this.variables.set(name, newVariable);
  9206. return newVariable;
  9207. }
  9208. }
  9209. class ParameterScope extends ChildScope {
  9210. constructor(parent, isCatchScope) {
  9211. super(parent, parent.context);
  9212. this.hasRest = false;
  9213. this.parameters = [];
  9214. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  9215. }
  9216. /**
  9217. * Adds a parameter to this scope. Parameters must be added in the correct
  9218. * order, i.e. from left to right.
  9219. */
  9220. addParameterDeclaration(identifier, argumentPath) {
  9221. const { name, start } = identifier;
  9222. const existingParameter = this.variables.get(name);
  9223. if (existingParameter) {
  9224. return this.context.error(parseAst_js.logDuplicateArgumentNameError(name), start);
  9225. }
  9226. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  9227. this.variables.set(name, variable);
  9228. // We also add it to the body scope to detect name conflicts with local
  9229. // variables. We still need the intermediate scope, though, as parameter
  9230. // defaults are NOT taken from the body scope but from the parameters or
  9231. // outside scope.
  9232. this.bodyScope.addHoistedVariable(name, variable);
  9233. return variable;
  9234. }
  9235. addParameterVariables(parameters, hasRest) {
  9236. this.parameters = parameters;
  9237. for (const parameterList of parameters) {
  9238. for (const parameter of parameterList) {
  9239. parameter.alwaysRendered = true;
  9240. }
  9241. }
  9242. this.hasRest = hasRest;
  9243. }
  9244. includeCallArguments({ args }, context) {
  9245. let calledFromTryStatement = false;
  9246. let argumentIncluded = false;
  9247. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  9248. let lastExplicitlyIncludedIndex = args.length - 1;
  9249. // If there is a SpreadElement, we need to include all arguments after it
  9250. // because we no longer know which argument corresponds to which parameter.
  9251. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9252. const argument = args[argumentIndex];
  9253. if (argument instanceof SpreadElement && !argumentIncluded) {
  9254. argumentIncluded = true;
  9255. lastExplicitlyIncludedIndex = argumentIndex - 1;
  9256. }
  9257. if (argumentIncluded) {
  9258. argument.includePath(UNKNOWN_PATH, context);
  9259. argument.include(context, false);
  9260. }
  9261. }
  9262. // Now we go backwards either starting from the last argument or before the
  9263. // first SpreadElement to ensure all arguments before are included as needed
  9264. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  9265. const parameterVariables = this.parameters[index - 1] || restParameter;
  9266. const argument = args[index];
  9267. if (parameterVariables) {
  9268. calledFromTryStatement = false;
  9269. if (parameterVariables.length === 0) {
  9270. // handle empty destructuring to avoid destructuring undefined
  9271. argumentIncluded = true;
  9272. }
  9273. else {
  9274. for (const parameterVariable of parameterVariables) {
  9275. if (parameterVariable.calledFromTryStatement) {
  9276. calledFromTryStatement = true;
  9277. }
  9278. if (parameterVariable.included) {
  9279. argumentIncluded = true;
  9280. if (calledFromTryStatement) {
  9281. argument.include(context, true);
  9282. }
  9283. else {
  9284. parameterVariable.includeArgumentPaths(argument, context);
  9285. argument.include(context, false);
  9286. }
  9287. }
  9288. }
  9289. }
  9290. }
  9291. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  9292. argumentIncluded = true;
  9293. argument.include(context, calledFromTryStatement);
  9294. }
  9295. }
  9296. }
  9297. }
  9298. class ReturnValueScope extends ParameterScope {
  9299. constructor() {
  9300. super(...arguments);
  9301. this.returnExpression = null;
  9302. this.returnExpressions = [];
  9303. }
  9304. addReturnExpression(expression) {
  9305. this.returnExpressions.push(expression);
  9306. }
  9307. deoptimizeArgumentsOnCall({ args }) {
  9308. const { parameters } = this;
  9309. let position = 0;
  9310. for (; position < args.length - 1; position++) {
  9311. // Only the "this" argument arg[0] can be null
  9312. const argument = args[position + 1];
  9313. if (argument instanceof SpreadElement) {
  9314. // This deoptimizes the current and remaining parameters and arguments
  9315. for (; position < parameters.length; position++) {
  9316. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  9317. for (const variable of parameters[position]) {
  9318. variable.markReassigned();
  9319. }
  9320. }
  9321. break;
  9322. }
  9323. if (this.hasRest && position >= parameters.length - 1) {
  9324. argument.deoptimizePath(UNKNOWN_PATH);
  9325. }
  9326. else {
  9327. const variables = parameters[position];
  9328. if (variables) {
  9329. for (const variable of variables) {
  9330. variable.addArgumentForDeoptimization(argument);
  9331. }
  9332. }
  9333. this.addArgumentToBeDeoptimized(argument);
  9334. }
  9335. }
  9336. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  9337. for (; position < nonRestParameterLength; position++) {
  9338. for (const variable of parameters[position]) {
  9339. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  9340. }
  9341. }
  9342. }
  9343. getReturnExpression() {
  9344. if (this.returnExpression === null)
  9345. this.updateReturnExpression();
  9346. return this.returnExpression;
  9347. }
  9348. deoptimizeAllParameters() {
  9349. for (const parameter of this.parameters) {
  9350. for (const variable of parameter) {
  9351. variable.deoptimizePath(UNKNOWN_PATH);
  9352. variable.markReassigned();
  9353. }
  9354. }
  9355. }
  9356. reassignAllParameters() {
  9357. for (const parameter of this.parameters) {
  9358. for (const variable of parameter) {
  9359. variable.markReassigned();
  9360. }
  9361. }
  9362. }
  9363. addArgumentToBeDeoptimized(_argument) { }
  9364. updateReturnExpression() {
  9365. if (this.returnExpressions.length === 1) {
  9366. this.returnExpression = this.returnExpressions[0];
  9367. }
  9368. else {
  9369. this.returnExpression = UNKNOWN_EXPRESSION;
  9370. for (const expression of this.returnExpressions) {
  9371. expression.deoptimizePath(UNKNOWN_PATH);
  9372. }
  9373. }
  9374. }
  9375. }
  9376. class FunctionScope extends ReturnValueScope {
  9377. constructor(parent, functionNode) {
  9378. super(parent, false);
  9379. this.functionNode = functionNode;
  9380. const { context } = parent;
  9381. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  9382. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  9383. }
  9384. findLexicalBoundary() {
  9385. return this;
  9386. }
  9387. includeCallArguments(interaction, context) {
  9388. super.includeCallArguments(interaction, context);
  9389. if (this.argumentsVariable.included) {
  9390. const { args } = interaction;
  9391. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9392. const argument = args[argumentIndex];
  9393. if (argument) {
  9394. argument.includePath(UNKNOWN_PATH, context);
  9395. argument.include(context, false);
  9396. }
  9397. }
  9398. }
  9399. }
  9400. addArgumentToBeDeoptimized(argument) {
  9401. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  9402. }
  9403. }
  9404. class ExpressionStatement extends NodeBase {
  9405. initialise() {
  9406. super.initialise();
  9407. if (this.directive &&
  9408. this.directive !== 'use strict' &&
  9409. this.parent.type === parseAst_js.Program) {
  9410. this.scope.context.log(parseAst_js.LOGLEVEL_WARN,
  9411. // This is necessary, because either way (deleting or not) can lead to errors.
  9412. parseAst_js.logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  9413. }
  9414. }
  9415. removeAnnotations(code) {
  9416. this.expression.removeAnnotations(code);
  9417. }
  9418. render(code, options) {
  9419. super.render(code, options);
  9420. if (code.original[this.end - 1] !== ';') {
  9421. code.appendLeft(this.end, ';');
  9422. }
  9423. }
  9424. shouldBeIncluded(context) {
  9425. if (this.directive && this.directive !== 'use strict')
  9426. return this.parent.type !== parseAst_js.Program;
  9427. return super.shouldBeIncluded(context);
  9428. }
  9429. }
  9430. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9431. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9432. class BlockStatement extends NodeBase {
  9433. get deoptimizeBody() {
  9434. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  9435. }
  9436. set deoptimizeBody(value) {
  9437. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  9438. }
  9439. get directlyIncluded() {
  9440. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  9441. }
  9442. set directlyIncluded(value) {
  9443. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  9444. }
  9445. addImplicitReturnExpressionToScope() {
  9446. const lastStatement = this.body[this.body.length - 1];
  9447. if (!lastStatement || lastStatement.type !== parseAst_js.ReturnStatement) {
  9448. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  9449. }
  9450. }
  9451. createScope(parentScope) {
  9452. this.scope = this.parent.preventChildBlockScope
  9453. ? parentScope
  9454. : new BlockScope(parentScope);
  9455. }
  9456. hasEffects(context) {
  9457. if (this.deoptimizeBody)
  9458. return true;
  9459. for (const node of this.body) {
  9460. if (context.brokenFlow)
  9461. break;
  9462. if (node.hasEffects(context))
  9463. return true;
  9464. }
  9465. return false;
  9466. }
  9467. include(context, includeChildrenRecursively) {
  9468. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  9469. this.included = true;
  9470. this.directlyIncluded = true;
  9471. if (this.deoptimizeBody)
  9472. includeChildrenRecursively = true;
  9473. for (const node of this.body) {
  9474. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9475. node.include(context, includeChildrenRecursively);
  9476. }
  9477. }
  9478. }
  9479. initialise() {
  9480. super.initialise();
  9481. const firstBodyStatement = this.body[0];
  9482. this.deoptimizeBody =
  9483. firstBodyStatement instanceof ExpressionStatement &&
  9484. firstBodyStatement.directive === 'use asm';
  9485. }
  9486. render(code, options) {
  9487. if (this.body.length > 0) {
  9488. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  9489. }
  9490. else {
  9491. super.render(code, options);
  9492. }
  9493. }
  9494. }
  9495. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9496. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9497. class RestElement extends NodeBase {
  9498. constructor() {
  9499. super(...arguments);
  9500. this.declarationInit = null;
  9501. }
  9502. addExportedVariables(variables, exportNamesByVariable) {
  9503. this.argument.addExportedVariables(variables, exportNamesByVariable);
  9504. }
  9505. declare(kind, destructuredInitPath, init) {
  9506. this.declarationInit = init;
  9507. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  9508. }
  9509. deoptimizeAssignment(destructuredInitPath, init) {
  9510. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  9511. }
  9512. deoptimizePath(path) {
  9513. if (path.length === 0) {
  9514. this.argument.deoptimizePath(EMPTY_PATH);
  9515. }
  9516. }
  9517. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9518. return (path.length > 0 ||
  9519. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9520. }
  9521. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  9522. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  9523. }
  9524. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  9525. return (this.included =
  9526. this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init) || this.included);
  9527. }
  9528. include(context, includeChildrenRecursively) {
  9529. if (!this.included)
  9530. this.includeNode(context);
  9531. // This should just include the identifier, its properties should be
  9532. // included where the variable is used.
  9533. this.argument.include(context, includeChildrenRecursively);
  9534. }
  9535. markDeclarationReached() {
  9536. this.argument.markDeclarationReached();
  9537. }
  9538. applyDeoptimizations() {
  9539. this.deoptimized = true;
  9540. if (this.declarationInit !== null) {
  9541. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  9542. this.scope.context.requestTreeshakingPass();
  9543. }
  9544. }
  9545. }
  9546. RestElement.prototype.includeNode = onlyIncludeSelf;
  9547. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  9548. ? destructuredInitPath
  9549. : [...destructuredInitPath, UnknownKey];
  9550. class FunctionBase extends NodeBase {
  9551. constructor() {
  9552. super(...arguments);
  9553. this.parameterVariableValuesDeoptimized = false;
  9554. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  9555. }
  9556. get async() {
  9557. return isFlagSet(this.flags, 256 /* Flag.async */);
  9558. }
  9559. set async(value) {
  9560. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  9561. }
  9562. get deoptimizedReturn() {
  9563. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  9564. }
  9565. set deoptimizedReturn(value) {
  9566. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  9567. }
  9568. get generator() {
  9569. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  9570. }
  9571. set generator(value) {
  9572. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  9573. }
  9574. get hasCachedEffects() {
  9575. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  9576. }
  9577. set hasCachedEffects(value) {
  9578. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  9579. }
  9580. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9581. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  9582. this.scope.deoptimizeArgumentsOnCall(interaction);
  9583. }
  9584. else {
  9585. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9586. }
  9587. }
  9588. deoptimizePath(path) {
  9589. this.getObjectEntity().deoptimizePath(path);
  9590. if (path.length === 1 && path[0] === UnknownKey) {
  9591. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  9592. // which means the return expression and parameters need to be reassigned
  9593. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9594. this.scope.deoptimizeAllParameters();
  9595. }
  9596. }
  9597. getLiteralValueAtPath(path, recursionTracker, origin) {
  9598. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9599. }
  9600. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9601. if (path.length > 0) {
  9602. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9603. }
  9604. if (this.async) {
  9605. if (!this.deoptimizedReturn) {
  9606. this.deoptimizedReturn = true;
  9607. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9608. this.scope.context.requestTreeshakingPass();
  9609. }
  9610. return UNKNOWN_RETURN_EXPRESSION;
  9611. }
  9612. return [this.scope.getReturnExpression(), false];
  9613. }
  9614. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9615. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  9616. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9617. }
  9618. if (this.hasCachedEffects) {
  9619. return true;
  9620. }
  9621. if (this.async) {
  9622. const { propertyReadSideEffects } = this.scope.context.options
  9623. .treeshake;
  9624. const returnExpression = this.scope.getReturnExpression();
  9625. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  9626. (propertyReadSideEffects &&
  9627. (propertyReadSideEffects === 'always' ||
  9628. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  9629. this.hasCachedEffects = true;
  9630. return true;
  9631. }
  9632. }
  9633. const { propertyReadSideEffects } = this.scope.context.options
  9634. .treeshake;
  9635. for (let index = 0; index < this.params.length; index++) {
  9636. const parameter = this.params[index];
  9637. if (parameter.hasEffects(context) ||
  9638. (propertyReadSideEffects &&
  9639. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  9640. this.hasCachedEffects = true;
  9641. return true;
  9642. }
  9643. }
  9644. return false;
  9645. }
  9646. /**
  9647. * If the function (expression or declaration) is only used as function calls
  9648. */
  9649. onlyFunctionCallUsed() {
  9650. let variable = null;
  9651. if (this.parent.type === parseAst_js.VariableDeclarator) {
  9652. variable = this.parent.id.variable ?? null;
  9653. }
  9654. if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
  9655. variable = this.parent.variable;
  9656. }
  9657. return variable?.getOnlyFunctionCallUsed() ?? false;
  9658. }
  9659. include(context, includeChildrenRecursively) {
  9660. if (!this.included)
  9661. this.includeNode(context);
  9662. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  9663. this.parameterVariableValuesDeoptimized = true;
  9664. this.scope.reassignAllParameters();
  9665. }
  9666. const { brokenFlow } = context;
  9667. context.brokenFlow = false;
  9668. this.body.include(context, includeChildrenRecursively);
  9669. context.brokenFlow = brokenFlow;
  9670. }
  9671. initialise() {
  9672. super.initialise();
  9673. if (this.body instanceof BlockStatement) {
  9674. this.body.addImplicitReturnExpressionToScope();
  9675. }
  9676. else {
  9677. this.scope.addReturnExpression(this.body);
  9678. }
  9679. if (this.annotations &&
  9680. this.scope.context.options.treeshake.annotations) {
  9681. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  9682. }
  9683. }
  9684. parseNode(esTreeNode) {
  9685. const { body, params } = esTreeNode;
  9686. const { scope } = this;
  9687. const { bodyScope, context } = scope;
  9688. // We need to ensure that parameters are declared before the body is parsed
  9689. // so that the scope already knows all parameters and can detect conflicts
  9690. // when parsing the body.
  9691. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  9692. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  9693. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  9694. return super.parseNode(esTreeNode);
  9695. }
  9696. }
  9697. FunctionBase.prototype.preventChildBlockScope = true;
  9698. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9699. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  9700. class FunctionNode extends FunctionBase {
  9701. constructor() {
  9702. super(...arguments);
  9703. this.objectEntity = null;
  9704. }
  9705. createScope(parentScope) {
  9706. this.scope = new FunctionScope(parentScope, this);
  9707. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  9708. // This makes sure that all deoptimizations of "this" are applied to the
  9709. // constructed entity.
  9710. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  9711. }
  9712. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9713. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9714. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  9715. // args[0] is the "this" argument
  9716. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  9717. }
  9718. }
  9719. hasEffects(context) {
  9720. if (this.annotationNoSideEffects) {
  9721. return false;
  9722. }
  9723. return !!this.id?.hasEffects(context);
  9724. }
  9725. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9726. if (this.annotationNoSideEffects &&
  9727. path.length === 0 &&
  9728. interaction.type === INTERACTION_CALLED) {
  9729. return false;
  9730. }
  9731. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  9732. return true;
  9733. }
  9734. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  9735. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  9736. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  9737. const { brokenFlow, ignore, replacedVariableInits } = context;
  9738. context.ignore = {
  9739. breaks: false,
  9740. continues: false,
  9741. labels: new Set(),
  9742. returnYield: true,
  9743. this: interaction.withNew
  9744. };
  9745. if (this.body.hasEffects(context)) {
  9746. this.hasCachedEffects = true;
  9747. return true;
  9748. }
  9749. context.brokenFlow = brokenFlow;
  9750. if (thisInit) {
  9751. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  9752. }
  9753. else {
  9754. replacedVariableInits.delete(this.scope.thisVariable);
  9755. }
  9756. context.ignore = ignore;
  9757. }
  9758. return false;
  9759. }
  9760. include(context, includeChildrenRecursively) {
  9761. super.include(context, includeChildrenRecursively);
  9762. this.id?.include(context, includeChildrenRecursively);
  9763. const hasArguments = this.scope.argumentsVariable.included;
  9764. for (const parameter of this.params) {
  9765. if (!(parameter instanceof Identifier) || hasArguments) {
  9766. parameter.include(context, includeChildrenRecursively);
  9767. }
  9768. }
  9769. }
  9770. includeNode(context) {
  9771. this.included = true;
  9772. const hasArguments = this.scope.argumentsVariable.included;
  9773. for (const parameter of this.params) {
  9774. if (!(parameter instanceof Identifier) || hasArguments) {
  9775. parameter.includePath(UNKNOWN_PATH, context);
  9776. }
  9777. }
  9778. }
  9779. initialise() {
  9780. super.initialise();
  9781. this.id?.declare('function', EMPTY_PATH, this);
  9782. }
  9783. getObjectEntity() {
  9784. if (this.objectEntity !== null) {
  9785. return this.objectEntity;
  9786. }
  9787. return (this.objectEntity = new ObjectEntity([
  9788. {
  9789. key: 'prototype',
  9790. kind: 'init',
  9791. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  9792. }
  9793. ], OBJECT_PROTOTYPE));
  9794. }
  9795. }
  9796. class FunctionDeclaration extends FunctionNode {
  9797. initialise() {
  9798. super.initialise();
  9799. if (this.id !== null) {
  9800. this.id.variable.isId = true;
  9801. }
  9802. }
  9803. onlyFunctionCallUsed() {
  9804. // call super.onlyFunctionCallUsed for export default anonymous function
  9805. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  9806. }
  9807. parseNode(esTreeNode) {
  9808. if (esTreeNode.id !== null) {
  9809. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  9810. }
  9811. return super.parseNode(esTreeNode);
  9812. }
  9813. }
  9814. // The header ends at the first non-white-space after "default"
  9815. function getDeclarationStart(code, start) {
  9816. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  9817. }
  9818. function getFunctionIdInsertPosition(code, start) {
  9819. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  9820. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  9821. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  9822. if (generatorStarPos === -1) {
  9823. return declarationEnd;
  9824. }
  9825. return declarationEnd + generatorStarPos + 1;
  9826. }
  9827. class ExportDefaultDeclaration extends NodeBase {
  9828. include(context, includeChildrenRecursively) {
  9829. this.included = true;
  9830. this.declaration.include(context, includeChildrenRecursively);
  9831. if (includeChildrenRecursively) {
  9832. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  9833. }
  9834. }
  9835. includePath(path, context) {
  9836. this.included = true;
  9837. this.declaration.includePath(path, context);
  9838. }
  9839. initialise() {
  9840. super.initialise();
  9841. const declaration = this.declaration;
  9842. this.declarationName =
  9843. (declaration.id && declaration.id.name) || this.declaration.name;
  9844. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  9845. this.scope.context.addExport(this);
  9846. }
  9847. removeAnnotations(code) {
  9848. this.declaration.removeAnnotations(code);
  9849. }
  9850. render(code, options, nodeRenderOptions) {
  9851. const { start, end } = nodeRenderOptions;
  9852. const declarationStart = getDeclarationStart(code.original, this.start);
  9853. if (this.declaration instanceof FunctionDeclaration) {
  9854. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9855. ? getFunctionIdInsertPosition(code.original, declarationStart)
  9856. : null, options);
  9857. }
  9858. else if (this.declaration instanceof ClassDeclaration) {
  9859. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9860. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  9861. : null, options);
  9862. }
  9863. else if (this.variable.getOriginalVariable() !== this.variable) {
  9864. // Remove altogether to prevent re-declaring the same variable
  9865. treeshakeNode(this, code, start, end);
  9866. return;
  9867. }
  9868. else if (this.variable.included) {
  9869. this.renderVariableDeclaration(code, declarationStart, options);
  9870. }
  9871. else {
  9872. code.remove(this.start, declarationStart);
  9873. this.declaration.render(code, options, {
  9874. renderedSurroundingElement: parseAst_js.ExpressionStatement
  9875. });
  9876. if (code.original[this.end - 1] !== ';') {
  9877. code.appendLeft(this.end, ';');
  9878. }
  9879. return;
  9880. }
  9881. this.declaration.render(code, options);
  9882. }
  9883. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  9884. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  9885. const name = this.variable.getName(getPropertyAccess);
  9886. // Remove `export default`
  9887. code.remove(this.start, declarationStart);
  9888. if (idInsertPosition !== null) {
  9889. code.appendLeft(idInsertPosition, ` ${name}`);
  9890. }
  9891. if (format === 'system' &&
  9892. this.declaration instanceof ClassDeclaration &&
  9893. exportNamesByVariable.has(this.variable)) {
  9894. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  9895. }
  9896. }
  9897. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  9898. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  9899. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  9900. if (systemExportNames) {
  9901. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  9902. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  9903. }
  9904. else {
  9905. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9906. if (!hasTrailingSemicolon) {
  9907. code.appendLeft(this.end, ';');
  9908. }
  9909. }
  9910. }
  9911. }
  9912. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9913. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9914. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  9915. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  9916. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  9917. const backSlashRegEx = /\\/g;
  9918. function escapeId(id) {
  9919. if (!needsEscapeRegEx.test(id))
  9920. return id;
  9921. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  9922. }
  9923. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9924. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  9925. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9926. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  9927. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9928. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9929. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9930. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  9931. const defaultInteropHelpersByInteropType = {
  9932. auto: INTEROP_DEFAULT_VARIABLE,
  9933. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  9934. default: null,
  9935. defaultOnly: null,
  9936. esModule: null
  9937. };
  9938. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9939. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  9940. const namespaceInteropHelpersByInteropType = {
  9941. auto: INTEROP_NAMESPACE_VARIABLE,
  9942. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  9943. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9944. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9945. esModule: null
  9946. };
  9947. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  9948. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  9949. const usedHelpers = new Set(additionalHelpers);
  9950. for (const variable of HELPER_NAMES) {
  9951. if (accessedGlobals.has(variable)) {
  9952. usedHelpers.add(variable);
  9953. }
  9954. }
  9955. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9956. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  9957. : '').join('');
  9958. };
  9959. const HELPER_GENERATORS = {
  9960. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  9961. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  9962. },
  9963. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  9964. const { _, getDirectReturnFunction, n } = snippets;
  9965. const [left, right] = getDirectReturnFunction(['e'], {
  9966. functionReturn: true,
  9967. lineBreakIndent: null,
  9968. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  9969. });
  9970. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  9971. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9972. },
  9973. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9974. const { _, getDirectReturnFunction, n } = snippets;
  9975. const [left, right] = getDirectReturnFunction(['e'], {
  9976. functionReturn: true,
  9977. lineBreakIndent: null,
  9978. name: INTEROP_DEFAULT_VARIABLE
  9979. });
  9980. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9981. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9982. },
  9983. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  9984. const { _, getDirectReturnFunction, n } = snippets;
  9985. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9986. const [left, right] = getDirectReturnFunction(['e'], {
  9987. functionReturn: true,
  9988. lineBreakIndent: null,
  9989. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  9990. });
  9991. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9992. }
  9993. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  9994. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  9995. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  9996. `}${n}${n}`);
  9997. },
  9998. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  9999. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  10000. const [left, right] = getDirectReturnFunction(['e'], {
  10001. functionReturn: true,
  10002. lineBreakIndent: null,
  10003. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10004. });
  10005. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  10006. [null, `__proto__:${_}null`],
  10007. ['default', 'e']
  10008. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10009. },
  10010. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10011. const { _, n } = snippets;
  10012. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10013. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10014. `}${n}${n}`);
  10015. },
  10016. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  10017. const { _, getDirectReturnFunction, n } = snippets;
  10018. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10019. const [left, right] = getDirectReturnFunction(['e'], {
  10020. functionReturn: true,
  10021. lineBreakIndent: null,
  10022. name: INTEROP_NAMESPACE_VARIABLE
  10023. });
  10024. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10025. }
  10026. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10027. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10028. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10029. `}${n}${n}`);
  10030. },
  10031. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10032. const { _, cnst, n } = snippets;
  10033. const useForEach = cnst === 'var' && liveBindings;
  10034. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10035. `${t}${loopOverNamespaces(`{${n}` +
  10036. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10037. (liveBindings
  10038. ? useForEach
  10039. ? copyOwnPropertyLiveBinding
  10040. : copyPropertyLiveBinding
  10041. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10042. `${t}${t}${t}}${n}` +
  10043. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10044. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  10045. `}${n}${n}`);
  10046. }
  10047. };
  10048. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10049. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10050. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10051. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  10052. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10053. const copyProperty = `{${n}` +
  10054. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10055. `${index}${t}}`;
  10056. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  10057. `${index}if${_}(e)${_}{${n}` +
  10058. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10059. `${index}}${n}` +
  10060. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10061. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10062. };
  10063. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10064. ? `for${_}(${cnst} k in e)${_}${body}`
  10065. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10066. isAsync: false,
  10067. name: null
  10068. })}${body})${s}`;
  10069. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10070. if (useForEach) {
  10071. const [left, right] = getDirectReturnFunction(['e'], {
  10072. functionReturn: false,
  10073. lineBreakIndent: { base: t, t },
  10074. name: null
  10075. });
  10076. return (`m.forEach(${left}` +
  10077. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10078. isAsync: false,
  10079. name: null
  10080. })}${body})${right});`);
  10081. }
  10082. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10083. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10084. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10085. };
  10086. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10087. const { _, n } = snippets;
  10088. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10089. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10090. `${index}}${n}`);
  10091. };
  10092. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10093. const [left, right] = getDirectReturnFunction([], {
  10094. functionReturn: true,
  10095. lineBreakIndent: null,
  10096. name: null
  10097. });
  10098. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10099. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10100. `${index}${t}enumerable:${_}true,${n}` +
  10101. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10102. `${index}});${n}`);
  10103. };
  10104. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10105. const [left, right] = getDirectReturnFunction([], {
  10106. functionReturn: true,
  10107. lineBreakIndent: null,
  10108. name: null
  10109. });
  10110. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10111. `${index}if${_}(d)${_}{${n}` +
  10112. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10113. `${index}${t}${t}enumerable:${_}true,${n}` +
  10114. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10115. `${index}${t}});${n}` +
  10116. `${index}}${n}`);
  10117. };
  10118. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10119. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10120. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  10121. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10122. : fragment;
  10123. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10124. function getToStringTagValue(getObject) {
  10125. return getObject([['value', "'Module'"]], {
  10126. lineBreakIndent: null
  10127. });
  10128. }
  10129. class Literal extends NodeBase {
  10130. deoptimizeArgumentsOnInteractionAtPath() { }
  10131. getLiteralValueAtPath(path) {
  10132. if (path.length > 0 ||
  10133. // unknown literals can also be null but do not start with an "n"
  10134. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  10135. typeof this.value === 'bigint' ||
  10136. // to support shims for regular expressions
  10137. this.scope.context.code.charCodeAt(this.start) === 47) {
  10138. return UnknownValue;
  10139. }
  10140. return this.value;
  10141. }
  10142. getReturnExpressionWhenCalledAtPath(path) {
  10143. if (path.length !== 1)
  10144. return UNKNOWN_RETURN_EXPRESSION;
  10145. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  10146. }
  10147. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10148. switch (interaction.type) {
  10149. case INTERACTION_ACCESSED: {
  10150. return path.length > (this.value === null ? 0 : 1);
  10151. }
  10152. case INTERACTION_ASSIGNED: {
  10153. return true;
  10154. }
  10155. case INTERACTION_CALLED: {
  10156. if (this.included &&
  10157. this.value instanceof RegExp &&
  10158. (this.value.global || this.value.sticky)) {
  10159. return true;
  10160. }
  10161. return (path.length !== 1 ||
  10162. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  10163. }
  10164. }
  10165. }
  10166. initialise() {
  10167. super.initialise();
  10168. this.members = getLiteralMembersForValue(this.value);
  10169. }
  10170. parseNode(esTreeNode) {
  10171. this.value = esTreeNode.value;
  10172. this.regex = esTreeNode.regex;
  10173. return super.parseNode(esTreeNode);
  10174. }
  10175. render(code) {
  10176. if (typeof this.value === 'string') {
  10177. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  10178. }
  10179. }
  10180. }
  10181. Literal.prototype.includeNode = onlyIncludeSelf;
  10182. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  10183. if ('getLiteralValueAtPathAsChainElement' in object) {
  10184. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  10185. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  10186. return IS_SKIPPED_CHAIN;
  10187. }
  10188. }
  10189. else if (element.optional &&
  10190. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  10191. return IS_SKIPPED_CHAIN;
  10192. }
  10193. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  10194. }
  10195. function getResolvablePropertyKey(memberExpression) {
  10196. return memberExpression.computed
  10197. ? getResolvableComputedPropertyKey(memberExpression.property)
  10198. : memberExpression.property.name;
  10199. }
  10200. function getResolvableComputedPropertyKey(propertyKey) {
  10201. if (propertyKey instanceof Literal) {
  10202. return String(propertyKey.value);
  10203. }
  10204. return null;
  10205. }
  10206. function getPathIfNotComputed(memberExpression) {
  10207. const nextPathKey = memberExpression.propertyKey;
  10208. const object = memberExpression.object;
  10209. if (typeof nextPathKey === 'string') {
  10210. if (object instanceof Identifier) {
  10211. return [
  10212. { key: object.name, pos: object.start },
  10213. { key: nextPathKey, pos: memberExpression.property.start }
  10214. ];
  10215. }
  10216. if (object instanceof MemberExpression) {
  10217. const parentPath = getPathIfNotComputed(object);
  10218. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  10219. }
  10220. }
  10221. return null;
  10222. }
  10223. function getStringFromPath(path) {
  10224. let pathString = path[0].key;
  10225. for (let index = 1; index < path.length; index++) {
  10226. pathString += '.' + path[index].key;
  10227. }
  10228. return pathString;
  10229. }
  10230. class MemberExpression extends NodeBase {
  10231. constructor() {
  10232. super(...arguments);
  10233. this.variable = null;
  10234. this.expressionsToBeDeoptimized = [];
  10235. }
  10236. get computed() {
  10237. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  10238. }
  10239. set computed(value) {
  10240. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  10241. }
  10242. get optional() {
  10243. return isFlagSet(this.flags, 128 /* Flag.optional */);
  10244. }
  10245. set optional(value) {
  10246. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  10247. }
  10248. get assignmentDeoptimized() {
  10249. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  10250. }
  10251. set assignmentDeoptimized(value) {
  10252. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  10253. }
  10254. get bound() {
  10255. return isFlagSet(this.flags, 32 /* Flag.bound */);
  10256. }
  10257. set bound(value) {
  10258. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  10259. }
  10260. get isUndefined() {
  10261. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  10262. }
  10263. set isUndefined(value) {
  10264. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  10265. }
  10266. bind() {
  10267. this.bound = true;
  10268. const path = getPathIfNotComputed(this);
  10269. const baseVariable = path && this.scope.findVariable(path[0].key);
  10270. if (baseVariable?.isNamespace) {
  10271. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  10272. if (!resolvedVariable) {
  10273. super.bind();
  10274. }
  10275. else if (resolvedVariable === 'undefined') {
  10276. this.isUndefined = true;
  10277. }
  10278. else {
  10279. this.variable = resolvedVariable;
  10280. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  10281. }
  10282. }
  10283. else {
  10284. super.bind();
  10285. }
  10286. }
  10287. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10288. if (this.variable) {
  10289. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10290. }
  10291. else if (!this.isUndefined) {
  10292. if (path.length < MAX_PATH_DEPTH) {
  10293. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  10294. }
  10295. else {
  10296. deoptimizeInteraction(interaction);
  10297. }
  10298. }
  10299. }
  10300. deoptimizeAssignment(destructuredInitPath, init) {
  10301. this.deoptimizePath(EMPTY_PATH);
  10302. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  10303. }
  10304. deoptimizeCache() {
  10305. if (this.propertyKey === this.dynamicPropertyKey)
  10306. return;
  10307. const { expressionsToBeDeoptimized, object } = this;
  10308. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  10309. this.dynamicPropertyKey = this.propertyKey;
  10310. object.deoptimizePath(UNKNOWN_PATH);
  10311. if (this.included) {
  10312. object.includePath(UNKNOWN_PATH, createInclusionContext());
  10313. }
  10314. for (const expression of expressionsToBeDeoptimized) {
  10315. expression.deoptimizeCache();
  10316. }
  10317. }
  10318. deoptimizePath(path) {
  10319. if (path.length === 0)
  10320. this.disallowNamespaceReassignment();
  10321. if (this.variable) {
  10322. this.variable.deoptimizePath(path);
  10323. }
  10324. else if (!this.isUndefined) {
  10325. const { propertyKey } = this;
  10326. this.object.deoptimizePath([
  10327. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  10328. ...(path.length < MAX_PATH_DEPTH
  10329. ? path
  10330. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10331. ]);
  10332. }
  10333. }
  10334. getLiteralValueAtPath(path, recursionTracker, origin) {
  10335. if (this.variable) {
  10336. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10337. }
  10338. if (this.isUndefined) {
  10339. return undefined;
  10340. }
  10341. const propertyKey = this.getDynamicPropertyKey();
  10342. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10343. if (propertyKey !== this.propertyKey)
  10344. this.expressionsToBeDeoptimized.push(origin);
  10345. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  10346. }
  10347. return UnknownValue;
  10348. }
  10349. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  10350. if (this.variable) {
  10351. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10352. }
  10353. if (this.isUndefined) {
  10354. return undefined;
  10355. }
  10356. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  10357. }
  10358. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10359. if (this.variable) {
  10360. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10361. }
  10362. if (this.isUndefined) {
  10363. return [UNDEFINED_EXPRESSION, false];
  10364. }
  10365. const propertyKey = this.getDynamicPropertyKey();
  10366. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10367. if (propertyKey !== this.propertyKey)
  10368. this.expressionsToBeDeoptimized.push(origin);
  10369. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  10370. }
  10371. return UNKNOWN_RETURN_EXPRESSION;
  10372. }
  10373. hasEffects(context) {
  10374. if (!this.deoptimized)
  10375. this.applyDeoptimizations();
  10376. return (this.property.hasEffects(context) ||
  10377. this.object.hasEffects(context) ||
  10378. this.hasAccessEffect(context));
  10379. }
  10380. hasEffectsAsChainElement(context) {
  10381. if (this.variable || this.isUndefined)
  10382. return this.hasEffects(context);
  10383. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  10384. ? this.object.hasEffectsAsChainElement(context)
  10385. : this.object.hasEffects(context);
  10386. if (objectHasEffects === IS_SKIPPED_CHAIN)
  10387. return IS_SKIPPED_CHAIN;
  10388. if (this.optional &&
  10389. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  10390. return objectHasEffects || IS_SKIPPED_CHAIN;
  10391. }
  10392. // We only apply deoptimizations lazily once we know we are not skipping
  10393. if (!this.deoptimized)
  10394. this.applyDeoptimizations();
  10395. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  10396. }
  10397. hasEffectsAsAssignmentTarget(context, checkAccess) {
  10398. if (checkAccess && !this.deoptimized)
  10399. this.applyDeoptimizations();
  10400. if (!this.assignmentDeoptimized)
  10401. this.applyAssignmentDeoptimization();
  10402. return (this.property.hasEffects(context) ||
  10403. this.object.hasEffects(context) ||
  10404. (checkAccess && this.hasAccessEffect(context)) ||
  10405. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  10406. }
  10407. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10408. if (this.variable) {
  10409. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10410. }
  10411. if (this.isUndefined) {
  10412. return true;
  10413. }
  10414. if (path.length < MAX_PATH_DEPTH) {
  10415. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  10416. }
  10417. return true;
  10418. }
  10419. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10420. return (destructuredInitPath.length > 0 &&
  10421. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  10422. }
  10423. include(context, includeChildrenRecursively) {
  10424. if (!this.included)
  10425. this.includeNode(context);
  10426. this.object.include(context, includeChildrenRecursively);
  10427. this.property.include(context, includeChildrenRecursively);
  10428. }
  10429. includeNode(context) {
  10430. this.included = true;
  10431. if (!this.deoptimized)
  10432. this.applyDeoptimizations();
  10433. if (this.variable) {
  10434. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10435. }
  10436. else if (!this.isUndefined) {
  10437. this.object.includePath([this.propertyKey], context);
  10438. }
  10439. }
  10440. includeNodeAsAssignmentTarget(context) {
  10441. this.included = true;
  10442. if (!this.assignmentDeoptimized)
  10443. this.applyAssignmentDeoptimization();
  10444. if (this.variable) {
  10445. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10446. }
  10447. else if (!this.isUndefined) {
  10448. this.object.includePath([this.propertyKey], context);
  10449. }
  10450. }
  10451. includePath(path, context) {
  10452. if (!this.included)
  10453. this.includeNode(context);
  10454. if (this.variable) {
  10455. this.variable?.includePath(path, context);
  10456. }
  10457. else if (!this.isUndefined) {
  10458. this.object.includePath([
  10459. this.propertyKey,
  10460. ...(path.length < MAX_PATH_DEPTH
  10461. ? path
  10462. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10463. ], context);
  10464. }
  10465. }
  10466. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  10467. if (!this.included)
  10468. this.includeNodeAsAssignmentTarget(context);
  10469. if (deoptimizeAccess && !this.deoptimized)
  10470. this.applyDeoptimizations();
  10471. this.object.include(context, includeChildrenRecursively);
  10472. this.property.include(context, includeChildrenRecursively);
  10473. }
  10474. includeCallArguments(interaction, context) {
  10475. if (this.variable) {
  10476. this.variable.includeCallArguments(interaction, context);
  10477. }
  10478. else {
  10479. if (isImportExpressionNode(this.object) ||
  10480. /**
  10481. * const c = await import('foo')
  10482. * c.foo();
  10483. */
  10484. (this.object.variable &&
  10485. !this.object.variable.isReassigned &&
  10486. this.object.variable instanceof LocalVariable &&
  10487. isAwaitExpressionNode(this.object.variable.init) &&
  10488. isImportExpressionNode(this.object.variable.init.argument))) {
  10489. includeInteractionWithoutThis(interaction, context);
  10490. }
  10491. else {
  10492. includeInteraction(interaction, context);
  10493. }
  10494. }
  10495. }
  10496. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10497. if ((this.included ||=
  10498. destructuredInitPath.length > 0 &&
  10499. !context.brokenFlow &&
  10500. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext()))) {
  10501. init.include(context, false);
  10502. return true;
  10503. }
  10504. return false;
  10505. }
  10506. initialise() {
  10507. super.initialise();
  10508. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  10509. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  10510. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  10511. }
  10512. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = parseAst_js.BLANK) {
  10513. if (this.variable || this.isUndefined) {
  10514. const { snippets: { getPropertyAccess } } = options;
  10515. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  10516. if (renderedParentType && isCalleeOfRenderedParent)
  10517. replacement = '0, ' + replacement;
  10518. code.overwrite(this.start, this.end, replacement, {
  10519. contentOnly: true,
  10520. storeName: true
  10521. });
  10522. }
  10523. else {
  10524. if (renderedParentType && isCalleeOfRenderedParent) {
  10525. code.appendRight(this.start, '0, ');
  10526. }
  10527. this.object.render(code, options, { renderedSurroundingElement });
  10528. this.property.render(code, options);
  10529. }
  10530. }
  10531. setAssignedValue(value) {
  10532. this.assignmentInteraction = {
  10533. args: [this.object, value],
  10534. type: INTERACTION_ASSIGNED
  10535. };
  10536. }
  10537. applyDeoptimizations() {
  10538. this.deoptimized = true;
  10539. const { propertyReadSideEffects } = this.scope.context.options
  10540. .treeshake;
  10541. if (
  10542. // Namespaces are not bound and should not be deoptimized
  10543. this.bound &&
  10544. propertyReadSideEffects &&
  10545. !(this.variable || this.isUndefined)) {
  10546. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10547. this.scope.context.requestTreeshakingPass();
  10548. }
  10549. if (this.variable) {
  10550. this.variable.addUsedPlace(this);
  10551. this.scope.context.requestTreeshakingPass();
  10552. }
  10553. }
  10554. applyAssignmentDeoptimization() {
  10555. this.assignmentDeoptimized = true;
  10556. const { propertyReadSideEffects } = this.scope.context.options
  10557. .treeshake;
  10558. if (
  10559. // Namespaces are not bound and should not be deoptimized
  10560. this.bound &&
  10561. propertyReadSideEffects &&
  10562. !(this.variable || this.isUndefined)) {
  10563. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10564. this.scope.context.requestTreeshakingPass();
  10565. }
  10566. }
  10567. disallowNamespaceReassignment() {
  10568. if (this.object instanceof Identifier) {
  10569. const variable = this.scope.findVariable(this.object.name);
  10570. if (variable.isNamespace) {
  10571. if (this.variable) {
  10572. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  10573. }
  10574. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  10575. }
  10576. }
  10577. }
  10578. getDynamicPropertyKey() {
  10579. if (this.dynamicPropertyKey === null) {
  10580. this.dynamicPropertyKey = this.propertyKey;
  10581. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10582. return (this.dynamicPropertyKey =
  10583. value === SymbolToStringTag
  10584. ? value
  10585. : typeof value === 'symbol'
  10586. ? UnknownKey
  10587. : String(value));
  10588. }
  10589. return this.dynamicPropertyKey;
  10590. }
  10591. hasAccessEffect(context) {
  10592. const { propertyReadSideEffects } = this.scope.context.options
  10593. .treeshake;
  10594. return (!(this.variable || this.isUndefined) &&
  10595. propertyReadSideEffects &&
  10596. (propertyReadSideEffects === 'always' ||
  10597. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  10598. }
  10599. }
  10600. function resolveNamespaceVariables(baseVariable, path, astContext) {
  10601. if (path.length === 0)
  10602. return baseVariable;
  10603. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  10604. return null;
  10605. const exportName = path[0].key;
  10606. const variable = baseVariable.context.traceExport(exportName);
  10607. if (!variable) {
  10608. if (path.length === 1) {
  10609. const fileName = baseVariable.context.fileName;
  10610. astContext.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  10611. return 'undefined';
  10612. }
  10613. return null;
  10614. }
  10615. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  10616. }
  10617. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10618. const IMPORT = 'import';
  10619. class MetaProperty extends NodeBase {
  10620. constructor() {
  10621. super(...arguments);
  10622. this.metaProperty = null;
  10623. this.preliminaryChunkId = null;
  10624. this.referenceId = null;
  10625. }
  10626. getReferencedFileName(outputPluginDriver) {
  10627. const { meta: { name }, metaProperty } = this;
  10628. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  10629. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10630. }
  10631. return null;
  10632. }
  10633. hasEffects() {
  10634. return false;
  10635. }
  10636. hasEffectsOnInteractionAtPath(path, { type }) {
  10637. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10638. }
  10639. include() {
  10640. if (!this.included)
  10641. this.includeNode();
  10642. }
  10643. includeNode() {
  10644. this.included = true;
  10645. if (this.meta.name === IMPORT) {
  10646. this.scope.context.addImportMeta(this);
  10647. const parent = this.parent;
  10648. const metaProperty = (this.metaProperty =
  10649. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10650. ? parent.propertyKey
  10651. : null);
  10652. if (metaProperty?.startsWith(FILE_PREFIX)) {
  10653. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10654. }
  10655. }
  10656. }
  10657. render(code, renderOptions) {
  10658. const { format, pluginDriver, snippets } = renderOptions;
  10659. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  10660. const { id: moduleId } = module;
  10661. if (name !== IMPORT)
  10662. return;
  10663. const chunkId = preliminaryChunkId;
  10664. if (referenceId) {
  10665. const fileName = pluginDriver.getFileName(referenceId);
  10666. const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
  10667. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  10668. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  10669. ]) || relativeUrlMechanisms[format](relativePath);
  10670. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10671. return;
  10672. }
  10673. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  10674. metaProperty,
  10675. { chunkId, format, moduleId }
  10676. ]);
  10677. if (!replacement) {
  10678. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  10679. renderOptions.accessedDocumentCurrentScript ||=
  10680. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  10681. }
  10682. if (typeof replacement === 'string') {
  10683. if (parent instanceof MemberExpression) {
  10684. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10685. }
  10686. else {
  10687. code.overwrite(start, end, replacement, { contentOnly: true });
  10688. }
  10689. }
  10690. }
  10691. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  10692. this.preliminaryChunkId = preliminaryChunkId;
  10693. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  10694. if (accessedGlobals.length > 0) {
  10695. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10696. }
  10697. }
  10698. }
  10699. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  10700. const accessedMetaUrlGlobals = {
  10701. amd: ['document', 'module', 'URL'],
  10702. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10703. es: [],
  10704. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10705. system: ['module'],
  10706. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  10707. };
  10708. const accessedFileUrlGlobals = {
  10709. amd: ['document', 'require', 'URL'],
  10710. cjs: ['document', 'require', 'URL'],
  10711. es: [],
  10712. iife: ['document', 'URL'],
  10713. system: ['module', 'URL'],
  10714. umd: ['document', 'require', 'URL']
  10715. };
  10716. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  10717. 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`);
  10718. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  10719. const urlMechanism = getUrl(chunkId);
  10720. return property === null
  10721. ? `({ url: ${urlMechanism} })`
  10722. : property === 'url'
  10723. ? urlMechanism
  10724. : 'undefined';
  10725. };
  10726. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  10727. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  10728. 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)`;
  10729. const relativeUrlMechanisms = {
  10730. amd: relativePath => {
  10731. if (relativePath[0] !== '.')
  10732. relativePath = './' + relativePath;
  10733. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  10734. },
  10735. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  10736. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  10737. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  10738. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  10739. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  10740. };
  10741. const importMetaMechanisms = {
  10742. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  10743. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  10744. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10745. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  10746. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  10747. };
  10748. class UndefinedVariable extends Variable {
  10749. constructor() {
  10750. super('undefined');
  10751. }
  10752. getLiteralValueAtPath() {
  10753. return undefined;
  10754. }
  10755. }
  10756. class ExportDefaultVariable extends LocalVariable {
  10757. constructor(name, exportDefaultDeclaration, context) {
  10758. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  10759. this.hasId = false;
  10760. this.originalId = null;
  10761. this.originalVariable = null;
  10762. const declaration = exportDefaultDeclaration.declaration;
  10763. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10764. declaration.id) {
  10765. this.hasId = true;
  10766. this.originalId = declaration.id;
  10767. }
  10768. else if (declaration instanceof Identifier) {
  10769. this.originalId = declaration;
  10770. }
  10771. }
  10772. addReference(identifier) {
  10773. if (!this.hasId) {
  10774. this.name = identifier.name;
  10775. }
  10776. }
  10777. addUsedPlace(usedPlace) {
  10778. const original = this.getOriginalVariable();
  10779. if (original === this) {
  10780. super.addUsedPlace(usedPlace);
  10781. }
  10782. else {
  10783. original.addUsedPlace(usedPlace);
  10784. }
  10785. }
  10786. forbidName(name) {
  10787. const original = this.getOriginalVariable();
  10788. if (original === this) {
  10789. super.forbidName(name);
  10790. }
  10791. else {
  10792. original.forbidName(name);
  10793. }
  10794. }
  10795. getAssignedVariableName() {
  10796. return (this.originalId && this.originalId.name) || null;
  10797. }
  10798. getBaseVariableName() {
  10799. const original = this.getOriginalVariable();
  10800. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  10801. }
  10802. getDirectOriginalVariable() {
  10803. return this.originalId &&
  10804. (this.hasId ||
  10805. !(this.originalId.isPossibleTDZ() ||
  10806. this.originalId.variable.isReassigned ||
  10807. this.originalId.variable instanceof UndefinedVariable ||
  10808. // this avoids a circular dependency
  10809. 'syntheticNamespace' in this.originalId.variable))
  10810. ? this.originalId.variable
  10811. : null;
  10812. }
  10813. getName(getPropertyAccess) {
  10814. const original = this.getOriginalVariable();
  10815. return original === this
  10816. ? super.getName(getPropertyAccess)
  10817. : original.getName(getPropertyAccess);
  10818. }
  10819. getOriginalVariable() {
  10820. if (this.originalVariable)
  10821. return this.originalVariable;
  10822. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10823. let original = this;
  10824. let currentVariable;
  10825. const checkedVariables = new Set();
  10826. do {
  10827. checkedVariables.add(original);
  10828. currentVariable = original;
  10829. original = currentVariable.getDirectOriginalVariable();
  10830. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10831. return (this.originalVariable = original || currentVariable);
  10832. }
  10833. }
  10834. class NamespaceVariable extends Variable {
  10835. constructor(context) {
  10836. super(context.getModuleName());
  10837. this.memberVariables = null;
  10838. this.mergedNamespaces = [];
  10839. this.referencedEarly = false;
  10840. this.references = [];
  10841. this.context = context;
  10842. this.module = context.module;
  10843. }
  10844. addReference(identifier) {
  10845. this.references.push(identifier);
  10846. this.name = identifier.name;
  10847. }
  10848. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10849. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  10850. const key = path[0];
  10851. if (typeof key === 'string') {
  10852. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  10853. }
  10854. else {
  10855. deoptimizeInteraction(interaction);
  10856. }
  10857. }
  10858. }
  10859. deoptimizePath(path) {
  10860. if (path.length > 1) {
  10861. const key = path[0];
  10862. if (typeof key === 'string') {
  10863. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  10864. }
  10865. }
  10866. }
  10867. getLiteralValueAtPath(path) {
  10868. if (path[0] === SymbolToStringTag) {
  10869. return 'Module';
  10870. }
  10871. return UnknownValue;
  10872. }
  10873. getMemberVariables() {
  10874. if (this.memberVariables) {
  10875. return this.memberVariables;
  10876. }
  10877. const memberVariables = Object.create(null);
  10878. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  10879. for (const name of sortedExports) {
  10880. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  10881. const exportedVariable = this.context.traceExport(name);
  10882. if (exportedVariable) {
  10883. memberVariables[name] = exportedVariable;
  10884. }
  10885. }
  10886. }
  10887. return (this.memberVariables = memberVariables);
  10888. }
  10889. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10890. const { type } = interaction;
  10891. if (path.length === 0) {
  10892. // This can only be a call anyway
  10893. return true;
  10894. }
  10895. if (path.length === 1 && type !== INTERACTION_CALLED) {
  10896. return type === INTERACTION_ASSIGNED;
  10897. }
  10898. const key = path[0];
  10899. if (typeof key !== 'string') {
  10900. return true;
  10901. }
  10902. const memberVariable = this.getMemberVariables()[key];
  10903. return (!memberVariable ||
  10904. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  10905. }
  10906. includePath(path, context) {
  10907. super.includePath(path, context);
  10908. this.context.includeAllExports();
  10909. }
  10910. prepare(accessedGlobalsByScope) {
  10911. if (this.mergedNamespaces.length > 0) {
  10912. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  10913. }
  10914. }
  10915. renderBlock(options) {
  10916. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  10917. const memberVariables = this.getMemberVariables();
  10918. const members = Object.entries(memberVariables)
  10919. .filter(([_, variable]) => variable.included)
  10920. .map(([name, variable]) => {
  10921. if (this.referencedEarly || variable.isReassigned || variable === this) {
  10922. return [
  10923. null,
  10924. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  10925. ];
  10926. }
  10927. return [name, variable.getName(getPropertyAccess)];
  10928. });
  10929. members.unshift([null, `__proto__:${_}null`]);
  10930. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  10931. if (this.mergedNamespaces.length > 0) {
  10932. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  10933. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  10934. }
  10935. else {
  10936. // The helper to merge namespaces will also take care of freezing and toStringTag
  10937. if (symbols) {
  10938. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  10939. }
  10940. if (freeze) {
  10941. output = `/*#__PURE__*/Object.freeze(${output})`;
  10942. }
  10943. }
  10944. const name = this.getName(getPropertyAccess);
  10945. output = `${cnst} ${name}${_}=${_}${output};`;
  10946. if (format === 'system' && exportNamesByVariable.has(this)) {
  10947. output += `${n}${getSystemExportStatement([this], options)};`;
  10948. }
  10949. return output;
  10950. }
  10951. renderFirst() {
  10952. return this.referencedEarly;
  10953. }
  10954. setMergedNamespaces(mergedNamespaces) {
  10955. this.mergedNamespaces = mergedNamespaces;
  10956. const moduleExecIndex = this.context.getModuleExecIndex();
  10957. for (const identifier of this.references) {
  10958. const { context } = identifier.scope;
  10959. if (context.getModuleExecIndex() <= moduleExecIndex) {
  10960. this.referencedEarly = true;
  10961. break;
  10962. }
  10963. }
  10964. }
  10965. }
  10966. NamespaceVariable.prototype.isNamespace = true;
  10967. class SyntheticNamedExportVariable extends Variable {
  10968. constructor(context, name, syntheticNamespace) {
  10969. super(name);
  10970. this.baseVariable = null;
  10971. this.context = context;
  10972. this.module = context.module;
  10973. this.syntheticNamespace = syntheticNamespace;
  10974. }
  10975. getBaseVariable() {
  10976. if (this.baseVariable)
  10977. return this.baseVariable;
  10978. let baseVariable = this.syntheticNamespace;
  10979. while (baseVariable instanceof ExportDefaultVariable ||
  10980. baseVariable instanceof SyntheticNamedExportVariable) {
  10981. if (baseVariable instanceof ExportDefaultVariable) {
  10982. const original = baseVariable.getOriginalVariable();
  10983. if (original === baseVariable)
  10984. break;
  10985. baseVariable = original;
  10986. }
  10987. if (baseVariable instanceof SyntheticNamedExportVariable) {
  10988. baseVariable = baseVariable.syntheticNamespace;
  10989. }
  10990. }
  10991. return (this.baseVariable = baseVariable);
  10992. }
  10993. getBaseVariableName() {
  10994. return this.syntheticNamespace.getBaseVariableName();
  10995. }
  10996. getName(getPropertyAccess) {
  10997. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  10998. }
  10999. includePath(path, context) {
  11000. super.includePath(path, context);
  11001. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  11002. }
  11003. setRenderNames(baseName, name) {
  11004. super.setRenderNames(baseName, name);
  11005. }
  11006. }
  11007. class ExternalChunk {
  11008. constructor(module, options, inputBase) {
  11009. this.options = options;
  11010. this.inputBase = inputBase;
  11011. this.defaultVariableName = '';
  11012. this.namespaceVariableName = '';
  11013. this.variableName = '';
  11014. this.fileName = null;
  11015. this.importAttributes = null;
  11016. this.id = module.id;
  11017. this.moduleInfo = module.info;
  11018. this.renormalizeRenderPath = module.renormalizeRenderPath;
  11019. this.suggestedVariableName = module.suggestedVariableName;
  11020. }
  11021. getFileName() {
  11022. if (this.fileName) {
  11023. return this.fileName;
  11024. }
  11025. const { paths } = this.options;
  11026. return (this.fileName =
  11027. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  11028. (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
  11029. }
  11030. getImportAttributes(snippets) {
  11031. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  11032. this.options.externalImportAttributes &&
  11033. this.moduleInfo.attributes, snippets));
  11034. }
  11035. getImportPath(importer) {
  11036. return escapeId(this.renormalizeRenderPath
  11037. ? parseAst_js.getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  11038. : this.getFileName());
  11039. }
  11040. }
  11041. function formatAttributes(attributes, { getObject }) {
  11042. if (!attributes) {
  11043. return null;
  11044. }
  11045. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  11046. if (assertionEntries.length > 0) {
  11047. return getObject(assertionEntries, { lineBreakIndent: null });
  11048. }
  11049. return null;
  11050. }
  11051. function removeJsExtension(name) {
  11052. return name.endsWith('.js') ? name.slice(0, -3) : name;
  11053. }
  11054. function getCompleteAmdId(options, chunkId) {
  11055. if (options.autoId) {
  11056. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  11057. }
  11058. return options.id ?? '';
  11059. }
  11060. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  11061. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  11062. if (!namedExportsMode) {
  11063. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  11064. }
  11065. let exportBlock = '';
  11066. if (namedExportsMode) {
  11067. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11068. if (!reexports) {
  11069. continue;
  11070. }
  11071. for (const specifier of reexports) {
  11072. if (specifier.reexported !== '*') {
  11073. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11074. if (exportBlock)
  11075. exportBlock += n;
  11076. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  11077. const [left, right] = getDirectReturnFunction([], {
  11078. functionReturn: true,
  11079. lineBreakIndent: null,
  11080. name: null
  11081. });
  11082. exportBlock +=
  11083. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  11084. `${t}enumerable:${_}true,${n}` +
  11085. `${t}get:${_}${left}${importName}${right}${n}});`;
  11086. }
  11087. else if (specifier.reexported === '__proto__') {
  11088. exportBlock +=
  11089. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11090. `${t}enumerable:${_}true,${n}` +
  11091. `${t}value:${_}${importName}${n}});`;
  11092. }
  11093. else {
  11094. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  11095. }
  11096. }
  11097. }
  11098. }
  11099. }
  11100. for (const { exported, local } of exports) {
  11101. const lhs = `exports${getPropertyAccess(exported)}`;
  11102. const rhs = local;
  11103. if (lhs !== rhs) {
  11104. if (exportBlock)
  11105. exportBlock += n;
  11106. exportBlock +=
  11107. exported === '__proto__'
  11108. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11109. `${t}enumerable:${_}true,${n}` +
  11110. `${t}value:${_}${rhs}${n}});`
  11111. : `${lhs}${_}=${_}${rhs};`;
  11112. }
  11113. }
  11114. if (namedExportsMode) {
  11115. for (const { name, reexports } of dependencies) {
  11116. if (!reexports) {
  11117. continue;
  11118. }
  11119. for (const specifier of reexports) {
  11120. if (specifier.reexported === '*') {
  11121. if (exportBlock)
  11122. exportBlock += n;
  11123. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  11124. const protoString = "'__proto__'";
  11125. exportBlock +=
  11126. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  11127. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  11128. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  11129. `${t}${t}enumerable:${_}true,${n}` +
  11130. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  11131. `${t}});${n}${n}`;
  11132. }
  11133. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  11134. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  11135. isAsync: false,
  11136. name: null
  11137. })}${copyPropertyIfNecessary});`;
  11138. }
  11139. }
  11140. }
  11141. }
  11142. if (exportBlock) {
  11143. return `${n}${n}${exportBlock}`;
  11144. }
  11145. return '';
  11146. }
  11147. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  11148. if (exports.length > 0) {
  11149. return exports[0].local;
  11150. }
  11151. else {
  11152. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11153. if (reexports) {
  11154. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11155. }
  11156. }
  11157. }
  11158. }
  11159. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  11160. if (imported === 'default') {
  11161. if (!isChunk) {
  11162. const moduleInterop = interop(moduleId);
  11163. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  11164. ? defaultVariableName
  11165. : moduleVariableName;
  11166. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  11167. ? `${variableName}${getPropertyAccess('default')}`
  11168. : variableName;
  11169. }
  11170. return depNamedExportsMode
  11171. ? `${moduleVariableName}${getPropertyAccess('default')}`
  11172. : moduleVariableName;
  11173. }
  11174. if (imported === '*') {
  11175. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  11176. ? namespaceVariableName
  11177. : moduleVariableName;
  11178. }
  11179. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  11180. }
  11181. function getEsModuleValue(getObject) {
  11182. return getObject([['value', 'true']], {
  11183. lineBreakIndent: null
  11184. });
  11185. }
  11186. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  11187. if (hasNamedExports) {
  11188. if (addEsModule) {
  11189. if (addNamespaceToStringTag) {
  11190. return `Object.defineProperties(exports,${_}${getObject([
  11191. ['__esModule', getEsModuleValue(getObject)],
  11192. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  11193. ], {
  11194. lineBreakIndent: null
  11195. })});`;
  11196. }
  11197. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  11198. }
  11199. if (addNamespaceToStringTag) {
  11200. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  11201. }
  11202. }
  11203. return '';
  11204. }
  11205. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  11206. if (needsLiveBinding) {
  11207. const [left, right] = getDirectReturnFunction([], {
  11208. functionReturn: true,
  11209. lineBreakIndent: null,
  11210. name: null
  11211. });
  11212. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  11213. `${t}${t}enumerable:${_}true,${n}` +
  11214. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  11215. }
  11216. return `exports[k]${_}=${_}${name}[k]`;
  11217. };
  11218. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  11219. const { _, cnst, n } = snippets;
  11220. const neededInteropHelpers = new Set();
  11221. const interopStatements = [];
  11222. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  11223. neededInteropHelpers.add(helper);
  11224. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  11225. };
  11226. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11227. if (isChunk) {
  11228. for (const { imported, reexported } of [
  11229. ...(imports || []),
  11230. ...(reexports || [])
  11231. ]) {
  11232. if (imported === '*' && reexported !== '*') {
  11233. if (!namedExportsMode) {
  11234. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  11235. }
  11236. break;
  11237. }
  11238. }
  11239. }
  11240. else {
  11241. const moduleInterop = interop(importPath);
  11242. let hasDefault = false;
  11243. let hasNamespace = false;
  11244. for (const { imported, reexported } of [
  11245. ...(imports || []),
  11246. ...(reexports || [])
  11247. ]) {
  11248. let helper;
  11249. let variableName;
  11250. if (imported === 'default') {
  11251. if (!hasDefault) {
  11252. hasDefault = true;
  11253. if (defaultVariableName !== namespaceVariableName) {
  11254. variableName = defaultVariableName;
  11255. helper = defaultInteropHelpersByInteropType[moduleInterop];
  11256. }
  11257. }
  11258. }
  11259. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  11260. hasNamespace = true;
  11261. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  11262. variableName = namespaceVariableName;
  11263. }
  11264. if (helper) {
  11265. addInteropStatement(variableName, helper, name);
  11266. }
  11267. }
  11268. }
  11269. }
  11270. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  11271. }
  11272. function addJsExtension(name) {
  11273. return name.endsWith('.js') ? name : name + '.js';
  11274. }
  11275. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  11276. // The assumption is that this makes sense for all relative ids:
  11277. // https://requirejs.org/docs/api.html#jsfiles
  11278. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  11279. if (id[0] !== '.') {
  11280. return id;
  11281. }
  11282. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  11283. }
  11284. const builtinModules = [
  11285. "node:assert",
  11286. "assert",
  11287. "node:assert/strict",
  11288. "assert/strict",
  11289. "node:async_hooks",
  11290. "async_hooks",
  11291. "node:buffer",
  11292. "buffer",
  11293. "node:child_process",
  11294. "child_process",
  11295. "node:cluster",
  11296. "cluster",
  11297. "node:console",
  11298. "console",
  11299. "node:constants",
  11300. "constants",
  11301. "node:crypto",
  11302. "crypto",
  11303. "node:dgram",
  11304. "dgram",
  11305. "node:diagnostics_channel",
  11306. "diagnostics_channel",
  11307. "node:dns",
  11308. "dns",
  11309. "node:dns/promises",
  11310. "dns/promises",
  11311. "node:domain",
  11312. "domain",
  11313. "node:events",
  11314. "events",
  11315. "node:fs",
  11316. "fs",
  11317. "node:fs/promises",
  11318. "fs/promises",
  11319. "node:http",
  11320. "http",
  11321. "node:http2",
  11322. "http2",
  11323. "node:https",
  11324. "https",
  11325. "node:inspector",
  11326. "inspector",
  11327. "node:inspector/promises",
  11328. "inspector/promises",
  11329. "node:module",
  11330. "module",
  11331. "node:net",
  11332. "net",
  11333. "node:os",
  11334. "os",
  11335. "node:path",
  11336. "path",
  11337. "node:path/posix",
  11338. "path/posix",
  11339. "node:path/win32",
  11340. "path/win32",
  11341. "node:perf_hooks",
  11342. "perf_hooks",
  11343. "node:process",
  11344. "process",
  11345. "node:querystring",
  11346. "querystring",
  11347. "node:quic",
  11348. "node:readline",
  11349. "readline",
  11350. "node:readline/promises",
  11351. "readline/promises",
  11352. "node:repl",
  11353. "repl",
  11354. "node:sea",
  11355. "node:sqlite",
  11356. "node:stream",
  11357. "stream",
  11358. "node:stream/consumers",
  11359. "stream/consumers",
  11360. "node:stream/promises",
  11361. "stream/promises",
  11362. "node:stream/web",
  11363. "stream/web",
  11364. "node:string_decoder",
  11365. "string_decoder",
  11366. "node:test",
  11367. "node:test/reporters",
  11368. "node:timers",
  11369. "timers",
  11370. "node:timers/promises",
  11371. "timers/promises",
  11372. "node:tls",
  11373. "tls",
  11374. "node:trace_events",
  11375. "trace_events",
  11376. "node:tty",
  11377. "tty",
  11378. "node:url",
  11379. "url",
  11380. "node:util",
  11381. "util",
  11382. "node:util/types",
  11383. "util/types",
  11384. "node:v8",
  11385. "v8",
  11386. "node:vm",
  11387. "vm",
  11388. "node:wasi",
  11389. "wasi",
  11390. "node:worker_threads",
  11391. "worker_threads",
  11392. "node:zlib",
  11393. "zlib"
  11394. ];
  11395. const nodeBuiltins = new Set(builtinModules);
  11396. function warnOnBuiltins(log, dependencies) {
  11397. const externalBuiltins = dependencies
  11398. .map(({ importPath }) => importPath)
  11399. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  11400. if (externalBuiltins.length === 0)
  11401. return;
  11402. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNodeBuiltins(externalBuiltins));
  11403. }
  11404. 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 }) {
  11405. warnOnBuiltins(log, dependencies);
  11406. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  11407. const parameters = dependencies.map(m => m.name);
  11408. const { n, getNonArrowFunctionIntro, _ } = snippets;
  11409. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  11410. parameters.unshift(`exports`);
  11411. deps.unshift(`'exports'`);
  11412. }
  11413. if (accessedGlobals.has('require')) {
  11414. parameters.unshift('require');
  11415. deps.unshift(`'require'`);
  11416. }
  11417. if (accessedGlobals.has('module')) {
  11418. parameters.unshift('module');
  11419. deps.unshift(`'module'`);
  11420. }
  11421. const completeAmdId = getCompleteAmdId(amd, id);
  11422. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  11423. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  11424. const useStrict = strict ? `${_}'use strict';` : '';
  11425. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  11426. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11427. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11428. if (namespaceMarkers) {
  11429. namespaceMarkers = n + n + namespaceMarkers;
  11430. }
  11431. magicString
  11432. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11433. .indent(t)
  11434. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11435. // cf. https://v8.dev/blog/preparser#pife
  11436. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  11437. isAsync: false,
  11438. name: null
  11439. })}{${useStrict}${n}${n}`)
  11440. .append(`${n}${n}}));`);
  11441. }
  11442. 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 }) {
  11443. const { _, n } = snippets;
  11444. const useStrict = strict ? `'use strict';${n}${n}` : '';
  11445. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11446. if (namespaceMarkers) {
  11447. namespaceMarkers += n + n;
  11448. }
  11449. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  11450. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  11451. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  11452. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  11453. magicString.append(`${exportBlock}${outro}`);
  11454. }
  11455. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  11456. let importBlock = '';
  11457. let definingVariable = false;
  11458. for (const { importPath, name, reexports, imports } of dependencies) {
  11459. if (!reexports && !imports) {
  11460. if (importBlock) {
  11461. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  11462. }
  11463. definingVariable = false;
  11464. importBlock += `require('${importPath}')`;
  11465. }
  11466. else {
  11467. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  11468. definingVariable = true;
  11469. importBlock += `${name}${_}=${_}require('${importPath}')`;
  11470. }
  11471. }
  11472. if (importBlock) {
  11473. return `${importBlock};${n}${n}`;
  11474. }
  11475. return '';
  11476. }
  11477. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  11478. const { n } = snippets;
  11479. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  11480. if (importBlock.length > 0)
  11481. intro += importBlock.join(n) + n + n;
  11482. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  11483. if (intro)
  11484. magicString.prepend(intro);
  11485. const exportBlock = getExportBlock(exports, snippets);
  11486. if (exportBlock.length > 0)
  11487. magicString.append(n + n + exportBlock.join(n).trim());
  11488. if (outro)
  11489. magicString.append(outro);
  11490. magicString.trim();
  11491. }
  11492. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  11493. const importBlock = [];
  11494. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  11495. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  11496. const pathWithAssertion = `'${importPath}'${assertion};`;
  11497. if (!reexports && !imports) {
  11498. importBlock.push(`import${_}${pathWithAssertion}`);
  11499. continue;
  11500. }
  11501. if (imports) {
  11502. let defaultImport = null;
  11503. let starImport = null;
  11504. const importedNames = [];
  11505. for (const specifier of imports) {
  11506. if (specifier.imported === 'default') {
  11507. defaultImport = specifier;
  11508. }
  11509. else if (specifier.imported === '*') {
  11510. starImport = specifier;
  11511. }
  11512. else {
  11513. importedNames.push(specifier);
  11514. }
  11515. }
  11516. if (starImport) {
  11517. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  11518. }
  11519. if (defaultImport && importedNames.length === 0) {
  11520. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  11521. }
  11522. else if (importedNames.length > 0) {
  11523. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  11524. .map(specifier => specifier.imported === specifier.local
  11525. ? specifier.imported
  11526. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  11527. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11528. }
  11529. }
  11530. if (reexports) {
  11531. let starExport = null;
  11532. const namespaceReexports = [];
  11533. const namedReexports = [];
  11534. for (const specifier of reexports) {
  11535. if (specifier.reexported === '*') {
  11536. starExport = specifier;
  11537. }
  11538. else if (specifier.imported === '*') {
  11539. namespaceReexports.push(specifier);
  11540. }
  11541. else {
  11542. namedReexports.push(specifier);
  11543. }
  11544. }
  11545. if (starExport) {
  11546. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  11547. }
  11548. if (namespaceReexports.length > 0) {
  11549. if (!imports ||
  11550. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  11551. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  11552. }
  11553. for (const specifier of namespaceReexports) {
  11554. importBlock.push(`export${_}{${_}${name === specifier.reexported
  11555. ? name
  11556. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  11557. }
  11558. }
  11559. if (namedReexports.length > 0) {
  11560. importBlock.push(`export${_}{${_}${namedReexports
  11561. .map(specifier => specifier.imported === specifier.reexported
  11562. ? stringifyIdentifierIfNeeded(specifier.imported)
  11563. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  11564. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11565. }
  11566. }
  11567. }
  11568. return importBlock;
  11569. }
  11570. function getExportBlock(exports, { _, cnst }) {
  11571. const exportBlock = [];
  11572. const exportDeclaration = new Array(exports.length);
  11573. let index = 0;
  11574. for (const specifier of exports) {
  11575. if (specifier.expression) {
  11576. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  11577. }
  11578. exportDeclaration[index++] =
  11579. specifier.exported === specifier.local
  11580. ? specifier.local
  11581. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  11582. }
  11583. if (exportDeclaration.length > 0) {
  11584. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  11585. }
  11586. return exportBlock;
  11587. }
  11588. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  11589. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  11590. const parts = name.split('.');
  11591. // Check if the key exists in the object's prototype.
  11592. const isReserved = parts[0] in Object.prototype;
  11593. if (log && isReserved) {
  11594. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  11595. }
  11596. parts[0] =
  11597. (typeof globals === 'function'
  11598. ? globals(parts[0])
  11599. : isReserved
  11600. ? parts[0]
  11601. : globals[parts[0]]) || parts[0];
  11602. parts.pop();
  11603. let propertyPath = root;
  11604. return (parts
  11605. .map(part => {
  11606. propertyPath += getPropertyAccess(part);
  11607. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  11608. })
  11609. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  11610. }
  11611. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  11612. const parts = deepName.split('.');
  11613. // Check if the key exists in the object's prototype.
  11614. const isReserved = parts[0] in Object.prototype;
  11615. if (log && isReserved) {
  11616. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  11617. }
  11618. parts[0] =
  11619. (typeof globals === 'function'
  11620. ? globals(parts[0])
  11621. : isReserved
  11622. ? parts[0]
  11623. : globals[parts[0]]) || parts[0];
  11624. const last = parts.pop();
  11625. let propertyPath = root;
  11626. let deepAssignment = [
  11627. ...parts.map(part => {
  11628. propertyPath += getPropertyAccess(part);
  11629. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  11630. }),
  11631. `${propertyPath}${getPropertyAccess(last)}`
  11632. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  11633. if (parts.length > 0) {
  11634. deepAssignment = `(${deepAssignment})`;
  11635. }
  11636. return deepAssignment;
  11637. }
  11638. function trimEmptyImports(dependencies) {
  11639. let index = dependencies.length;
  11640. while (index--) {
  11641. const { imports, reexports } = dependencies[index];
  11642. if (imports || reexports) {
  11643. return dependencies.slice(0, index + 1);
  11644. }
  11645. }
  11646. return [];
  11647. }
  11648. 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 }) {
  11649. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  11650. const isNamespaced = name && name.includes('.');
  11651. const useVariableAssignment = !extend && !isNamespaced;
  11652. if (name && useVariableAssignment && !isLegal(name)) {
  11653. return parseAst_js.error(parseAst_js.logIllegalIdentifierAsName(name));
  11654. }
  11655. warnOnBuiltins(log, dependencies);
  11656. const external = trimEmptyImports(dependencies);
  11657. const deps = external.map(dep => dep.globalName || 'null');
  11658. const parameters = external.map(m => m.name);
  11659. if (hasExports && !name) {
  11660. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNameOptionForIifeExport());
  11661. }
  11662. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  11663. if (extend) {
  11664. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  11665. parameters.unshift('exports');
  11666. }
  11667. else {
  11668. deps.unshift('{}');
  11669. parameters.unshift('exports');
  11670. }
  11671. }
  11672. const useStrict = strict ? `${t}'use strict';${n}` : '';
  11673. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  11674. magicString.prepend(`${intro}${interopBlock}`);
  11675. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  11676. isAsync: false,
  11677. name: null
  11678. })}{${n}${useStrict}${n}`;
  11679. if (hasExports) {
  11680. if (name && !(extend && namedExportsMode)) {
  11681. wrapperIntro =
  11682. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  11683. `${_}=${_}${wrapperIntro}`;
  11684. }
  11685. if (isNamespaced) {
  11686. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  11687. }
  11688. }
  11689. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  11690. if (hasExports && !extend && namedExportsMode) {
  11691. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  11692. }
  11693. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11694. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  11695. if (namespaceMarkers) {
  11696. namespaceMarkers = n + n + namespaceMarkers;
  11697. }
  11698. magicString
  11699. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11700. .indent(t)
  11701. .prepend(wrapperIntro)
  11702. .append(wrapperOutro);
  11703. }
  11704. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11705. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  11706. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  11707. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  11708. const registeredName = name ? `'${name}',${_}` : '';
  11709. const wrapperParameters = accessedGlobals.has('module')
  11710. ? ['exports', 'module']
  11711. : hasExports
  11712. ? ['exports']
  11713. : [];
  11714. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11715. // cf. https://v8.dev/blog/preparser#pife
  11716. let wrapperStart = `System.register(${registeredName}[` +
  11717. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  11718. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  11719. isAsync: false,
  11720. name: null
  11721. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  11722. getStarExcludesBlock(starExcludes, t, snippets) +
  11723. getImportBindingsBlock(importBindings, t, snippets) +
  11724. `${n}${t}return${_}{${setters.length > 0
  11725. ? `${n}${t}${t}setters:${_}[${setters
  11726. .map(setter => setter
  11727. ? `${getFunctionIntro(['module'], {
  11728. isAsync: false,
  11729. name: null
  11730. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  11731. : systemNullSetters
  11732. ? `null`
  11733. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  11734. .join(`,${_}`)}],`
  11735. : ''}${n}`;
  11736. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  11737. isAsync: usesTopLevelAwait,
  11738. name: null
  11739. })}{${n}${n}`;
  11740. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  11741. magicString
  11742. .prepend(intro +
  11743. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  11744. getHoistedExportsBlock(exports, t, snippets))
  11745. .append(`${outro}${n}${n}` +
  11746. getSyntheticExportsBlock(exports, t, snippets) +
  11747. getMissingExportsBlock(exports, t, snippets))
  11748. .indent(`${t}${t}${t}`)
  11749. .append(wrapperEnd)
  11750. .prepend(wrapperStart);
  11751. }
  11752. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  11753. const importBindings = [];
  11754. const setters = [];
  11755. let starExcludes = null;
  11756. for (const { imports, reexports } of dependencies) {
  11757. const setter = [];
  11758. if (imports) {
  11759. for (const specifier of imports) {
  11760. importBindings.push(specifier.local);
  11761. if (specifier.imported === '*') {
  11762. setter.push(`${specifier.local}${_}=${_}module;`);
  11763. }
  11764. else {
  11765. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  11766. }
  11767. }
  11768. }
  11769. if (reexports) {
  11770. const reexportedNames = [];
  11771. let hasStarReexport = false;
  11772. for (const { imported, reexported } of reexports) {
  11773. if (reexported === '*') {
  11774. hasStarReexport = true;
  11775. }
  11776. else {
  11777. reexportedNames.push([
  11778. reexported,
  11779. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  11780. ]);
  11781. }
  11782. }
  11783. if (reexportedNames.length > 1 || hasStarReexport) {
  11784. if (hasStarReexport) {
  11785. if (!starExcludes) {
  11786. starExcludes = getStarExcludes({ dependencies, exports });
  11787. }
  11788. reexportedNames.unshift([null, `__proto__:${_}null`]);
  11789. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  11790. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  11791. }
  11792. else {
  11793. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  11794. setter.push(`exports(${exportMapping});`);
  11795. }
  11796. }
  11797. else {
  11798. const [key, value] = reexportedNames[0];
  11799. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  11800. }
  11801. }
  11802. setters.push(setter.join(`${n}${t}${t}${t}`));
  11803. }
  11804. return { importBindings, setters, starExcludes };
  11805. }
  11806. const getStarExcludes = ({ dependencies, exports }) => {
  11807. const starExcludes = new Set(exports.map(expt => expt.exported));
  11808. starExcludes.add('default');
  11809. for (const { reexports } of dependencies) {
  11810. if (reexports) {
  11811. for (const reexport of reexports) {
  11812. if (reexport.reexported !== '*')
  11813. starExcludes.add(reexport.reexported);
  11814. }
  11815. }
  11816. }
  11817. return starExcludes;
  11818. };
  11819. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  11820. if (starExcludes) {
  11821. const fields = [...starExcludes].map(property => [
  11822. property,
  11823. '1'
  11824. ]);
  11825. fields.unshift([null, `__proto__:${_}null`]);
  11826. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  11827. lineBreakIndent: { base: t, t }
  11828. })};`;
  11829. }
  11830. return '';
  11831. };
  11832. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  11833. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  11834. function getExportsBlock(exports, t, { _, n }) {
  11835. if (exports.length === 0) {
  11836. return '';
  11837. }
  11838. if (exports.length === 1) {
  11839. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  11840. }
  11841. return (`exports({${n}` +
  11842. exports
  11843. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  11844. .join(`,${n}`) +
  11845. `${n}});${n}${n}`);
  11846. }
  11847. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  11848. .filter(expt => expt.expression)
  11849. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  11850. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  11851. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  11852. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  11853. function globalProperty(name, globalVariable, getPropertyAccess) {
  11854. if (!name)
  11855. return 'null';
  11856. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  11857. }
  11858. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  11859. let propertyPath = globalVariable;
  11860. return name
  11861. .split('.')
  11862. .map(part => (propertyPath += getPropertyAccess(part)))
  11863. .join(`${_}&&${_}`);
  11864. }
  11865. 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 }) {
  11866. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  11867. const factoryVariable = compact ? 'f' : 'factory';
  11868. const globalVariable = compact ? 'g' : 'global';
  11869. if (hasExports && !name) {
  11870. return parseAst_js.error(parseAst_js.logMissingNameOptionForUmdExport());
  11871. }
  11872. warnOnBuiltins(log, dependencies);
  11873. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  11874. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  11875. const trimmedImports = trimEmptyImports(dependencies);
  11876. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  11877. const factoryParameters = trimmedImports.map(m => m.name);
  11878. if ((hasExports || noConflict) &&
  11879. (namedExportsMode || (hasExports && exports[0]?.local === 'exports.default'))) {
  11880. amdDeps.unshift(`'exports'`);
  11881. cjsDeps.unshift(`exports`);
  11882. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  11883. factoryParameters.unshift('exports');
  11884. }
  11885. const completeAmdId = getCompleteAmdId(amd, id);
  11886. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  11887. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  11888. const define = amd.define;
  11889. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  11890. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  11891. let iifeExport;
  11892. if (noConflict) {
  11893. const noConflictExportsVariable = compact ? 'e' : 'exports';
  11894. let factory;
  11895. if (!namedExportsMode && hasExports) {
  11896. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  11897. }
  11898. else {
  11899. const module = globalDeps.shift();
  11900. factory =
  11901. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  11902. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  11903. }
  11904. iifeExport =
  11905. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  11906. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  11907. `${t}${t}${factory}${n}` +
  11908. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  11909. isAsync: false,
  11910. name: null
  11911. })}{${_}` +
  11912. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  11913. `${t}})()`;
  11914. }
  11915. else {
  11916. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  11917. if (!namedExportsMode && hasExports) {
  11918. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  11919. }
  11920. }
  11921. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  11922. const wrapperParameters = [factoryVariable];
  11923. if (iifeNeedsGlobal) {
  11924. wrapperParameters.unshift(globalVariable);
  11925. }
  11926. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  11927. const iifeStart = iifeNeedsGlobal
  11928. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  11929. : '';
  11930. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  11931. const cjsIntro = iifeNeedsGlobal
  11932. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  11933. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  11934. : '';
  11935. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  11936. cjsIntro +
  11937. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  11938. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  11939. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11940. // cf. https://v8.dev/blog/preparser#pife
  11941. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  11942. isAsync: false,
  11943. name: null
  11944. })}{${useStrict}${n}`;
  11945. const wrapperOutro = n + n + '}));';
  11946. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  11947. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11948. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  11949. if (namespaceMarkers) {
  11950. namespaceMarkers = n + n + namespaceMarkers;
  11951. }
  11952. magicString
  11953. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11954. .trim()
  11955. .indent(t)
  11956. .append(wrapperOutro)
  11957. .prepend(wrapperIntro);
  11958. }
  11959. const finalisers = { amd, cjs, es, iife, system, umd };
  11960. const extractors = {
  11961. ArrayPattern(names, param) {
  11962. for (const element of param.elements) {
  11963. if (element)
  11964. extractors[element.type](names, element);
  11965. }
  11966. },
  11967. AssignmentPattern(names, param) {
  11968. extractors[param.left.type](names, param.left);
  11969. },
  11970. Identifier(names, param) {
  11971. names.push(param.name);
  11972. },
  11973. MemberExpression() { },
  11974. ObjectPattern(names, param) {
  11975. for (const prop of param.properties) {
  11976. // @ts-ignore Typescript reports that this is not a valid type
  11977. if (prop.type === 'RestElement') {
  11978. extractors.RestElement(names, prop);
  11979. }
  11980. else {
  11981. extractors[prop.value.type](names, prop.value);
  11982. }
  11983. }
  11984. },
  11985. RestElement(names, param) {
  11986. extractors[param.argument.type](names, param.argument);
  11987. }
  11988. };
  11989. const extractAssignedNames = function extractAssignedNames(param) {
  11990. const names = [];
  11991. extractors[param.type](names, param);
  11992. return names;
  11993. };
  11994. // Helper since Typescript can't detect readonly arrays with Array.isArray
  11995. function isArray(arg) {
  11996. return Array.isArray(arg);
  11997. }
  11998. function ensureArray(thing) {
  11999. if (isArray(thing))
  12000. return thing;
  12001. if (thing == null)
  12002. return [];
  12003. return [thing];
  12004. }
  12005. const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
  12006. const normalizePath = function normalizePath(filename) {
  12007. return filename.replace(normalizePathRegExp, require$$0.posix.sep);
  12008. };
  12009. function getMatcherString(id, resolutionBase) {
  12010. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
  12011. return normalizePath(id);
  12012. }
  12013. // resolve('') is valid and will default to process.cwd()
  12014. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  12015. // escape all possible (posix + win) path characters that might interfere with regex
  12016. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  12017. // Note that we use posix.join because:
  12018. // 1. the basePath has been normalized to use /
  12019. // 2. the incoming glob (id) matcher, also uses /
  12020. // otherwise Node will force backslash (\) on windows
  12021. return require$$0.posix.join(basePath, normalizePath(id));
  12022. }
  12023. const createFilter = function createFilter(include, exclude, options) {
  12024. const resolutionBase = options && options.resolve;
  12025. const getMatcher = (id) => id instanceof RegExp
  12026. ? id
  12027. : {
  12028. test: (what) => {
  12029. // this refactor is a tad overly verbose but makes for easy debugging
  12030. const pattern = getMatcherString(id, resolutionBase);
  12031. const fn = pm(pattern, { dot: true });
  12032. const result = fn(what);
  12033. return result;
  12034. }
  12035. };
  12036. const includeMatchers = ensureArray(include).map(getMatcher);
  12037. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  12038. if (!includeMatchers.length && !excludeMatchers.length)
  12039. return (id) => typeof id === 'string' && !id.includes('\0');
  12040. return function result(id) {
  12041. if (typeof id !== 'string')
  12042. return false;
  12043. if (id.includes('\0'))
  12044. return false;
  12045. const pathId = normalizePath(id);
  12046. for (let i = 0; i < excludeMatchers.length; ++i) {
  12047. const matcher = excludeMatchers[i];
  12048. if (matcher instanceof RegExp) {
  12049. matcher.lastIndex = 0;
  12050. }
  12051. if (matcher.test(pathId))
  12052. return false;
  12053. }
  12054. for (let i = 0; i < includeMatchers.length; ++i) {
  12055. const matcher = includeMatchers[i];
  12056. if (matcher instanceof RegExp) {
  12057. matcher.lastIndex = 0;
  12058. }
  12059. if (matcher.test(pathId))
  12060. return true;
  12061. }
  12062. return !includeMatchers.length;
  12063. };
  12064. };
  12065. 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';
  12066. 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';
  12067. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  12068. forbiddenIdentifiers.add('');
  12069. class ArrayPattern extends NodeBase {
  12070. addExportedVariables(variables, exportNamesByVariable) {
  12071. for (const element of this.elements) {
  12072. element?.addExportedVariables(variables, exportNamesByVariable);
  12073. }
  12074. }
  12075. declare(kind, destructuredInitPath, init) {
  12076. const variables = [];
  12077. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12078. for (const element of this.elements) {
  12079. if (element !== null) {
  12080. variables.push(...element.declare(kind, includedPatternPath, init));
  12081. }
  12082. }
  12083. return variables;
  12084. }
  12085. deoptimizeAssignment(destructuredInitPath, init) {
  12086. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12087. for (const element of this.elements) {
  12088. element?.deoptimizeAssignment(includedPatternPath, init);
  12089. }
  12090. }
  12091. // Patterns can only be deoptimized at the empty path at the moment
  12092. deoptimizePath() {
  12093. for (const element of this.elements) {
  12094. element?.deoptimizePath(EMPTY_PATH);
  12095. }
  12096. }
  12097. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12098. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12099. for (const element of this.elements) {
  12100. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  12101. return true;
  12102. }
  12103. }
  12104. return false;
  12105. }
  12106. // Patterns are only checked at the empty path at the moment
  12107. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  12108. for (const element of this.elements) {
  12109. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12110. return true;
  12111. }
  12112. return false;
  12113. }
  12114. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12115. let included = false;
  12116. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12117. for (const element of this.elements) {
  12118. if (element) {
  12119. element.included ||= included;
  12120. included =
  12121. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  12122. }
  12123. }
  12124. if (included) {
  12125. // This is necessary so that if any pattern element is included, all are
  12126. // included for proper deconflicting
  12127. for (const element of this.elements) {
  12128. if (element && !element.included) {
  12129. element.included = true;
  12130. element.includeDestructuredIfNecessary(context, includedPatternPath, init);
  12131. }
  12132. }
  12133. }
  12134. return (this.included ||= included);
  12135. }
  12136. markDeclarationReached() {
  12137. for (const element of this.elements) {
  12138. element?.markDeclarationReached();
  12139. }
  12140. }
  12141. }
  12142. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  12143. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  12144. ? destructuredInitPath
  12145. : [...destructuredInitPath, UnknownInteger];
  12146. class ArrowFunctionExpression extends FunctionBase {
  12147. constructor() {
  12148. super(...arguments);
  12149. this.objectEntity = null;
  12150. }
  12151. get expression() {
  12152. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  12153. }
  12154. set expression(value) {
  12155. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  12156. }
  12157. createScope(parentScope) {
  12158. this.scope = new ReturnValueScope(parentScope, false);
  12159. }
  12160. hasEffects() {
  12161. return false;
  12162. }
  12163. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12164. if (this.annotationNoSideEffects &&
  12165. path.length === 0 &&
  12166. interaction.type === INTERACTION_CALLED) {
  12167. return false;
  12168. }
  12169. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  12170. return true;
  12171. }
  12172. if (interaction.type === INTERACTION_CALLED) {
  12173. const { ignore, brokenFlow } = context;
  12174. context.ignore = {
  12175. breaks: false,
  12176. continues: false,
  12177. labels: new Set(),
  12178. returnYield: true,
  12179. this: false
  12180. };
  12181. if (this.body.hasEffects(context))
  12182. return true;
  12183. context.ignore = ignore;
  12184. context.brokenFlow = brokenFlow;
  12185. }
  12186. return false;
  12187. }
  12188. onlyFunctionCallUsed() {
  12189. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  12190. this.parent.callee === this;
  12191. return isIIFE || super.onlyFunctionCallUsed();
  12192. }
  12193. include(context, includeChildrenRecursively) {
  12194. super.include(context, includeChildrenRecursively);
  12195. for (const parameter of this.params) {
  12196. if (!(parameter instanceof Identifier)) {
  12197. parameter.include(context, includeChildrenRecursively);
  12198. }
  12199. }
  12200. }
  12201. includeNode(context) {
  12202. this.included = true;
  12203. this.body.includePath(UNKNOWN_PATH, context);
  12204. for (const parameter of this.params) {
  12205. if (!(parameter instanceof Identifier)) {
  12206. parameter.includePath(UNKNOWN_PATH, context);
  12207. }
  12208. }
  12209. }
  12210. getObjectEntity() {
  12211. if (this.objectEntity !== null) {
  12212. return this.objectEntity;
  12213. }
  12214. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  12215. }
  12216. }
  12217. class ObjectPattern extends NodeBase {
  12218. addExportedVariables(variables, exportNamesByVariable) {
  12219. for (const property of this.properties) {
  12220. if (property.type === parseAst_js.Property) {
  12221. property.value.addExportedVariables(variables, exportNamesByVariable);
  12222. }
  12223. else {
  12224. property.argument.addExportedVariables(variables, exportNamesByVariable);
  12225. }
  12226. }
  12227. }
  12228. declare(kind, destructuredInitPath, init) {
  12229. const variables = [];
  12230. for (const property of this.properties) {
  12231. variables.push(...property.declare(kind, destructuredInitPath, init));
  12232. }
  12233. return variables;
  12234. }
  12235. deoptimizeAssignment(destructuredInitPath, init) {
  12236. for (const property of this.properties) {
  12237. property.deoptimizeAssignment(destructuredInitPath, init);
  12238. }
  12239. }
  12240. deoptimizePath(path) {
  12241. if (path.length === 0) {
  12242. for (const property of this.properties) {
  12243. property.deoptimizePath(path);
  12244. }
  12245. }
  12246. }
  12247. hasEffectsOnInteractionAtPath(
  12248. // At the moment, this is only triggered for assignment left-hand sides,
  12249. // where the path is empty
  12250. _path, interaction, context) {
  12251. for (const property of this.properties) {
  12252. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12253. return true;
  12254. }
  12255. return false;
  12256. }
  12257. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12258. for (const property of this.properties) {
  12259. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  12260. return true;
  12261. }
  12262. return false;
  12263. }
  12264. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12265. if (!this.properties.length)
  12266. return false;
  12267. const lastProperty = this.properties.at(-1);
  12268. const lastPropertyIncluded = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12269. const lastPropertyIsRestElement = lastProperty.type === parseAst_js.RestElement;
  12270. let included = lastPropertyIsRestElement ? lastPropertyIncluded : false;
  12271. for (const property of this.properties.slice(0, -1)) {
  12272. if (lastPropertyIsRestElement && lastPropertyIncluded) {
  12273. property.includeNode(context);
  12274. }
  12275. included =
  12276. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  12277. }
  12278. return (this.included ||= included);
  12279. }
  12280. markDeclarationReached() {
  12281. for (const property of this.properties) {
  12282. property.markDeclarationReached();
  12283. }
  12284. }
  12285. render(code, options) {
  12286. if (this.properties.length > 0) {
  12287. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  12288. let lastSeparatorPos = null;
  12289. for (const { node, separator, start, end } of separatedNodes) {
  12290. if (!node.included) {
  12291. treeshakeNode(node, code, start, end);
  12292. continue;
  12293. }
  12294. lastSeparatorPos = separator;
  12295. node.render(code, options);
  12296. }
  12297. if (lastSeparatorPos) {
  12298. code.remove(lastSeparatorPos, this.end - 1);
  12299. }
  12300. }
  12301. }
  12302. }
  12303. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12304. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  12305. class AssignmentExpression extends NodeBase {
  12306. hasEffects(context) {
  12307. const { deoptimized, left, operator, right } = this;
  12308. if (!deoptimized)
  12309. this.applyDeoptimizations();
  12310. // MemberExpressions do not access the property before assignments if the
  12311. // operator is '='.
  12312. return (right.hasEffects(context) ||
  12313. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  12314. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  12315. }
  12316. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12317. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  12318. }
  12319. include(context, includeChildrenRecursively) {
  12320. const { deoptimized, left, right, operator } = this;
  12321. if (!deoptimized)
  12322. this.applyDeoptimizations();
  12323. if (!this.included)
  12324. this.includeNode(context);
  12325. const hasEffectsContext = createHasEffectsContext();
  12326. if (includeChildrenRecursively ||
  12327. operator !== '=' ||
  12328. left.included ||
  12329. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  12330. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  12331. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  12332. }
  12333. right.include(context, includeChildrenRecursively);
  12334. }
  12335. includeNode(context) {
  12336. this.included = true;
  12337. if (!this.deoptimized)
  12338. this.applyDeoptimizations();
  12339. this.right.includePath(UNKNOWN_PATH, context);
  12340. }
  12341. initialise() {
  12342. super.initialise();
  12343. if (this.left instanceof Identifier) {
  12344. const variable = this.scope.variables.get(this.left.name);
  12345. if (variable?.kind === 'const') {
  12346. this.scope.context.error(parseAst_js.logConstVariableReassignError(), this.left.start);
  12347. }
  12348. }
  12349. this.left.setAssignedValue(this.right);
  12350. }
  12351. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12352. const { left, right, start, end, parent } = this;
  12353. if (left.included) {
  12354. left.render(code, options);
  12355. right.render(code, options);
  12356. }
  12357. else {
  12358. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  12359. code.remove(start, inclusionStart);
  12360. if (preventASI) {
  12361. removeLineBreaks(code, inclusionStart, right.start);
  12362. }
  12363. right.render(code, options, {
  12364. renderedParentType: renderedParentType || parent.type,
  12365. renderedSurroundingElement: renderedSurroundingElement || parent.type
  12366. });
  12367. }
  12368. if (options.format === 'system') {
  12369. if (left instanceof Identifier) {
  12370. const variable = left.variable;
  12371. const exportNames = options.exportNamesByVariable.get(variable);
  12372. if (exportNames) {
  12373. if (exportNames.length === 1) {
  12374. renderSystemExportExpression(variable, start, end, code, options);
  12375. }
  12376. else {
  12377. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== parseAst_js.ExpressionStatement, code, options);
  12378. }
  12379. return;
  12380. }
  12381. }
  12382. else {
  12383. const systemPatternExports = [];
  12384. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  12385. if (systemPatternExports.length > 0) {
  12386. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === parseAst_js.ExpressionStatement, code, options);
  12387. return;
  12388. }
  12389. }
  12390. }
  12391. if (left.included &&
  12392. left instanceof ObjectPattern &&
  12393. (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  12394. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression)) {
  12395. code.appendRight(start, '(');
  12396. code.prependLeft(end, ')');
  12397. }
  12398. }
  12399. applyDeoptimizations() {
  12400. this.deoptimized = true;
  12401. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  12402. this.scope.context.requestTreeshakingPass();
  12403. }
  12404. }
  12405. class AssignmentPattern extends NodeBase {
  12406. addExportedVariables(variables, exportNamesByVariable) {
  12407. this.left.addExportedVariables(variables, exportNamesByVariable);
  12408. }
  12409. declare(kind, destructuredInitPath, init) {
  12410. return this.left.declare(kind, destructuredInitPath, init);
  12411. }
  12412. deoptimizeAssignment(destructuredInitPath, init) {
  12413. this.left.deoptimizeAssignment(destructuredInitPath, init);
  12414. }
  12415. deoptimizePath(path) {
  12416. if (path.length === 0) {
  12417. this.left.deoptimizePath(path);
  12418. }
  12419. }
  12420. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12421. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  12422. }
  12423. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12424. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  12425. }
  12426. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12427. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  12428. this.included;
  12429. if ((included ||= this.right.shouldBeIncluded(context))) {
  12430. this.right.include(context, false);
  12431. if (!this.left.included) {
  12432. this.left.included = true;
  12433. // Unfortunately, we need to include the left side again now, so that
  12434. // any declared variables are properly included.
  12435. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12436. }
  12437. }
  12438. return (this.included = included);
  12439. }
  12440. includeNode(context) {
  12441. this.included = true;
  12442. if (!this.deoptimized)
  12443. this.applyDeoptimizations();
  12444. this.right.includePath(UNKNOWN_PATH, context);
  12445. }
  12446. markDeclarationReached() {
  12447. this.left.markDeclarationReached();
  12448. }
  12449. render(code, options, { isShorthandProperty } = parseAst_js.BLANK) {
  12450. this.left.render(code, options, { isShorthandProperty });
  12451. this.right.render(code, options);
  12452. }
  12453. applyDeoptimizations() {
  12454. this.deoptimized = true;
  12455. this.left.deoptimizePath(EMPTY_PATH);
  12456. this.right.deoptimizePath(UNKNOWN_PATH);
  12457. this.scope.context.requestTreeshakingPass();
  12458. }
  12459. }
  12460. class AwaitExpression extends NodeBase {
  12461. hasEffects() {
  12462. if (!this.deoptimized)
  12463. this.applyDeoptimizations();
  12464. return true;
  12465. }
  12466. initialise() {
  12467. super.initialise();
  12468. let parent = this.parent;
  12469. do {
  12470. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  12471. return;
  12472. } while ((parent = parent.parent));
  12473. this.scope.context.usesTopLevelAwait = true;
  12474. }
  12475. include(context, includeChildrenRecursively) {
  12476. if (!this.included)
  12477. this.includeNode(context);
  12478. this.argument.include(context, includeChildrenRecursively);
  12479. }
  12480. includeNode(context) {
  12481. this.included = true;
  12482. if (!this.deoptimized)
  12483. this.applyDeoptimizations();
  12484. // Thenables need to be included
  12485. this.argument.includePath(THEN_PATH, context);
  12486. }
  12487. includePath(path, context) {
  12488. if (!this.deoptimized)
  12489. this.applyDeoptimizations();
  12490. if (!this.included)
  12491. this.includeNode(context);
  12492. this.argument.includePath(path, context);
  12493. }
  12494. }
  12495. const THEN_PATH = ['then'];
  12496. const binaryOperators = {
  12497. '!=': (left, right) => left != right,
  12498. '!==': (left, right) => left !== right,
  12499. '%': (left, right) => left % right,
  12500. '&': (left, right) => left & right,
  12501. '*': (left, right) => left * right,
  12502. // At the moment, "**" will be transpiled to Math.pow
  12503. '**': (left, right) => left ** right,
  12504. '+': (left, right) => left + right,
  12505. '-': (left, right) => left - right,
  12506. '/': (left, right) => left / right,
  12507. '<': (left, right) => left < right,
  12508. '<<': (left, right) => left << right,
  12509. '<=': (left, right) => left <= right,
  12510. '==': (left, right) => left == right,
  12511. '===': (left, right) => left === right,
  12512. '>': (left, right) => left > right,
  12513. '>=': (left, right) => left >= right,
  12514. '>>': (left, right) => left >> right,
  12515. '>>>': (left, right) => left >>> right,
  12516. '^': (left, right) => left ^ right,
  12517. '|': (left, right) => left | right
  12518. // We use the fallback for cases where we return something unknown
  12519. // in: () => UnknownValue,
  12520. // instanceof: () => UnknownValue,
  12521. };
  12522. class BinaryExpression extends NodeBase {
  12523. deoptimizeCache() { }
  12524. getLiteralValueAtPath(path, recursionTracker, origin) {
  12525. if (path.length > 0)
  12526. return UnknownValue;
  12527. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12528. if (typeof leftValue === 'symbol')
  12529. return UnknownValue;
  12530. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12531. if (typeof rightValue === 'symbol')
  12532. return UnknownValue;
  12533. const operatorFunction = binaryOperators[this.operator];
  12534. if (!operatorFunction)
  12535. return UnknownValue;
  12536. return operatorFunction(leftValue, rightValue);
  12537. }
  12538. hasEffects(context) {
  12539. // support some implicit type coercion runtime errors
  12540. if (this.operator === '+' &&
  12541. this.parent instanceof ExpressionStatement &&
  12542. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  12543. return true;
  12544. }
  12545. return super.hasEffects(context);
  12546. }
  12547. hasEffectsOnInteractionAtPath(path, { type }) {
  12548. return type !== INTERACTION_ACCESSED || path.length > 1;
  12549. }
  12550. includeNode(context) {
  12551. this.included = true;
  12552. if (this.operator === 'in') {
  12553. this.right.includePath(UNKNOWN_PATH, context);
  12554. }
  12555. }
  12556. removeAnnotations(code) {
  12557. this.left.removeAnnotations(code);
  12558. }
  12559. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12560. this.left.render(code, options, { renderedSurroundingElement });
  12561. this.right.render(code, options);
  12562. }
  12563. }
  12564. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12565. class BreakStatement extends NodeBase {
  12566. hasEffects(context) {
  12567. if (this.label) {
  12568. if (!context.ignore.labels.has(this.label.name))
  12569. return true;
  12570. context.includedLabels.add(this.label.name);
  12571. }
  12572. else {
  12573. if (!context.ignore.breaks)
  12574. return true;
  12575. context.hasBreak = true;
  12576. }
  12577. context.brokenFlow = true;
  12578. return false;
  12579. }
  12580. include(context, includeChildrenRecursively) {
  12581. this.included = true;
  12582. if (this.label) {
  12583. this.label.include(context, includeChildrenRecursively);
  12584. context.includedLabels.add(this.label.name);
  12585. }
  12586. else {
  12587. context.hasBreak = true;
  12588. }
  12589. context.brokenFlow = true;
  12590. }
  12591. }
  12592. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12593. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12594. function renderCallArguments(code, options, node) {
  12595. if (node.arguments.length > 0) {
  12596. if (node.arguments[node.arguments.length - 1].included) {
  12597. for (const argument of node.arguments) {
  12598. argument.render(code, options);
  12599. }
  12600. }
  12601. else {
  12602. let lastIncludedIndex = node.arguments.length - 2;
  12603. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  12604. lastIncludedIndex--;
  12605. }
  12606. if (lastIncludedIndex >= 0) {
  12607. for (let index = 0; index <= lastIncludedIndex; index++) {
  12608. node.arguments[index].render(code, options);
  12609. }
  12610. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  12611. }
  12612. else {
  12613. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  12614. }
  12615. }
  12616. }
  12617. }
  12618. class CallExpressionBase extends NodeBase {
  12619. constructor() {
  12620. super(...arguments);
  12621. this.returnExpression = null;
  12622. this.deoptimizableDependentExpressions = [];
  12623. this.expressionsToBeDeoptimized = new Set();
  12624. }
  12625. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12626. const { args } = interaction;
  12627. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  12628. if (isPure)
  12629. return;
  12630. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  12631. if (deoptimizedExpressions.length === 0)
  12632. return;
  12633. if (returnExpression === UNKNOWN_EXPRESSION) {
  12634. for (const expression of deoptimizedExpressions) {
  12635. expression.deoptimizePath(UNKNOWN_PATH);
  12636. }
  12637. }
  12638. else {
  12639. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12640. for (const expression of deoptimizedExpressions) {
  12641. this.expressionsToBeDeoptimized.add(expression);
  12642. }
  12643. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12644. }, null);
  12645. }
  12646. }
  12647. deoptimizeCache() {
  12648. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  12649. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12650. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  12651. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_SET;
  12652. this.deoptimizableDependentExpressions = parseAst_js.EMPTY_ARRAY;
  12653. for (const expression of deoptimizableDependentExpressions) {
  12654. expression.deoptimizeCache();
  12655. }
  12656. for (const expression of expressionsToBeDeoptimized) {
  12657. expression.deoptimizePath(UNKNOWN_PATH);
  12658. }
  12659. }
  12660. }
  12661. deoptimizePath(path) {
  12662. if (path.length === 0 ||
  12663. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  12664. return;
  12665. }
  12666. const [returnExpression] = this.getReturnExpression();
  12667. if (returnExpression !== UNKNOWN_EXPRESSION) {
  12668. returnExpression.deoptimizePath(path);
  12669. }
  12670. }
  12671. getLiteralValueAtPath(path, recursionTracker, origin) {
  12672. const [returnExpression] = this.getReturnExpression(recursionTracker);
  12673. if (returnExpression === UNKNOWN_EXPRESSION) {
  12674. return UnknownValue;
  12675. }
  12676. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12677. this.deoptimizableDependentExpressions.push(origin);
  12678. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  12679. }, UnknownValue);
  12680. }
  12681. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12682. const returnExpression = this.getReturnExpression(recursionTracker);
  12683. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  12684. return returnExpression;
  12685. }
  12686. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12687. this.deoptimizableDependentExpressions.push(origin);
  12688. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12689. return [expression, isPure || returnExpression[1]];
  12690. }, UNKNOWN_RETURN_EXPRESSION);
  12691. }
  12692. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12693. const { type } = interaction;
  12694. if (type === INTERACTION_CALLED) {
  12695. const { args, withNew } = interaction;
  12696. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  12697. return false;
  12698. }
  12699. }
  12700. else if ((type === INTERACTION_ASSIGNED
  12701. ? context.assigned
  12702. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  12703. return false;
  12704. }
  12705. const [returnExpression, isPure] = this.getReturnExpression();
  12706. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  12707. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  12708. }
  12709. }
  12710. class CallExpression extends CallExpressionBase {
  12711. get hasCheckedForWarnings() {
  12712. return isFlagSet(this.flags, 268435456 /* Flag.checkedForWarnings */);
  12713. }
  12714. set hasCheckedForWarnings(value) {
  12715. this.flags = setFlag(this.flags, 268435456 /* Flag.checkedForWarnings */, value);
  12716. }
  12717. get optional() {
  12718. return isFlagSet(this.flags, 128 /* Flag.optional */);
  12719. }
  12720. set optional(value) {
  12721. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  12722. }
  12723. bind() {
  12724. super.bind();
  12725. this.interaction = {
  12726. args: [
  12727. this.callee instanceof MemberExpression && !this.callee.variable
  12728. ? this.callee.object
  12729. : null,
  12730. ...this.arguments
  12731. ],
  12732. type: INTERACTION_CALLED,
  12733. withNew: false
  12734. };
  12735. }
  12736. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  12737. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  12738. }
  12739. hasEffects(context) {
  12740. if (!this.deoptimized)
  12741. this.applyDeoptimizations();
  12742. for (const argument of this.arguments) {
  12743. if (argument.hasEffects(context))
  12744. return true;
  12745. }
  12746. if (this.annotationPure) {
  12747. return false;
  12748. }
  12749. return (this.callee.hasEffects(context) ||
  12750. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12751. }
  12752. hasEffectsAsChainElement(context) {
  12753. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  12754. ? this.callee.hasEffectsAsChainElement(context)
  12755. : this.callee.hasEffects(context);
  12756. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  12757. return IS_SKIPPED_CHAIN;
  12758. if (this.optional &&
  12759. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  12760. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  12761. }
  12762. // We only apply deoptimizations lazily once we know we are not skipping
  12763. if (!this.deoptimized)
  12764. this.applyDeoptimizations();
  12765. for (const argument of this.arguments) {
  12766. if (argument.hasEffects(context))
  12767. return true;
  12768. }
  12769. return (!this.annotationPure &&
  12770. (calleeHasEffects ||
  12771. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  12772. }
  12773. include(context, includeChildrenRecursively) {
  12774. if (!this.included)
  12775. this.includeNode(context);
  12776. if (includeChildrenRecursively) {
  12777. super.include(context, true);
  12778. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  12779. this.callee instanceof Identifier &&
  12780. this.callee.variable) {
  12781. this.callee.variable.markCalledFromTryStatement();
  12782. }
  12783. }
  12784. else {
  12785. this.callee.include(context, false);
  12786. this.callee.includeCallArguments(this.interaction, context);
  12787. }
  12788. }
  12789. includeNode(context) {
  12790. this.included = true;
  12791. if (!this.deoptimized)
  12792. this.applyDeoptimizations();
  12793. this.callee.includePath(UNKNOWN_PATH, context);
  12794. }
  12795. initialise() {
  12796. super.initialise();
  12797. if (this.annotations &&
  12798. this.scope.context.options.treeshake.annotations) {
  12799. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  12800. }
  12801. }
  12802. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12803. this.callee.render(code, options, {
  12804. isCalleeOfRenderedParent: true,
  12805. renderedSurroundingElement
  12806. });
  12807. renderCallArguments(code, options, this);
  12808. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  12809. this.hasCheckedForWarnings = true;
  12810. const variable = this.scope.findVariable(this.callee.name);
  12811. if (variable.isNamespace) {
  12812. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(this.callee.name), this.start);
  12813. }
  12814. if (this.callee.name === 'eval') {
  12815. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEval(this.scope.context.module.id), this.start);
  12816. }
  12817. }
  12818. }
  12819. applyDeoptimizations() {
  12820. this.deoptimized = true;
  12821. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12822. this.scope.context.requestTreeshakingPass();
  12823. }
  12824. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  12825. if (this.returnExpression === null) {
  12826. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12827. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  12828. }
  12829. return this.returnExpression;
  12830. }
  12831. }
  12832. class CatchClause extends NodeBase {
  12833. createScope(parentScope) {
  12834. this.scope = new ParameterScope(parentScope, true);
  12835. }
  12836. parseNode(esTreeNode) {
  12837. const { body, param, type } = esTreeNode;
  12838. this.type = type;
  12839. if (param) {
  12840. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  12841. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  12842. }
  12843. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  12844. return super.parseNode(esTreeNode);
  12845. }
  12846. }
  12847. CatchClause.prototype.preventChildBlockScope = true;
  12848. CatchClause.prototype.includeNode = onlyIncludeSelf;
  12849. class ChainExpression extends NodeBase {
  12850. // deoptimizations are not relevant as we are not caching values
  12851. deoptimizeCache() { }
  12852. getLiteralValueAtPath(path, recursionTracker, origin) {
  12853. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  12854. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  12855. }
  12856. hasEffects(context) {
  12857. return this.expression.hasEffectsAsChainElement(context) === true;
  12858. }
  12859. includePath(path, context) {
  12860. this.included = true;
  12861. this.expression.includePath(path, context);
  12862. }
  12863. removeAnnotations(code) {
  12864. this.expression.removeAnnotations(code);
  12865. }
  12866. }
  12867. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12868. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12869. class ClassBodyScope extends ChildScope {
  12870. constructor(parent, classNode) {
  12871. const { context } = parent;
  12872. super(parent, context);
  12873. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  12874. this.instanceScope = new ChildScope(this, context);
  12875. this.instanceScope.variables.set('this', new ThisVariable(context));
  12876. }
  12877. findLexicalBoundary() {
  12878. return this;
  12879. }
  12880. }
  12881. class ClassBody extends NodeBase {
  12882. createScope(parentScope) {
  12883. this.scope = new ClassBodyScope(parentScope, this.parent);
  12884. }
  12885. include(context, includeChildrenRecursively) {
  12886. this.included = true;
  12887. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  12888. for (const definition of this.body) {
  12889. definition.include(context, includeChildrenRecursively);
  12890. }
  12891. }
  12892. parseNode(esTreeNode) {
  12893. const body = (this.body = new Array(esTreeNode.body.length));
  12894. let index = 0;
  12895. for (const definition of esTreeNode.body) {
  12896. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  12897. }
  12898. return super.parseNode(esTreeNode);
  12899. }
  12900. }
  12901. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12902. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  12903. class ClassExpression extends ClassNode {
  12904. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12905. super.render(code, options);
  12906. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  12907. code.appendRight(this.start, '(');
  12908. code.prependLeft(this.end, ')');
  12909. }
  12910. }
  12911. }
  12912. function tryCastLiteralValueToBoolean(literalValue) {
  12913. if (typeof literalValue === 'symbol') {
  12914. if (literalValue === UnknownFalsyValue) {
  12915. return false;
  12916. }
  12917. if (literalValue === UnknownTruthyValue) {
  12918. return true;
  12919. }
  12920. return UnknownValue;
  12921. }
  12922. return !!literalValue;
  12923. }
  12924. class MultiExpression extends ExpressionEntity {
  12925. constructor(expressions) {
  12926. super();
  12927. this.expressions = expressions;
  12928. }
  12929. deoptimizePath(path) {
  12930. for (const expression of this.expressions) {
  12931. expression.deoptimizePath(path);
  12932. }
  12933. }
  12934. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12935. return [
  12936. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  12937. false
  12938. ];
  12939. }
  12940. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12941. for (const expression of this.expressions) {
  12942. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  12943. return true;
  12944. }
  12945. return false;
  12946. }
  12947. }
  12948. class ConditionalExpression extends NodeBase {
  12949. constructor() {
  12950. super(...arguments);
  12951. this.expressionsToBeDeoptimized = [];
  12952. this.usedBranch = null;
  12953. }
  12954. get isBranchResolutionAnalysed() {
  12955. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  12956. }
  12957. set isBranchResolutionAnalysed(value) {
  12958. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  12959. }
  12960. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12961. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12962. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12963. }
  12964. deoptimizeCache() {
  12965. if (this.usedBranch !== null) {
  12966. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  12967. this.usedBranch = null;
  12968. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12969. if (this.included) {
  12970. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  12971. }
  12972. const { expressionsToBeDeoptimized } = this;
  12973. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  12974. for (const expression of expressionsToBeDeoptimized) {
  12975. expression.deoptimizeCache();
  12976. }
  12977. }
  12978. }
  12979. deoptimizePath(path) {
  12980. const usedBranch = this.getUsedBranch();
  12981. if (usedBranch) {
  12982. usedBranch.deoptimizePath(path);
  12983. }
  12984. else {
  12985. this.consequent.deoptimizePath(path);
  12986. this.alternate.deoptimizePath(path);
  12987. }
  12988. }
  12989. getLiteralValueAtPath(path, recursionTracker, origin) {
  12990. const usedBranch = this.getUsedBranch();
  12991. if (!usedBranch)
  12992. return UnknownValue;
  12993. this.expressionsToBeDeoptimized.push(origin);
  12994. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12995. }
  12996. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12997. const usedBranch = this.getUsedBranch();
  12998. if (!usedBranch)
  12999. return [
  13000. new MultiExpression([
  13001. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13002. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13003. ]),
  13004. false
  13005. ];
  13006. this.expressionsToBeDeoptimized.push(origin);
  13007. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13008. }
  13009. hasEffects(context) {
  13010. if (this.test.hasEffects(context))
  13011. return true;
  13012. const usedBranch = this.getUsedBranch();
  13013. if (!usedBranch) {
  13014. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  13015. }
  13016. return usedBranch.hasEffects(context);
  13017. }
  13018. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13019. const usedBranch = this.getUsedBranch();
  13020. if (!usedBranch) {
  13021. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13022. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  13023. }
  13024. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13025. }
  13026. include(context, includeChildrenRecursively) {
  13027. this.included = true;
  13028. const usedBranch = this.getUsedBranch();
  13029. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  13030. this.test.include(context, includeChildrenRecursively);
  13031. this.consequent.include(context, includeChildrenRecursively);
  13032. this.alternate.include(context, includeChildrenRecursively);
  13033. }
  13034. else {
  13035. usedBranch.include(context, includeChildrenRecursively);
  13036. }
  13037. }
  13038. includePath(path, context) {
  13039. this.included = true;
  13040. const usedBranch = this.getUsedBranch();
  13041. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  13042. this.consequent.includePath(path, context);
  13043. this.alternate.includePath(path, context);
  13044. }
  13045. else {
  13046. usedBranch.includePath(path, context);
  13047. }
  13048. }
  13049. includeCallArguments(interaction, context) {
  13050. const usedBranch = this.getUsedBranch();
  13051. if (usedBranch) {
  13052. usedBranch.includeCallArguments(interaction, context);
  13053. }
  13054. else {
  13055. this.consequent.includeCallArguments(interaction, context);
  13056. this.alternate.includeCallArguments(interaction, context);
  13057. }
  13058. }
  13059. removeAnnotations(code) {
  13060. this.test.removeAnnotations(code);
  13061. }
  13062. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  13063. if (this.test.included) {
  13064. this.test.render(code, options, { renderedSurroundingElement });
  13065. this.consequent.render(code, options);
  13066. this.alternate.render(code, options);
  13067. }
  13068. else {
  13069. const usedBranch = this.getUsedBranch();
  13070. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  13071. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  13072. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  13073. : colonPos) + 1);
  13074. if (preventASI) {
  13075. removeLineBreaks(code, inclusionStart, usedBranch.start);
  13076. }
  13077. code.remove(this.start, inclusionStart);
  13078. if (this.consequent.included) {
  13079. code.remove(colonPos, this.end);
  13080. }
  13081. this.test.removeAnnotations(code);
  13082. usedBranch.render(code, options, {
  13083. isCalleeOfRenderedParent,
  13084. preventASI: true,
  13085. renderedParentType: renderedParentType || this.parent.type,
  13086. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13087. });
  13088. }
  13089. }
  13090. getUsedBranch() {
  13091. if (this.isBranchResolutionAnalysed) {
  13092. return this.usedBranch;
  13093. }
  13094. this.isBranchResolutionAnalysed = true;
  13095. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  13096. return typeof testValue === 'symbol'
  13097. ? null
  13098. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  13099. }
  13100. }
  13101. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13102. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13103. class ContinueStatement extends NodeBase {
  13104. hasEffects(context) {
  13105. if (this.label) {
  13106. if (!context.ignore.labels.has(this.label.name))
  13107. return true;
  13108. context.includedLabels.add(this.label.name);
  13109. }
  13110. else {
  13111. if (!context.ignore.continues)
  13112. return true;
  13113. context.hasContinue = true;
  13114. }
  13115. context.brokenFlow = true;
  13116. return false;
  13117. }
  13118. include(context, includeChildrenRecursively) {
  13119. this.included = true;
  13120. if (this.label) {
  13121. this.label.include(context, includeChildrenRecursively);
  13122. context.includedLabels.add(this.label.name);
  13123. }
  13124. else {
  13125. context.hasContinue = true;
  13126. }
  13127. context.brokenFlow = true;
  13128. }
  13129. }
  13130. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13131. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13132. class DebuggerStatement extends NodeBase {
  13133. hasEffects() {
  13134. return true;
  13135. }
  13136. }
  13137. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  13138. class Decorator extends NodeBase {
  13139. hasEffects(context) {
  13140. return (this.expression.hasEffects(context) ||
  13141. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  13142. }
  13143. }
  13144. Decorator.prototype.includeNode = onlyIncludeSelf;
  13145. function hasLoopBodyEffects(context, body) {
  13146. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  13147. const { breaks, continues } = ignore;
  13148. ignore.breaks = true;
  13149. ignore.continues = true;
  13150. context.hasBreak = false;
  13151. context.hasContinue = false;
  13152. if (body.hasEffects(context))
  13153. return true;
  13154. ignore.breaks = breaks;
  13155. ignore.continues = continues;
  13156. context.hasBreak = hasBreak;
  13157. context.hasContinue = hasContinue;
  13158. context.brokenFlow = brokenFlow;
  13159. return false;
  13160. }
  13161. function includeLoopBody(context, body, includeChildrenRecursively) {
  13162. const { brokenFlow, hasBreak, hasContinue } = context;
  13163. context.hasBreak = false;
  13164. context.hasContinue = false;
  13165. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  13166. context.hasBreak = hasBreak;
  13167. context.hasContinue = hasContinue;
  13168. context.brokenFlow = brokenFlow;
  13169. }
  13170. class DoWhileStatement extends NodeBase {
  13171. hasEffects(context) {
  13172. if (this.test.hasEffects(context))
  13173. return true;
  13174. return hasLoopBodyEffects(context, this.body);
  13175. }
  13176. include(context, includeChildrenRecursively) {
  13177. this.included = true;
  13178. this.test.include(context, includeChildrenRecursively);
  13179. includeLoopBody(context, this.body, includeChildrenRecursively);
  13180. }
  13181. }
  13182. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13183. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13184. class EmptyStatement extends NodeBase {
  13185. hasEffects() {
  13186. return false;
  13187. }
  13188. }
  13189. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  13190. class ExportAllDeclaration extends NodeBase {
  13191. hasEffects() {
  13192. return false;
  13193. }
  13194. initialise() {
  13195. super.initialise();
  13196. this.scope.context.addExport(this);
  13197. }
  13198. render(code, _options, nodeRenderOptions) {
  13199. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13200. }
  13201. }
  13202. ExportAllDeclaration.prototype.needsBoundaries = true;
  13203. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13204. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13205. class ExportNamedDeclaration extends NodeBase {
  13206. bind() {
  13207. // Do not bind specifiers
  13208. this.declaration?.bind();
  13209. }
  13210. hasEffects(context) {
  13211. return !!this.declaration?.hasEffects(context);
  13212. }
  13213. initialise() {
  13214. super.initialise();
  13215. this.scope.context.addExport(this);
  13216. }
  13217. removeAnnotations(code) {
  13218. this.declaration?.removeAnnotations(code);
  13219. }
  13220. render(code, options, nodeRenderOptions) {
  13221. const { start, end } = nodeRenderOptions;
  13222. if (this.declaration === null) {
  13223. code.remove(start, end);
  13224. }
  13225. else {
  13226. let endBoundary = this.declaration.start;
  13227. // the start of the decorator may be before the start of the class declaration
  13228. if (this.declaration instanceof ClassDeclaration) {
  13229. const decorators = this.declaration.decorators;
  13230. for (const decorator of decorators) {
  13231. endBoundary = Math.min(endBoundary, decorator.start);
  13232. }
  13233. if (endBoundary <= this.start) {
  13234. endBoundary = this.declaration.start;
  13235. }
  13236. }
  13237. code.remove(this.start, endBoundary);
  13238. this.declaration.render(code, options, { end, start });
  13239. }
  13240. }
  13241. }
  13242. ExportNamedDeclaration.prototype.needsBoundaries = true;
  13243. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13244. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13245. class ExportSpecifier extends NodeBase {
  13246. }
  13247. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13248. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13249. class ForInStatement extends NodeBase {
  13250. createScope(parentScope) {
  13251. this.scope = new BlockScope(parentScope);
  13252. }
  13253. hasEffects(context) {
  13254. const { body, deoptimized, left, right } = this;
  13255. if (!deoptimized)
  13256. this.applyDeoptimizations();
  13257. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  13258. return true;
  13259. return hasLoopBodyEffects(context, body);
  13260. }
  13261. include(context, includeChildrenRecursively) {
  13262. const { body, deoptimized, left, right } = this;
  13263. if (!deoptimized)
  13264. this.applyDeoptimizations();
  13265. if (!this.included)
  13266. this.includeNode(context);
  13267. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13268. right.include(context, includeChildrenRecursively);
  13269. includeLoopBody(context, body, includeChildrenRecursively);
  13270. }
  13271. includeNode(context) {
  13272. this.included = true;
  13273. if (!this.deoptimized)
  13274. this.applyDeoptimizations();
  13275. this.right.includePath(UNKNOWN_PATH, context);
  13276. }
  13277. initialise() {
  13278. super.initialise();
  13279. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13280. }
  13281. render(code, options) {
  13282. this.left.render(code, options, NO_SEMICOLON);
  13283. this.right.render(code, options, NO_SEMICOLON);
  13284. // handle no space between "in" and the right side
  13285. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  13286. code.prependLeft(this.right.start, ' ');
  13287. }
  13288. this.body.render(code, options);
  13289. }
  13290. applyDeoptimizations() {
  13291. this.deoptimized = true;
  13292. this.left.deoptimizePath(EMPTY_PATH);
  13293. this.scope.context.requestTreeshakingPass();
  13294. }
  13295. }
  13296. class ForOfStatement extends NodeBase {
  13297. get await() {
  13298. return isFlagSet(this.flags, 131072 /* Flag.await */);
  13299. }
  13300. set await(value) {
  13301. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  13302. }
  13303. createScope(parentScope) {
  13304. this.scope = new BlockScope(parentScope);
  13305. }
  13306. hasEffects() {
  13307. if (!this.deoptimized)
  13308. this.applyDeoptimizations();
  13309. // Placeholder until proper Symbol.Iterator support
  13310. return true;
  13311. }
  13312. include(context, includeChildrenRecursively) {
  13313. const { body, deoptimized, left, right } = this;
  13314. if (!deoptimized)
  13315. this.applyDeoptimizations();
  13316. if (!this.included)
  13317. this.includeNode(context);
  13318. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13319. right.include(context, includeChildrenRecursively);
  13320. includeLoopBody(context, body, includeChildrenRecursively);
  13321. }
  13322. includeNode(context) {
  13323. this.included = true;
  13324. if (!this.deoptimized)
  13325. this.applyDeoptimizations();
  13326. this.right.includePath(UNKNOWN_PATH, context);
  13327. }
  13328. initialise() {
  13329. super.initialise();
  13330. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13331. }
  13332. render(code, options) {
  13333. this.left.render(code, options, NO_SEMICOLON);
  13334. this.right.render(code, options, NO_SEMICOLON);
  13335. // handle no space between "of" and the right side
  13336. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  13337. code.prependLeft(this.right.start, ' ');
  13338. }
  13339. this.body.render(code, options);
  13340. }
  13341. applyDeoptimizations() {
  13342. this.deoptimized = true;
  13343. this.left.deoptimizePath(EMPTY_PATH);
  13344. this.right.deoptimizePath(UNKNOWN_PATH);
  13345. this.scope.context.requestTreeshakingPass();
  13346. }
  13347. }
  13348. class ForStatement extends NodeBase {
  13349. createScope(parentScope) {
  13350. this.scope = new BlockScope(parentScope);
  13351. }
  13352. hasEffects(context) {
  13353. if (this.init?.hasEffects(context) ||
  13354. this.test?.hasEffects(context) ||
  13355. this.update?.hasEffects(context)) {
  13356. return true;
  13357. }
  13358. return hasLoopBodyEffects(context, this.body);
  13359. }
  13360. include(context, includeChildrenRecursively) {
  13361. this.included = true;
  13362. this.init?.include(context, includeChildrenRecursively, {
  13363. asSingleStatement: true
  13364. });
  13365. this.test?.include(context, includeChildrenRecursively);
  13366. this.update?.include(context, includeChildrenRecursively);
  13367. includeLoopBody(context, this.body, includeChildrenRecursively);
  13368. }
  13369. render(code, options) {
  13370. this.init?.render(code, options, NO_SEMICOLON);
  13371. this.test?.render(code, options, NO_SEMICOLON);
  13372. this.update?.render(code, options, NO_SEMICOLON);
  13373. this.body.render(code, options);
  13374. }
  13375. }
  13376. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13377. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13378. class FunctionExpression extends FunctionNode {
  13379. createScope(parentScope) {
  13380. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  13381. }
  13382. parseNode(esTreeNode) {
  13383. if (esTreeNode.id !== null) {
  13384. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  13385. }
  13386. return super.parseNode(esTreeNode);
  13387. }
  13388. onlyFunctionCallUsed() {
  13389. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  13390. this.parent.callee === this &&
  13391. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  13392. return isIIFE || super.onlyFunctionCallUsed();
  13393. }
  13394. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13395. super.render(code, options);
  13396. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13397. code.appendRight(this.start, '(');
  13398. code.prependLeft(this.end, ')');
  13399. }
  13400. }
  13401. }
  13402. class TrackingScope extends BlockScope {
  13403. constructor() {
  13404. super(...arguments);
  13405. this.hoistedDeclarations = [];
  13406. }
  13407. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13408. this.hoistedDeclarations.push(identifier);
  13409. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13410. }
  13411. }
  13412. const unset = Symbol('unset');
  13413. class IfStatement extends NodeBase {
  13414. constructor() {
  13415. super(...arguments);
  13416. this.testValue = unset;
  13417. }
  13418. deoptimizeCache() {
  13419. this.testValue = UnknownValue;
  13420. }
  13421. hasEffects(context) {
  13422. if (this.test.hasEffects(context)) {
  13423. return true;
  13424. }
  13425. const testValue = this.getTestValue();
  13426. if (typeof testValue === 'symbol') {
  13427. const { brokenFlow } = context;
  13428. if (this.consequent.hasEffects(context))
  13429. return true;
  13430. const consequentBrokenFlow = context.brokenFlow;
  13431. context.brokenFlow = brokenFlow;
  13432. if (this.alternate === null)
  13433. return false;
  13434. if (this.alternate.hasEffects(context))
  13435. return true;
  13436. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13437. return false;
  13438. }
  13439. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  13440. }
  13441. include(context, includeChildrenRecursively) {
  13442. this.included = true;
  13443. if (includeChildrenRecursively) {
  13444. this.includeRecursively(includeChildrenRecursively, context);
  13445. }
  13446. else {
  13447. const testValue = this.getTestValue();
  13448. if (typeof testValue === 'symbol') {
  13449. this.includeUnknownTest(context);
  13450. }
  13451. else {
  13452. this.includeKnownTest(context, testValue);
  13453. }
  13454. }
  13455. }
  13456. parseNode(esTreeNode) {
  13457. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  13458. if (esTreeNode.alternate) {
  13459. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  13460. }
  13461. return super.parseNode(esTreeNode);
  13462. }
  13463. render(code, options) {
  13464. const { snippets: { getPropertyAccess } } = options;
  13465. // Note that unknown test values are always included
  13466. const testValue = this.getTestValue();
  13467. const hoistedDeclarations = [];
  13468. const includesIfElse = this.test.included;
  13469. const noTreeshake = !this.scope.context.options.treeshake;
  13470. if (includesIfElse) {
  13471. this.test.render(code, options);
  13472. }
  13473. else {
  13474. code.remove(this.start, this.consequent.start);
  13475. }
  13476. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  13477. this.consequent.render(code, options);
  13478. }
  13479. else {
  13480. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  13481. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  13482. }
  13483. if (this.alternate) {
  13484. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  13485. if (includesIfElse) {
  13486. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  13487. code.prependLeft(this.alternate.start, ' ');
  13488. }
  13489. }
  13490. else {
  13491. code.remove(this.consequent.end, this.alternate.start);
  13492. }
  13493. this.alternate.render(code, options);
  13494. }
  13495. else {
  13496. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  13497. code.overwrite(this.alternate.start, this.end, ';');
  13498. }
  13499. else {
  13500. code.remove(this.consequent.end, this.end);
  13501. }
  13502. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  13503. }
  13504. }
  13505. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  13506. }
  13507. getTestValue() {
  13508. if (this.testValue === unset) {
  13509. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  13510. }
  13511. return this.testValue;
  13512. }
  13513. includeKnownTest(context, testValue) {
  13514. if (this.test.shouldBeIncluded(context)) {
  13515. this.test.include(context, false);
  13516. }
  13517. if (testValue && this.consequent.shouldBeIncluded(context)) {
  13518. this.consequent.include(context, false, { asSingleStatement: true });
  13519. }
  13520. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  13521. this.alternate.include(context, false, { asSingleStatement: true });
  13522. }
  13523. }
  13524. includeRecursively(includeChildrenRecursively, context) {
  13525. this.test.include(context, includeChildrenRecursively);
  13526. this.consequent.include(context, includeChildrenRecursively);
  13527. this.alternate?.include(context, includeChildrenRecursively);
  13528. }
  13529. includeUnknownTest(context) {
  13530. this.test.include(context, false);
  13531. const { brokenFlow } = context;
  13532. let consequentBrokenFlow = false;
  13533. if (this.consequent.shouldBeIncluded(context)) {
  13534. this.consequent.include(context, false, { asSingleStatement: true });
  13535. consequentBrokenFlow = context.brokenFlow;
  13536. context.brokenFlow = brokenFlow;
  13537. }
  13538. if (this.alternate?.shouldBeIncluded(context)) {
  13539. this.alternate.include(context, false, { asSingleStatement: true });
  13540. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13541. }
  13542. }
  13543. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  13544. const hoistedVariables = [
  13545. ...new Set(hoistedDeclarations.map(identifier => {
  13546. const variable = identifier.variable;
  13547. return variable.included ? variable.getName(getPropertyAccess) : '';
  13548. }))
  13549. ]
  13550. .filter(Boolean)
  13551. .join(', ');
  13552. if (hoistedVariables) {
  13553. const parentType = this.parent.type;
  13554. const needsBraces = parentType !== parseAst_js.Program && parentType !== parseAst_js.BlockStatement;
  13555. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  13556. if (needsBraces) {
  13557. code.appendLeft(this.end, ` }`);
  13558. }
  13559. }
  13560. }
  13561. shouldKeepAlternateBranch() {
  13562. let currentParent = this.parent;
  13563. do {
  13564. if (currentParent instanceof IfStatement && currentParent.alternate) {
  13565. return true;
  13566. }
  13567. if (currentParent instanceof BlockStatement) {
  13568. return false;
  13569. }
  13570. currentParent = currentParent.parent;
  13571. } while (currentParent);
  13572. return false;
  13573. }
  13574. }
  13575. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13576. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13577. class ImportAttribute extends NodeBase {
  13578. }
  13579. class ImportDeclaration extends NodeBase {
  13580. // Do not bind specifiers or attributes
  13581. bind() { }
  13582. hasEffects() {
  13583. return false;
  13584. }
  13585. initialise() {
  13586. super.initialise();
  13587. this.scope.context.addImport(this);
  13588. }
  13589. render(code, _options, nodeRenderOptions) {
  13590. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13591. }
  13592. }
  13593. ImportDeclaration.prototype.needsBoundaries = true;
  13594. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13595. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13596. class ImportDefaultSpecifier extends NodeBase {
  13597. }
  13598. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13599. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13600. function isReassignedExportsMember(variable, exportNamesByVariable) {
  13601. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  13602. }
  13603. class VariableDeclarator extends NodeBase {
  13604. declareDeclarator(kind, isUsingDeclaration) {
  13605. this.isUsingDeclaration = isUsingDeclaration;
  13606. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  13607. }
  13608. deoptimizePath(path) {
  13609. this.id.deoptimizePath(path);
  13610. }
  13611. hasEffects(context) {
  13612. const initEffect = this.init?.hasEffects(context);
  13613. this.id.markDeclarationReached();
  13614. return (initEffect ||
  13615. this.isUsingDeclaration ||
  13616. this.id.hasEffects(context) ||
  13617. (this.scope.context.options.treeshake
  13618. .propertyReadSideEffects &&
  13619. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  13620. }
  13621. include(context, includeChildrenRecursively) {
  13622. const { id, init } = this;
  13623. if (!this.included)
  13624. this.includeNode();
  13625. init?.include(context, includeChildrenRecursively);
  13626. id.markDeclarationReached();
  13627. if (includeChildrenRecursively) {
  13628. id.include(context, includeChildrenRecursively);
  13629. }
  13630. else {
  13631. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  13632. }
  13633. }
  13634. removeAnnotations(code) {
  13635. this.init?.removeAnnotations(code);
  13636. }
  13637. render(code, options) {
  13638. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  13639. const { end, id, init, start } = this;
  13640. const renderId = id.included || this.isUsingDeclaration;
  13641. if (renderId) {
  13642. id.render(code, options);
  13643. }
  13644. else {
  13645. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  13646. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  13647. }
  13648. if (init) {
  13649. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13650. const renderedVariable = id.variable.getName(getPropertyAccess);
  13651. if (renderedVariable !== id.name) {
  13652. code.appendLeft(init.start + 5, ` ${id.name}`);
  13653. }
  13654. }
  13655. init.render(code, options, renderId ? parseAst_js.BLANK : { renderedSurroundingElement: parseAst_js.ExpressionStatement });
  13656. }
  13657. else if (id instanceof Identifier &&
  13658. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  13659. code.appendLeft(end, `${_}=${_}void 0`);
  13660. }
  13661. }
  13662. includeNode() {
  13663. this.included = true;
  13664. const { id, init } = this;
  13665. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13666. const { name, variable } = id;
  13667. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  13668. if (accessedVariable !== variable) {
  13669. accessedVariable.forbidName(name);
  13670. }
  13671. }
  13672. }
  13673. }
  13674. }
  13675. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  13676. function getChunkInfoWithPath(chunk) {
  13677. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  13678. }
  13679. class ImportExpression extends NodeBase {
  13680. constructor() {
  13681. super(...arguments);
  13682. this.inlineNamespace = null;
  13683. this.hasUnknownAccessedKey = false;
  13684. this.accessedPropKey = new Set();
  13685. this.attributes = null;
  13686. this.mechanism = null;
  13687. this.namespaceExportName = undefined;
  13688. this.resolution = null;
  13689. this.resolutionString = null;
  13690. }
  13691. get withinTopLevelAwait() {
  13692. return isFlagSet(this.flags, 134217728 /* Flag.withinTopLevelAwait */);
  13693. }
  13694. set withinTopLevelAwait(value) {
  13695. this.flags = setFlag(this.flags, 134217728 /* Flag.withinTopLevelAwait */, value);
  13696. }
  13697. // Do not bind attributes
  13698. bind() {
  13699. this.source.bind();
  13700. }
  13701. /**
  13702. * Get imported variables for deterministic usage, valid cases are:
  13703. *
  13704. * 1. `const { foo } = await import('bar')`.
  13705. * 2. `(await import('bar')).foo`
  13706. * 3. `import('bar').then(({ foo }) => {})`
  13707. *
  13708. * Returns empty array if it's side-effect only import.
  13709. * Returns undefined if it's not fully deterministic.
  13710. */
  13711. getDeterministicImportedNames() {
  13712. const parent1 = this.parent;
  13713. // Side-effect only: import('bar')
  13714. if (parent1 instanceof ExpressionStatement) {
  13715. return parseAst_js.EMPTY_ARRAY;
  13716. }
  13717. if (parent1 instanceof AwaitExpression) {
  13718. const parent2 = parent1.parent;
  13719. // Side-effect only: await import('bar')
  13720. if (parent2 instanceof ExpressionStatement) {
  13721. return parseAst_js.EMPTY_ARRAY;
  13722. }
  13723. // Case 1: const { foo } / module = await import('bar')
  13724. if (parent2 instanceof VariableDeclarator) {
  13725. const declaration = parent2.id;
  13726. if (declaration instanceof Identifier) {
  13727. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  13728. }
  13729. if (declaration instanceof ObjectPattern) {
  13730. return getDeterministicObjectDestructure(declaration);
  13731. }
  13732. }
  13733. // Case 2: (await import('bar')).foo
  13734. if (parent2 instanceof MemberExpression) {
  13735. const id = parent2.property;
  13736. if (!parent2.computed && id instanceof Identifier) {
  13737. return [id.name];
  13738. }
  13739. }
  13740. return;
  13741. }
  13742. if (parent1 instanceof MemberExpression) {
  13743. const callExpression = parent1.parent;
  13744. const property = parent1.property;
  13745. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  13746. return;
  13747. }
  13748. const memberName = property.name;
  13749. // side-effect only, when only chaining .catch or .finally
  13750. if (callExpression.parent instanceof ExpressionStatement &&
  13751. ['catch', 'finally'].includes(memberName)) {
  13752. return parseAst_js.EMPTY_ARRAY;
  13753. }
  13754. if (memberName !== 'then')
  13755. return;
  13756. // Side-effect only: import('bar').then()
  13757. if (callExpression.arguments.length === 0) {
  13758. return parseAst_js.EMPTY_ARRAY;
  13759. }
  13760. const thenCallback = callExpression.arguments[0];
  13761. if (callExpression.arguments.length !== 1 ||
  13762. !(thenCallback instanceof ArrowFunctionExpression ||
  13763. thenCallback instanceof FunctionExpression)) {
  13764. return;
  13765. }
  13766. // Side-effect only: import('bar').then(() => {})
  13767. if (thenCallback.params.length === 0) {
  13768. return parseAst_js.EMPTY_ARRAY;
  13769. }
  13770. const declaration = thenCallback.params[0];
  13771. if (thenCallback.params.length === 1 && declaration instanceof ObjectPattern) {
  13772. return getDeterministicObjectDestructure(declaration);
  13773. }
  13774. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  13775. }
  13776. }
  13777. hasEffects() {
  13778. return true;
  13779. }
  13780. include(context, includeChildrenRecursively) {
  13781. if (!this.included)
  13782. this.includeNode();
  13783. this.source.include(context, includeChildrenRecursively);
  13784. }
  13785. includeNode() {
  13786. this.included = true;
  13787. this.scope.context.includeDynamicImport(this);
  13788. this.scope.addAccessedDynamicImport(this);
  13789. }
  13790. includePath(path) {
  13791. if (!this.included)
  13792. this.includeNode();
  13793. // Technically, this is not correct as dynamic imports return a Promise.
  13794. if (this.hasUnknownAccessedKey)
  13795. return;
  13796. if (path[0] === UnknownKey) {
  13797. this.hasUnknownAccessedKey = true;
  13798. }
  13799. else if (typeof path[0] === 'string') {
  13800. this.accessedPropKey.add(path[0]);
  13801. }
  13802. // Update included paths
  13803. this.scope.context.includeDynamicImport(this);
  13804. }
  13805. initialise() {
  13806. super.initialise();
  13807. this.scope.context.addDynamicImport(this);
  13808. let parent = this.parent;
  13809. let withinAwaitExpression = false;
  13810. let withinTopLevelAwait = false;
  13811. do {
  13812. if (withinAwaitExpression &&
  13813. (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)) {
  13814. withinTopLevelAwait = false;
  13815. }
  13816. if (parent instanceof AwaitExpression) {
  13817. withinAwaitExpression = true;
  13818. withinTopLevelAwait = true;
  13819. }
  13820. } while ((parent = parent.parent));
  13821. if (withinAwaitExpression && withinTopLevelAwait) {
  13822. this.withinTopLevelAwait = true;
  13823. }
  13824. }
  13825. parseNode(esTreeNode) {
  13826. this.sourceAstNode = esTreeNode.source;
  13827. return super.parseNode(esTreeNode);
  13828. }
  13829. render(code, options) {
  13830. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  13831. if (this.inlineNamespace) {
  13832. const [left, right] = getDirectReturnFunction([], {
  13833. functionReturn: true,
  13834. lineBreakIndent: null,
  13835. name: null
  13836. });
  13837. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  13838. return;
  13839. }
  13840. if (this.mechanism) {
  13841. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  13842. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  13843. }
  13844. if (this.resolutionString) {
  13845. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  13846. if (this.namespaceExportName) {
  13847. const [left, right] = getDirectReturnFunction(['n'], {
  13848. functionReturn: true,
  13849. lineBreakIndent: null,
  13850. name: null
  13851. });
  13852. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  13853. }
  13854. }
  13855. else {
  13856. this.source.render(code, options);
  13857. }
  13858. if (this.attributes !== true) {
  13859. if (this.options) {
  13860. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  13861. }
  13862. if (this.attributes) {
  13863. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  13864. lineBreakIndent: null
  13865. })}`);
  13866. }
  13867. }
  13868. }
  13869. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  13870. const { format } = options;
  13871. this.inlineNamespace = null;
  13872. this.resolution = resolution;
  13873. this.resolutionString = resolutionString;
  13874. this.namespaceExportName = namespaceExportName;
  13875. this.attributes = attributes;
  13876. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  13877. let helper;
  13878. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  13879. if (helper) {
  13880. accessedGlobals.push(helper);
  13881. }
  13882. if (accessedGlobals.length > 0) {
  13883. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  13884. }
  13885. }
  13886. setInternalResolution(inlineNamespace) {
  13887. this.inlineNamespace = inlineNamespace;
  13888. }
  13889. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  13890. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  13891. {
  13892. chunk: getChunkInfoWithPath(ownChunk),
  13893. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  13894. format,
  13895. getTargetChunkImports() {
  13896. if (targetChunk === null)
  13897. return null;
  13898. const chunkInfos = [];
  13899. const importerPath = ownChunk.getFileName();
  13900. for (const dep of targetChunk.dependencies) {
  13901. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  13902. if (dep instanceof ExternalChunk) {
  13903. chunkInfos.push({
  13904. fileName: dep.getFileName(),
  13905. resolvedImportPath,
  13906. type: 'external'
  13907. });
  13908. }
  13909. else {
  13910. chunkInfos.push({
  13911. chunk: dep.getPreRenderedChunkInfo(),
  13912. fileName: dep.getFileName(),
  13913. resolvedImportPath,
  13914. type: 'internal'
  13915. });
  13916. }
  13917. }
  13918. return chunkInfos;
  13919. },
  13920. moduleId: this.scope.context.module.id,
  13921. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  13922. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  13923. }
  13924. ]);
  13925. if (mechanism) {
  13926. return { helper: null, mechanism };
  13927. }
  13928. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  13929. switch (format) {
  13930. case 'cjs': {
  13931. if (dynamicImportInCjs &&
  13932. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  13933. return { helper: null, mechanism: null };
  13934. }
  13935. const helper = getInteropHelper(resolution, exportMode, interop);
  13936. let left = `require(`;
  13937. let right = `)`;
  13938. if (helper) {
  13939. left = `/*#__PURE__*/${helper}(${left}`;
  13940. right += ')';
  13941. }
  13942. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  13943. functionReturn: true,
  13944. lineBreakIndent: null,
  13945. name: null
  13946. });
  13947. left = `Promise.resolve().then(${functionLeft}${left}`;
  13948. right += `${functionRight})`;
  13949. if (!arrowFunctions && hasDynamicTarget) {
  13950. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13951. needsArrowReturnParens: false,
  13952. needsWrappedFunction: true
  13953. });
  13954. right = ')';
  13955. }
  13956. return {
  13957. helper,
  13958. mechanism: { left, right }
  13959. };
  13960. }
  13961. case 'amd': {
  13962. const resolve = compact ? 'c' : 'resolve';
  13963. const reject = compact ? 'e' : 'reject';
  13964. const helper = getInteropHelper(resolution, exportMode, interop);
  13965. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  13966. functionReturn: false,
  13967. lineBreakIndent: null,
  13968. name: null
  13969. });
  13970. const resolveNamespace = helper
  13971. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  13972. : resolve;
  13973. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  13974. functionReturn: false,
  13975. lineBreakIndent: null,
  13976. name: null
  13977. });
  13978. let left = `new Promise(${handlerLeft}require([`;
  13979. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  13980. if (!arrowFunctions && hasDynamicTarget) {
  13981. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13982. needsArrowReturnParens: false,
  13983. needsWrappedFunction: true
  13984. });
  13985. right = ')';
  13986. }
  13987. return {
  13988. helper,
  13989. mechanism: { left, right }
  13990. };
  13991. }
  13992. case 'system': {
  13993. return {
  13994. helper: null,
  13995. mechanism: {
  13996. left: 'module.import(',
  13997. right: ')'
  13998. }
  13999. };
  14000. }
  14001. }
  14002. return { helper: null, mechanism: null };
  14003. }
  14004. }
  14005. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14006. function getInteropHelper(resolution, exportMode, interop) {
  14007. return exportMode === 'external'
  14008. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  14009. : exportMode === 'default'
  14010. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  14011. : null;
  14012. }
  14013. const accessedImportGlobals = {
  14014. amd: ['require'],
  14015. cjs: ['require'],
  14016. system: ['module']
  14017. };
  14018. function getDeterministicObjectDestructure(objectPattern) {
  14019. const variables = [];
  14020. for (const property of objectPattern.properties) {
  14021. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  14022. return;
  14023. variables.push(property.key.name);
  14024. }
  14025. return variables;
  14026. }
  14027. class ImportNamespaceSpecifier extends NodeBase {
  14028. }
  14029. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14030. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14031. class ImportSpecifier extends NodeBase {
  14032. }
  14033. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14034. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14035. class JSXIdentifier extends IdentifierBase {
  14036. constructor() {
  14037. super(...arguments);
  14038. this.isNativeElement = false;
  14039. }
  14040. bind() {
  14041. const type = this.getType();
  14042. if (type === 0 /* IdentifierType.Reference */) {
  14043. this.variable = this.scope.findVariable(this.name);
  14044. this.variable.addReference(this);
  14045. }
  14046. else if (type === 1 /* IdentifierType.NativeElementName */) {
  14047. this.isNativeElement = true;
  14048. }
  14049. }
  14050. include(context) {
  14051. if (!this.included)
  14052. this.includeNode(context);
  14053. }
  14054. includeNode(context) {
  14055. this.included = true;
  14056. if (!this.deoptimized)
  14057. this.applyDeoptimizations();
  14058. if (this.variable !== null) {
  14059. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14060. }
  14061. }
  14062. includePath(path, context) {
  14063. if (!this.included) {
  14064. this.included = true;
  14065. if (this.variable !== null) {
  14066. this.scope.context.includeVariableInModule(this.variable, path, context);
  14067. }
  14068. }
  14069. else if (path.length > 0) {
  14070. this.variable?.includePath(path, context);
  14071. }
  14072. }
  14073. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  14074. if (this.variable) {
  14075. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  14076. if (name !== this.name) {
  14077. code.overwrite(this.start, this.end, name, {
  14078. contentOnly: true,
  14079. storeName: true
  14080. });
  14081. }
  14082. }
  14083. else if (this.isNativeElement &&
  14084. this.scope.context.options.jsx.mode !== 'preserve') {
  14085. code.update(this.start, this.end, JSON.stringify(this.name));
  14086. }
  14087. }
  14088. getType() {
  14089. switch (this.parent.type) {
  14090. case 'JSXOpeningElement':
  14091. case 'JSXClosingElement': {
  14092. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  14093. ? 0 /* IdentifierType.Reference */
  14094. : 1 /* IdentifierType.NativeElementName */;
  14095. }
  14096. case 'JSXMemberExpression': {
  14097. return this.parent.object === this
  14098. ? 0 /* IdentifierType.Reference */
  14099. : 2 /* IdentifierType.Other */;
  14100. }
  14101. case 'JSXAttribute':
  14102. case 'JSXNamespacedName': {
  14103. return 2 /* IdentifierType.Other */;
  14104. }
  14105. default: {
  14106. /* istanbul ignore next */
  14107. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  14108. }
  14109. }
  14110. }
  14111. }
  14112. class JSXAttribute extends NodeBase {
  14113. render(code, options, { jsxMode } = parseAst_js.BLANK) {
  14114. super.render(code, options);
  14115. if (['classic', 'automatic'].includes(jsxMode)) {
  14116. const { name, value } = this;
  14117. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  14118. if (!(jsxMode === 'automatic' && key === 'key')) {
  14119. const safeKey = stringifyObjectKeyIfNeeded(key);
  14120. if (key !== safeKey) {
  14121. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  14122. }
  14123. if (value) {
  14124. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  14125. }
  14126. else {
  14127. code.appendLeft(name.end, ': true');
  14128. }
  14129. }
  14130. }
  14131. }
  14132. }
  14133. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  14134. class JSXClosingBase extends NodeBase {
  14135. render(code, options) {
  14136. const { mode } = this.scope.context.options.jsx;
  14137. if (mode !== 'preserve') {
  14138. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  14139. }
  14140. else {
  14141. super.render(code, options);
  14142. }
  14143. }
  14144. }
  14145. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  14146. class JSXClosingElement extends JSXClosingBase {
  14147. }
  14148. class JSXClosingFragment extends JSXClosingBase {
  14149. }
  14150. class JSXSpreadAttribute extends NodeBase {
  14151. render(code, options) {
  14152. this.argument.render(code, options);
  14153. const { mode } = this.scope.context.options.jsx;
  14154. if (mode !== 'preserve') {
  14155. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  14156. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  14157. }
  14158. }
  14159. }
  14160. class JSXEmptyExpression extends NodeBase {
  14161. }
  14162. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  14163. class JSXExpressionContainer extends NodeBase {
  14164. includeNode(context) {
  14165. this.included = true;
  14166. if (!this.deoptimized)
  14167. this.applyDeoptimizations();
  14168. this.expression.includePath(UNKNOWN_PATH, context);
  14169. }
  14170. render(code, options) {
  14171. const { mode } = this.scope.context.options.jsx;
  14172. if (mode !== 'preserve') {
  14173. code.remove(this.start, this.expression.start);
  14174. code.remove(this.expression.end, this.end);
  14175. }
  14176. this.expression.render(code, options);
  14177. }
  14178. }
  14179. function getRenderedJsxChildren(children) {
  14180. let renderedChildren = 0;
  14181. for (const child of children) {
  14182. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  14183. renderedChildren++;
  14184. }
  14185. }
  14186. return renderedChildren;
  14187. }
  14188. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  14189. const [baseName, nestedName] = factory.split('.');
  14190. let factoryVariable;
  14191. if (importSource) {
  14192. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  14193. if (preserve) {
  14194. // This pretends we are accessing an included global variable of the same name
  14195. const globalVariable = node.scope.findGlobal(baseName);
  14196. globalVariable.includePath(UNKNOWN_PATH, context);
  14197. // This excludes this variable from renaming
  14198. factoryVariable.globalName = baseName;
  14199. }
  14200. }
  14201. else {
  14202. factoryVariable = node.scope.findGlobal(baseName);
  14203. }
  14204. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  14205. if (factoryVariable instanceof LocalVariable) {
  14206. factoryVariable.consolidateInitializers();
  14207. factoryVariable.addUsedPlace(node);
  14208. node.scope.context.requestTreeshakingPass();
  14209. }
  14210. return factoryVariable;
  14211. }
  14212. class JSXElementBase extends NodeBase {
  14213. constructor() {
  14214. super(...arguments);
  14215. this.factoryVariable = null;
  14216. this.factory = null;
  14217. }
  14218. initialise() {
  14219. super.initialise();
  14220. const { importSource } = (this.jsxMode = this.getRenderingMode());
  14221. if (importSource) {
  14222. this.scope.context.addImportSource(importSource);
  14223. }
  14224. }
  14225. include(context, includeChildrenRecursively) {
  14226. if (!this.included)
  14227. this.includeNode(context);
  14228. for (const child of this.children) {
  14229. child.include(context, includeChildrenRecursively);
  14230. }
  14231. }
  14232. includeNode(context) {
  14233. this.included = true;
  14234. const { factory, importSource, mode } = this.jsxMode;
  14235. if (factory) {
  14236. this.factory = factory;
  14237. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  14238. }
  14239. }
  14240. getRenderingMode() {
  14241. const jsx = this.scope.context.options.jsx;
  14242. const { mode, factory, importSource } = jsx;
  14243. if (mode === 'automatic') {
  14244. return {
  14245. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  14246. importSource: jsx.jsxImportSource,
  14247. mode
  14248. };
  14249. }
  14250. return { factory, importSource, mode };
  14251. }
  14252. renderChildren(code, options, openingEnd) {
  14253. const { children } = this;
  14254. let hasMultipleChildren = false;
  14255. let childrenEnd = openingEnd;
  14256. let firstChild = null;
  14257. for (const child of children) {
  14258. if (child instanceof JSXExpressionContainer &&
  14259. child.expression instanceof JSXEmptyExpression) {
  14260. code.remove(childrenEnd, child.end);
  14261. }
  14262. else {
  14263. code.appendLeft(childrenEnd, ', ');
  14264. child.render(code, options);
  14265. if (firstChild) {
  14266. hasMultipleChildren = true;
  14267. }
  14268. else {
  14269. firstChild = child;
  14270. }
  14271. }
  14272. childrenEnd = child.end;
  14273. }
  14274. return { childrenEnd, firstChild, hasMultipleChildren };
  14275. }
  14276. }
  14277. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  14278. class JSXElement extends JSXElementBase {
  14279. include(context, includeChildrenRecursively) {
  14280. super.include(context, includeChildrenRecursively);
  14281. this.openingElement.include(context, includeChildrenRecursively);
  14282. this.closingElement?.include(context, includeChildrenRecursively);
  14283. }
  14284. render(code, options) {
  14285. switch (this.jsxMode.mode) {
  14286. case 'classic': {
  14287. this.renderClassicMode(code, options);
  14288. break;
  14289. }
  14290. case 'automatic': {
  14291. this.renderAutomaticMode(code, options);
  14292. break;
  14293. }
  14294. default: {
  14295. super.render(code, options);
  14296. }
  14297. }
  14298. }
  14299. getRenderingMode() {
  14300. const jsx = this.scope.context.options.jsx;
  14301. const { mode, factory, importSource } = jsx;
  14302. if (mode === 'automatic') {
  14303. // In the case there is a key after a spread attribute, we fall back to
  14304. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  14305. // for reasoning.
  14306. let hasSpread = false;
  14307. for (const attribute of this.openingElement.attributes) {
  14308. if (attribute instanceof JSXSpreadAttribute) {
  14309. hasSpread = true;
  14310. }
  14311. else if (hasSpread && attribute.name.name === 'key') {
  14312. return { factory, importSource, mode: 'classic' };
  14313. }
  14314. }
  14315. }
  14316. return super.getRenderingMode();
  14317. }
  14318. renderClassicMode(code, options) {
  14319. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14320. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  14321. const [, ...nestedName] = factory.split('.');
  14322. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  14323. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  14324. this.renderChildren(code, options, openingEnd);
  14325. if (selfClosing) {
  14326. code.appendLeft(end, ')');
  14327. }
  14328. else {
  14329. closingElement.render(code, options);
  14330. }
  14331. }
  14332. renderAutomaticMode(code, options) {
  14333. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14334. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  14335. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  14336. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  14337. if (firstChild) {
  14338. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  14339. if (!inObject) {
  14340. code.prependRight(firstChild.start, '{ ');
  14341. inObject = true;
  14342. }
  14343. previousEnd = closingElement.start;
  14344. if (hasMultipleChildren) {
  14345. code.appendLeft(previousEnd, ']');
  14346. }
  14347. }
  14348. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  14349. if (keyAttribute) {
  14350. const { value } = keyAttribute;
  14351. // This will appear to the left of the moved code...
  14352. code.appendLeft(childrenEnd, ', ');
  14353. if (value) {
  14354. code.move(value.start, value.end, childrenEnd);
  14355. }
  14356. else {
  14357. code.appendLeft(childrenEnd, 'true');
  14358. }
  14359. }
  14360. if (selfClosing) {
  14361. // Moving the key attribute will also move the parenthesis to the right position
  14362. code.appendLeft(keyAttribute?.value?.end || end, ')');
  14363. }
  14364. else {
  14365. closingElement.render(code, options);
  14366. }
  14367. }
  14368. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  14369. const { jsxMode: { mode }, openingElement } = this;
  14370. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  14371. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  14372. openingElement.render(code, options, { jsxMode: mode });
  14373. let keyAttribute = null;
  14374. let hasSpread = false;
  14375. let inObject = false;
  14376. let previousEnd = nameEnd;
  14377. let hasAttributes = false;
  14378. let firstAttribute = null;
  14379. for (const attribute of attributes) {
  14380. if (attribute instanceof JSXAttribute) {
  14381. if (extractKeyAttribute && attribute.name.name === 'key') {
  14382. keyAttribute = attribute;
  14383. code.remove(previousEnd, attribute.value?.start || attribute.end);
  14384. continue;
  14385. }
  14386. code.appendLeft(previousEnd, ',');
  14387. if (!inObject) {
  14388. code.prependRight(attribute.start, '{ ');
  14389. inObject = true;
  14390. }
  14391. hasAttributes = true;
  14392. }
  14393. else {
  14394. if (inObject) {
  14395. if (hasAttributes) {
  14396. code.appendLeft(previousEnd, ' ');
  14397. }
  14398. code.appendLeft(previousEnd, '},');
  14399. inObject = false;
  14400. }
  14401. else {
  14402. code.appendLeft(previousEnd, ',');
  14403. }
  14404. hasSpread = true;
  14405. }
  14406. previousEnd = attribute.end;
  14407. if (!firstAttribute) {
  14408. firstAttribute = attribute;
  14409. }
  14410. }
  14411. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  14412. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  14413. }
  14414. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  14415. if (inObject) {
  14416. code.appendLeft(attributesEnd, ' }');
  14417. }
  14418. if (hasSpread) {
  14419. if (hasAttributes) {
  14420. const { start } = firstAttribute;
  14421. if (firstAttribute instanceof JSXSpreadAttribute) {
  14422. code.prependRight(start, '{}, ');
  14423. }
  14424. code.prependRight(start, 'Object.assign(');
  14425. code.appendLeft(attributesEnd, ')');
  14426. }
  14427. }
  14428. else if (!hasAttributes) {
  14429. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  14430. }
  14431. }
  14432. }
  14433. class JSXFragment extends JSXElementBase {
  14434. include(context, includeChildrenRecursively) {
  14435. super.include(context, includeChildrenRecursively);
  14436. this.openingFragment.include(context, includeChildrenRecursively);
  14437. this.closingFragment.include(context, includeChildrenRecursively);
  14438. }
  14439. render(code, options) {
  14440. switch (this.jsxMode.mode) {
  14441. case 'classic': {
  14442. this.renderClassicMode(code, options);
  14443. break;
  14444. }
  14445. case 'automatic': {
  14446. this.renderAutomaticMode(code, options);
  14447. break;
  14448. }
  14449. default: {
  14450. super.render(code, options);
  14451. }
  14452. }
  14453. }
  14454. renderClassicMode(code, options) {
  14455. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14456. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  14457. const [, ...nestedName] = factory.split('.');
  14458. openingFragment.render(code, options);
  14459. code.prependRight(start, `/*#__PURE__*/${[
  14460. factoryVariable.getName(getPropertyAccess, useOriginalName),
  14461. ...nestedName
  14462. ].join('.')}(`);
  14463. code.appendLeft(openingFragment.end, ', null');
  14464. this.renderChildren(code, options, openingFragment.end);
  14465. closingFragment.render(code, options);
  14466. }
  14467. renderAutomaticMode(code, options) {
  14468. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14469. const { closingFragment, factoryVariable, openingFragment, start } = this;
  14470. openingFragment.render(code, options);
  14471. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  14472. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  14473. if (firstChild) {
  14474. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  14475. if (hasMultipleChildren) {
  14476. code.appendLeft(closingFragment.start, ']');
  14477. }
  14478. code.appendLeft(childrenEnd, ' }');
  14479. }
  14480. else {
  14481. code.appendLeft(openingFragment.end, ', {}');
  14482. }
  14483. closingFragment.render(code, options);
  14484. }
  14485. }
  14486. class JSXMemberExpression extends NodeBase {
  14487. includeNode(context) {
  14488. this.included = true;
  14489. if (!this.deoptimized)
  14490. this.applyDeoptimizations();
  14491. this.object.includePath([this.property.name], context);
  14492. }
  14493. includePath(path, context) {
  14494. if (!this.included)
  14495. this.includeNode(context);
  14496. this.object.includePath([this.property.name, ...path], context);
  14497. }
  14498. }
  14499. class JSXNamespacedName extends NodeBase {
  14500. }
  14501. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  14502. class JSXOpeningElement extends NodeBase {
  14503. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  14504. this.name.render(code, options);
  14505. for (const attribute of this.attributes) {
  14506. attribute.render(code, options, { jsxMode });
  14507. }
  14508. }
  14509. }
  14510. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  14511. class JSXOpeningFragment extends NodeBase {
  14512. constructor() {
  14513. super(...arguments);
  14514. this.fragment = null;
  14515. this.fragmentVariable = null;
  14516. }
  14517. includeNode(context) {
  14518. this.included = true;
  14519. if (!this.deoptimized)
  14520. this.applyDeoptimizations();
  14521. const jsx = this.scope.context.options.jsx;
  14522. if (jsx.mode === 'automatic') {
  14523. this.fragment = 'Fragment';
  14524. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  14525. }
  14526. else {
  14527. const { fragment, importSource, mode } = jsx;
  14528. if (fragment != null) {
  14529. this.fragment = fragment;
  14530. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  14531. }
  14532. }
  14533. }
  14534. render(code, options) {
  14535. const { mode } = this.scope.context.options.jsx;
  14536. if (mode !== 'preserve') {
  14537. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14538. const [, ...nestedFragment] = this.fragment.split('.');
  14539. const fragment = [
  14540. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  14541. ...nestedFragment
  14542. ].join('.');
  14543. code.update(this.start, this.end, fragment);
  14544. }
  14545. }
  14546. }
  14547. class JSXSpreadChild extends NodeBase {
  14548. render(code, options) {
  14549. super.render(code, options);
  14550. const { mode } = this.scope.context.options.jsx;
  14551. if (mode !== 'preserve') {
  14552. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  14553. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  14554. }
  14555. }
  14556. }
  14557. class JSXText extends NodeBase {
  14558. render(code) {
  14559. const { mode } = this.scope.context.options.jsx;
  14560. if (mode !== 'preserve') {
  14561. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  14562. contentOnly: true
  14563. });
  14564. }
  14565. }
  14566. }
  14567. JSXText.prototype.includeNode = onlyIncludeSelf;
  14568. class LabeledStatement extends NodeBase {
  14569. hasEffects(context) {
  14570. const { brokenFlow, includedLabels } = context;
  14571. context.ignore.labels.add(this.label.name);
  14572. context.includedLabels = new Set();
  14573. let bodyHasEffects = false;
  14574. if (this.body.hasEffects(context)) {
  14575. bodyHasEffects = true;
  14576. }
  14577. else {
  14578. context.ignore.labels.delete(this.label.name);
  14579. if (context.includedLabels.has(this.label.name)) {
  14580. context.includedLabels.delete(this.label.name);
  14581. context.brokenFlow = brokenFlow;
  14582. }
  14583. }
  14584. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14585. return bodyHasEffects;
  14586. }
  14587. include(context, includeChildrenRecursively) {
  14588. if (!this.included)
  14589. this.includeNode(context);
  14590. const { brokenFlow, includedLabels } = context;
  14591. context.includedLabels = new Set();
  14592. this.body.include(context, includeChildrenRecursively);
  14593. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  14594. this.label.include(context, includeChildrenRecursively);
  14595. context.includedLabels.delete(this.label.name);
  14596. context.brokenFlow = brokenFlow;
  14597. }
  14598. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14599. }
  14600. includeNode(context) {
  14601. this.included = true;
  14602. this.body.includePath(UNKNOWN_PATH, context);
  14603. }
  14604. render(code, options) {
  14605. if (this.label.included) {
  14606. this.label.render(code, options);
  14607. }
  14608. else {
  14609. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  14610. }
  14611. this.body.render(code, options);
  14612. }
  14613. }
  14614. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14615. class LogicalExpression extends NodeBase {
  14616. constructor() {
  14617. super(...arguments);
  14618. // We collect deoptimization information if usedBranch !== null
  14619. this.expressionsToBeDeoptimized = [];
  14620. this.usedBranch = null;
  14621. }
  14622. //private isBranchResolutionAnalysed = false;
  14623. get isBranchResolutionAnalysed() {
  14624. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  14625. }
  14626. set isBranchResolutionAnalysed(value) {
  14627. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  14628. }
  14629. get hasDeoptimizedCache() {
  14630. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  14631. }
  14632. set hasDeoptimizedCache(value) {
  14633. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  14634. }
  14635. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14636. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14637. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14638. }
  14639. deoptimizeCache() {
  14640. if (this.hasDeoptimizedCache)
  14641. return;
  14642. this.hasDeoptimizedCache = true;
  14643. if (this.usedBranch) {
  14644. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  14645. this.usedBranch = null;
  14646. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  14647. if (this.included) {
  14648. // As we are not tracking inclusions, we just include everything
  14649. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  14650. }
  14651. }
  14652. const { scope: { context }, expressionsToBeDeoptimized } = this;
  14653. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  14654. for (const expression of expressionsToBeDeoptimized) {
  14655. expression.deoptimizeCache();
  14656. }
  14657. // Request another pass because we need to ensure "include" runs again if
  14658. // it is rendered
  14659. context.requestTreeshakingPass();
  14660. }
  14661. deoptimizePath(path) {
  14662. const usedBranch = this.getUsedBranch();
  14663. if (usedBranch) {
  14664. usedBranch.deoptimizePath(path);
  14665. }
  14666. else {
  14667. this.left.deoptimizePath(path);
  14668. this.right.deoptimizePath(path);
  14669. }
  14670. }
  14671. getLiteralValueAtPath(path, recursionTracker, origin) {
  14672. if (origin === this)
  14673. return UnknownValue;
  14674. const usedBranch = this.getUsedBranch();
  14675. if (usedBranch) {
  14676. this.expressionsToBeDeoptimized.push(origin);
  14677. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  14678. }
  14679. else if (!this.hasDeoptimizedCache && !path.length) {
  14680. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  14681. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  14682. if (typeof booleanOrUnknown !== 'symbol') {
  14683. if (!booleanOrUnknown && this.operator === '&&') {
  14684. this.expressionsToBeDeoptimized.push(origin);
  14685. return UnknownFalsyValue;
  14686. }
  14687. if (booleanOrUnknown && this.operator === '||') {
  14688. this.expressionsToBeDeoptimized.push(origin);
  14689. return UnknownTruthyValue;
  14690. }
  14691. }
  14692. }
  14693. return UnknownValue;
  14694. }
  14695. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14696. const usedBranch = this.getUsedBranch();
  14697. if (usedBranch) {
  14698. this.expressionsToBeDeoptimized.push(origin);
  14699. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  14700. }
  14701. return [
  14702. new MultiExpression([
  14703. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  14704. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  14705. ]),
  14706. false
  14707. ];
  14708. }
  14709. hasEffects(context) {
  14710. if (this.left.hasEffects(context)) {
  14711. return true;
  14712. }
  14713. if (this.getUsedBranch() !== this.left) {
  14714. return this.right.hasEffects(context);
  14715. }
  14716. return false;
  14717. }
  14718. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14719. const usedBranch = this.getUsedBranch();
  14720. if (usedBranch) {
  14721. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  14722. }
  14723. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  14724. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  14725. }
  14726. include(context, includeChildrenRecursively) {
  14727. this.included = true;
  14728. const usedBranch = this.getUsedBranch();
  14729. if (includeChildrenRecursively ||
  14730. !usedBranch ||
  14731. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14732. this.left.include(context, includeChildrenRecursively);
  14733. this.right.include(context, includeChildrenRecursively);
  14734. }
  14735. else {
  14736. usedBranch.include(context, includeChildrenRecursively);
  14737. }
  14738. }
  14739. includePath(path, context) {
  14740. this.included = true;
  14741. const usedBranch = this.getUsedBranch();
  14742. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14743. this.left.includePath(path, context);
  14744. this.right.includePath(path, context);
  14745. }
  14746. else {
  14747. usedBranch.includePath(path, context);
  14748. }
  14749. }
  14750. removeAnnotations(code) {
  14751. this.left.removeAnnotations(code);
  14752. }
  14753. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  14754. if (!this.left.included || !this.right.included) {
  14755. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  14756. if (this.right.included) {
  14757. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  14758. code.remove(this.start, removePos);
  14759. if (preventASI) {
  14760. removeLineBreaks(code, removePos, this.right.start);
  14761. }
  14762. this.left.removeAnnotations(code);
  14763. }
  14764. else {
  14765. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  14766. }
  14767. this.getUsedBranch().render(code, options, {
  14768. isCalleeOfRenderedParent,
  14769. preventASI,
  14770. renderedParentType: renderedParentType || this.parent.type,
  14771. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  14772. });
  14773. }
  14774. else {
  14775. this.left.render(code, options, {
  14776. preventASI,
  14777. renderedSurroundingElement
  14778. });
  14779. this.right.render(code, options);
  14780. }
  14781. }
  14782. getUsedBranch() {
  14783. if (!this.isBranchResolutionAnalysed) {
  14784. this.isBranchResolutionAnalysed = true;
  14785. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  14786. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  14787. if (typeof booleanOrUnknown === 'symbol') {
  14788. return null;
  14789. }
  14790. else {
  14791. this.usedBranch =
  14792. (this.operator === '||' && booleanOrUnknown) ||
  14793. (this.operator === '&&' && !booleanOrUnknown) ||
  14794. (this.operator === '??' && leftValue != null)
  14795. ? this.left
  14796. : this.right;
  14797. }
  14798. }
  14799. return this.usedBranch;
  14800. }
  14801. }
  14802. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14803. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14804. class NewExpression extends NodeBase {
  14805. hasEffects(context) {
  14806. if (!this.deoptimized)
  14807. this.applyDeoptimizations();
  14808. for (const argument of this.arguments) {
  14809. if (argument.hasEffects(context))
  14810. return true;
  14811. }
  14812. if (this.annotationPure) {
  14813. return false;
  14814. }
  14815. return (this.callee.hasEffects(context) ||
  14816. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14817. }
  14818. hasEffectsOnInteractionAtPath(path, { type }) {
  14819. return path.length > 0 || type !== INTERACTION_ACCESSED;
  14820. }
  14821. include(context, includeChildrenRecursively) {
  14822. if (!this.included)
  14823. this.includeNode(context);
  14824. if (includeChildrenRecursively) {
  14825. super.include(context, true);
  14826. }
  14827. else {
  14828. this.callee.include(context, false);
  14829. this.callee.includeCallArguments(this.interaction, context);
  14830. }
  14831. }
  14832. includeNode(context) {
  14833. this.included = true;
  14834. if (!this.deoptimized)
  14835. this.applyDeoptimizations();
  14836. this.callee.includePath(UNKNOWN_PATH, context);
  14837. }
  14838. initialise() {
  14839. super.initialise();
  14840. this.interaction = {
  14841. args: [null, ...this.arguments],
  14842. type: INTERACTION_CALLED,
  14843. withNew: true
  14844. };
  14845. if (this.annotations &&
  14846. this.scope.context.options.treeshake.annotations) {
  14847. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  14848. }
  14849. }
  14850. render(code, options) {
  14851. this.callee.render(code, options);
  14852. renderCallArguments(code, options, this);
  14853. }
  14854. applyDeoptimizations() {
  14855. this.deoptimized = true;
  14856. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  14857. this.scope.context.requestTreeshakingPass();
  14858. }
  14859. }
  14860. class ObjectExpression extends NodeBase {
  14861. constructor() {
  14862. super(...arguments);
  14863. this.objectEntity = null;
  14864. this.protoProp = null;
  14865. }
  14866. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14867. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14868. }
  14869. deoptimizeCache() {
  14870. this.getObjectEntity().deoptimizeAllProperties();
  14871. }
  14872. deoptimizePath(path) {
  14873. this.getObjectEntity().deoptimizePath(path);
  14874. }
  14875. getLiteralValueAtPath(path, recursionTracker, origin) {
  14876. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  14877. }
  14878. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14879. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  14880. }
  14881. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14882. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  14883. }
  14884. include(context, includeChildrenRecursively) {
  14885. if (!this.included)
  14886. this.includeNode(context);
  14887. this.getObjectEntity().include(context, includeChildrenRecursively);
  14888. this.protoProp?.include(context, includeChildrenRecursively);
  14889. }
  14890. includeNode(context) {
  14891. this.included = true;
  14892. this.protoProp?.includePath(UNKNOWN_PATH, context);
  14893. }
  14894. includePath(path, context) {
  14895. if (!this.included)
  14896. this.includeNode(context);
  14897. this.getObjectEntity().includePath(path, context);
  14898. }
  14899. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  14900. if (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  14901. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression) {
  14902. code.appendRight(this.start, '(');
  14903. code.prependLeft(this.end, ')');
  14904. }
  14905. if (this.properties.length > 0) {
  14906. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  14907. let lastSeparatorPos = null;
  14908. for (const { node, separator, start, end } of separatedNodes) {
  14909. if (!node.included) {
  14910. treeshakeNode(node, code, start, end);
  14911. continue;
  14912. }
  14913. lastSeparatorPos = separator;
  14914. node.render(code, options);
  14915. }
  14916. if (lastSeparatorPos) {
  14917. code.remove(lastSeparatorPos, this.end - 1);
  14918. }
  14919. }
  14920. }
  14921. getObjectEntity() {
  14922. if (this.objectEntity !== null) {
  14923. return this.objectEntity;
  14924. }
  14925. let prototype = OBJECT_PROTOTYPE;
  14926. const properties = [];
  14927. for (const property of this.properties) {
  14928. if (property instanceof SpreadElement) {
  14929. properties.push({ key: UnknownKey, kind: 'init', property });
  14930. continue;
  14931. }
  14932. let key;
  14933. if (property.computed) {
  14934. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  14935. if (typeof keyValue === 'symbol') {
  14936. properties.push({ key: UnknownKey, kind: property.kind, property });
  14937. continue;
  14938. }
  14939. else {
  14940. key = String(keyValue);
  14941. }
  14942. }
  14943. else {
  14944. key =
  14945. property.key instanceof Identifier
  14946. ? property.key.name
  14947. : String(property.key.value);
  14948. if (key === '__proto__' && property.kind === 'init') {
  14949. this.protoProp = property;
  14950. prototype =
  14951. property.value instanceof Literal && property.value.value === null
  14952. ? null
  14953. : property.value;
  14954. continue;
  14955. }
  14956. }
  14957. properties.push({ key, kind: property.kind, property });
  14958. }
  14959. return (this.objectEntity = new ObjectEntity(properties, prototype));
  14960. }
  14961. }
  14962. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14963. class PanicError extends NodeBase {
  14964. initialise() {
  14965. const id = this.scope.context.module.id;
  14966. // This simulates the current nested error structure. We could also just
  14967. // replace it with a flat error.
  14968. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message));
  14969. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  14970. return parseAst_js.error(moduleParseError);
  14971. }
  14972. }
  14973. class ParseError extends NodeBase {
  14974. initialise() {
  14975. const pos = this.start;
  14976. const id = this.scope.context.module.id;
  14977. // This simulates the current nested error structure. We could also just
  14978. // replace it with a flat error.
  14979. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message, pos));
  14980. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  14981. this.scope.context.error(moduleParseError, pos);
  14982. }
  14983. }
  14984. class PrivateIdentifier extends NodeBase {
  14985. }
  14986. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  14987. class Program extends NodeBase {
  14988. constructor() {
  14989. super(...arguments);
  14990. this.hasCachedEffect = null;
  14991. this.hasLoggedEffect = false;
  14992. }
  14993. hasCachedEffects() {
  14994. if (!this.included) {
  14995. return false;
  14996. }
  14997. return this.hasCachedEffect === null
  14998. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  14999. : this.hasCachedEffect;
  15000. }
  15001. hasEffects(context) {
  15002. for (const node of this.body) {
  15003. if (node.hasEffects(context)) {
  15004. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  15005. this.hasLoggedEffect = true;
  15006. const { code, log, module } = this.scope.context;
  15007. log(parseAst_js.LOGLEVEL_INFO, parseAst_js.logFirstSideEffect(code, module.id, parseAst_js.locate(code, node.start, { offsetLine: 1 })), node.start);
  15008. }
  15009. return (this.hasCachedEffect = true);
  15010. }
  15011. }
  15012. return false;
  15013. }
  15014. include(context, includeChildrenRecursively) {
  15015. this.included = true;
  15016. for (const node of this.body) {
  15017. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  15018. node.include(context, includeChildrenRecursively);
  15019. }
  15020. }
  15021. }
  15022. initialise() {
  15023. super.initialise();
  15024. if (this.invalidAnnotations)
  15025. for (const { start, end, type } of this.invalidAnnotations) {
  15026. this.scope.context.magicString.remove(start, end);
  15027. if (type === 'pure' || type === 'noSideEffects') {
  15028. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  15029. }
  15030. }
  15031. }
  15032. render(code, options) {
  15033. let start = this.start;
  15034. if (code.original.startsWith('#!')) {
  15035. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  15036. code.remove(0, start);
  15037. }
  15038. if (this.body.length > 0) {
  15039. // Keep all consecutive lines that start with a comment
  15040. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  15041. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  15042. if (firstLineBreak[0] === -1) {
  15043. break;
  15044. }
  15045. start += firstLineBreak[1];
  15046. }
  15047. renderStatementList(this.body, code, start, this.end, options);
  15048. }
  15049. else {
  15050. super.render(code, options);
  15051. }
  15052. }
  15053. }
  15054. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15055. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  15056. class Property extends MethodBase {
  15057. //declare method: boolean;
  15058. get method() {
  15059. return isFlagSet(this.flags, 262144 /* Flag.method */);
  15060. }
  15061. set method(value) {
  15062. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  15063. }
  15064. //declare shorthand: boolean;
  15065. get shorthand() {
  15066. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  15067. }
  15068. set shorthand(value) {
  15069. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  15070. }
  15071. declare(kind, destructuredInitPath, init) {
  15072. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  15073. }
  15074. deoptimizeAssignment(destructuredInitPath, init) {
  15075. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  15076. }
  15077. hasEffects(context) {
  15078. return this.key.hasEffects(context) || this.value.hasEffects(context);
  15079. }
  15080. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  15081. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  15082. }
  15083. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  15084. const path = this.getPathInProperty(destructuredInitPath);
  15085. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  15086. this.included;
  15087. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  15088. this.key.include(context, false);
  15089. if (!this.value.included) {
  15090. this.value.included = true;
  15091. // Unfortunately, we need to include the value again now, so that any
  15092. // declared variables are properly included.
  15093. this.value.includeDestructuredIfNecessary(context, path, init);
  15094. }
  15095. }
  15096. return (this.included = included);
  15097. }
  15098. include(context, includeChildrenRecursively) {
  15099. this.included = true;
  15100. this.key.include(context, includeChildrenRecursively);
  15101. this.value.include(context, includeChildrenRecursively);
  15102. }
  15103. includePath(path, context) {
  15104. this.included = true;
  15105. this.value.includePath(path, context);
  15106. }
  15107. markDeclarationReached() {
  15108. this.value.markDeclarationReached();
  15109. }
  15110. render(code, options) {
  15111. if (!this.shorthand) {
  15112. this.key.render(code, options);
  15113. }
  15114. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  15115. }
  15116. getPathInProperty(destructuredInitPath) {
  15117. return destructuredInitPath.at(-1) === UnknownKey
  15118. ? destructuredInitPath
  15119. : // For now, we only consider static paths as we do not know how to
  15120. // deoptimize the path in the dynamic case.
  15121. this.computed
  15122. ? [...destructuredInitPath, UnknownKey]
  15123. : this.key instanceof Identifier
  15124. ? [...destructuredInitPath, this.key.name]
  15125. : [...destructuredInitPath, String(this.key.value)];
  15126. }
  15127. }
  15128. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15129. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  15130. class PropertyDefinition extends NodeBase {
  15131. get computed() {
  15132. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  15133. }
  15134. set computed(value) {
  15135. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  15136. }
  15137. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15138. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15139. }
  15140. deoptimizePath(path) {
  15141. this.value?.deoptimizePath(path);
  15142. }
  15143. getLiteralValueAtPath(path, recursionTracker, origin) {
  15144. return this.value
  15145. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  15146. : UnknownValue;
  15147. }
  15148. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15149. return this.value
  15150. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  15151. : UNKNOWN_RETURN_EXPRESSION;
  15152. }
  15153. hasEffects(context) {
  15154. return (this.key.hasEffects(context) ||
  15155. (this.static && !!this.value?.hasEffects(context)) ||
  15156. checkEffectForNodes(this.decorators, context));
  15157. }
  15158. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15159. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  15160. }
  15161. includeNode(context) {
  15162. this.included = true;
  15163. this.value?.includePath(UNKNOWN_PATH, context);
  15164. for (const decorator of this.decorators) {
  15165. decorator.includePath(UNKNOWN_PATH, context);
  15166. }
  15167. }
  15168. }
  15169. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  15170. class ReturnStatement extends NodeBase {
  15171. hasEffects(context) {
  15172. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  15173. return true;
  15174. context.brokenFlow = true;
  15175. return false;
  15176. }
  15177. include(context, includeChildrenRecursively) {
  15178. if (!this.included)
  15179. this.includeNode(context);
  15180. this.argument?.include(context, includeChildrenRecursively);
  15181. context.brokenFlow = true;
  15182. }
  15183. includeNode(context) {
  15184. this.included = true;
  15185. this.argument?.includePath(UNKNOWN_PATH, context);
  15186. }
  15187. initialise() {
  15188. super.initialise();
  15189. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  15190. }
  15191. render(code, options) {
  15192. if (this.argument) {
  15193. this.argument.render(code, options, { preventASI: true });
  15194. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  15195. code.prependLeft(this.start + 6, ' ');
  15196. }
  15197. }
  15198. }
  15199. }
  15200. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15201. class SequenceExpression extends NodeBase {
  15202. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15203. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15204. }
  15205. deoptimizePath(path) {
  15206. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  15207. }
  15208. getLiteralValueAtPath(path, recursionTracker, origin) {
  15209. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  15210. }
  15211. hasEffects(context) {
  15212. for (const expression of this.expressions) {
  15213. if (expression.hasEffects(context))
  15214. return true;
  15215. }
  15216. return false;
  15217. }
  15218. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15219. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  15220. }
  15221. include(context, includeChildrenRecursively) {
  15222. this.included = true;
  15223. const lastExpression = this.expressions[this.expressions.length - 1];
  15224. for (const expression of this.expressions) {
  15225. if (includeChildrenRecursively ||
  15226. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  15227. expression.shouldBeIncluded(context)) {
  15228. expression.include(context, includeChildrenRecursively);
  15229. }
  15230. }
  15231. }
  15232. includePath(path, context) {
  15233. this.included = true;
  15234. this.expressions[this.expressions.length - 1].includePath(path, context);
  15235. }
  15236. removeAnnotations(code) {
  15237. this.expressions[0].removeAnnotations(code);
  15238. }
  15239. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = parseAst_js.BLANK) {
  15240. let includedNodes = 0;
  15241. let lastSeparatorPos = null;
  15242. const lastNode = this.expressions[this.expressions.length - 1];
  15243. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  15244. if (!node.included) {
  15245. treeshakeNode(node, code, start, end);
  15246. continue;
  15247. }
  15248. includedNodes++;
  15249. lastSeparatorPos = separator;
  15250. if (includedNodes === 1 && preventASI) {
  15251. removeLineBreaks(code, start, node.start);
  15252. }
  15253. if (includedNodes === 1) {
  15254. const parentType = renderedParentType || this.parent.type;
  15255. node.render(code, options, {
  15256. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  15257. renderedParentType: parentType,
  15258. renderedSurroundingElement: parentType
  15259. });
  15260. }
  15261. else {
  15262. node.render(code, options);
  15263. }
  15264. }
  15265. if (lastSeparatorPos) {
  15266. code.remove(lastSeparatorPos, this.end);
  15267. }
  15268. }
  15269. }
  15270. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15271. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15272. class Super extends NodeBase {
  15273. bind() {
  15274. this.variable = this.scope.findVariable('this');
  15275. }
  15276. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15277. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15278. }
  15279. deoptimizePath(path) {
  15280. this.variable.deoptimizePath(path);
  15281. }
  15282. include(context) {
  15283. if (!this.included)
  15284. this.includeNode(context);
  15285. }
  15286. includeNode(context) {
  15287. this.included = true;
  15288. if (!this.deoptimized)
  15289. this.applyDeoptimizations();
  15290. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15291. }
  15292. }
  15293. class SwitchCase extends NodeBase {
  15294. hasEffects(context) {
  15295. if (this.test?.hasEffects(context))
  15296. return true;
  15297. for (const node of this.consequent) {
  15298. if (context.brokenFlow)
  15299. break;
  15300. if (node.hasEffects(context))
  15301. return true;
  15302. }
  15303. return false;
  15304. }
  15305. include(context, includeChildrenRecursively) {
  15306. this.included = true;
  15307. this.test?.include(context, includeChildrenRecursively);
  15308. for (const node of this.consequent) {
  15309. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  15310. node.include(context, includeChildrenRecursively);
  15311. }
  15312. }
  15313. render(code, options, nodeRenderOptions) {
  15314. if (this.test) {
  15315. this.test.render(code, options);
  15316. if (this.test.start === this.start + 4) {
  15317. code.prependLeft(this.test.start, ' ');
  15318. }
  15319. }
  15320. if (this.consequent.length > 0) {
  15321. const testEnd = this.test
  15322. ? this.test.end
  15323. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  15324. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  15325. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  15326. }
  15327. }
  15328. }
  15329. SwitchCase.prototype.needsBoundaries = true;
  15330. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15331. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  15332. class SwitchStatement extends NodeBase {
  15333. createScope(parentScope) {
  15334. this.parentScope = parentScope;
  15335. this.scope = new BlockScope(parentScope);
  15336. }
  15337. hasEffects(context) {
  15338. if (this.discriminant.hasEffects(context))
  15339. return true;
  15340. const { brokenFlow, hasBreak, ignore } = context;
  15341. const { breaks } = ignore;
  15342. ignore.breaks = true;
  15343. context.hasBreak = false;
  15344. let onlyHasBrokenFlow = true;
  15345. for (const switchCase of this.cases) {
  15346. if (switchCase.hasEffects(context))
  15347. return true;
  15348. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15349. context.hasBreak = false;
  15350. context.brokenFlow = brokenFlow;
  15351. }
  15352. if (this.defaultCase !== null) {
  15353. context.brokenFlow = onlyHasBrokenFlow;
  15354. }
  15355. ignore.breaks = breaks;
  15356. context.hasBreak = hasBreak;
  15357. return false;
  15358. }
  15359. include(context, includeChildrenRecursively) {
  15360. this.included = true;
  15361. this.discriminant.include(context, includeChildrenRecursively);
  15362. const { brokenFlow, hasBreak } = context;
  15363. context.hasBreak = false;
  15364. let onlyHasBrokenFlow = true;
  15365. let isCaseIncluded = includeChildrenRecursively ||
  15366. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  15367. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  15368. const switchCase = this.cases[caseIndex];
  15369. if (switchCase.included) {
  15370. isCaseIncluded = true;
  15371. }
  15372. if (!isCaseIncluded) {
  15373. const hasEffectsContext = createHasEffectsContext();
  15374. hasEffectsContext.ignore.breaks = true;
  15375. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  15376. }
  15377. if (isCaseIncluded) {
  15378. switchCase.include(context, includeChildrenRecursively);
  15379. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15380. context.hasBreak = false;
  15381. context.brokenFlow = brokenFlow;
  15382. }
  15383. else {
  15384. onlyHasBrokenFlow = brokenFlow;
  15385. }
  15386. }
  15387. if (isCaseIncluded && this.defaultCase !== null) {
  15388. context.brokenFlow = onlyHasBrokenFlow;
  15389. }
  15390. context.hasBreak = hasBreak;
  15391. }
  15392. initialise() {
  15393. super.initialise();
  15394. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  15395. if (this.cases[caseIndex].test === null) {
  15396. this.defaultCase = caseIndex;
  15397. return;
  15398. }
  15399. }
  15400. this.defaultCase = null;
  15401. }
  15402. parseNode(esTreeNode) {
  15403. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  15404. return super.parseNode(esTreeNode);
  15405. }
  15406. render(code, options) {
  15407. this.discriminant.render(code, options);
  15408. if (this.cases.length > 0) {
  15409. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  15410. }
  15411. }
  15412. }
  15413. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15414. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15415. class TaggedTemplateExpression extends CallExpressionBase {
  15416. get hasCheckedForWarnings() {
  15417. return isFlagSet(this.flags, 268435456 /* Flag.checkedForWarnings */);
  15418. }
  15419. set hasCheckedForWarnings(value) {
  15420. this.flags = setFlag(this.flags, 268435456 /* Flag.checkedForWarnings */, value);
  15421. }
  15422. bind() {
  15423. super.bind();
  15424. }
  15425. hasEffects(context) {
  15426. if (!this.deoptimized)
  15427. this.applyDeoptimizations();
  15428. for (const argument of this.quasi.expressions) {
  15429. if (argument.hasEffects(context))
  15430. return true;
  15431. }
  15432. return (this.tag.hasEffects(context) ||
  15433. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  15434. }
  15435. include(context, includeChildrenRecursively) {
  15436. if (!this.included)
  15437. this.includeNode(context);
  15438. if (includeChildrenRecursively) {
  15439. super.include(context, true);
  15440. }
  15441. else {
  15442. this.quasi.include(context, false);
  15443. this.tag.include(context, false);
  15444. this.tag.includeCallArguments(this.interaction, context);
  15445. }
  15446. }
  15447. initialise() {
  15448. super.initialise();
  15449. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  15450. this.interaction = {
  15451. args: [
  15452. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  15453. ...this.args
  15454. ],
  15455. type: INTERACTION_CALLED,
  15456. withNew: false
  15457. };
  15458. }
  15459. render(code, options) {
  15460. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  15461. this.quasi.render(code, options);
  15462. if (!this.hasCheckedForWarnings && this.tag.type === parseAst_js.Identifier) {
  15463. this.hasCheckedForWarnings = true;
  15464. const name = this.tag.name;
  15465. const variable = this.scope.findVariable(name);
  15466. if (variable.isNamespace) {
  15467. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
  15468. }
  15469. }
  15470. }
  15471. applyDeoptimizations() {
  15472. this.deoptimized = true;
  15473. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15474. this.scope.context.requestTreeshakingPass();
  15475. }
  15476. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  15477. if (this.returnExpression === null) {
  15478. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  15479. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  15480. }
  15481. return this.returnExpression;
  15482. }
  15483. }
  15484. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  15485. class TemplateElement extends NodeBase {
  15486. get tail() {
  15487. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  15488. }
  15489. set tail(value) {
  15490. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  15491. }
  15492. // Do not try to bind value
  15493. bind() { }
  15494. hasEffects() {
  15495. return false;
  15496. }
  15497. parseNode(esTreeNode) {
  15498. this.value = esTreeNode.value;
  15499. return super.parseNode(esTreeNode);
  15500. }
  15501. render() { }
  15502. }
  15503. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  15504. class TemplateLiteral extends NodeBase {
  15505. deoptimizeArgumentsOnInteractionAtPath() { }
  15506. getLiteralValueAtPath(path) {
  15507. if (path.length > 0 || this.quasis.length !== 1) {
  15508. return UnknownValue;
  15509. }
  15510. return this.quasis[0].value.cooked;
  15511. }
  15512. getReturnExpressionWhenCalledAtPath(path) {
  15513. if (path.length !== 1) {
  15514. return UNKNOWN_RETURN_EXPRESSION;
  15515. }
  15516. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  15517. }
  15518. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15519. if (interaction.type === INTERACTION_ACCESSED) {
  15520. return path.length > 1;
  15521. }
  15522. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  15523. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  15524. }
  15525. return true;
  15526. }
  15527. includeNode(context) {
  15528. this.included = true;
  15529. if (!this.deoptimized)
  15530. this.applyDeoptimizations();
  15531. for (const node of this.expressions) {
  15532. node.includePath(UNKNOWN_PATH, context);
  15533. }
  15534. }
  15535. render(code, options) {
  15536. code.indentExclusionRanges.push([this.start, this.end]);
  15537. super.render(code, options);
  15538. }
  15539. }
  15540. class ModuleScope extends ChildScope {
  15541. constructor(parent, context) {
  15542. super(parent, context);
  15543. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  15544. }
  15545. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  15546. if (this.context.module.importDescriptions.has(identifier.name)) {
  15547. context.error(parseAst_js.logRedeclarationError(identifier.name), identifier.start);
  15548. }
  15549. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  15550. }
  15551. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  15552. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  15553. this.variables.set('default', variable);
  15554. return variable;
  15555. }
  15556. addNamespaceMemberAccess() { }
  15557. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  15558. // all module level variables are already deconflicted when deconflicting the chunk
  15559. for (const scope of this.children)
  15560. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15561. }
  15562. findLexicalBoundary() {
  15563. return this;
  15564. }
  15565. findVariable(name) {
  15566. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  15567. if (knownVariable) {
  15568. return knownVariable;
  15569. }
  15570. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  15571. if (variable instanceof GlobalVariable) {
  15572. this.accessedOutsideVariables.set(name, variable);
  15573. }
  15574. return variable;
  15575. }
  15576. }
  15577. class ThisExpression extends NodeBase {
  15578. bind() {
  15579. this.variable = this.scope.findVariable('this');
  15580. }
  15581. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15582. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15583. }
  15584. deoptimizePath(path) {
  15585. this.variable.deoptimizePath(path);
  15586. }
  15587. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15588. if (path.length === 0) {
  15589. return interaction.type !== INTERACTION_ACCESSED;
  15590. }
  15591. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  15592. }
  15593. include(context) {
  15594. if (!this.included)
  15595. this.includeNode(context);
  15596. }
  15597. includeNode(context) {
  15598. this.included = true;
  15599. if (!this.deoptimized)
  15600. this.applyDeoptimizations();
  15601. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15602. }
  15603. includePath(path, context) {
  15604. if (!this.included) {
  15605. this.included = true;
  15606. this.scope.context.includeVariableInModule(this.variable, path, context);
  15607. }
  15608. else if (path.length > 0) {
  15609. this.variable.includePath(path, context);
  15610. }
  15611. const functionScope = findFunctionScope(this.scope, this.variable);
  15612. if (functionScope &&
  15613. functionScope.functionNode.parent instanceof Property &&
  15614. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  15615. functionScope.functionNode.parent.parent.includePath(path, context);
  15616. }
  15617. }
  15618. initialise() {
  15619. super.initialise();
  15620. this.alias =
  15621. this.scope.findLexicalBoundary() instanceof ModuleScope
  15622. ? this.scope.context.moduleContext
  15623. : null;
  15624. if (this.alias === 'undefined') {
  15625. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logThisIsUndefined(), this.start);
  15626. }
  15627. }
  15628. render(code) {
  15629. if (this.alias !== null) {
  15630. code.overwrite(this.start, this.end, this.alias, {
  15631. contentOnly: false,
  15632. storeName: true
  15633. });
  15634. }
  15635. }
  15636. }
  15637. function findFunctionScope(scope, thisVariable) {
  15638. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  15639. if (!(scope instanceof ChildScope)) {
  15640. return null;
  15641. }
  15642. scope = scope.parent;
  15643. }
  15644. return scope;
  15645. }
  15646. class ThrowStatement extends NodeBase {
  15647. hasEffects() {
  15648. return true;
  15649. }
  15650. include(context, includeChildrenRecursively) {
  15651. if (!this.included)
  15652. this.includeNode(context);
  15653. this.argument.include(context, includeChildrenRecursively);
  15654. context.brokenFlow = true;
  15655. }
  15656. includeNode(context) {
  15657. if (!this.included) {
  15658. this.included = true;
  15659. this.argument.includePath(UNKNOWN_PATH, context);
  15660. }
  15661. }
  15662. render(code, options) {
  15663. this.argument.render(code, options, { preventASI: true });
  15664. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  15665. code.prependLeft(this.start + 5, ' ');
  15666. }
  15667. }
  15668. }
  15669. class TryStatement extends NodeBase {
  15670. constructor() {
  15671. super(...arguments);
  15672. this.directlyIncluded = false;
  15673. this.includedLabelsAfterBlock = null;
  15674. }
  15675. hasEffects(context) {
  15676. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  15677. ? this.block.body.length > 0
  15678. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  15679. }
  15680. include(context, includeChildrenRecursively) {
  15681. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  15682. const { brokenFlow, includedLabels } = context;
  15683. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  15684. this.included = true;
  15685. this.directlyIncluded = true;
  15686. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  15687. if (includedLabels.size > 0) {
  15688. this.includedLabelsAfterBlock = [...includedLabels];
  15689. }
  15690. context.brokenFlow = brokenFlow;
  15691. }
  15692. else if (this.includedLabelsAfterBlock) {
  15693. for (const label of this.includedLabelsAfterBlock) {
  15694. includedLabels.add(label);
  15695. }
  15696. }
  15697. if (this.handler !== null) {
  15698. this.handler.include(context, includeChildrenRecursively);
  15699. context.brokenFlow = brokenFlow;
  15700. }
  15701. this.finalizer?.include(context, includeChildrenRecursively);
  15702. }
  15703. }
  15704. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15705. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15706. const unaryOperators = {
  15707. '!': value => !value,
  15708. '+': value => +value,
  15709. '-': value => -value,
  15710. delete: () => UnknownValue,
  15711. typeof: value => typeof value,
  15712. void: () => undefined,
  15713. '~': value => ~value
  15714. };
  15715. const UNASSIGNED = Symbol('Unassigned');
  15716. class UnaryExpression extends NodeBase {
  15717. constructor() {
  15718. super(...arguments);
  15719. this.renderedLiteralValue = UNASSIGNED;
  15720. }
  15721. get prefix() {
  15722. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  15723. }
  15724. set prefix(value) {
  15725. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  15726. }
  15727. deoptimizeCache() {
  15728. this.renderedLiteralValue = UnknownValue;
  15729. }
  15730. getLiteralValueAtPath(path, recursionTracker, origin) {
  15731. if (path.length > 0)
  15732. return UnknownValue;
  15733. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  15734. if (typeof argumentValue === 'symbol') {
  15735. if (this.operator === 'void')
  15736. return undefined;
  15737. if (this.operator === '!') {
  15738. if (argumentValue === UnknownFalsyValue)
  15739. return true;
  15740. if (argumentValue === UnknownTruthyValue)
  15741. return false;
  15742. }
  15743. return UnknownValue;
  15744. }
  15745. return unaryOperators[this.operator](argumentValue);
  15746. }
  15747. hasEffects(context) {
  15748. if (!this.deoptimized)
  15749. this.applyDeoptimizations();
  15750. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  15751. return false;
  15752. return (this.argument.hasEffects(context) ||
  15753. (this.operator === 'delete' &&
  15754. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  15755. }
  15756. hasEffectsOnInteractionAtPath(path, { type }) {
  15757. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  15758. }
  15759. applyDeoptimizations() {
  15760. this.deoptimized = true;
  15761. if (this.operator === 'delete') {
  15762. this.argument.deoptimizePath(EMPTY_PATH);
  15763. this.scope.context.requestTreeshakingPass();
  15764. }
  15765. }
  15766. getRenderedLiteralValue(includeChildrenRecursively) {
  15767. if (this.renderedLiteralValue !== UNASSIGNED)
  15768. return this.renderedLiteralValue;
  15769. return (this.renderedLiteralValue = includeChildrenRecursively
  15770. ? UnknownValue
  15771. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  15772. }
  15773. include(context, includeChildrenRecursively, _options) {
  15774. if (!this.deoptimized)
  15775. this.applyDeoptimizations();
  15776. this.included = true;
  15777. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  15778. this.argument.shouldBeIncluded(context)) {
  15779. this.argument.include(context, includeChildrenRecursively);
  15780. this.renderedLiteralValue = UnknownValue;
  15781. }
  15782. }
  15783. render(code, options) {
  15784. if (typeof this.renderedLiteralValue === 'symbol') {
  15785. super.render(code, options);
  15786. }
  15787. else {
  15788. let value = this.renderedLiteralValue;
  15789. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  15790. value = ` ${value}`;
  15791. }
  15792. code.overwrite(this.start, this.end, value);
  15793. }
  15794. }
  15795. }
  15796. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  15797. function getRenderedLiteralValue(value) {
  15798. if (value === undefined) {
  15799. // At the moment, the undefined only happens when the operator is void
  15800. return 'void 0';
  15801. }
  15802. if (typeof value === 'boolean') {
  15803. return String(value);
  15804. }
  15805. if (typeof value === 'string') {
  15806. return JSON.stringify(value);
  15807. }
  15808. if (typeof value === 'number') {
  15809. return getSimplifiedNumber(value);
  15810. }
  15811. return UnknownValue;
  15812. }
  15813. function getSimplifiedNumber(value) {
  15814. if (Object.is(-0, value)) {
  15815. return '-0';
  15816. }
  15817. const exp = value.toExponential();
  15818. const [base, exponent] = exp.split('e');
  15819. const floatLength = base.split('.')[1]?.length || 0;
  15820. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  15821. const stringifiedValue = String(value).replace('+', '');
  15822. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  15823. }
  15824. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  15825. class UpdateExpression extends NodeBase {
  15826. hasEffects(context) {
  15827. if (!this.deoptimized)
  15828. this.applyDeoptimizations();
  15829. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  15830. }
  15831. hasEffectsOnInteractionAtPath(path, { type }) {
  15832. return path.length > 1 || type !== INTERACTION_ACCESSED;
  15833. }
  15834. include(context, includeChildrenRecursively) {
  15835. if (!this.included)
  15836. this.includeNode(context);
  15837. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  15838. }
  15839. initialise() {
  15840. super.initialise();
  15841. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  15842. }
  15843. render(code, options) {
  15844. const { exportNamesByVariable, format, snippets: { _ } } = options;
  15845. this.argument.render(code, options);
  15846. if (format === 'system') {
  15847. const variable = this.argument.variable;
  15848. const exportNames = exportNamesByVariable.get(variable);
  15849. if (exportNames) {
  15850. if (this.prefix) {
  15851. if (exportNames.length === 1) {
  15852. renderSystemExportExpression(variable, this.start, this.end, code, options);
  15853. }
  15854. else {
  15855. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options);
  15856. }
  15857. }
  15858. else {
  15859. const operator = this.operator[0];
  15860. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options, `${_}${operator}${_}1`);
  15861. }
  15862. }
  15863. }
  15864. }
  15865. applyDeoptimizations() {
  15866. this.deoptimized = true;
  15867. this.argument.deoptimizePath(EMPTY_PATH);
  15868. if (this.argument instanceof Identifier) {
  15869. const variable = this.scope.findVariable(this.argument.name);
  15870. variable.markReassigned();
  15871. }
  15872. this.scope.context.requestTreeshakingPass();
  15873. }
  15874. }
  15875. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  15876. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  15877. for (const declarator of declarations) {
  15878. if (!declarator.id.included)
  15879. return false;
  15880. if (declarator.id.type === parseAst_js.Identifier) {
  15881. if (exportNamesByVariable.has(declarator.id.variable))
  15882. return false;
  15883. }
  15884. else {
  15885. const exportedVariables = [];
  15886. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  15887. if (exportedVariables.length > 0)
  15888. return false;
  15889. }
  15890. }
  15891. return true;
  15892. }
  15893. class VariableDeclaration extends NodeBase {
  15894. deoptimizePath() {
  15895. for (const declarator of this.declarations) {
  15896. declarator.deoptimizePath(EMPTY_PATH);
  15897. }
  15898. }
  15899. hasEffectsOnInteractionAtPath() {
  15900. return false;
  15901. }
  15902. include(context, includeChildrenRecursively, { asSingleStatement } = parseAst_js.BLANK) {
  15903. this.included = true;
  15904. for (const declarator of this.declarations) {
  15905. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  15906. declarator.include(context, includeChildrenRecursively);
  15907. }
  15908. const { id, init } = declarator;
  15909. if (asSingleStatement) {
  15910. id.include(context, includeChildrenRecursively);
  15911. }
  15912. if (init &&
  15913. id.included &&
  15914. !init.included &&
  15915. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  15916. init.include(context, includeChildrenRecursively);
  15917. }
  15918. }
  15919. }
  15920. initialise() {
  15921. super.initialise();
  15922. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  15923. for (const declarator of this.declarations) {
  15924. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  15925. }
  15926. }
  15927. removeAnnotations(code) {
  15928. this.declarations[0].removeAnnotations(code);
  15929. }
  15930. render(code, options, nodeRenderOptions = parseAst_js.BLANK) {
  15931. if (this.isUsingDeclaration ||
  15932. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  15933. for (const declarator of this.declarations) {
  15934. declarator.render(code, options);
  15935. }
  15936. if (!nodeRenderOptions.isNoStatement &&
  15937. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  15938. code.appendLeft(this.end, ';');
  15939. }
  15940. }
  15941. else {
  15942. this.renderReplacedDeclarations(code, options);
  15943. }
  15944. }
  15945. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  15946. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  15947. code.remove(this.end - 1, this.end);
  15948. }
  15949. separatorString += ';';
  15950. if (lastSeparatorPos === null) {
  15951. code.appendLeft(renderedContentEnd, separatorString);
  15952. }
  15953. else {
  15954. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  15955. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  15956. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  15957. actualContentEnd--;
  15958. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  15959. actualContentEnd--;
  15960. }
  15961. }
  15962. if (actualContentEnd === lastSeparatorPos + 1) {
  15963. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  15964. }
  15965. else {
  15966. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  15967. code.remove(actualContentEnd, renderedContentEnd);
  15968. }
  15969. }
  15970. if (systemPatternExports.length > 0) {
  15971. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  15972. }
  15973. }
  15974. renderReplacedDeclarations(code, options) {
  15975. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  15976. let actualContentEnd, renderedContentEnd;
  15977. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  15978. let lastSeparatorPos = renderedContentEnd - 1;
  15979. code.remove(this.start, lastSeparatorPos);
  15980. let isInDeclaration = false;
  15981. let hasRenderedContent = false;
  15982. let separatorString = '', leadingString, nextSeparatorString;
  15983. const aggregatedSystemExports = [];
  15984. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  15985. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  15986. if (!node.included) {
  15987. treeshakeNode(node, code, start, end);
  15988. continue;
  15989. }
  15990. node.render(code, options);
  15991. leadingString = '';
  15992. nextSeparatorString = '';
  15993. if (!node.id.included ||
  15994. (node.id instanceof Identifier &&
  15995. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  15996. if (hasRenderedContent) {
  15997. separatorString += ';';
  15998. }
  15999. isInDeclaration = false;
  16000. }
  16001. else {
  16002. if (singleSystemExport && singleSystemExport === node.id.variable) {
  16003. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  16004. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  16005. }
  16006. if (isInDeclaration) {
  16007. separatorString += ',';
  16008. }
  16009. else {
  16010. if (hasRenderedContent) {
  16011. separatorString += ';';
  16012. }
  16013. leadingString += `${this.kind} `;
  16014. isInDeclaration = true;
  16015. }
  16016. }
  16017. if (renderedContentEnd === lastSeparatorPos + 1) {
  16018. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  16019. }
  16020. else {
  16021. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  16022. code.appendLeft(renderedContentEnd, leadingString);
  16023. }
  16024. actualContentEnd = contentEnd;
  16025. renderedContentEnd = end;
  16026. hasRenderedContent = true;
  16027. lastSeparatorPos = separator;
  16028. separatorString = nextSeparatorString;
  16029. }
  16030. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  16031. }
  16032. }
  16033. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  16034. let singleSystemExport = null;
  16035. if (options.format === 'system') {
  16036. for (const { node } of separatedNodes) {
  16037. if (node.id instanceof Identifier &&
  16038. node.init &&
  16039. aggregatedSystemExports.length === 0 &&
  16040. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  16041. singleSystemExport = node.id.variable;
  16042. aggregatedSystemExports.push(singleSystemExport);
  16043. }
  16044. else {
  16045. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  16046. }
  16047. }
  16048. if (aggregatedSystemExports.length > 1) {
  16049. singleSystemExport = null;
  16050. }
  16051. else if (singleSystemExport) {
  16052. aggregatedSystemExports.length = 0;
  16053. }
  16054. }
  16055. return singleSystemExport;
  16056. }
  16057. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16058. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  16059. class WhileStatement extends NodeBase {
  16060. hasEffects(context) {
  16061. if (this.test.hasEffects(context))
  16062. return true;
  16063. return hasLoopBodyEffects(context, this.body);
  16064. }
  16065. include(context, includeChildrenRecursively) {
  16066. this.included = true;
  16067. this.test.include(context, includeChildrenRecursively);
  16068. includeLoopBody(context, this.body, includeChildrenRecursively);
  16069. }
  16070. }
  16071. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16072. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  16073. class YieldExpression extends NodeBase {
  16074. applyDeoptimizations() {
  16075. this.deoptimized = true;
  16076. this.argument?.deoptimizePath(UNKNOWN_PATH);
  16077. }
  16078. hasEffects(context) {
  16079. if (!this.deoptimized)
  16080. this.applyDeoptimizations();
  16081. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  16082. }
  16083. includeNode(context) {
  16084. this.included = true;
  16085. if (!this.deoptimized)
  16086. this.applyDeoptimizations();
  16087. this.argument?.includePath(UNKNOWN_PATH, context);
  16088. }
  16089. render(code, options) {
  16090. if (this.argument) {
  16091. this.argument.render(code, options, { preventASI: true });
  16092. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  16093. code.prependLeft(this.start + 5, ' ');
  16094. }
  16095. }
  16096. }
  16097. }
  16098. // This file is generated by scripts/generate-buffer-parsers.js.
  16099. // Do not edit this file directly.
  16100. function convertProgram(buffer, parent, parentScope) {
  16101. return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
  16102. }
  16103. const nodeTypeStrings = [
  16104. 'PanicError',
  16105. 'ParseError',
  16106. 'ArrayExpression',
  16107. 'ArrayPattern',
  16108. 'ArrowFunctionExpression',
  16109. 'AssignmentExpression',
  16110. 'AssignmentPattern',
  16111. 'AwaitExpression',
  16112. 'BinaryExpression',
  16113. 'BlockStatement',
  16114. 'BreakStatement',
  16115. 'CallExpression',
  16116. 'CatchClause',
  16117. 'ChainExpression',
  16118. 'ClassBody',
  16119. 'ClassDeclaration',
  16120. 'ClassExpression',
  16121. 'ConditionalExpression',
  16122. 'ContinueStatement',
  16123. 'DebuggerStatement',
  16124. 'Decorator',
  16125. 'ExpressionStatement',
  16126. 'DoWhileStatement',
  16127. 'EmptyStatement',
  16128. 'ExportAllDeclaration',
  16129. 'ExportDefaultDeclaration',
  16130. 'ExportNamedDeclaration',
  16131. 'ExportSpecifier',
  16132. 'ExpressionStatement',
  16133. 'ForInStatement',
  16134. 'ForOfStatement',
  16135. 'ForStatement',
  16136. 'FunctionDeclaration',
  16137. 'FunctionExpression',
  16138. 'Identifier',
  16139. 'IfStatement',
  16140. 'ImportAttribute',
  16141. 'ImportDeclaration',
  16142. 'ImportDefaultSpecifier',
  16143. 'ImportExpression',
  16144. 'ImportNamespaceSpecifier',
  16145. 'ImportSpecifier',
  16146. 'JSXAttribute',
  16147. 'JSXClosingElement',
  16148. 'JSXClosingFragment',
  16149. 'JSXElement',
  16150. 'JSXEmptyExpression',
  16151. 'JSXExpressionContainer',
  16152. 'JSXFragment',
  16153. 'JSXIdentifier',
  16154. 'JSXMemberExpression',
  16155. 'JSXNamespacedName',
  16156. 'JSXOpeningElement',
  16157. 'JSXOpeningFragment',
  16158. 'JSXSpreadAttribute',
  16159. 'JSXSpreadChild',
  16160. 'JSXText',
  16161. 'LabeledStatement',
  16162. 'Literal',
  16163. 'Literal',
  16164. 'Literal',
  16165. 'Literal',
  16166. 'Literal',
  16167. 'Literal',
  16168. 'LogicalExpression',
  16169. 'MemberExpression',
  16170. 'MetaProperty',
  16171. 'MethodDefinition',
  16172. 'NewExpression',
  16173. 'ObjectExpression',
  16174. 'ObjectPattern',
  16175. 'PrivateIdentifier',
  16176. 'Program',
  16177. 'Property',
  16178. 'PropertyDefinition',
  16179. 'RestElement',
  16180. 'ReturnStatement',
  16181. 'SequenceExpression',
  16182. 'SpreadElement',
  16183. 'StaticBlock',
  16184. 'Super',
  16185. 'SwitchCase',
  16186. 'SwitchStatement',
  16187. 'TaggedTemplateExpression',
  16188. 'TemplateElement',
  16189. 'TemplateLiteral',
  16190. 'ThisExpression',
  16191. 'ThrowStatement',
  16192. 'TryStatement',
  16193. 'UnaryExpression',
  16194. 'UpdateExpression',
  16195. 'VariableDeclaration',
  16196. 'VariableDeclarator',
  16197. 'WhileStatement',
  16198. 'YieldExpression'
  16199. ];
  16200. const nodeConstructors$1 = [
  16201. PanicError,
  16202. ParseError,
  16203. ArrayExpression,
  16204. ArrayPattern,
  16205. ArrowFunctionExpression,
  16206. AssignmentExpression,
  16207. AssignmentPattern,
  16208. AwaitExpression,
  16209. BinaryExpression,
  16210. BlockStatement,
  16211. BreakStatement,
  16212. CallExpression,
  16213. CatchClause,
  16214. ChainExpression,
  16215. ClassBody,
  16216. ClassDeclaration,
  16217. ClassExpression,
  16218. ConditionalExpression,
  16219. ContinueStatement,
  16220. DebuggerStatement,
  16221. Decorator,
  16222. ExpressionStatement,
  16223. DoWhileStatement,
  16224. EmptyStatement,
  16225. ExportAllDeclaration,
  16226. ExportDefaultDeclaration,
  16227. ExportNamedDeclaration,
  16228. ExportSpecifier,
  16229. ExpressionStatement,
  16230. ForInStatement,
  16231. ForOfStatement,
  16232. ForStatement,
  16233. FunctionDeclaration,
  16234. FunctionExpression,
  16235. Identifier,
  16236. IfStatement,
  16237. ImportAttribute,
  16238. ImportDeclaration,
  16239. ImportDefaultSpecifier,
  16240. ImportExpression,
  16241. ImportNamespaceSpecifier,
  16242. ImportSpecifier,
  16243. JSXAttribute,
  16244. JSXClosingElement,
  16245. JSXClosingFragment,
  16246. JSXElement,
  16247. JSXEmptyExpression,
  16248. JSXExpressionContainer,
  16249. JSXFragment,
  16250. JSXIdentifier,
  16251. JSXMemberExpression,
  16252. JSXNamespacedName,
  16253. JSXOpeningElement,
  16254. JSXOpeningFragment,
  16255. JSXSpreadAttribute,
  16256. JSXSpreadChild,
  16257. JSXText,
  16258. LabeledStatement,
  16259. Literal,
  16260. Literal,
  16261. Literal,
  16262. Literal,
  16263. Literal,
  16264. Literal,
  16265. LogicalExpression,
  16266. MemberExpression,
  16267. MetaProperty,
  16268. MethodDefinition,
  16269. NewExpression,
  16270. ObjectExpression,
  16271. ObjectPattern,
  16272. PrivateIdentifier,
  16273. Program,
  16274. Property,
  16275. PropertyDefinition,
  16276. RestElement,
  16277. ReturnStatement,
  16278. SequenceExpression,
  16279. SpreadElement,
  16280. StaticBlock,
  16281. Super,
  16282. SwitchCase,
  16283. SwitchStatement,
  16284. TaggedTemplateExpression,
  16285. TemplateElement,
  16286. TemplateLiteral,
  16287. ThisExpression,
  16288. ThrowStatement,
  16289. TryStatement,
  16290. UnaryExpression,
  16291. UpdateExpression,
  16292. VariableDeclaration,
  16293. VariableDeclarator,
  16294. WhileStatement,
  16295. YieldExpression
  16296. ];
  16297. const bufferParsers = [
  16298. function panicError(node, position, buffer) {
  16299. node.message = buffer.convertString(buffer[position]);
  16300. },
  16301. function parseError(node, position, buffer) {
  16302. node.message = buffer.convertString(buffer[position]);
  16303. },
  16304. function arrayExpression(node, position, buffer) {
  16305. const { scope } = node;
  16306. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16307. },
  16308. function arrayPattern(node, position, buffer) {
  16309. const { scope } = node;
  16310. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16311. },
  16312. function arrowFunctionExpression(node, position, buffer) {
  16313. const { scope } = node;
  16314. const flags = buffer[position];
  16315. node.async = (flags & 1) === 1;
  16316. node.expression = (flags & 2) === 2;
  16317. node.generator = (flags & 4) === 4;
  16318. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16319. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16320. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  16321. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16322. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  16323. },
  16324. function assignmentExpression(node, position, buffer) {
  16325. const { scope } = node;
  16326. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16327. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16328. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16329. },
  16330. function assignmentPattern(node, position, buffer) {
  16331. const { scope } = node;
  16332. node.left = convertNode(node, scope, buffer[position], buffer);
  16333. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16334. },
  16335. function awaitExpression(node, position, buffer) {
  16336. const { scope } = node;
  16337. node.argument = convertNode(node, scope, buffer[position], buffer);
  16338. },
  16339. function binaryExpression(node, position, buffer) {
  16340. const { scope } = node;
  16341. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16342. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16343. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16344. },
  16345. function blockStatement(node, position, buffer) {
  16346. const { scope } = node;
  16347. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16348. },
  16349. function breakStatement(node, position, buffer) {
  16350. const { scope } = node;
  16351. const labelPosition = buffer[position];
  16352. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16353. },
  16354. function callExpression(node, position, buffer) {
  16355. const { scope } = node;
  16356. const flags = buffer[position];
  16357. node.optional = (flags & 1) === 1;
  16358. node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16359. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  16360. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  16361. },
  16362. function catchClause(node, position, buffer) {
  16363. const { scope } = node;
  16364. const parameterPosition = buffer[position];
  16365. const parameter = (node.param =
  16366. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  16367. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  16368. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  16369. },
  16370. function chainExpression(node, position, buffer) {
  16371. const { scope } = node;
  16372. node.expression = convertNode(node, scope, buffer[position], buffer);
  16373. },
  16374. function classBody(node, position, buffer) {
  16375. const { scope } = node;
  16376. const bodyPosition = buffer[position];
  16377. if (bodyPosition) {
  16378. const length = buffer[bodyPosition];
  16379. const body = (node.body = new Array(length));
  16380. for (let index = 0; index < length; index++) {
  16381. const nodePosition = buffer[bodyPosition + 1 + index];
  16382. body[index] = convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer);
  16383. }
  16384. }
  16385. else {
  16386. node.body = [];
  16387. }
  16388. },
  16389. function classDeclaration(node, position, buffer) {
  16390. const { scope } = node;
  16391. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16392. const idPosition = buffer[position + 1];
  16393. node.id =
  16394. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16395. const superClassPosition = buffer[position + 2];
  16396. node.superClass =
  16397. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16398. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16399. },
  16400. function classExpression(node, position, buffer) {
  16401. const { scope } = node;
  16402. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16403. const idPosition = buffer[position + 1];
  16404. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  16405. const superClassPosition = buffer[position + 2];
  16406. node.superClass =
  16407. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16408. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16409. },
  16410. function conditionalExpression(node, position, buffer) {
  16411. const { scope } = node;
  16412. node.test = convertNode(node, scope, buffer[position], buffer);
  16413. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  16414. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  16415. },
  16416. function continueStatement(node, position, buffer) {
  16417. const { scope } = node;
  16418. const labelPosition = buffer[position];
  16419. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16420. },
  16421. function debuggerStatement() { },
  16422. function decorator(node, position, buffer) {
  16423. const { scope } = node;
  16424. node.expression = convertNode(node, scope, buffer[position], buffer);
  16425. },
  16426. function directive(node, position, buffer) {
  16427. const { scope } = node;
  16428. node.directive = buffer.convertString(buffer[position]);
  16429. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  16430. },
  16431. function doWhileStatement(node, position, buffer) {
  16432. const { scope } = node;
  16433. node.body = convertNode(node, scope, buffer[position], buffer);
  16434. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  16435. },
  16436. function emptyStatement() { },
  16437. function exportAllDeclaration(node, position, buffer) {
  16438. const { scope } = node;
  16439. const exportedPosition = buffer[position];
  16440. node.exported =
  16441. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  16442. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16443. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16444. },
  16445. function exportDefaultDeclaration(node, position, buffer) {
  16446. const { scope } = node;
  16447. node.declaration = convertNode(node, scope, buffer[position], buffer);
  16448. },
  16449. function exportNamedDeclaration(node, position, buffer) {
  16450. const { scope } = node;
  16451. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16452. const sourcePosition = buffer[position + 1];
  16453. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  16454. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16455. const declarationPosition = buffer[position + 3];
  16456. node.declaration =
  16457. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  16458. },
  16459. function exportSpecifier(node, position, buffer) {
  16460. const { scope } = node;
  16461. node.local = convertNode(node, scope, buffer[position], buffer);
  16462. const exportedPosition = buffer[position + 1];
  16463. node.exported =
  16464. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  16465. },
  16466. function expressionStatement(node, position, buffer) {
  16467. const { scope } = node;
  16468. node.expression = convertNode(node, scope, buffer[position], buffer);
  16469. },
  16470. function forInStatement(node, position, buffer) {
  16471. const { scope } = node;
  16472. node.left = convertNode(node, scope, buffer[position], buffer);
  16473. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16474. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  16475. },
  16476. function forOfStatement(node, position, buffer) {
  16477. const { scope } = node;
  16478. const flags = buffer[position];
  16479. node.await = (flags & 1) === 1;
  16480. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16481. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16482. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16483. },
  16484. function forStatement(node, position, buffer) {
  16485. const { scope } = node;
  16486. const initPosition = buffer[position];
  16487. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16488. const testPosition = buffer[position + 1];
  16489. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16490. const updatePosition = buffer[position + 2];
  16491. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  16492. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16493. },
  16494. function functionDeclaration(node, position, buffer) {
  16495. const { scope } = node;
  16496. const flags = buffer[position];
  16497. node.async = (flags & 1) === 1;
  16498. node.generator = (flags & 2) === 2;
  16499. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16500. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16501. const idPosition = buffer[position + 2];
  16502. node.id =
  16503. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16504. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16505. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16506. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16507. },
  16508. function functionExpression(node, position, buffer) {
  16509. const { scope } = node;
  16510. const flags = buffer[position];
  16511. node.async = (flags & 1) === 1;
  16512. node.generator = (flags & 2) === 2;
  16513. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16514. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16515. const idPosition = buffer[position + 2];
  16516. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  16517. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16518. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16519. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16520. },
  16521. function identifier(node, position, buffer) {
  16522. node.name = buffer.convertString(buffer[position]);
  16523. },
  16524. function ifStatement(node, position, buffer) {
  16525. const { scope } = node;
  16526. node.test = convertNode(node, scope, buffer[position], buffer);
  16527. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  16528. const alternatePosition = buffer[position + 2];
  16529. node.alternate =
  16530. alternatePosition === 0
  16531. ? null
  16532. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  16533. },
  16534. function importAttribute(node, position, buffer) {
  16535. const { scope } = node;
  16536. node.key = convertNode(node, scope, buffer[position], buffer);
  16537. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  16538. },
  16539. function importDeclaration(node, position, buffer) {
  16540. const { scope } = node;
  16541. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16542. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16543. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16544. },
  16545. function importDefaultSpecifier(node, position, buffer) {
  16546. const { scope } = node;
  16547. node.local = convertNode(node, scope, buffer[position], buffer);
  16548. },
  16549. function importExpression(node, position, buffer) {
  16550. const { scope } = node;
  16551. node.source = convertNode(node, scope, buffer[position], buffer);
  16552. node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
  16553. const optionsPosition = buffer[position + 1];
  16554. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  16555. },
  16556. function importNamespaceSpecifier(node, position, buffer) {
  16557. const { scope } = node;
  16558. node.local = convertNode(node, scope, buffer[position], buffer);
  16559. },
  16560. function importSpecifier(node, position, buffer) {
  16561. const { scope } = node;
  16562. const importedPosition = buffer[position];
  16563. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  16564. node.imported =
  16565. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  16566. },
  16567. function jsxAttribute(node, position, buffer) {
  16568. const { scope } = node;
  16569. node.name = convertNode(node, scope, buffer[position], buffer);
  16570. const valuePosition = buffer[position + 1];
  16571. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16572. },
  16573. function jsxClosingElement(node, position, buffer) {
  16574. const { scope } = node;
  16575. node.name = convertNode(node, scope, buffer[position], buffer);
  16576. },
  16577. function jsxClosingFragment() { },
  16578. function jsxElement(node, position, buffer) {
  16579. const { scope } = node;
  16580. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  16581. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16582. const closingElementPosition = buffer[position + 2];
  16583. node.closingElement =
  16584. closingElementPosition === 0
  16585. ? null
  16586. : convertNode(node, scope, closingElementPosition, buffer);
  16587. },
  16588. function jsxEmptyExpression() { },
  16589. function jsxExpressionContainer(node, position, buffer) {
  16590. const { scope } = node;
  16591. node.expression = convertNode(node, scope, buffer[position], buffer);
  16592. },
  16593. function jsxFragment(node, position, buffer) {
  16594. const { scope } = node;
  16595. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  16596. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16597. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  16598. },
  16599. function jsxIdentifier(node, position, buffer) {
  16600. node.name = buffer.convertString(buffer[position]);
  16601. },
  16602. function jsxMemberExpression(node, position, buffer) {
  16603. const { scope } = node;
  16604. node.object = convertNode(node, scope, buffer[position], buffer);
  16605. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16606. },
  16607. function jsxNamespacedName(node, position, buffer) {
  16608. const { scope } = node;
  16609. node.namespace = convertNode(node, scope, buffer[position], buffer);
  16610. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16611. },
  16612. function jsxOpeningElement(node, position, buffer) {
  16613. const { scope } = node;
  16614. const flags = buffer[position];
  16615. node.selfClosing = (flags & 1) === 1;
  16616. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16617. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16618. },
  16619. function jsxOpeningFragment(node) {
  16620. node.attributes = [];
  16621. node.selfClosing = false;
  16622. },
  16623. function jsxSpreadAttribute(node, position, buffer) {
  16624. const { scope } = node;
  16625. node.argument = convertNode(node, scope, buffer[position], buffer);
  16626. },
  16627. function jsxSpreadChild(node, position, buffer) {
  16628. const { scope } = node;
  16629. node.expression = convertNode(node, scope, buffer[position], buffer);
  16630. },
  16631. function jsxText(node, position, buffer) {
  16632. node.value = buffer.convertString(buffer[position]);
  16633. node.raw = buffer.convertString(buffer[position + 1]);
  16634. },
  16635. function labeledStatement(node, position, buffer) {
  16636. const { scope } = node;
  16637. node.label = convertNode(node, scope, buffer[position], buffer);
  16638. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16639. },
  16640. function literalBigInt(node, position, buffer) {
  16641. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  16642. node.raw = buffer.convertString(buffer[position + 1]);
  16643. node.value = BigInt(bigint);
  16644. },
  16645. function literalBoolean(node, position, buffer) {
  16646. const flags = buffer[position];
  16647. const value = (node.value = (flags & 1) === 1);
  16648. node.raw = value ? 'true' : 'false';
  16649. },
  16650. function literalNull(node) {
  16651. node.value = null;
  16652. },
  16653. function literalNumber(node, position, buffer) {
  16654. const rawPosition = buffer[position];
  16655. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16656. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  16657. },
  16658. function literalRegExp(node, position, buffer) {
  16659. const flags = buffer.convertString(buffer[position]);
  16660. const pattern = buffer.convertString(buffer[position + 1]);
  16661. node.raw = `/${pattern}/${flags}`;
  16662. node.regex = { flags, pattern };
  16663. node.value = new RegExp(pattern, flags);
  16664. },
  16665. function literalString(node, position, buffer) {
  16666. node.value = buffer.convertString(buffer[position]);
  16667. const rawPosition = buffer[position + 1];
  16668. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16669. },
  16670. function logicalExpression(node, position, buffer) {
  16671. const { scope } = node;
  16672. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16673. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16674. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16675. },
  16676. function memberExpression(node, position, buffer) {
  16677. const { scope } = node;
  16678. const flags = buffer[position];
  16679. node.computed = (flags & 1) === 1;
  16680. node.optional = (flags & 2) === 2;
  16681. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  16682. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  16683. },
  16684. function metaProperty(node, position, buffer) {
  16685. const { scope } = node;
  16686. node.meta = convertNode(node, scope, buffer[position], buffer);
  16687. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16688. },
  16689. function methodDefinition(node, position, buffer) {
  16690. const { scope } = node;
  16691. const flags = buffer[position];
  16692. node.static = (flags & 1) === 1;
  16693. node.computed = (flags & 2) === 2;
  16694. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16695. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16696. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  16697. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 4]];
  16698. },
  16699. function newExpression(node, position, buffer) {
  16700. const { scope } = node;
  16701. node.annotations = parseAst_js.convertAnnotations(buffer[position], buffer);
  16702. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  16703. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  16704. },
  16705. function objectExpression(node, position, buffer) {
  16706. const { scope } = node;
  16707. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16708. },
  16709. function objectPattern(node, position, buffer) {
  16710. const { scope } = node;
  16711. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16712. },
  16713. function privateIdentifier(node, position, buffer) {
  16714. node.name = buffer.convertString(buffer[position]);
  16715. },
  16716. function program(node, position, buffer) {
  16717. const { scope } = node;
  16718. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16719. node.invalidAnnotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16720. },
  16721. function property(node, position, buffer) {
  16722. const { scope } = node;
  16723. const flags = buffer[position];
  16724. node.method = (flags & 1) === 1;
  16725. node.shorthand = (flags & 2) === 2;
  16726. node.computed = (flags & 4) === 4;
  16727. const keyPosition = buffer[position + 1];
  16728. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  16729. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 3]];
  16730. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  16731. },
  16732. function propertyDefinition(node, position, buffer) {
  16733. const { scope } = node;
  16734. const flags = buffer[position];
  16735. node.static = (flags & 1) === 1;
  16736. node.computed = (flags & 2) === 2;
  16737. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16738. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16739. const valuePosition = buffer[position + 3];
  16740. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16741. },
  16742. function restElement(node, position, buffer) {
  16743. const { scope } = node;
  16744. node.argument = convertNode(node, scope, buffer[position], buffer);
  16745. },
  16746. function returnStatement(node, position, buffer) {
  16747. const { scope } = node;
  16748. const argumentPosition = buffer[position];
  16749. node.argument =
  16750. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16751. },
  16752. function sequenceExpression(node, position, buffer) {
  16753. const { scope } = node;
  16754. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  16755. },
  16756. function spreadElement(node, position, buffer) {
  16757. const { scope } = node;
  16758. node.argument = convertNode(node, scope, buffer[position], buffer);
  16759. },
  16760. function staticBlock(node, position, buffer) {
  16761. const { scope } = node;
  16762. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16763. },
  16764. function superElement() { },
  16765. function switchCase(node, position, buffer) {
  16766. const { scope } = node;
  16767. const testPosition = buffer[position];
  16768. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16769. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  16770. },
  16771. function switchStatement(node, position, buffer) {
  16772. const { scope } = node;
  16773. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  16774. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  16775. },
  16776. function taggedTemplateExpression(node, position, buffer) {
  16777. const { scope } = node;
  16778. node.tag = convertNode(node, scope, buffer[position], buffer);
  16779. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  16780. },
  16781. function templateElement(node, position, buffer) {
  16782. const flags = buffer[position];
  16783. node.tail = (flags & 1) === 1;
  16784. const cookedPosition = buffer[position + 1];
  16785. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  16786. const raw = buffer.convertString(buffer[position + 2]);
  16787. node.value = { cooked, raw };
  16788. },
  16789. function templateLiteral(node, position, buffer) {
  16790. const { scope } = node;
  16791. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  16792. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  16793. },
  16794. function thisExpression() { },
  16795. function throwStatement(node, position, buffer) {
  16796. const { scope } = node;
  16797. node.argument = convertNode(node, scope, buffer[position], buffer);
  16798. },
  16799. function tryStatement(node, position, buffer) {
  16800. const { scope } = node;
  16801. node.block = convertNode(node, scope, buffer[position], buffer);
  16802. const handlerPosition = buffer[position + 1];
  16803. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  16804. const finalizerPosition = buffer[position + 2];
  16805. node.finalizer =
  16806. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  16807. },
  16808. function unaryExpression(node, position, buffer) {
  16809. const { scope } = node;
  16810. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16811. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  16812. },
  16813. function updateExpression(node, position, buffer) {
  16814. const { scope } = node;
  16815. const flags = buffer[position];
  16816. node.prefix = (flags & 1) === 1;
  16817. node.operator = parseAst_js.FIXED_STRINGS[buffer[position + 1]];
  16818. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  16819. },
  16820. function variableDeclaration(node, position, buffer) {
  16821. const { scope } = node;
  16822. node.kind = parseAst_js.FIXED_STRINGS[buffer[position]];
  16823. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  16824. },
  16825. function variableDeclarator(node, position, buffer) {
  16826. const { scope } = node;
  16827. node.id = convertNode(node, scope, buffer[position], buffer);
  16828. const initPosition = buffer[position + 1];
  16829. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16830. },
  16831. function whileStatement(node, position, buffer) {
  16832. const { scope } = node;
  16833. node.test = convertNode(node, scope, buffer[position], buffer);
  16834. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16835. },
  16836. function yieldExpression(node, position, buffer) {
  16837. const { scope } = node;
  16838. const flags = buffer[position];
  16839. node.delegate = (flags & 1) === 1;
  16840. const argumentPosition = buffer[position + 1];
  16841. node.argument =
  16842. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16843. }
  16844. ];
  16845. function convertNode(parent, parentScope, position, buffer) {
  16846. const nodeType = buffer[position];
  16847. const NodeConstructor = nodeConstructors$1[nodeType];
  16848. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  16849. if (!NodeConstructor) {
  16850. console.trace();
  16851. throw new Error(`Unknown node type: ${nodeType}`);
  16852. }
  16853. const node = new NodeConstructor(parent, parentScope);
  16854. node.type = nodeTypeStrings[nodeType];
  16855. node.start = buffer[position + 1];
  16856. node.end = buffer[position + 2];
  16857. bufferParsers[nodeType](node, position + 3, buffer);
  16858. node.initialise();
  16859. return node;
  16860. }
  16861. function convertNodeList(parent, parentScope, position, buffer) {
  16862. if (position === 0)
  16863. return parseAst_js.EMPTY_ARRAY;
  16864. const length = buffer[position++];
  16865. const list = new Array(length);
  16866. for (let index = 0; index < length; index++) {
  16867. const nodePosition = buffer[position++];
  16868. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  16869. }
  16870. return list;
  16871. }
  16872. class UnknownNode extends NodeBase {
  16873. hasEffects() {
  16874. return true;
  16875. }
  16876. include(context) {
  16877. super.include(context, true);
  16878. }
  16879. }
  16880. // This file is generated by scripts/generate-node-index.js.
  16881. // Do not edit this file directly.
  16882. const nodeConstructors = {
  16883. ArrayExpression,
  16884. ArrayPattern,
  16885. ArrowFunctionExpression,
  16886. AssignmentExpression,
  16887. AssignmentPattern,
  16888. AwaitExpression,
  16889. BinaryExpression,
  16890. BlockStatement,
  16891. BreakStatement,
  16892. CallExpression,
  16893. CatchClause,
  16894. ChainExpression,
  16895. ClassBody,
  16896. ClassDeclaration,
  16897. ClassExpression,
  16898. ConditionalExpression,
  16899. ContinueStatement,
  16900. DebuggerStatement,
  16901. Decorator,
  16902. DoWhileStatement,
  16903. EmptyStatement,
  16904. ExportAllDeclaration,
  16905. ExportDefaultDeclaration,
  16906. ExportNamedDeclaration,
  16907. ExportSpecifier,
  16908. ExpressionStatement,
  16909. ForInStatement,
  16910. ForOfStatement,
  16911. ForStatement,
  16912. FunctionDeclaration,
  16913. FunctionExpression,
  16914. Identifier,
  16915. IfStatement,
  16916. ImportAttribute,
  16917. ImportDeclaration,
  16918. ImportDefaultSpecifier,
  16919. ImportExpression,
  16920. ImportNamespaceSpecifier,
  16921. ImportSpecifier,
  16922. JSXAttribute,
  16923. JSXClosingElement,
  16924. JSXClosingFragment,
  16925. JSXElement,
  16926. JSXEmptyExpression,
  16927. JSXExpressionContainer,
  16928. JSXFragment,
  16929. JSXIdentifier,
  16930. JSXMemberExpression,
  16931. JSXNamespacedName,
  16932. JSXOpeningElement,
  16933. JSXOpeningFragment,
  16934. JSXSpreadAttribute,
  16935. JSXSpreadChild,
  16936. JSXText,
  16937. LabeledStatement,
  16938. Literal,
  16939. LogicalExpression,
  16940. MemberExpression,
  16941. MetaProperty,
  16942. MethodDefinition,
  16943. NewExpression,
  16944. ObjectExpression,
  16945. ObjectPattern,
  16946. PanicError,
  16947. ParseError,
  16948. PrivateIdentifier,
  16949. Program,
  16950. Property,
  16951. PropertyDefinition,
  16952. RestElement,
  16953. ReturnStatement,
  16954. SequenceExpression,
  16955. SpreadElement,
  16956. StaticBlock,
  16957. Super,
  16958. SwitchCase,
  16959. SwitchStatement,
  16960. TaggedTemplateExpression,
  16961. TemplateElement,
  16962. TemplateLiteral,
  16963. ThisExpression,
  16964. ThrowStatement,
  16965. TryStatement,
  16966. UnaryExpression,
  16967. UnknownNode,
  16968. UpdateExpression,
  16969. VariableDeclaration,
  16970. VariableDeclarator,
  16971. WhileStatement,
  16972. YieldExpression
  16973. };
  16974. class ExportShimVariable extends Variable {
  16975. constructor(module) {
  16976. super(MISSING_EXPORT_SHIM_VARIABLE);
  16977. this.module = module;
  16978. }
  16979. includePath(path, context) {
  16980. super.includePath(path, context);
  16981. this.module.needsExportShim = true;
  16982. }
  16983. }
  16984. const sourceMapCache = new WeakMap();
  16985. /**
  16986. * This clears the decoded array and falls back to the encoded string form.
  16987. * Sourcemap mappings arrays can be very large and holding on to them for longer
  16988. * than is necessary leads to poor heap utilization.
  16989. */
  16990. function resetCacheToEncoded(cache) {
  16991. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  16992. cache.encodedMappings = encode(cache.decodedMappings);
  16993. }
  16994. cache.decodedMappings = undefined;
  16995. }
  16996. function resetSourcemapCache(map, sourcemapChain) {
  16997. if (map) {
  16998. const cache = sourceMapCache.get(map);
  16999. if (cache) {
  17000. resetCacheToEncoded(cache);
  17001. }
  17002. }
  17003. if (!sourcemapChain) {
  17004. return;
  17005. }
  17006. for (const map of sourcemapChain) {
  17007. if (map.missing)
  17008. continue;
  17009. resetSourcemapCache(map);
  17010. }
  17011. }
  17012. function decodedSourcemap(map) {
  17013. if (!map)
  17014. return null;
  17015. if (typeof map === 'string') {
  17016. map = JSON.parse(map);
  17017. }
  17018. if (!map.mappings) {
  17019. return {
  17020. mappings: [],
  17021. names: [],
  17022. sources: [],
  17023. version: 3
  17024. };
  17025. }
  17026. const originalMappings = map.mappings;
  17027. const isAlreadyDecoded = Array.isArray(originalMappings);
  17028. const cache = {
  17029. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  17030. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  17031. };
  17032. const decodedMap = {
  17033. ...map,
  17034. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  17035. // where the mappings field is never actually accessed. This appears to greatly reduce
  17036. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  17037. get mappings() {
  17038. if (cache.decodedMappings) {
  17039. return cache.decodedMappings;
  17040. }
  17041. // If decodedMappings doesn't exist then encodedMappings should.
  17042. // The only scenario where cache.encodedMappings should be undefined is if the map
  17043. // this was constructed from was already decoded, or if mappings was set to a new
  17044. // decoded string. In either case, this line shouldn't get hit.
  17045. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  17046. cache.encodedMappings = undefined;
  17047. return cache.decodedMappings;
  17048. }
  17049. };
  17050. sourceMapCache.set(decodedMap, cache);
  17051. return decodedMap;
  17052. }
  17053. function getId(m) {
  17054. return m.id;
  17055. }
  17056. function getOriginalLocation(sourcemapChain, location) {
  17057. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  17058. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  17059. const sourcemap = filteredSourcemapChain.pop();
  17060. const line = sourcemap.mappings[location.line - 1];
  17061. if (line) {
  17062. const filteredLine = line.filter((segment) => segment.length > 1);
  17063. const lastSegment = filteredLine[filteredLine.length - 1];
  17064. for (const segment of filteredLine) {
  17065. if (segment[0] >= location.column || segment === lastSegment) {
  17066. location = {
  17067. column: segment[3],
  17068. line: segment[2] + 1
  17069. };
  17070. continue traceSourcemap;
  17071. }
  17072. }
  17073. }
  17074. throw new Error("Can't resolve original location of error.");
  17075. }
  17076. return location;
  17077. }
  17078. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  17079. function getAttributesFromImportExpression(node) {
  17080. const { scope: { context }, options, start } = node;
  17081. if (!(options instanceof ObjectExpression)) {
  17082. if (options) {
  17083. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), start);
  17084. }
  17085. return parseAst_js.EMPTY_OBJECT;
  17086. }
  17087. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  17088. if (!assertProperty) {
  17089. return parseAst_js.EMPTY_OBJECT;
  17090. }
  17091. if (!(assertProperty instanceof ObjectExpression)) {
  17092. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportOptionsAreInvalid(context.module.id), start);
  17093. return parseAst_js.EMPTY_OBJECT;
  17094. }
  17095. const assertFields = assertProperty.properties
  17096. .map(property => {
  17097. const key = getPropertyKey(property);
  17098. if (typeof key === 'string' &&
  17099. typeof property.value.value === 'string') {
  17100. return [key, property.value.value];
  17101. }
  17102. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), property.start);
  17103. return null;
  17104. })
  17105. .filter((property) => !!property);
  17106. if (assertFields.length > 0) {
  17107. return Object.fromEntries(assertFields);
  17108. }
  17109. return parseAst_js.EMPTY_OBJECT;
  17110. }
  17111. const getPropertyKey = (property) => {
  17112. const key = property.key;
  17113. return (key &&
  17114. !property.computed &&
  17115. (key.name || key.value));
  17116. };
  17117. function getAttributesFromImportExportDeclaration(attributes) {
  17118. return attributes?.length
  17119. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  17120. : parseAst_js.EMPTY_OBJECT;
  17121. }
  17122. function doAttributesDiffer(assertionA, assertionB) {
  17123. const keysA = Object.keys(assertionA);
  17124. return (keysA.length !== Object.keys(assertionB).length ||
  17125. keysA.some(key => assertionA[key] !== assertionB[key]));
  17126. }
  17127. let timers = new Map();
  17128. function getPersistedLabel(label, level) {
  17129. switch (level) {
  17130. case 1: {
  17131. return `# ${label}`;
  17132. }
  17133. case 2: {
  17134. return `## ${label}`;
  17135. }
  17136. case 3: {
  17137. return label;
  17138. }
  17139. default: {
  17140. return `- ${label}`;
  17141. }
  17142. }
  17143. }
  17144. function timeStartImpl(label, level = 3) {
  17145. label = getPersistedLabel(label, level);
  17146. const startMemory = process$1.memoryUsage().heapUsed;
  17147. const startTime = node_perf_hooks.performance.now();
  17148. const timer = timers.get(label);
  17149. if (timer === undefined) {
  17150. timers.set(label, {
  17151. memory: 0,
  17152. startMemory,
  17153. startTime,
  17154. time: 0,
  17155. totalMemory: 0
  17156. });
  17157. }
  17158. else {
  17159. timer.startMemory = startMemory;
  17160. timer.startTime = startTime;
  17161. }
  17162. }
  17163. function timeEndImpl(label, level = 3) {
  17164. label = getPersistedLabel(label, level);
  17165. const timer = timers.get(label);
  17166. if (timer !== undefined) {
  17167. const currentMemory = process$1.memoryUsage().heapUsed;
  17168. timer.memory += currentMemory - timer.startMemory;
  17169. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  17170. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  17171. }
  17172. }
  17173. function getTimings() {
  17174. const newTimings = {};
  17175. for (const [label, { memory, time, totalMemory }] of timers) {
  17176. newTimings[label] = [time, memory, totalMemory];
  17177. }
  17178. return newTimings;
  17179. }
  17180. let timeStart = doNothing;
  17181. let timeEnd = doNothing;
  17182. const TIMED_PLUGIN_HOOKS = [
  17183. 'augmentChunkHash',
  17184. 'buildEnd',
  17185. 'buildStart',
  17186. 'generateBundle',
  17187. 'load',
  17188. 'moduleParsed',
  17189. 'options',
  17190. 'outputOptions',
  17191. 'renderChunk',
  17192. 'renderDynamicImport',
  17193. 'renderStart',
  17194. 'resolveDynamicImport',
  17195. 'resolveFileUrl',
  17196. 'resolveId',
  17197. 'resolveImportMeta',
  17198. 'shouldTransformCachedModule',
  17199. 'transform',
  17200. 'writeBundle'
  17201. ];
  17202. function getPluginWithTimers(plugin, index) {
  17203. if (plugin._hasTimer)
  17204. return plugin;
  17205. plugin._hasTimer = true;
  17206. for (const hook of TIMED_PLUGIN_HOOKS) {
  17207. if (hook in plugin) {
  17208. let timerLabel = `plugin ${index}`;
  17209. if (plugin.name) {
  17210. timerLabel += ` (${plugin.name})`;
  17211. }
  17212. timerLabel += ` - ${hook}`;
  17213. const handler = function (...parameters) {
  17214. timeStart(timerLabel, 4);
  17215. const result = hookFunction.apply(this, parameters);
  17216. timeEnd(timerLabel, 4);
  17217. return result;
  17218. };
  17219. let hookFunction;
  17220. if (typeof plugin[hook].handler === 'function') {
  17221. hookFunction = plugin[hook].handler;
  17222. plugin[hook].handler = handler;
  17223. }
  17224. else {
  17225. hookFunction = plugin[hook];
  17226. plugin[hook] = handler;
  17227. }
  17228. }
  17229. }
  17230. return plugin;
  17231. }
  17232. function initialiseTimers(inputOptions) {
  17233. if (inputOptions.perf) {
  17234. timers = new Map();
  17235. timeStart = timeStartImpl;
  17236. timeEnd = timeEndImpl;
  17237. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  17238. }
  17239. else {
  17240. timeStart = doNothing;
  17241. timeEnd = doNothing;
  17242. }
  17243. }
  17244. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  17245. identifier: null,
  17246. localName: MISSING_EXPORT_SHIM_VARIABLE
  17247. };
  17248. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  17249. const searchedModules = searchedNamesAndModules.get(name);
  17250. if (searchedModules) {
  17251. if (searchedModules.has(target)) {
  17252. return isExportAllSearch ? [null] : parseAst_js.error(parseAst_js.logCircularReexport(name, target.id));
  17253. }
  17254. searchedModules.add(target);
  17255. }
  17256. else {
  17257. searchedNamesAndModules.set(name, new Set([target]));
  17258. }
  17259. return target.getVariableForExportName(name, {
  17260. importerForSideEffects,
  17261. isExportAllSearch,
  17262. searchedNamesAndModules
  17263. });
  17264. }
  17265. function getAndExtendSideEffectModules(variable, module) {
  17266. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  17267. let currentVariable = variable;
  17268. const referencedVariables = new Set([currentVariable]);
  17269. while (true) {
  17270. const importingModule = currentVariable.module;
  17271. currentVariable =
  17272. currentVariable instanceof ExportDefaultVariable
  17273. ? currentVariable.getDirectOriginalVariable()
  17274. : currentVariable instanceof SyntheticNamedExportVariable
  17275. ? currentVariable.syntheticNamespace
  17276. : null;
  17277. if (!currentVariable || referencedVariables.has(currentVariable)) {
  17278. break;
  17279. }
  17280. referencedVariables.add(currentVariable);
  17281. sideEffectModules.add(importingModule);
  17282. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  17283. if (originalSideEffects) {
  17284. for (const module of originalSideEffects) {
  17285. sideEffectModules.add(module);
  17286. }
  17287. }
  17288. }
  17289. return sideEffectModules;
  17290. }
  17291. class Module {
  17292. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  17293. this.graph = graph;
  17294. this.id = id;
  17295. this.options = options;
  17296. this.alternativeReexportModules = new Map();
  17297. this.chunkFileNames = new Set();
  17298. this.chunkNames = [];
  17299. this.cycles = new Set();
  17300. this.dependencies = new Set();
  17301. this.dynamicDependencies = new Set();
  17302. this.dynamicImporters = [];
  17303. this.dynamicImports = [];
  17304. this.execIndex = Infinity;
  17305. this.hasTreeShakingPassStarted = false;
  17306. this.implicitlyLoadedAfter = new Set();
  17307. this.implicitlyLoadedBefore = new Set();
  17308. this.importDescriptions = new Map();
  17309. this.importMetas = [];
  17310. this.importedFromNotTreeshaken = false;
  17311. this.importers = [];
  17312. this.includedDynamicImporters = [];
  17313. this.includedDirectTopLevelAwaitingDynamicImporters = new Set();
  17314. this.includedImports = new Set();
  17315. this.isExecuted = false;
  17316. this.isUserDefinedEntryPoint = false;
  17317. this.needsExportShim = false;
  17318. this.sideEffectDependenciesByVariable = new Map();
  17319. this.sourcesWithAttributes = new Map();
  17320. this.allExportNames = null;
  17321. this.allExportsIncluded = false;
  17322. this.ast = null;
  17323. this.exportAllModules = [];
  17324. this.exportAllSources = new Set();
  17325. this.exportNamesByVariable = null;
  17326. this.exportShimVariable = new ExportShimVariable(this);
  17327. this.exports = new Map();
  17328. this.namespaceReexportsByName = new Map();
  17329. this.reexportDescriptions = new Map();
  17330. this.relevantDependencies = null;
  17331. this.syntheticExports = new Map();
  17332. this.syntheticNamespace = null;
  17333. this.transformDependencies = [];
  17334. this.transitiveReexports = null;
  17335. this.excludeFromSourcemap = /\0/.test(id);
  17336. this.context = options.moduleContext(id);
  17337. this.preserveSignature = this.options.preserveEntrySignatures;
  17338. // eslint-disable-next-line @typescript-eslint/no-this-alias
  17339. const module = this;
  17340. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  17341. this.info = {
  17342. ast: null,
  17343. attributes,
  17344. code: null,
  17345. get dynamicallyImportedIdResolutions() {
  17346. return dynamicImports
  17347. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  17348. .filter(Boolean);
  17349. },
  17350. get dynamicallyImportedIds() {
  17351. // We cannot use this.dynamicDependencies because this is needed before
  17352. // dynamicDependencies are populated
  17353. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  17354. },
  17355. get dynamicImporters() {
  17356. return dynamicImporters.sort();
  17357. },
  17358. get exportedBindings() {
  17359. const exportBindings = { '.': [...exports.keys()] };
  17360. for (const [name, { source }] of reexportDescriptions) {
  17361. (exportBindings[source] ??= []).push(name);
  17362. }
  17363. for (const source of exportAllSources) {
  17364. (exportBindings[source] ??= []).push('*');
  17365. }
  17366. return exportBindings;
  17367. },
  17368. get exports() {
  17369. return [
  17370. ...exports.keys(),
  17371. ...reexportDescriptions.keys(),
  17372. ...[...exportAllSources].map(() => '*')
  17373. ];
  17374. },
  17375. get hasDefaultExport() {
  17376. // This information is only valid after parsing
  17377. if (!module.ast) {
  17378. return null;
  17379. }
  17380. return module.exports.has('default') || reexportDescriptions.has('default');
  17381. },
  17382. id,
  17383. get implicitlyLoadedAfterOneOf() {
  17384. return Array.from(implicitlyLoadedAfter, getId).sort();
  17385. },
  17386. get implicitlyLoadedBefore() {
  17387. return Array.from(implicitlyLoadedBefore, getId).sort();
  17388. },
  17389. get importedIdResolutions() {
  17390. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  17391. },
  17392. get importedIds() {
  17393. // We cannot use this.dependencies because this is needed before
  17394. // dependencies are populated
  17395. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  17396. },
  17397. get importers() {
  17398. return importers.sort();
  17399. },
  17400. isEntry,
  17401. isExternal: false,
  17402. get isIncluded() {
  17403. if (graph.phase !== BuildPhase.GENERATE) {
  17404. return null;
  17405. }
  17406. return module.isIncluded();
  17407. },
  17408. meta: { ...meta },
  17409. moduleSideEffects,
  17410. syntheticNamedExports
  17411. };
  17412. }
  17413. basename() {
  17414. const base = path.basename(this.id);
  17415. const extension = path.extname(this.id);
  17416. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  17417. }
  17418. bindReferences() {
  17419. this.ast.bind();
  17420. }
  17421. cacheInfoGetters() {
  17422. cacheObjectGetters(this.info, [
  17423. 'dynamicallyImportedIdResolutions',
  17424. 'dynamicallyImportedIds',
  17425. 'dynamicImporters',
  17426. 'exportedBindings',
  17427. 'exports',
  17428. 'hasDefaultExport',
  17429. 'implicitlyLoadedAfterOneOf',
  17430. 'implicitlyLoadedBefore',
  17431. 'importedIdResolutions',
  17432. 'importedIds',
  17433. 'importers'
  17434. ]);
  17435. }
  17436. error(properties, pos) {
  17437. if (pos !== undefined) {
  17438. this.addLocationToLogProps(properties, pos);
  17439. }
  17440. return parseAst_js.error(properties);
  17441. }
  17442. // sum up the length of all ast nodes that are included
  17443. estimateSize() {
  17444. let size = 0;
  17445. for (const node of this.ast.body) {
  17446. if (node.included) {
  17447. size += node.end - node.start;
  17448. }
  17449. }
  17450. return size;
  17451. }
  17452. getAllExportNames() {
  17453. if (this.allExportNames) {
  17454. return this.allExportNames;
  17455. }
  17456. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  17457. for (const module of this.exportAllModules) {
  17458. if (module instanceof ExternalModule) {
  17459. this.allExportNames.add(`*${module.id}`);
  17460. continue;
  17461. }
  17462. for (const name of module.getAllExportNames()) {
  17463. if (name !== 'default')
  17464. this.allExportNames.add(name);
  17465. }
  17466. }
  17467. // We do not count the synthetic namespace as a regular export to hide it
  17468. // from entry signatures and namespace objects
  17469. if (typeof this.info.syntheticNamedExports === 'string') {
  17470. this.allExportNames.delete(this.info.syntheticNamedExports);
  17471. }
  17472. return this.allExportNames;
  17473. }
  17474. getDependenciesToBeIncluded() {
  17475. if (this.relevantDependencies)
  17476. return this.relevantDependencies;
  17477. this.relevantDependencies = new Set();
  17478. const necessaryDependencies = new Set();
  17479. const alwaysCheckedDependencies = new Set();
  17480. const dependencyVariables = new Set(this.includedImports);
  17481. if (this.info.isEntry ||
  17482. this.includedDynamicImporters.length > 0 ||
  17483. this.namespace.included ||
  17484. this.implicitlyLoadedAfter.size > 0) {
  17485. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  17486. const [exportedVariable] = this.getVariableForExportName(exportName);
  17487. if (exportedVariable?.included) {
  17488. dependencyVariables.add(exportedVariable);
  17489. }
  17490. }
  17491. }
  17492. for (let variable of dependencyVariables) {
  17493. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  17494. if (sideEffectDependencies) {
  17495. for (const module of sideEffectDependencies) {
  17496. alwaysCheckedDependencies.add(module);
  17497. }
  17498. }
  17499. if (variable instanceof SyntheticNamedExportVariable) {
  17500. variable = variable.getBaseVariable();
  17501. }
  17502. else if (variable instanceof ExportDefaultVariable) {
  17503. variable = variable.getOriginalVariable();
  17504. }
  17505. necessaryDependencies.add(variable.module);
  17506. }
  17507. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  17508. for (const dependency of this.dependencies) {
  17509. this.relevantDependencies.add(dependency);
  17510. }
  17511. }
  17512. else {
  17513. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  17514. }
  17515. for (const dependency of necessaryDependencies) {
  17516. this.relevantDependencies.add(dependency);
  17517. }
  17518. return this.relevantDependencies;
  17519. }
  17520. getExportNamesByVariable() {
  17521. if (this.exportNamesByVariable) {
  17522. return this.exportNamesByVariable;
  17523. }
  17524. const exportNamesByVariable = new Map();
  17525. for (const exportName of this.getAllExportNames()) {
  17526. let [tracedVariable] = this.getVariableForExportName(exportName);
  17527. if (tracedVariable instanceof ExportDefaultVariable) {
  17528. tracedVariable = tracedVariable.getOriginalVariable();
  17529. }
  17530. if (!tracedVariable ||
  17531. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  17532. continue;
  17533. }
  17534. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  17535. if (existingExportNames) {
  17536. existingExportNames.push(exportName);
  17537. }
  17538. else {
  17539. exportNamesByVariable.set(tracedVariable, [exportName]);
  17540. }
  17541. }
  17542. return (this.exportNamesByVariable = exportNamesByVariable);
  17543. }
  17544. getExports() {
  17545. return [...this.exports.keys()];
  17546. }
  17547. getReexports() {
  17548. if (this.transitiveReexports) {
  17549. return this.transitiveReexports;
  17550. }
  17551. // to avoid infinite recursion when using circular `export * from X`
  17552. this.transitiveReexports = [];
  17553. const reexports = new Set(this.reexportDescriptions.keys());
  17554. for (const module of this.exportAllModules) {
  17555. if (module instanceof ExternalModule) {
  17556. reexports.add(`*${module.id}`);
  17557. }
  17558. else {
  17559. for (const name of [...module.getReexports(), ...module.getExports()]) {
  17560. if (name !== 'default')
  17561. reexports.add(name);
  17562. }
  17563. }
  17564. }
  17565. return (this.transitiveReexports = [...reexports]);
  17566. }
  17567. getRenderedExports() {
  17568. // only direct exports are counted here, not reexports at all
  17569. const renderedExports = [];
  17570. const removedExports = [];
  17571. for (const exportName of this.exports.keys()) {
  17572. const [variable] = this.getVariableForExportName(exportName);
  17573. (variable?.included ? renderedExports : removedExports).push(exportName);
  17574. }
  17575. return { removedExports, renderedExports };
  17576. }
  17577. getSyntheticNamespace() {
  17578. if (this.syntheticNamespace === null) {
  17579. this.syntheticNamespace = undefined;
  17580. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  17581. ? this.info.syntheticNamedExports
  17582. : 'default', { onlyExplicit: true });
  17583. }
  17584. if (!this.syntheticNamespace) {
  17585. return parseAst_js.error(parseAst_js.logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  17586. }
  17587. return this.syntheticNamespace;
  17588. }
  17589. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  17590. if (name[0] === '*') {
  17591. if (name.length === 1) {
  17592. // export * from './other'
  17593. return [this.namespace];
  17594. }
  17595. // export * from 'external'
  17596. const module = this.graph.modulesById.get(name.slice(1));
  17597. return module.getVariableForExportName('*');
  17598. }
  17599. // export { foo } from './other'
  17600. const reexportDeclaration = this.reexportDescriptions.get(name);
  17601. if (reexportDeclaration) {
  17602. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  17603. if (!variable) {
  17604. return this.error(parseAst_js.logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  17605. }
  17606. if (importerForSideEffects) {
  17607. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17608. if (this.info.moduleSideEffects) {
  17609. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17610. }
  17611. }
  17612. return [variable];
  17613. }
  17614. const exportDeclaration = this.exports.get(name);
  17615. if (exportDeclaration) {
  17616. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  17617. return [this.exportShimVariable];
  17618. }
  17619. const name = exportDeclaration.localName;
  17620. const variable = this.traceVariable(name, {
  17621. importerForSideEffects,
  17622. searchedNamesAndModules
  17623. });
  17624. if (importerForSideEffects) {
  17625. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17626. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17627. }
  17628. return [variable];
  17629. }
  17630. if (onlyExplicit) {
  17631. return [null];
  17632. }
  17633. if (name !== 'default') {
  17634. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  17635. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  17636. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  17637. if (foundNamespaceReexport[0]) {
  17638. return foundNamespaceReexport;
  17639. }
  17640. }
  17641. if (this.info.syntheticNamedExports) {
  17642. return [
  17643. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  17644. ];
  17645. }
  17646. // we don't want to create shims when we are just
  17647. // probing export * modules for exports
  17648. if (!isExportAllSearch && this.options.shimMissingExports) {
  17649. this.shimMissingExport(name);
  17650. return [this.exportShimVariable];
  17651. }
  17652. return [null];
  17653. }
  17654. hasEffects() {
  17655. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  17656. }
  17657. include() {
  17658. const context = createInclusionContext();
  17659. if (this.ast.shouldBeIncluded(context))
  17660. this.ast.include(context, false);
  17661. }
  17662. includeAllExports(includeNamespaceMembers) {
  17663. if (includeNamespaceMembers) {
  17664. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17665. }
  17666. if (this.allExportsIncluded)
  17667. return;
  17668. this.allExportsIncluded = true;
  17669. if (!this.isExecuted) {
  17670. markModuleAndImpureDependenciesAsExecuted(this);
  17671. this.graph.needsTreeshakingPass = true;
  17672. }
  17673. const inclusionContext = createInclusionContext();
  17674. for (const exportName of this.exports.keys()) {
  17675. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  17676. const variable = this.getVariableForExportName(exportName)[0];
  17677. if (!variable) {
  17678. return parseAst_js.error(parseAst_js.logMissingEntryExport(exportName, this.id));
  17679. }
  17680. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17681. variable.deoptimizePath(UNKNOWN_PATH);
  17682. }
  17683. }
  17684. for (const name of this.getReexports()) {
  17685. const [variable] = this.getVariableForExportName(name);
  17686. if (variable) {
  17687. variable.deoptimizePath(UNKNOWN_PATH);
  17688. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17689. if (variable instanceof ExternalVariable) {
  17690. variable.module.reexported = true;
  17691. }
  17692. }
  17693. }
  17694. }
  17695. includeAllInBundle() {
  17696. this.ast.include(createInclusionContext(), true);
  17697. this.includeAllExports(false);
  17698. }
  17699. includeExportsByNames(names) {
  17700. if (!this.isExecuted) {
  17701. markModuleAndImpureDependenciesAsExecuted(this);
  17702. this.graph.needsTreeshakingPass = true;
  17703. }
  17704. let includeNamespaceMembers = false;
  17705. const inclusionContext = createInclusionContext();
  17706. for (const name of names) {
  17707. const variable = this.getVariableForExportName(name)[0];
  17708. if (variable) {
  17709. variable.deoptimizePath(UNKNOWN_PATH);
  17710. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17711. }
  17712. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  17713. includeNamespaceMembers = true;
  17714. }
  17715. }
  17716. if (includeNamespaceMembers) {
  17717. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17718. }
  17719. }
  17720. isIncluded() {
  17721. // Modules where this.ast is missing have been loaded via this.load and are
  17722. // not yet fully processed, hence they cannot be included.
  17723. return (this.ast &&
  17724. (this.ast.included ||
  17725. this.namespace.included ||
  17726. this.importedFromNotTreeshaken ||
  17727. this.exportShimVariable.included));
  17728. }
  17729. linkImports() {
  17730. this.addModulesToImportDescriptions(this.importDescriptions);
  17731. this.addModulesToImportDescriptions(this.reexportDescriptions);
  17732. const externalExportAllModules = [];
  17733. for (const source of this.exportAllSources) {
  17734. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  17735. if (module instanceof ExternalModule) {
  17736. externalExportAllModules.push(module);
  17737. continue;
  17738. }
  17739. this.exportAllModules.push(module);
  17740. }
  17741. this.exportAllModules.push(...externalExportAllModules);
  17742. }
  17743. log(level, properties, pos) {
  17744. this.addLocationToLogProps(properties, pos);
  17745. this.options.onLog(level, properties);
  17746. }
  17747. render(options) {
  17748. const source = this.magicString.clone();
  17749. this.ast.render(source, options);
  17750. source.trim();
  17751. const { usesTopLevelAwait } = this.astContext;
  17752. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  17753. return parseAst_js.error(parseAst_js.logInvalidFormatForTopLevelAwait(this.id, options.format));
  17754. }
  17755. return { source, usesTopLevelAwait };
  17756. }
  17757. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  17758. timeStart('generate ast', 3);
  17759. if (code.startsWith('#!')) {
  17760. const shebangEndPosition = code.indexOf('\n');
  17761. this.shebang = code.slice(2, shebangEndPosition);
  17762. }
  17763. this.info.code = code;
  17764. this.originalCode = originalCode;
  17765. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  17766. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  17767. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  17768. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  17769. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  17770. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  17771. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  17772. if (transformFiles) {
  17773. this.transformFiles = transformFiles;
  17774. }
  17775. this.transformDependencies = transformDependencies;
  17776. this.customTransformCache = customTransformCache;
  17777. this.updateOptions(moduleOptions);
  17778. this.resolvedIds = resolvedIds ?? Object.create(null);
  17779. // By default, `id` is the file name. Custom resolvers and loaders
  17780. // can change that, but it makes sense to use it for the source file name
  17781. const fileName = this.id;
  17782. this.magicString = new MagicString(code, {
  17783. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  17784. indentExclusionRanges: []
  17785. });
  17786. this.astContext = {
  17787. addDynamicImport: this.addDynamicImport.bind(this),
  17788. addExport: this.addExport.bind(this),
  17789. addImport: this.addImport.bind(this),
  17790. addImportMeta: this.addImportMeta.bind(this),
  17791. addImportSource: this.addImportSource.bind(this),
  17792. code, // Only needed for debugging
  17793. deoptimizationTracker: this.graph.deoptimizationTracker,
  17794. error: this.error.bind(this),
  17795. fileName, // Needed for warnings
  17796. getExports: this.getExports.bind(this),
  17797. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  17798. getModuleExecIndex: () => this.execIndex,
  17799. getModuleName: this.basename.bind(this),
  17800. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  17801. getReexports: this.getReexports.bind(this),
  17802. importDescriptions: this.importDescriptions,
  17803. includeAllExports: () => this.includeAllExports(true),
  17804. includeDynamicImport: this.includeDynamicImport.bind(this),
  17805. includeVariableInModule: this.includeVariableInModule.bind(this),
  17806. log: this.log.bind(this),
  17807. magicString: this.magicString,
  17808. manualPureFunctions: this.graph.pureFunctions,
  17809. module: this,
  17810. moduleContext: this.context,
  17811. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  17812. options: this.options,
  17813. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  17814. traceExport: (name) => this.getVariableForExportName(name)[0],
  17815. traceVariable: this.traceVariable.bind(this),
  17816. usesTopLevelAwait: false
  17817. };
  17818. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  17819. this.namespace = new NamespaceVariable(this.astContext);
  17820. const programParent = { context: this.astContext, type: 'Module' };
  17821. if (ast) {
  17822. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  17823. this.info.ast = ast;
  17824. }
  17825. else {
  17826. // Measuring asynchronous code does not provide reasonable results
  17827. timeEnd('generate ast', 3);
  17828. const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
  17829. timeStart('generate ast', 3);
  17830. this.ast = convertProgram(astBuffer, programParent, this.scope);
  17831. // Make lazy and apply LRU cache to not hog the memory
  17832. Object.defineProperty(this.info, 'ast', {
  17833. get: () => {
  17834. if (this.graph.astLru.has(fileName)) {
  17835. return this.graph.astLru.get(fileName);
  17836. }
  17837. else {
  17838. const parsedAst = this.tryParse();
  17839. // If the cache is not disabled, we need to keep the AST in memory
  17840. // until the end when the cache is generated
  17841. if (this.options.cache !== false) {
  17842. Object.defineProperty(this.info, 'ast', {
  17843. value: parsedAst
  17844. });
  17845. return parsedAst;
  17846. }
  17847. // Otherwise, we keep it in a small LRU cache to not hog too much
  17848. // memory but allow the same AST to be requested several times.
  17849. this.graph.astLru.set(fileName, parsedAst);
  17850. return parsedAst;
  17851. }
  17852. }
  17853. });
  17854. }
  17855. timeEnd('generate ast', 3);
  17856. }
  17857. toJSON() {
  17858. return {
  17859. ast: this.info.ast,
  17860. attributes: this.info.attributes,
  17861. code: this.info.code,
  17862. customTransformCache: this.customTransformCache,
  17863. dependencies: Array.from(this.dependencies, getId),
  17864. id: this.id,
  17865. meta: this.info.meta,
  17866. moduleSideEffects: this.info.moduleSideEffects,
  17867. originalCode: this.originalCode,
  17868. originalSourcemap: this.originalSourcemap,
  17869. resolvedIds: this.resolvedIds,
  17870. sourcemapChain: this.sourcemapChain,
  17871. syntheticNamedExports: this.info.syntheticNamedExports,
  17872. transformDependencies: this.transformDependencies,
  17873. transformFiles: this.transformFiles
  17874. };
  17875. }
  17876. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  17877. const localVariable = this.scope.variables.get(name);
  17878. if (localVariable) {
  17879. return localVariable;
  17880. }
  17881. const importDescription = this.importDescriptions.get(name);
  17882. if (importDescription) {
  17883. const otherModule = importDescription.module;
  17884. if (otherModule instanceof Module && importDescription.name === '*') {
  17885. return otherModule.namespace;
  17886. }
  17887. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  17888. if (!declaration) {
  17889. return this.error(parseAst_js.logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  17890. }
  17891. return declaration;
  17892. }
  17893. return null;
  17894. }
  17895. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  17896. if (moduleSideEffects != null) {
  17897. this.info.moduleSideEffects = moduleSideEffects;
  17898. }
  17899. if (syntheticNamedExports != null) {
  17900. this.info.syntheticNamedExports = syntheticNamedExports;
  17901. }
  17902. if (meta != null) {
  17903. Object.assign(this.info.meta, meta);
  17904. }
  17905. }
  17906. addDynamicImport(node) {
  17907. let argument = node.sourceAstNode;
  17908. if (argument.type === parseAst_js.TemplateLiteral) {
  17909. if (argument.quasis.length === 1 &&
  17910. typeof argument.quasis[0].value.cooked === 'string') {
  17911. argument = argument.quasis[0].value.cooked;
  17912. }
  17913. }
  17914. else if (argument.type === parseAst_js.Literal &&
  17915. typeof argument.value === 'string') {
  17916. argument = argument.value;
  17917. }
  17918. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  17919. }
  17920. assertUniqueExportName(name, nodeStart) {
  17921. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  17922. this.error(parseAst_js.logDuplicateExportError(name), nodeStart);
  17923. }
  17924. }
  17925. addExport(node) {
  17926. if (node instanceof ExportDefaultDeclaration) {
  17927. // export default foo;
  17928. this.assertUniqueExportName('default', node.start);
  17929. this.exports.set('default', {
  17930. identifier: node.variable.getAssignedVariableName(),
  17931. localName: 'default'
  17932. });
  17933. }
  17934. else if (node instanceof ExportAllDeclaration) {
  17935. const source = node.source.value;
  17936. this.addSource(source, node);
  17937. if (node.exported) {
  17938. // export * as name from './other'
  17939. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  17940. this.assertUniqueExportName(name, node.exported.start);
  17941. this.reexportDescriptions.set(name, {
  17942. localName: '*',
  17943. module: null, // filled in later,
  17944. source,
  17945. start: node.start
  17946. });
  17947. }
  17948. else {
  17949. // export * from './other'
  17950. this.exportAllSources.add(source);
  17951. }
  17952. }
  17953. else if (node.source instanceof Literal) {
  17954. // export { name } from './other'
  17955. const source = node.source.value;
  17956. this.addSource(source, node);
  17957. for (const { exported, local, start } of node.specifiers) {
  17958. const name = exported instanceof Literal ? exported.value : exported.name;
  17959. this.assertUniqueExportName(name, start);
  17960. this.reexportDescriptions.set(name, {
  17961. localName: local instanceof Literal ? local.value : local.name,
  17962. module: null, // filled in later,
  17963. source,
  17964. start
  17965. });
  17966. }
  17967. }
  17968. else if (node.declaration) {
  17969. const declaration = node.declaration;
  17970. if (declaration instanceof VariableDeclaration) {
  17971. // export var { foo, bar } = ...
  17972. // export var foo = 1, bar = 2;
  17973. for (const declarator of declaration.declarations) {
  17974. for (const localName of extractAssignedNames(declarator.id)) {
  17975. this.assertUniqueExportName(localName, declarator.id.start);
  17976. this.exports.set(localName, { identifier: null, localName });
  17977. }
  17978. }
  17979. }
  17980. else {
  17981. // export function foo () {}
  17982. const localName = declaration.id.name;
  17983. this.assertUniqueExportName(localName, declaration.id.start);
  17984. this.exports.set(localName, { identifier: null, localName });
  17985. }
  17986. }
  17987. else {
  17988. // export { foo, bar, baz }
  17989. for (const { local, exported } of node.specifiers) {
  17990. // except for reexports, local must be an Identifier
  17991. const localName = local.name;
  17992. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  17993. this.assertUniqueExportName(exportedName, exported.start);
  17994. this.exports.set(exportedName, { identifier: null, localName });
  17995. }
  17996. }
  17997. }
  17998. addImport(node) {
  17999. const source = node.source.value;
  18000. this.addSource(source, node);
  18001. for (const specifier of node.specifiers) {
  18002. const localName = specifier.local.name;
  18003. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  18004. this.error(parseAst_js.logRedeclarationError(localName), specifier.local.start);
  18005. }
  18006. const name = specifier instanceof ImportDefaultSpecifier
  18007. ? 'default'
  18008. : specifier instanceof ImportNamespaceSpecifier
  18009. ? '*'
  18010. : specifier.imported instanceof Identifier
  18011. ? specifier.imported.name
  18012. : specifier.imported.value;
  18013. this.importDescriptions.set(localName, {
  18014. module: null, // filled in later
  18015. name,
  18016. source,
  18017. start: specifier.start
  18018. });
  18019. }
  18020. }
  18021. addImportSource(importSource) {
  18022. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  18023. this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
  18024. }
  18025. }
  18026. addImportMeta(node) {
  18027. this.importMetas.push(node);
  18028. }
  18029. addLocationToLogProps(properties, pos) {
  18030. properties.id = this.id;
  18031. properties.pos = pos;
  18032. let code = this.info.code;
  18033. const location = parseAst_js.locate(code, pos, { offsetLine: 1 });
  18034. if (location) {
  18035. let { column, line } = location;
  18036. try {
  18037. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  18038. code = this.originalCode;
  18039. }
  18040. catch (error_) {
  18041. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidSourcemapForError(error_, this.id, column, line, pos));
  18042. }
  18043. parseAst_js.augmentCodeLocation(properties, { column, line }, code, this.id);
  18044. }
  18045. }
  18046. addModulesToImportDescriptions(importDescription) {
  18047. for (const specifier of importDescription.values()) {
  18048. const { id } = this.resolvedIds[specifier.source];
  18049. specifier.module = this.graph.modulesById.get(id);
  18050. }
  18051. }
  18052. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  18053. const handledDependencies = new Set();
  18054. const addSideEffectDependencies = (possibleDependencies) => {
  18055. for (const dependency of possibleDependencies) {
  18056. if (handledDependencies.has(dependency)) {
  18057. continue;
  18058. }
  18059. handledDependencies.add(dependency);
  18060. if (necessaryDependencies.has(dependency)) {
  18061. relevantDependencies.add(dependency);
  18062. continue;
  18063. }
  18064. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  18065. continue;
  18066. }
  18067. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  18068. relevantDependencies.add(dependency);
  18069. continue;
  18070. }
  18071. addSideEffectDependencies(dependency.dependencies);
  18072. }
  18073. };
  18074. addSideEffectDependencies(this.dependencies);
  18075. addSideEffectDependencies(alwaysCheckedDependencies);
  18076. }
  18077. addSource(source, declaration) {
  18078. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  18079. const existingAttributes = this.sourcesWithAttributes.get(source);
  18080. if (existingAttributes) {
  18081. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  18082. this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  18083. }
  18084. }
  18085. else {
  18086. this.sourcesWithAttributes.set(source, parsedAttributes);
  18087. }
  18088. }
  18089. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  18090. const { id } = this.resolvedIds[importSource];
  18091. const module = this.graph.modulesById.get(id);
  18092. const [variable] = module.getVariableForExportName(baseName);
  18093. if (!variable) {
  18094. return this.error(parseAst_js.logMissingJsxExport(baseName, id, this.id), nodeStart);
  18095. }
  18096. return variable;
  18097. }
  18098. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  18099. let foundSyntheticDeclaration = null;
  18100. const foundInternalDeclarations = new Map();
  18101. const foundExternalDeclarations = new Set();
  18102. for (const module of this.exportAllModules) {
  18103. // Synthetic namespaces should not hide "regular" exports of the same name
  18104. if (module.info.syntheticNamedExports === name) {
  18105. continue;
  18106. }
  18107. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  18108. // We are creating a copy to handle the case where the same binding is
  18109. // imported through different namespace reexports gracefully
  18110. copyNameToModulesMap(searchedNamesAndModules));
  18111. if (module instanceof ExternalModule || indirectExternal) {
  18112. foundExternalDeclarations.add(variable);
  18113. }
  18114. else if (variable instanceof SyntheticNamedExportVariable) {
  18115. if (!foundSyntheticDeclaration) {
  18116. foundSyntheticDeclaration = variable;
  18117. }
  18118. }
  18119. else if (variable) {
  18120. foundInternalDeclarations.set(variable, module);
  18121. }
  18122. }
  18123. if (foundInternalDeclarations.size > 0) {
  18124. const foundDeclarationList = [...foundInternalDeclarations];
  18125. const usedDeclaration = foundDeclarationList[0][0];
  18126. if (foundDeclarationList.length === 1) {
  18127. return [usedDeclaration];
  18128. }
  18129. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  18130. // TODO we are pretending it was not found while it should behave like "undefined"
  18131. return [null];
  18132. }
  18133. if (foundExternalDeclarations.size > 0) {
  18134. const foundDeclarationList = [...foundExternalDeclarations];
  18135. const usedDeclaration = foundDeclarationList[0];
  18136. if (foundDeclarationList.length > 1) {
  18137. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  18138. }
  18139. return [usedDeclaration, true];
  18140. }
  18141. if (foundSyntheticDeclaration) {
  18142. return [foundSyntheticDeclaration];
  18143. }
  18144. return [null];
  18145. }
  18146. includeAndGetAdditionalMergedNamespaces() {
  18147. const externalNamespaces = new Set();
  18148. const syntheticNamespaces = new Set();
  18149. for (const module of [this, ...this.exportAllModules]) {
  18150. if (module instanceof ExternalModule) {
  18151. const [externalVariable] = module.getVariableForExportName('*');
  18152. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  18153. this.includedImports.add(externalVariable);
  18154. externalNamespaces.add(externalVariable);
  18155. }
  18156. else if (module.info.syntheticNamedExports) {
  18157. const syntheticNamespace = module.getSyntheticNamespace();
  18158. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  18159. this.includedImports.add(syntheticNamespace);
  18160. syntheticNamespaces.add(syntheticNamespace);
  18161. }
  18162. }
  18163. return [...syntheticNamespaces, ...externalNamespaces];
  18164. }
  18165. includeDynamicImport(node) {
  18166. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  18167. if (resolution instanceof Module) {
  18168. if (!resolution.includedDynamicImporters.includes(this)) {
  18169. resolution.includedDynamicImporters.push(this);
  18170. if (node.withinTopLevelAwait) {
  18171. resolution.includedDirectTopLevelAwaitingDynamicImporters.add(this);
  18172. }
  18173. }
  18174. const importedNames = this.options.treeshake
  18175. ? node.getDeterministicImportedNames()
  18176. : undefined;
  18177. if (importedNames) {
  18178. resolution.includeExportsByNames(importedNames);
  18179. }
  18180. else {
  18181. resolution.includeAllExports(true);
  18182. }
  18183. }
  18184. }
  18185. includeVariable(variable, path, context) {
  18186. const { included, module: variableModule } = variable;
  18187. variable.includePath(path, context);
  18188. if (included) {
  18189. if (variableModule instanceof Module && variableModule !== this) {
  18190. getAndExtendSideEffectModules(variable, this);
  18191. }
  18192. }
  18193. else {
  18194. this.graph.needsTreeshakingPass = true;
  18195. if (variableModule instanceof Module) {
  18196. if (!variableModule.isExecuted) {
  18197. markModuleAndImpureDependenciesAsExecuted(variableModule);
  18198. }
  18199. if (variableModule !== this) {
  18200. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  18201. for (const module of sideEffectModules) {
  18202. if (!module.isExecuted) {
  18203. markModuleAndImpureDependenciesAsExecuted(module);
  18204. }
  18205. }
  18206. }
  18207. }
  18208. }
  18209. }
  18210. includeVariableInModule(variable, path, context) {
  18211. this.includeVariable(variable, path, context);
  18212. const variableModule = variable.module;
  18213. if (variableModule && variableModule !== this) {
  18214. this.includedImports.add(variable);
  18215. }
  18216. }
  18217. shimMissingExport(name) {
  18218. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
  18219. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  18220. }
  18221. tryParse() {
  18222. try {
  18223. return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
  18224. }
  18225. catch (error_) {
  18226. return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
  18227. }
  18228. }
  18229. }
  18230. // if there is a cyclic import in the reexport chain, we should not
  18231. // import from the original module but from the cyclic module to not
  18232. // mess up execution order.
  18233. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  18234. if (variable.module instanceof Module && variable.module !== reexporter) {
  18235. const exporterCycles = variable.module.cycles;
  18236. if (exporterCycles.size > 0) {
  18237. const importerCycles = reexporter.cycles;
  18238. for (const cycleSymbol of importerCycles) {
  18239. if (exporterCycles.has(cycleSymbol)) {
  18240. importer.alternativeReexportModules.set(variable, reexporter);
  18241. break;
  18242. }
  18243. }
  18244. }
  18245. }
  18246. }
  18247. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  18248. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  18249. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  18250. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  18251. async function createAddons(options, outputPluginDriver, chunk) {
  18252. try {
  18253. let [banner, footer, intro, outro] = await Promise.all([
  18254. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  18255. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  18256. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  18257. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  18258. ]);
  18259. if (intro)
  18260. intro += '\n\n';
  18261. if (outro)
  18262. outro = `\n\n${outro}`;
  18263. if (banner)
  18264. banner += '\n';
  18265. if (footer)
  18266. footer = '\n' + footer;
  18267. return { banner, footer, intro, outro };
  18268. }
  18269. catch (error_) {
  18270. return parseAst_js.error(parseAst_js.logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  18271. }
  18272. }
  18273. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  18274. amd: deconflictImportsOther,
  18275. cjs: deconflictImportsOther,
  18276. es: deconflictImportsEsmOrSystem,
  18277. iife: deconflictImportsOther,
  18278. system: deconflictImportsEsmOrSystem,
  18279. umd: deconflictImportsOther
  18280. };
  18281. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  18282. const reversedModules = [...modules].reverse();
  18283. for (const module of reversedModules) {
  18284. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  18285. }
  18286. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  18287. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  18288. for (const module of reversedModules) {
  18289. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  18290. }
  18291. }
  18292. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  18293. // This is needed for namespace reexports
  18294. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  18295. if (preserveModules || dependency instanceof ExternalChunk) {
  18296. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  18297. }
  18298. }
  18299. for (const variable of imports) {
  18300. const module = variable.module;
  18301. const name = variable.name;
  18302. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  18303. variable.setRenderNames(null, (module instanceof ExternalModule
  18304. ? externalChunkByModule.get(module)
  18305. : chunkByModule.get(module)).variableName);
  18306. }
  18307. else if (module instanceof ExternalModule && name === 'default') {
  18308. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  18309. ? module.suggestedVariableName + '__default'
  18310. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  18311. }
  18312. else {
  18313. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  18314. }
  18315. }
  18316. for (const variable of syntheticExports) {
  18317. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18318. }
  18319. }
  18320. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  18321. for (const chunk of dependencies) {
  18322. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  18323. }
  18324. for (const chunk of deconflictedNamespace) {
  18325. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  18326. }
  18327. for (const externalModule of deconflictedDefault) {
  18328. externalModule.defaultVariableName =
  18329. deconflictedNamespace.has(externalModule) &&
  18330. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  18331. ? externalModule.namespaceVariableName
  18332. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  18333. }
  18334. for (const variable of imports) {
  18335. const module = variable.module;
  18336. if (module instanceof ExternalModule) {
  18337. const chunk = externalChunkByModule.get(module);
  18338. const name = variable.name;
  18339. if (name === 'default') {
  18340. const moduleInterop = interop(module.id);
  18341. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  18342. ? chunk.defaultVariableName
  18343. : chunk.variableName;
  18344. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  18345. variable.setRenderNames(variableName, 'default');
  18346. }
  18347. else {
  18348. variable.setRenderNames(null, variableName);
  18349. }
  18350. }
  18351. else if (name === '*') {
  18352. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  18353. ? chunk.namespaceVariableName
  18354. : chunk.variableName);
  18355. }
  18356. else {
  18357. // if the second parameter is `null`, it uses its "name" for the property name
  18358. variable.setRenderNames(chunk.variableName, null);
  18359. }
  18360. }
  18361. else {
  18362. const chunk = chunkByModule.get(module);
  18363. if (preserveModules && variable.isNamespace) {
  18364. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  18365. }
  18366. else if (chunk.exportMode === 'default') {
  18367. variable.setRenderNames(null, chunk.variableName);
  18368. }
  18369. else {
  18370. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  18371. }
  18372. }
  18373. }
  18374. }
  18375. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  18376. for (const module of modules) {
  18377. for (const variable of module.scope.variables.values()) {
  18378. if (variable.included &&
  18379. // this will only happen for exports in some formats
  18380. !(variable.renderBaseName ||
  18381. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  18382. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18383. }
  18384. }
  18385. if (includedNamespaces.has(module)) {
  18386. const namespace = module.namespace;
  18387. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  18388. }
  18389. }
  18390. }
  18391. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  18392. let nameIndex = 0;
  18393. for (const variable of exports) {
  18394. let [exportName] = variable.name;
  18395. if (exportsByName.has(exportName)) {
  18396. do {
  18397. exportName = toBase64(++nameIndex);
  18398. // skip past leading number identifiers
  18399. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  18400. nameIndex += 9 * 64 ** (exportName.length - 1);
  18401. exportName = toBase64(nameIndex);
  18402. }
  18403. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  18404. }
  18405. exportsByName.set(exportName, variable);
  18406. exportNamesByVariable.set(variable, [exportName]);
  18407. }
  18408. }
  18409. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  18410. for (const variable of exports) {
  18411. let nameIndex = 0;
  18412. let exportName = variable.name;
  18413. while (exportsByName.has(exportName)) {
  18414. exportName = variable.name + '$' + ++nameIndex;
  18415. }
  18416. exportsByName.set(exportName, variable);
  18417. exportNamesByVariable.set(variable, [exportName]);
  18418. }
  18419. }
  18420. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  18421. const exportKeys = chunk.getExportNames();
  18422. if (exportMode === 'default') {
  18423. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  18424. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  18425. }
  18426. }
  18427. else if (exportMode === 'none' && exportKeys.length > 0) {
  18428. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  18429. }
  18430. if (exportMode === 'auto') {
  18431. if (exportKeys.length === 0) {
  18432. exportMode = 'none';
  18433. }
  18434. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  18435. exportMode = 'default';
  18436. }
  18437. else {
  18438. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  18439. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMixedExport(facadeModuleId, name));
  18440. }
  18441. exportMode = 'named';
  18442. }
  18443. }
  18444. return exportMode;
  18445. }
  18446. function guessIndentString(code) {
  18447. const lines = code.split('\n');
  18448. const tabbed = lines.filter(line => /^\t+/.test(line));
  18449. const spaced = lines.filter(line => /^ {2,}/.test(line));
  18450. if (tabbed.length === 0 && spaced.length === 0) {
  18451. return null;
  18452. }
  18453. // More lines tabbed than spaced? Assume tabs, and
  18454. // default to tabs in the case of a tie (or nothing
  18455. // to go on)
  18456. if (tabbed.length >= spaced.length) {
  18457. return '\t';
  18458. }
  18459. // Otherwise, we need to guess the multiple
  18460. const min = spaced.reduce((previous, current) => {
  18461. const numberSpaces = /^ +/.exec(current)[0].length;
  18462. return Math.min(numberSpaces, previous);
  18463. }, Infinity);
  18464. return ' '.repeat(min);
  18465. }
  18466. function getIndentString(modules, options) {
  18467. if (options.indent !== true)
  18468. return options.indent;
  18469. for (const module of modules) {
  18470. const indent = guessIndentString(module.originalCode);
  18471. if (indent !== null)
  18472. return indent;
  18473. }
  18474. return '\t';
  18475. }
  18476. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  18477. const staticDependencyBlocks = [];
  18478. const handledDependencies = new Set();
  18479. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  18480. const module = orderedModules[modulePos];
  18481. if (!handledDependencies.has(module)) {
  18482. const staticDependencies = [];
  18483. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  18484. staticDependencyBlocks.unshift(staticDependencies);
  18485. }
  18486. }
  18487. const dependencies = new Set();
  18488. for (const block of staticDependencyBlocks) {
  18489. for (const dependency of block) {
  18490. dependencies.add(dependency);
  18491. }
  18492. }
  18493. return dependencies;
  18494. }
  18495. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  18496. const dependencies = module.getDependenciesToBeIncluded();
  18497. for (const dependency of dependencies) {
  18498. if (dependency instanceof ExternalModule) {
  18499. staticDependencies.push(externalChunkByModule.get(dependency));
  18500. continue;
  18501. }
  18502. const dependencyChunk = chunkByModule.get(dependency);
  18503. if (dependencyChunk !== chunk) {
  18504. staticDependencies.push(dependencyChunk);
  18505. continue;
  18506. }
  18507. if (!handledModules.has(dependency)) {
  18508. handledModules.add(dependency);
  18509. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  18510. }
  18511. }
  18512. }
  18513. const NON_ASSET_EXTENSIONS = new Set([
  18514. '.js',
  18515. '.jsx',
  18516. '.ts',
  18517. '.tsx',
  18518. '.mjs',
  18519. '.mts',
  18520. '.cjs',
  18521. '.cts'
  18522. ]);
  18523. function getGlobalName(chunk, globals, hasExports, log) {
  18524. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  18525. if (globalName) {
  18526. return globalName;
  18527. }
  18528. if (hasExports) {
  18529. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingGlobalName(chunk.id, chunk.variableName));
  18530. return chunk.variableName;
  18531. }
  18532. }
  18533. class Chunk {
  18534. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  18535. this.orderedModules = orderedModules;
  18536. this.inputOptions = inputOptions;
  18537. this.outputOptions = outputOptions;
  18538. this.unsetOptions = unsetOptions;
  18539. this.pluginDriver = pluginDriver;
  18540. this.modulesById = modulesById;
  18541. this.chunkByModule = chunkByModule;
  18542. this.externalChunkByModule = externalChunkByModule;
  18543. this.facadeChunkByModule = facadeChunkByModule;
  18544. this.includedNamespaces = includedNamespaces;
  18545. this.manualChunkAlias = manualChunkAlias;
  18546. this.getPlaceholder = getPlaceholder;
  18547. this.bundle = bundle;
  18548. this.inputBase = inputBase;
  18549. this.snippets = snippets;
  18550. this.dependencies = new Set();
  18551. this.entryModules = [];
  18552. this.exportMode = 'named';
  18553. this.facadeModule = null;
  18554. this.namespaceVariableName = '';
  18555. this.variableName = '';
  18556. this.accessedGlobalsByScope = new Map();
  18557. this.dynamicEntryModules = [];
  18558. this.dynamicName = null;
  18559. this.exportNamesByVariable = new Map();
  18560. this.exports = new Set();
  18561. this.exportsByName = new Map();
  18562. this.fileName = null;
  18563. this.implicitEntryModules = [];
  18564. this.implicitlyLoadedBefore = new Set();
  18565. this.imports = new Set();
  18566. this.includedDynamicImports = null;
  18567. this.includedReexportsByModule = new Map();
  18568. // This may be updated in the constructor
  18569. this.isEmpty = true;
  18570. this.name = null;
  18571. this.needsExportsShim = false;
  18572. this.preRenderedChunkInfo = null;
  18573. this.preliminaryFileName = null;
  18574. this.preliminarySourcemapFileName = null;
  18575. this.renderedChunkInfo = null;
  18576. this.renderedDependencies = null;
  18577. this.renderedModules = Object.create(null);
  18578. this.sortedExportNames = null;
  18579. this.strictFacade = false;
  18580. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  18581. this.allowExtensionModules = new Set();
  18582. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  18583. const chunkModules = new Set(orderedModules);
  18584. for (const module of orderedModules) {
  18585. chunkByModule.set(module, this);
  18586. if (module.namespace.included && !outputOptions.preserveModules) {
  18587. includedNamespaces.add(module);
  18588. }
  18589. if (this.isEmpty && module.isIncluded()) {
  18590. this.isEmpty = false;
  18591. }
  18592. if (module.info.isEntry || outputOptions.preserveModules) {
  18593. this.entryModules.push(module);
  18594. }
  18595. for (const importer of module.includedDynamicImporters) {
  18596. if (!chunkModules.has(importer)) {
  18597. this.dynamicEntryModules.push(module);
  18598. // Modules with synthetic exports need an artificial namespace for dynamic imports
  18599. if (module.info.syntheticNamedExports) {
  18600. includedNamespaces.add(module);
  18601. this.exports.add(module.namespace);
  18602. }
  18603. }
  18604. }
  18605. if (module.implicitlyLoadedAfter.size > 0) {
  18606. this.implicitEntryModules.push(module);
  18607. }
  18608. }
  18609. this.suggestedVariableName = makeLegal(this.generateVariableName());
  18610. }
  18611. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  18612. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  18613. chunk.assignFacadeName(facadeName, facadedModule);
  18614. if (!facadeChunkByModule.has(facadedModule)) {
  18615. facadeChunkByModule.set(facadedModule, chunk);
  18616. }
  18617. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  18618. chunk.dependencies.add(dependency instanceof Module
  18619. ? chunkByModule.get(dependency)
  18620. : externalChunkByModule.get(dependency));
  18621. }
  18622. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  18623. facadedModule.info.moduleSideEffects &&
  18624. facadedModule.hasEffects()) {
  18625. chunk.dependencies.add(chunkByModule.get(facadedModule));
  18626. }
  18627. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  18628. chunk.facadeModule = facadedModule;
  18629. chunk.strictFacade = true;
  18630. return chunk;
  18631. }
  18632. canModuleBeFacade(module, exposedVariables) {
  18633. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  18634. // All exports of this chunk need to be exposed by the candidate module
  18635. for (const exposedVariable of this.exports) {
  18636. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  18637. return false;
  18638. }
  18639. }
  18640. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  18641. for (const exposedVariable of exposedVariables) {
  18642. if (!(exposedVariable.module === module ||
  18643. moduleExportNamesByVariable.has(exposedVariable) ||
  18644. (exposedVariable instanceof SyntheticNamedExportVariable &&
  18645. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  18646. return false;
  18647. }
  18648. }
  18649. return true;
  18650. }
  18651. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  18652. const renderedChunkInfo = this.getRenderedChunkInfo();
  18653. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  18654. const preliminaryFileName = renderedChunkInfo.fileName;
  18655. const fileName = (this.fileName = finalize(preliminaryFileName));
  18656. return {
  18657. ...renderedChunkInfo,
  18658. code,
  18659. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  18660. fileName,
  18661. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  18662. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  18663. finalize(fileName),
  18664. bindings
  18665. ])),
  18666. imports: renderedChunkInfo.imports.map(finalize),
  18667. map,
  18668. preliminaryFileName,
  18669. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  18670. sourcemapFileName
  18671. };
  18672. }
  18673. generateExports() {
  18674. this.sortedExportNames = null;
  18675. const remainingExports = new Set(this.exports);
  18676. if (this.facadeModule !== null &&
  18677. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  18678. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  18679. for (const [variable, exportNames] of exportNamesByVariable) {
  18680. this.exportNamesByVariable.set(variable, [...exportNames]);
  18681. for (const exportName of exportNames) {
  18682. this.exportsByName.set(exportName, variable);
  18683. }
  18684. remainingExports.delete(variable);
  18685. }
  18686. }
  18687. for (const module of this.allowExtensionModules) {
  18688. const exportNamesByVariable = module.getExportNamesByVariable();
  18689. for (const [variable, exportNames] of exportNamesByVariable) {
  18690. this.exportNamesByVariable.set(variable, [...exportNames]);
  18691. for (const exportName of exportNames) {
  18692. this.exportsByName.set(exportName, variable);
  18693. }
  18694. remainingExports.delete(variable);
  18695. }
  18696. }
  18697. if (this.outputOptions.minifyInternalExports) {
  18698. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18699. }
  18700. else {
  18701. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18702. }
  18703. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  18704. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  18705. }
  18706. generateFacades() {
  18707. const facades = [];
  18708. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  18709. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  18710. for (const module of entryModules) {
  18711. if (module.preserveSignature === 'allow-extension') {
  18712. const canPreserveExports = this.canPreserveModuleExports(module);
  18713. if (canPreserveExports &&
  18714. !module.chunkFileNames.size &&
  18715. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  18716. this.allowExtensionModules.add(module);
  18717. if (!this.facadeModule) {
  18718. this.facadeModule = module;
  18719. this.strictFacade = false;
  18720. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  18721. }
  18722. this.facadeChunkByModule.set(module, this);
  18723. continue;
  18724. }
  18725. }
  18726. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  18727. // mapping must run after Set 'name' dedupe
  18728. name => ({
  18729. name
  18730. }));
  18731. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  18732. requiredFacades.push({});
  18733. }
  18734. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  18735. if (requiredFacades.length === 0) {
  18736. requiredFacades.push({});
  18737. }
  18738. if (!this.facadeModule) {
  18739. const needsStrictFacade = !this.outputOptions.preserveModules &&
  18740. (module.preserveSignature === 'strict' ||
  18741. (module.preserveSignature === 'exports-only' &&
  18742. module.getExportNamesByVariable().size > 0));
  18743. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  18744. this.facadeModule = module;
  18745. this.facadeChunkByModule.set(module, this);
  18746. if (module.preserveSignature) {
  18747. this.strictFacade = needsStrictFacade;
  18748. }
  18749. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  18750. }
  18751. }
  18752. for (const facadeName of requiredFacades) {
  18753. 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));
  18754. }
  18755. }
  18756. for (const module of this.dynamicEntryModules) {
  18757. if (module.info.syntheticNamedExports)
  18758. continue;
  18759. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  18760. this.facadeModule = module;
  18761. this.facadeChunkByModule.set(module, this);
  18762. this.strictFacade = true;
  18763. this.dynamicName = getChunkNameFromModule(module);
  18764. }
  18765. else if (this.facadeModule === module &&
  18766. !this.strictFacade &&
  18767. this.canModuleBeFacade(module, exposedVariables)) {
  18768. this.strictFacade = true;
  18769. }
  18770. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  18771. this.includedNamespaces.add(module);
  18772. this.exports.add(module.namespace);
  18773. }
  18774. }
  18775. if (!this.outputOptions.preserveModules) {
  18776. this.addNecessaryImportsForFacades();
  18777. }
  18778. return facades;
  18779. }
  18780. canPreserveModuleExports(module) {
  18781. const exportNamesByVariable = module.getExportNamesByVariable();
  18782. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  18783. for (const [variable, exportNames] of exportNamesByVariable) {
  18784. for (const exportName of exportNames) {
  18785. const existingVariable = this.exportsByName.get(exportName);
  18786. // It's ok if the same export name in two modules references the exact same variable
  18787. if (existingVariable && existingVariable !== variable) {
  18788. return false;
  18789. }
  18790. }
  18791. }
  18792. // No actual conflicts found, add export names for future conflict checks
  18793. for (const [variable, exportNames] of exportNamesByVariable) {
  18794. for (const exportName of exportNames) {
  18795. this.exportsByName.set(exportName, variable);
  18796. }
  18797. }
  18798. return true;
  18799. }
  18800. getChunkName() {
  18801. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  18802. }
  18803. getExportNames() {
  18804. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  18805. }
  18806. getFileName() {
  18807. return this.fileName || this.getPreliminaryFileName().fileName;
  18808. }
  18809. getImportPath(importer) {
  18810. return escapeId(parseAst_js.getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  18811. }
  18812. getPreliminaryFileName() {
  18813. if (this.preliminaryFileName) {
  18814. return this.preliminaryFileName;
  18815. }
  18816. let fileName;
  18817. let hashPlaceholder = null;
  18818. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  18819. if (file) {
  18820. fileName = path.basename(file);
  18821. }
  18822. else if (this.fileName === null) {
  18823. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  18824. ? [entryFileNames, 'output.entryFileNames']
  18825. : [chunkFileNames, 'output.chunkFileNames'];
  18826. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  18827. format: () => format,
  18828. hash: size => hashPlaceholder ||
  18829. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  18830. name: () => this.getChunkName()
  18831. });
  18832. if (!hashPlaceholder) {
  18833. fileName = makeUnique(fileName, this.bundle);
  18834. }
  18835. }
  18836. else {
  18837. fileName = this.fileName;
  18838. }
  18839. if (!hashPlaceholder) {
  18840. this.bundle[fileName] = FILE_PLACEHOLDER;
  18841. }
  18842. // Caching is essential to not conflict with the file name reservation above
  18843. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  18844. }
  18845. getPreliminarySourcemapFileName() {
  18846. if (this.preliminarySourcemapFileName) {
  18847. return this.preliminarySourcemapFileName;
  18848. }
  18849. let sourcemapFileName = null;
  18850. let hashPlaceholder = null;
  18851. const { sourcemapFileNames, format } = this.outputOptions;
  18852. if (sourcemapFileNames) {
  18853. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  18854. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  18855. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  18856. format: () => format,
  18857. hash: size => hashPlaceholder ||
  18858. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  18859. name: () => this.getChunkName()
  18860. });
  18861. if (!hashPlaceholder) {
  18862. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  18863. }
  18864. }
  18865. else {
  18866. return null;
  18867. }
  18868. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  18869. }
  18870. getRenderedChunkInfo() {
  18871. if (this.renderedChunkInfo) {
  18872. return this.renderedChunkInfo;
  18873. }
  18874. return (this.renderedChunkInfo = {
  18875. ...this.getPreRenderedChunkInfo(),
  18876. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  18877. fileName: this.getFileName(),
  18878. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  18879. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  18880. imports: Array.from(this.dependencies, resolveFileName),
  18881. modules: this.renderedModules,
  18882. referencedFiles: this.getReferencedFiles()
  18883. });
  18884. }
  18885. getVariableExportName(variable) {
  18886. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  18887. return '*';
  18888. }
  18889. return this.exportNamesByVariable.get(variable)[0];
  18890. }
  18891. link() {
  18892. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  18893. for (const module of this.orderedModules) {
  18894. this.addImplicitlyLoadedBeforeFromModule(module);
  18895. this.setUpChunkImportsAndExportsForModule(module);
  18896. }
  18897. }
  18898. inlineTransitiveImports() {
  18899. const { facadeModule, dependencies, outputOptions } = this;
  18900. const { hoistTransitiveImports, preserveModules } = outputOptions;
  18901. // for static and dynamic entry points, add transitive dependencies to this
  18902. // chunk's dependencies to avoid loading latency
  18903. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  18904. for (const dep of dependencies) {
  18905. if (dep instanceof Chunk)
  18906. this.inlineChunkDependencies(dep);
  18907. }
  18908. }
  18909. }
  18910. async render() {
  18911. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  18912. const { format, preserveModules } = outputOptions;
  18913. const preliminaryFileName = this.getPreliminaryFileName();
  18914. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  18915. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  18916. const renderedDependencies = [...this.getRenderedDependencies().values()];
  18917. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  18918. let hasExports = renderedExports.length > 0;
  18919. let hasDefaultExport = false;
  18920. for (const renderedDependency of renderedDependencies) {
  18921. const { reexports } = renderedDependency;
  18922. if (reexports?.length) {
  18923. hasExports = true;
  18924. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  18925. hasDefaultExport = true;
  18926. }
  18927. if (format === 'es') {
  18928. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  18929. }
  18930. }
  18931. }
  18932. if (!hasDefaultExport) {
  18933. for (const { exported } of renderedExports) {
  18934. if (exported === 'default') {
  18935. hasDefaultExport = true;
  18936. break;
  18937. }
  18938. }
  18939. }
  18940. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  18941. finalisers[format](renderedSource, {
  18942. accessedGlobals,
  18943. dependencies: renderedDependencies,
  18944. exports: renderedExports,
  18945. hasDefaultExport,
  18946. hasExports,
  18947. id: preliminaryFileName.fileName,
  18948. indent,
  18949. intro,
  18950. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  18951. isModuleFacade: facadeModule !== null,
  18952. log: onLog,
  18953. namedExportsMode: exportMode !== 'default',
  18954. outro,
  18955. snippets,
  18956. usesTopLevelAwait
  18957. }, outputOptions);
  18958. if (banner)
  18959. magicString.prepend(banner);
  18960. if (format === 'es' || format === 'cjs') {
  18961. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  18962. if (shebang) {
  18963. magicString.prepend(`#!${shebang}\n`);
  18964. }
  18965. }
  18966. if (footer)
  18967. magicString.append(footer);
  18968. return {
  18969. chunk: this,
  18970. magicString,
  18971. preliminaryFileName,
  18972. preliminarySourcemapFileName,
  18973. usedModules
  18974. };
  18975. }
  18976. addImplicitlyLoadedBeforeFromModule(baseModule) {
  18977. const { chunkByModule, implicitlyLoadedBefore } = this;
  18978. for (const module of baseModule.implicitlyLoadedBefore) {
  18979. const chunk = chunkByModule.get(module);
  18980. if (chunk && chunk !== this) {
  18981. implicitlyLoadedBefore.add(chunk);
  18982. }
  18983. }
  18984. }
  18985. addNecessaryImportsForFacades() {
  18986. for (const [module, variables] of this.includedReexportsByModule) {
  18987. if (this.includedNamespaces.has(module)) {
  18988. for (const variable of variables) {
  18989. this.imports.add(variable);
  18990. }
  18991. }
  18992. }
  18993. }
  18994. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  18995. if (fileName) {
  18996. this.fileName = fileName;
  18997. }
  18998. else {
  18999. this.name = this.outputOptions.sanitizeFileName(name ||
  19000. (preservePath
  19001. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  19002. : getChunkNameFromModule(facadedModule)));
  19003. }
  19004. }
  19005. checkCircularDependencyImport(variable, importingModule) {
  19006. const variableModule = variable.module;
  19007. if (variableModule instanceof Module) {
  19008. const exportChunk = this.chunkByModule.get(variableModule);
  19009. let alternativeReexportModule;
  19010. do {
  19011. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  19012. if (alternativeReexportModule) {
  19013. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  19014. if (exportingChunk !== exportChunk) {
  19015. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCyclicCrossChunkReexport(
  19016. // Namespaces do not have an export name
  19017. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  19018. }
  19019. importingModule = alternativeReexportModule;
  19020. }
  19021. } while (alternativeReexportModule);
  19022. }
  19023. }
  19024. ensureReexportsAreAvailableForModule(module) {
  19025. const includedReexports = [];
  19026. const map = module.getExportNamesByVariable();
  19027. for (const exportedVariable of map.keys()) {
  19028. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  19029. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  19030. this.checkCircularDependencyImport(importedVariable, module);
  19031. // When preserving modules, we do not create namespace objects but directly
  19032. // use the actual namespaces, which would be broken by this logic.
  19033. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19034. const exportingModule = importedVariable.module;
  19035. if (exportingModule instanceof Module) {
  19036. const chunk = this.chunkByModule.get(exportingModule);
  19037. if (chunk && chunk !== this) {
  19038. chunk.exports.add(importedVariable);
  19039. includedReexports.push(importedVariable);
  19040. if (isSynthetic) {
  19041. this.imports.add(importedVariable);
  19042. }
  19043. }
  19044. }
  19045. }
  19046. }
  19047. if (includedReexports.length > 0) {
  19048. this.includedReexportsByModule.set(module, includedReexports);
  19049. }
  19050. }
  19051. generateVariableName() {
  19052. if (this.manualChunkAlias) {
  19053. return this.manualChunkAlias;
  19054. }
  19055. const moduleForNaming = this.entryModules[0] ||
  19056. this.implicitEntryModules[0] ||
  19057. this.dynamicEntryModules[0] ||
  19058. this.orderedModules[this.orderedModules.length - 1];
  19059. if (moduleForNaming) {
  19060. return getChunkNameFromModule(moduleForNaming);
  19061. }
  19062. return 'chunk';
  19063. }
  19064. getChunkExportDeclarations(format) {
  19065. const exports = [];
  19066. for (const exportName of this.getExportNames()) {
  19067. if (exportName[0] === '*')
  19068. continue;
  19069. const variable = this.exportsByName.get(exportName);
  19070. if (!(variable instanceof SyntheticNamedExportVariable)) {
  19071. const module = variable.module;
  19072. if (module) {
  19073. const chunk = this.chunkByModule.get(module);
  19074. if (chunk !== this) {
  19075. if (!chunk || format !== 'es') {
  19076. continue;
  19077. }
  19078. const chunkDep = this.renderedDependencies.get(chunk);
  19079. if (!chunkDep) {
  19080. continue;
  19081. }
  19082. const { imports, reexports } = chunkDep;
  19083. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  19084. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  19085. if (!isImported) {
  19086. continue;
  19087. }
  19088. }
  19089. }
  19090. }
  19091. let expression = null;
  19092. let hoisted = false;
  19093. let local = variable.getName(this.snippets.getPropertyAccess);
  19094. if (variable instanceof LocalVariable) {
  19095. for (const declaration of variable.declarations) {
  19096. if (declaration.parent instanceof FunctionDeclaration ||
  19097. (declaration instanceof ExportDefaultDeclaration &&
  19098. declaration.declaration instanceof FunctionDeclaration)) {
  19099. hoisted = true;
  19100. break;
  19101. }
  19102. }
  19103. }
  19104. else if (variable instanceof SyntheticNamedExportVariable) {
  19105. expression = local;
  19106. if (format === 'es') {
  19107. local = variable.renderName;
  19108. }
  19109. }
  19110. exports.push({
  19111. exported: exportName,
  19112. expression,
  19113. hoisted,
  19114. local
  19115. });
  19116. }
  19117. return exports;
  19118. }
  19119. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  19120. const dependencies = new Set();
  19121. const deconflictedDefault = new Set();
  19122. const deconflictedNamespace = new Set();
  19123. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  19124. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  19125. const module = variable.module;
  19126. if (module instanceof ExternalModule) {
  19127. const chunk = this.externalChunkByModule.get(module);
  19128. dependencies.add(chunk);
  19129. if (addNonNamespacesAndInteropHelpers) {
  19130. if (variable.name === 'default') {
  19131. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  19132. deconflictedDefault.add(chunk);
  19133. }
  19134. }
  19135. else if (variable.isNamespace &&
  19136. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  19137. (this.imports.has(variable) ||
  19138. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  19139. // We only need to deconflict it if the namespace is actually
  19140. // created as a variable, i.e. because it is used internally or
  19141. // because it is reexported as an object
  19142. deconflictedNamespace.add(chunk);
  19143. }
  19144. }
  19145. }
  19146. else {
  19147. const chunk = this.chunkByModule.get(module);
  19148. if (chunk !== this) {
  19149. dependencies.add(chunk);
  19150. if (addNonNamespacesAndInteropHelpers &&
  19151. chunk.exportMode === 'default' &&
  19152. variable.isNamespace) {
  19153. deconflictedNamespace.add(chunk);
  19154. }
  19155. }
  19156. }
  19157. }
  19158. }
  19159. if (addDependenciesWithoutBindings) {
  19160. for (const dependency of this.dependencies) {
  19161. dependencies.add(dependency);
  19162. }
  19163. }
  19164. return { deconflictedDefault, deconflictedNamespace, dependencies };
  19165. }
  19166. getDynamicDependencies() {
  19167. return this.getIncludedDynamicImports()
  19168. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  19169. resolvedDynamicImport.chunk ||
  19170. resolvedDynamicImport.externalChunk ||
  19171. resolvedDynamicImport.resolution)
  19172. .filter((resolution) => resolution !== this &&
  19173. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  19174. }
  19175. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  19176. if (resolution instanceof ExternalModule) {
  19177. const chunk = this.externalChunkByModule.get(resolution);
  19178. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  19179. }
  19180. let attributes = null;
  19181. if (['es', 'cjs'].includes(this.outputOptions.format) &&
  19182. this.outputOptions.externalImportAttributes) {
  19183. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  19184. attributes =
  19185. attributesFromImportAttributes === parseAst_js.EMPTY_OBJECT
  19186. ? true
  19187. : formatAttributes(attributesFromImportAttributes, this.snippets);
  19188. }
  19189. return [resolution || '', attributes];
  19190. }
  19191. getFallbackChunkName() {
  19192. if (this.manualChunkAlias) {
  19193. return this.manualChunkAlias;
  19194. }
  19195. if (this.dynamicName) {
  19196. return this.dynamicName;
  19197. }
  19198. if (this.fileName) {
  19199. return parseAst_js.getAliasName(this.fileName);
  19200. }
  19201. return parseAst_js.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  19202. }
  19203. getImportSpecifiers() {
  19204. const { interop } = this.outputOptions;
  19205. const importsByDependency = new Map();
  19206. for (const variable of this.imports) {
  19207. const module = variable.module;
  19208. let dependency;
  19209. let imported;
  19210. if (module instanceof ExternalModule) {
  19211. dependency = this.externalChunkByModule.get(module);
  19212. imported = variable.name;
  19213. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  19214. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, false));
  19215. }
  19216. }
  19217. else {
  19218. dependency = this.chunkByModule.get(module);
  19219. imported = dependency.getVariableExportName(variable);
  19220. }
  19221. getOrCreate(importsByDependency, dependency, getNewArray).push({
  19222. imported,
  19223. local: variable.getName(this.snippets.getPropertyAccess)
  19224. });
  19225. }
  19226. return importsByDependency;
  19227. }
  19228. getIncludedDynamicImports() {
  19229. if (this.includedDynamicImports) {
  19230. return this.includedDynamicImports;
  19231. }
  19232. const includedDynamicImports = [];
  19233. for (const module of this.orderedModules) {
  19234. for (const { node, resolution } of module.dynamicImports) {
  19235. if (!node.included) {
  19236. continue;
  19237. }
  19238. includedDynamicImports.push(resolution instanceof Module
  19239. ? {
  19240. chunk: this.chunkByModule.get(resolution),
  19241. externalChunk: null,
  19242. facadeChunk: this.facadeChunkByModule.get(resolution),
  19243. node,
  19244. resolution
  19245. }
  19246. : resolution instanceof ExternalModule
  19247. ? {
  19248. chunk: null,
  19249. externalChunk: this.externalChunkByModule.get(resolution),
  19250. facadeChunk: null,
  19251. node,
  19252. resolution
  19253. }
  19254. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  19255. }
  19256. }
  19257. return (this.includedDynamicImports = includedDynamicImports);
  19258. }
  19259. getPreRenderedChunkInfo() {
  19260. if (this.preRenderedChunkInfo) {
  19261. return this.preRenderedChunkInfo;
  19262. }
  19263. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  19264. return (this.preRenderedChunkInfo = {
  19265. exports: this.getExportNames(),
  19266. facadeModuleId: facadeModule && facadeModule.id,
  19267. isDynamicEntry: dynamicEntryModules.length > 0,
  19268. isEntry: !!facadeModule?.info.isEntry,
  19269. isImplicitEntry: implicitEntryModules.length > 0,
  19270. moduleIds: orderedModules.map(({ id }) => id),
  19271. name: this.getChunkName(),
  19272. type: 'chunk'
  19273. });
  19274. }
  19275. getPreserveModulesChunkNameFromModule(module) {
  19276. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  19277. if (predefinedChunkName)
  19278. return predefinedChunkName;
  19279. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  19280. const sanitizedId = sanitizeFileName(parseAst_js.normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  19281. const extensionName = path.extname(sanitizedId);
  19282. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  19283. ? sanitizedId.slice(0, -extensionName.length)
  19284. : sanitizedId;
  19285. if (parseAst_js.isAbsolute(idWithoutExtension)) {
  19286. if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
  19287. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  19288. }
  19289. else {
  19290. // handle edge case in Windows
  19291. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  19292. return parseAst_js.relative(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  19293. }
  19294. return parseAst_js.relative(this.inputBase, idWithoutExtension);
  19295. }
  19296. }
  19297. else {
  19298. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
  19299. }
  19300. }
  19301. getReexportSpecifiers() {
  19302. const { externalLiveBindings, interop } = this.outputOptions;
  19303. const reexportSpecifiers = new Map();
  19304. for (let exportName of this.getExportNames()) {
  19305. let dependency;
  19306. let imported;
  19307. let needsLiveBinding = false;
  19308. if (exportName[0] === '*') {
  19309. const id = exportName.slice(1);
  19310. if (interop(id) === 'defaultOnly') {
  19311. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnexpectedNamespaceReexport(id));
  19312. }
  19313. needsLiveBinding = externalLiveBindings;
  19314. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  19315. imported = exportName = '*';
  19316. }
  19317. else {
  19318. const variable = this.exportsByName.get(exportName);
  19319. if (variable instanceof SyntheticNamedExportVariable)
  19320. continue;
  19321. const module = variable.module;
  19322. if (module instanceof Module) {
  19323. dependency = this.chunkByModule.get(module);
  19324. if (dependency === this)
  19325. continue;
  19326. imported = dependency.getVariableExportName(variable);
  19327. needsLiveBinding = variable.isReassigned;
  19328. }
  19329. else {
  19330. dependency = this.externalChunkByModule.get(module);
  19331. imported = variable.name;
  19332. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  19333. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, true));
  19334. }
  19335. needsLiveBinding =
  19336. externalLiveBindings &&
  19337. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  19338. }
  19339. }
  19340. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  19341. imported,
  19342. needsLiveBinding,
  19343. reexported: exportName
  19344. });
  19345. }
  19346. return reexportSpecifiers;
  19347. }
  19348. getReferencedFiles() {
  19349. const referencedFiles = new Set();
  19350. for (const module of this.orderedModules) {
  19351. for (const meta of module.importMetas) {
  19352. const fileName = meta.getReferencedFileName(this.pluginDriver);
  19353. if (fileName) {
  19354. referencedFiles.add(fileName);
  19355. }
  19356. }
  19357. }
  19358. return [...referencedFiles];
  19359. }
  19360. getRenderedDependencies() {
  19361. if (this.renderedDependencies) {
  19362. return this.renderedDependencies;
  19363. }
  19364. const importSpecifiers = this.getImportSpecifiers();
  19365. const reexportSpecifiers = this.getReexportSpecifiers();
  19366. const renderedDependencies = new Map();
  19367. const fileName = this.getFileName();
  19368. for (const dependency of this.dependencies) {
  19369. const imports = importSpecifiers.get(dependency) || null;
  19370. const reexports = reexportSpecifiers.get(dependency) || null;
  19371. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  19372. const importPath = dependency.getImportPath(fileName);
  19373. renderedDependencies.set(dependency, {
  19374. attributes: dependency instanceof ExternalChunk
  19375. ? dependency.getImportAttributes(this.snippets)
  19376. : null,
  19377. defaultVariableName: dependency.defaultVariableName,
  19378. globalName: dependency instanceof ExternalChunk &&
  19379. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  19380. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  19381. importPath,
  19382. imports,
  19383. isChunk: dependency instanceof Chunk,
  19384. name: dependency.variableName,
  19385. namedExportsMode,
  19386. namespaceVariableName: dependency.namespaceVariableName,
  19387. reexports
  19388. });
  19389. }
  19390. return (this.renderedDependencies = renderedDependencies);
  19391. }
  19392. inlineChunkDependencies(chunk) {
  19393. for (const dep of chunk.dependencies) {
  19394. if (this.dependencies.has(dep))
  19395. continue;
  19396. this.dependencies.add(dep);
  19397. if (dep instanceof Chunk) {
  19398. this.inlineChunkDependencies(dep);
  19399. }
  19400. }
  19401. }
  19402. // This method changes properties on the AST before rendering and must not be async
  19403. renderModules(fileName) {
  19404. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  19405. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  19406. const { _, cnst, n } = snippets;
  19407. this.setDynamicImportResolutions(fileName);
  19408. this.setImportMetaResolutions(fileName);
  19409. this.setIdentifierRenderResolutions();
  19410. const magicString = new Bundle$1({ separator: `${n}${n}` });
  19411. const indent = getIndentString(orderedModules, outputOptions);
  19412. const usedModules = [];
  19413. let hoistedSource = '';
  19414. const accessedGlobals = new Set();
  19415. const renderedModuleSources = new Map();
  19416. const renderOptions = {
  19417. accessedDocumentCurrentScript: false,
  19418. exportNamesByVariable,
  19419. format,
  19420. freeze,
  19421. importAttributesKey,
  19422. indent,
  19423. pluginDriver,
  19424. snippets,
  19425. symbols,
  19426. useOriginalName: null
  19427. };
  19428. let usesTopLevelAwait = false;
  19429. for (const module of orderedModules) {
  19430. let renderedLength = 0;
  19431. let source;
  19432. if (module.isIncluded() || includedNamespaces.has(module)) {
  19433. const rendered = module.render(renderOptions);
  19434. if (!renderOptions.accessedDocumentCurrentScript &&
  19435. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  19436. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  19437. }
  19438. renderOptions.accessedDocumentCurrentScript = false;
  19439. ({ source } = rendered);
  19440. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  19441. renderedLength = source.length();
  19442. if (renderedLength) {
  19443. if (compact && source.lastLine().includes('//'))
  19444. source.append('\n');
  19445. renderedModuleSources.set(module, source);
  19446. magicString.addSource(source);
  19447. usedModules.push(module);
  19448. }
  19449. const namespace = module.namespace;
  19450. if (includedNamespaces.has(module)) {
  19451. const rendered = namespace.renderBlock(renderOptions);
  19452. if (namespace.renderFirst())
  19453. hoistedSource += n + rendered;
  19454. else
  19455. magicString.addSource(new MagicString(rendered));
  19456. }
  19457. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  19458. if (accessedGlobalVariables) {
  19459. for (const name of accessedGlobalVariables) {
  19460. accessedGlobals.add(name);
  19461. }
  19462. }
  19463. }
  19464. const { renderedExports, removedExports } = module.getRenderedExports();
  19465. renderedModules[module.id] = {
  19466. get code() {
  19467. return source?.toString() ?? null;
  19468. },
  19469. originalLength: module.originalCode.length,
  19470. removedExports,
  19471. renderedExports,
  19472. renderedLength
  19473. };
  19474. }
  19475. if (hoistedSource)
  19476. magicString.prepend(hoistedSource + n + n);
  19477. if (this.needsExportsShim) {
  19478. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  19479. }
  19480. const renderedSource = compact ? magicString : magicString.trim();
  19481. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  19482. onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyChunk(this.getChunkName()));
  19483. }
  19484. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  19485. }
  19486. setDynamicImportResolutions(fileName) {
  19487. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  19488. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  19489. if (resolvedDynamicImport.chunk) {
  19490. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  19491. if (chunk === this) {
  19492. node.setInternalResolution(resolution.namespace);
  19493. }
  19494. else {
  19495. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  19496. }
  19497. }
  19498. else {
  19499. const { node, resolution } = resolvedDynamicImport;
  19500. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  19501. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  19502. }
  19503. }
  19504. }
  19505. setIdentifierRenderResolutions() {
  19506. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  19507. const syntheticExports = new Set();
  19508. for (const exportName of this.getExportNames()) {
  19509. const exportVariable = this.exportsByName.get(exportName);
  19510. if (format !== 'es' &&
  19511. format !== 'system' &&
  19512. exportVariable.isReassigned &&
  19513. !exportVariable.isId) {
  19514. exportVariable.setRenderNames('exports', exportName);
  19515. }
  19516. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  19517. syntheticExports.add(exportVariable);
  19518. }
  19519. else {
  19520. exportVariable.setRenderNames(null, null);
  19521. }
  19522. }
  19523. for (const module of this.orderedModules) {
  19524. if (module.needsExportShim) {
  19525. this.needsExportsShim = true;
  19526. break;
  19527. }
  19528. }
  19529. const usedNames = new Set(['Object', 'Promise']);
  19530. if (this.needsExportsShim) {
  19531. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  19532. }
  19533. if (symbols) {
  19534. usedNames.add('Symbol');
  19535. }
  19536. switch (format) {
  19537. case 'system': {
  19538. usedNames.add('module').add('exports');
  19539. break;
  19540. }
  19541. case 'es': {
  19542. break;
  19543. }
  19544. case 'cjs': {
  19545. usedNames.add('module').add('require').add('__filename').add('__dirname');
  19546. }
  19547. // fallthrough
  19548. default: {
  19549. usedNames.add('exports');
  19550. for (const helper of HELPER_NAMES) {
  19551. usedNames.add(helper);
  19552. }
  19553. }
  19554. }
  19555. 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);
  19556. }
  19557. setImportMetaResolutions(fileName) {
  19558. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  19559. for (const module of orderedModules) {
  19560. for (const importMeta of module.importMetas) {
  19561. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  19562. }
  19563. if (includedNamespaces.has(module)) {
  19564. module.namespace.prepare(accessedGlobalsByScope);
  19565. }
  19566. }
  19567. }
  19568. setUpChunkImportsAndExportsForModule(module) {
  19569. const moduleImports = new Set(module.includedImports);
  19570. // when we are not preserving modules, we need to make all namespace variables available for
  19571. // rendering the namespace object
  19572. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  19573. const memberVariables = module.namespace.getMemberVariables();
  19574. for (const variable of Object.values(memberVariables)) {
  19575. if (variable.included) {
  19576. moduleImports.add(variable);
  19577. }
  19578. }
  19579. }
  19580. for (let variable of moduleImports) {
  19581. if (variable instanceof ExportDefaultVariable) {
  19582. variable = variable.getOriginalVariable();
  19583. }
  19584. if (variable instanceof SyntheticNamedExportVariable) {
  19585. variable = variable.getBaseVariable();
  19586. }
  19587. const chunk = this.chunkByModule.get(variable.module);
  19588. if (chunk !== this) {
  19589. this.imports.add(variable);
  19590. if (variable.module instanceof Module) {
  19591. this.checkCircularDependencyImport(variable, module);
  19592. // When preserving modules, we do not create namespace objects but directly
  19593. // use the actual namespaces, which would be broken by this logic.
  19594. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19595. chunk.exports.add(variable);
  19596. }
  19597. }
  19598. }
  19599. }
  19600. if (this.includedNamespaces.has(module) ||
  19601. (module.info.isEntry && module.preserveSignature !== false) ||
  19602. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  19603. this.ensureReexportsAreAvailableForModule(module);
  19604. }
  19605. for (const { node, resolution } of module.dynamicImports) {
  19606. if (node.included &&
  19607. resolution instanceof Module &&
  19608. this.chunkByModule.get(resolution) === this &&
  19609. !this.includedNamespaces.has(resolution)) {
  19610. this.includedNamespaces.add(resolution);
  19611. this.ensureReexportsAreAvailableForModule(resolution);
  19612. }
  19613. }
  19614. }
  19615. }
  19616. function getChunkNameFromModule(module) {
  19617. return getPredefinedChunkNameFromModule(module) ?? parseAst_js.getAliasName(module.id);
  19618. }
  19619. function getPredefinedChunkNameFromModule(module) {
  19620. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  19621. }
  19622. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  19623. const importedBindingsPerDependency = {};
  19624. for (const [dependency, declaration] of renderedDependencies) {
  19625. const specifiers = new Set();
  19626. if (declaration.imports) {
  19627. for (const { imported } of declaration.imports) {
  19628. specifiers.add(imported);
  19629. }
  19630. }
  19631. if (declaration.reexports) {
  19632. for (const { imported } of declaration.reexports) {
  19633. specifiers.add(imported);
  19634. }
  19635. }
  19636. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  19637. }
  19638. return importedBindingsPerDependency;
  19639. }
  19640. const QUERY_HASH_REGEX = /[#?]/;
  19641. const resolveFileName = (dependency) => dependency.getFileName();
  19642. /**
  19643. * Concatenate a number of iterables to a new iterable without fully evaluating
  19644. * their iterators. Useful when e.g. working with large sets or lists and when
  19645. * there is a chance that the iterators will not be fully exhausted.
  19646. */
  19647. function* concatLazy(iterables) {
  19648. for (const iterable of iterables) {
  19649. yield* iterable;
  19650. }
  19651. }
  19652. /**
  19653. * At its core, the algorithm first starts from each static or dynamic entry
  19654. * point and then assigns that entry point to all modules than can be reached
  19655. * via static imports. We call this the *dependent entry points* of that
  19656. * module.
  19657. *
  19658. * Then we group all modules with the same dependent entry points into chunks
  19659. * as those modules will always be loaded together.
  19660. *
  19661. * One non-trivial optimization we can apply is that dynamic entries are
  19662. * different from static entries in so far as when a dynamic import occurs,
  19663. * some modules are already in memory. If some of these modules are also
  19664. * dependencies of the dynamic entry, then it does not make sense to create a
  19665. * separate chunk for them. Instead, the dynamic import target can load them
  19666. * from the importing chunk.
  19667. *
  19668. * With regard to chunking, if B is implicitly loaded after A, then this can be
  19669. * handled the same way as if there was a dynamic import A => B.
  19670. *
  19671. * Example:
  19672. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  19673. * Then the initial algorithm would assign A into the A chunk, C into the C
  19674. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  19675. * points A and C.
  19676. * However we know that C can only be loaded from A, so A and its dependency B
  19677. * must already be in memory when C is loaded. So it is enough to create only
  19678. * two chunks A containing [AB] and C containing [C].
  19679. *
  19680. * So we do not assign the dynamic entry C as dependent entry point to modules
  19681. * that are already loaded.
  19682. *
  19683. * In a more complex example, let us assume that we have entry points X and Y.
  19684. * Further, let us assume
  19685. * X -> A, X -> B, X -> C,
  19686. * Y -> A, Y -> B,
  19687. * A => D,
  19688. * D -> B, D -> C
  19689. * So without dynamic import optimization, the dependent entry points are
  19690. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  19691. * chunks.
  19692. *
  19693. * Now D is loaded only after A is loaded. But A is loaded if either X is
  19694. * loaded or Y is loaded. So the modules that are already in memory when D is
  19695. * loaded are the intersection of all modules that X depends on with all
  19696. * modules that Y depends on, which in this case are the modules A and B.
  19697. * We could also say they are all modules that have both X and Y as dependent
  19698. * entry points.
  19699. *
  19700. * So we can remove D as dependent entry point from A and B, which means they
  19701. * both now have only XY as dependent entry points and can be merged into the
  19702. * same chunk.
  19703. *
  19704. * Now let us extend this to the most general case where we have several
  19705. * dynamic importers for one dynamic entry point.
  19706. *
  19707. * In the most general form, it works like this:
  19708. * For each dynamic entry point, we have a number of dynamic importers, which
  19709. * are the modules importing it. Using the previous ideas, we can determine
  19710. * the modules already in memory for each dynamic importer by looking for all
  19711. * modules that have all the dependent entry points of the dynamic importer as
  19712. * dependent entry points.
  19713. * So the modules that are guaranteed to be in memory when the dynamic entry
  19714. * point is loaded are the intersection of the modules already in memory for
  19715. * each dynamic importer.
  19716. *
  19717. * Assuming that A => D and B => D and A has dependent entry points XY and B
  19718. * has dependent entry points YZ, then the modules guaranteed to be in memory
  19719. * are all modules that have at least XYZ as dependent entry points.
  19720. * We call XYZ the *dynamically dependent entry points* of D.
  19721. *
  19722. * Now there is one last case to consider: If one of the dynamically dependent
  19723. * entries is itself a dynamic entry, then any module is in memory that either
  19724. * is a dependency of that dynamic entry or again has the dynamic dependent
  19725. * entries of that dynamic entry as dependent entry points.
  19726. *
  19727. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  19728. * complexity with regard to dynamic entries that blew up for very large
  19729. * projects.
  19730. *
  19731. * If we have an efficient way to do Set operations, an alternative approach
  19732. * would be to instead collect already loaded modules per dynamic entry. And as
  19733. * all chunks from the initial grouping would behave the same, we can instead
  19734. * collect already loaded chunks for a performance improvement.
  19735. *
  19736. * To do that efficiently, need
  19737. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  19738. * imports that can be triggered by a dynamic entry
  19739. * - a Map of static dependencies per entry
  19740. * - a Map of already loaded chunks per entry that we initially populate with
  19741. * empty Sets for static entries and Sets containing all entries for dynamic
  19742. * entries
  19743. *
  19744. * For efficient operations, we assign each entry a numerical index and
  19745. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  19746. * bit index. Then the last two maps can be represented as arrays of BigInt
  19747. * values.
  19748. *
  19749. * Then we iterate through each dynamic entry. We set the already loaded modules
  19750. * to the intersection of the previously already loaded modules with the union
  19751. * of the already loaded modules of that chunk with its static dependencies.
  19752. *
  19753. * If the already loaded modules changed, then we use the Map of dynamic imports
  19754. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  19755. * them back into the iteration. As an additional optimization, we note for
  19756. * each dynamic entry which dynamic dependent entries have changed and only
  19757. * intersect those entries again on subsequent interations.
  19758. *
  19759. * Then we remove the dynamic entries from the list of dependent entries for
  19760. * those chunks that are already loaded for that dynamic entry and create
  19761. * another round of chunks.
  19762. */
  19763. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  19764. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  19765. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  19766. // Each chunk is identified by its position in this array
  19767. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  19768. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  19769. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19770. // If we no longer want this, we should make a copy here.
  19771. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  19772. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  19773. // This mutates the dependentEntries in chunkAtoms
  19774. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  19775. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  19776. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  19777. alias: null,
  19778. modules
  19779. })));
  19780. return chunkDefinitions;
  19781. }
  19782. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  19783. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  19784. const manualChunkModulesByAlias = Object.create(null);
  19785. for (const [entry, alias] of manualChunkAliasByEntry) {
  19786. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  19787. }
  19788. const manualChunks = Object.entries(manualChunkModulesByAlias);
  19789. const chunkDefinitions = new Array(manualChunks.length);
  19790. let index = 0;
  19791. for (const [alias, modules] of manualChunks) {
  19792. chunkDefinitions[index++] = { alias, modules };
  19793. }
  19794. return { chunkDefinitions, modulesInManualChunks };
  19795. }
  19796. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  19797. const modulesToHandle = new Set([entry]);
  19798. for (const module of modulesToHandle) {
  19799. modulesInManualChunks.add(module);
  19800. manualChunkModules.push(module);
  19801. for (const dependency of module.dependencies) {
  19802. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  19803. modulesToHandle.add(dependency);
  19804. }
  19805. }
  19806. }
  19807. }
  19808. function analyzeModuleGraph(entries) {
  19809. const dynamicEntryModules = new Set();
  19810. const awaitedDynamicEntryModules = new Set();
  19811. const dependentEntriesByModule = new Map();
  19812. const allEntriesSet = new Set(entries);
  19813. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  19814. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  19815. let entryIndex = 0;
  19816. for (const currentEntry of allEntriesSet) {
  19817. const dynamicImportsForCurrentEntry = new Set();
  19818. const awaitedDynamicImportsForCurrentEntry = new Set();
  19819. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  19820. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  19821. const staticDependencies = new Set([currentEntry]);
  19822. for (const module of staticDependencies) {
  19823. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  19824. for (const dependency of module.getDependenciesToBeIncluded()) {
  19825. if (!(dependency instanceof ExternalModule)) {
  19826. staticDependencies.add(dependency);
  19827. }
  19828. }
  19829. for (const { resolution } of module.dynamicImports) {
  19830. if (resolution instanceof Module &&
  19831. resolution.includedDynamicImporters.length > 0 &&
  19832. !allEntriesSet.has(resolution)) {
  19833. dynamicEntryModules.add(resolution);
  19834. allEntriesSet.add(resolution);
  19835. dynamicImportsForCurrentEntry.add(resolution);
  19836. for (const includedDirectTopLevelAwaitingDynamicImporter of resolution.includedDirectTopLevelAwaitingDynamicImporters) {
  19837. if (staticDependencies.has(includedDirectTopLevelAwaitingDynamicImporter)) {
  19838. awaitedDynamicEntryModules.add(resolution);
  19839. awaitedDynamicImportsForCurrentEntry.add(resolution);
  19840. break;
  19841. }
  19842. }
  19843. }
  19844. }
  19845. for (const dependency of module.implicitlyLoadedBefore) {
  19846. if (!allEntriesSet.has(dependency)) {
  19847. dynamicEntryModules.add(dependency);
  19848. allEntriesSet.add(dependency);
  19849. }
  19850. }
  19851. }
  19852. entryIndex++;
  19853. }
  19854. const allEntries = [...allEntriesSet];
  19855. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  19856. return {
  19857. allEntries,
  19858. awaitedDynamicImportsByEntry,
  19859. dependentEntriesByModule,
  19860. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDirectTopLevelAwaitingDynamicImporters),
  19861. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  19862. dynamicImportsByEntry
  19863. };
  19864. }
  19865. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  19866. const entryIndexByModule = new Map();
  19867. const dynamicEntries = new Set();
  19868. const awaitedDynamicEntries = new Set();
  19869. for (const [entryIndex, entry] of allEntries.entries()) {
  19870. entryIndexByModule.set(entry, entryIndex);
  19871. if (dynamicEntryModules.has(entry)) {
  19872. dynamicEntries.add(entryIndex);
  19873. }
  19874. if (awaitedDynamicEntryModules.has(entry)) {
  19875. awaitedDynamicEntries.add(entryIndex);
  19876. }
  19877. }
  19878. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  19879. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  19880. return {
  19881. awaitedDynamicEntries,
  19882. awaitedDynamicImportsByEntry,
  19883. dynamicEntries,
  19884. dynamicImportsByEntry
  19885. };
  19886. }
  19887. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  19888. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  19889. let index = 0;
  19890. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  19891. const dynamicImports = new Set();
  19892. for (const dynamicEntry of dynamicImportModules) {
  19893. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  19894. }
  19895. dynamicImportsByEntry[index++] = dynamicImports;
  19896. }
  19897. return dynamicImportsByEntry;
  19898. }
  19899. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  19900. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  19901. for (const dynamicEntryIndex of dynamicEntries) {
  19902. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  19903. const dynamicEntry = allEntries[dynamicEntryIndex];
  19904. for (const importer of concatLazy([
  19905. getDynamicImporters(dynamicEntry),
  19906. dynamicEntry.implicitlyLoadedAfter
  19907. ])) {
  19908. for (const entry of dependentEntriesByModule.get(importer)) {
  19909. dynamicallyDependentEntries.add(entry);
  19910. }
  19911. }
  19912. }
  19913. return dynamicallyDependentEntriesByDynamicEntry;
  19914. }
  19915. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  19916. const chunkModules = Object.create(null);
  19917. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  19918. let chunkSignature = 0n;
  19919. for (const entryIndex of dependentEntries) {
  19920. chunkSignature |= 1n << BigInt(entryIndex);
  19921. }
  19922. (chunkModules[String(chunkSignature)] ||= {
  19923. dependentEntries: new Set(dependentEntries),
  19924. modules: []
  19925. }).modules.push(...modules);
  19926. }
  19927. return Object.values(chunkModules);
  19928. }
  19929. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  19930. for (const [module, dependentEntries] of dependentEntriesByModule) {
  19931. if (!modulesInManualChunks.has(module)) {
  19932. yield { dependentEntries, modules: [module] };
  19933. }
  19934. }
  19935. }
  19936. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  19937. // The indices correspond to the indices in allEntries. The atoms correspond
  19938. // to bits in the bigint values where chunk 0 is the lowest bit.
  19939. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  19940. // This toggles the bits for each atom that is a dependency of an entry
  19941. let atomMask = 1n;
  19942. for (const { dependentEntries } of chunkAtoms) {
  19943. for (const entryIndex of dependentEntries) {
  19944. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  19945. }
  19946. atomMask <<= 1n;
  19947. }
  19948. return staticDependencyAtomsByEntry;
  19949. }
  19950. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19951. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  19952. // Dynamic entries have all atoms as already loaded initially because we then
  19953. // intersect with the static dependency atoms of all dynamic importers.
  19954. // Static entries cannot have already loaded atoms.
  19955. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  19956. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  19957. // We delete here so that they can be added again if necessary to be handled
  19958. // again by the loop
  19959. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  19960. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  19961. let updatedLoadedAtoms = knownLoadedAtoms;
  19962. for (const entryIndex of dynamicallyDependentEntries) {
  19963. updatedLoadedAtoms &=
  19964. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  19965. }
  19966. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  19967. // updated again
  19968. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  19969. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  19970. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  19971. // If this adds an entry that was deleted before, it will be handled
  19972. // again. This is the reason why we delete every entry from this map
  19973. // that we processed.
  19974. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  19975. }
  19976. }
  19977. }
  19978. return alreadyLoadedAtomsByEntry;
  19979. }
  19980. /**
  19981. * This removes all unnecessary dynamic entries from the dependentEntries in its
  19982. * first argument if a chunk is already loaded without that entry.
  19983. */
  19984. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  19985. // Remove entries from dependent entries if a chunk is already loaded without
  19986. // that entry. Do not remove already loaded atoms where all dynamic imports
  19987. // are awaited to avoid cycles in the output.
  19988. let chunkMask = 1n;
  19989. for (const { dependentEntries } of chunkAtoms) {
  19990. for (const entryIndex of dependentEntries) {
  19991. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  19992. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  19993. dependentEntries.delete(entryIndex);
  19994. }
  19995. }
  19996. chunkMask <<= 1n;
  19997. }
  19998. }
  19999. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  20000. const chunksBySignature = Object.create(null);
  20001. const chunkByModule = new Map();
  20002. const sizeByAtom = new Array(chunkAtoms.length);
  20003. let sideEffectAtoms = 0n;
  20004. let atomMask = 1n;
  20005. let index = 0;
  20006. for (const { dependentEntries, modules } of chunkAtoms) {
  20007. let chunkSignature = 0n;
  20008. let correlatedAtoms = -1n;
  20009. for (const entryIndex of dependentEntries) {
  20010. chunkSignature |= 1n << BigInt(entryIndex);
  20011. // Correlated atoms are the atoms that are guaranteed to be loaded as
  20012. // well when a given atom is loaded. It is the intersection of the already
  20013. // loaded modules of each chunk merged with its static dependencies.
  20014. correlatedAtoms &=
  20015. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  20016. }
  20017. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  20018. containedAtoms: 0n,
  20019. correlatedAtoms,
  20020. dependencies: new Set(),
  20021. dependentChunks: new Set(),
  20022. dependentEntries: new Set(dependentEntries),
  20023. modules: [],
  20024. pure: true,
  20025. size: 0
  20026. });
  20027. let atomSize = 0;
  20028. let pure = true;
  20029. for (const module of modules) {
  20030. chunkByModule.set(module, chunk);
  20031. // Unfortunately, we cannot take tree-shaking into account here because
  20032. // rendering did not happen yet, but we can detect empty modules
  20033. if (module.isIncluded()) {
  20034. pure &&= !module.hasEffects();
  20035. // we use a trivial size for the default minChunkSize to improve
  20036. // performance
  20037. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  20038. }
  20039. }
  20040. if (!pure) {
  20041. sideEffectAtoms |= atomMask;
  20042. }
  20043. sizeByAtom[index++] = atomSize;
  20044. chunk.containedAtoms |= atomMask;
  20045. chunk.modules.push(...modules);
  20046. chunk.pure &&= pure;
  20047. chunk.size += atomSize;
  20048. atomMask <<= 1n;
  20049. }
  20050. const chunks = Object.values(chunksBySignature);
  20051. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  20052. return { chunks, sideEffectAtoms, sizeByAtom };
  20053. }
  20054. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  20055. const signatureByExternalModule = new Map();
  20056. let externalSideEffectAtoms = 0n;
  20057. for (const chunk of chunks) {
  20058. const { dependencies, modules } = chunk;
  20059. for (const module of modules) {
  20060. for (const dependency of module.getDependenciesToBeIncluded()) {
  20061. if (dependency instanceof ExternalModule) {
  20062. if (dependency.info.moduleSideEffects) {
  20063. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  20064. const signature = nextAvailableAtomMask;
  20065. nextAvailableAtomMask <<= 1n;
  20066. externalSideEffectAtoms |= signature;
  20067. return signature;
  20068. });
  20069. chunk.containedAtoms |= signature;
  20070. chunk.correlatedAtoms |= signature;
  20071. }
  20072. }
  20073. else {
  20074. const dependencyChunk = chunkByModule.get(dependency);
  20075. if (dependencyChunk && dependencyChunk !== chunk) {
  20076. dependencies.add(dependencyChunk);
  20077. dependencyChunk.dependentChunks.add(chunk);
  20078. }
  20079. }
  20080. }
  20081. }
  20082. }
  20083. return externalSideEffectAtoms;
  20084. }
  20085. /**
  20086. * This function tries to get rid of small chunks by merging them with other
  20087. * chunks.
  20088. *
  20089. * We can only merge chunks safely if after the merge, loading any entry point
  20090. * in any allowed order will not trigger side effects that should not have been
  20091. * triggered. While side effects are usually things like global function calls,
  20092. * global variable mutations or potentially thrown errors, details do not
  20093. * matter here, and we just discern chunks without side effects (pure chunks)
  20094. * from other chunks.
  20095. *
  20096. * As a first step, we assign each pre-generated chunk with side effects a
  20097. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  20098. *
  20099. * Now to determine the side effects of loading a chunk, one also has to take
  20100. * the side effects of its dependencies into account. So if A depends on B
  20101. * (A -> B) and both have side effects, loading A triggers effects AB.
  20102. *
  20103. * Now from the previous step we know that each chunk is uniquely determine by
  20104. * the entry points that depend on it and cause it to load, which we will call
  20105. * its dependent entry points.
  20106. *
  20107. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  20108. * Starting from that idea, we can determine a set of chunks—and thus a set
  20109. * of side effects—that must have been triggered if a certain chunk has been
  20110. * loaded. Basically, it is the intersection of all chunks loaded by the
  20111. * dependent entry points of a given chunk. We call the corresponding side
  20112. * effects the correlated side effects of that chunk.
  20113. *
  20114. * Example:
  20115. * X -> ABC, Y -> ADE, A-> F, B -> D
  20116. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  20117. * The intersection is ADF. So we know that when A is loaded, D and F must also
  20118. * be in memory even though neither D nor A is a dependency of the other.
  20119. * If all have side effects, we call ADF the correlated side effects of A. The
  20120. * correlated side effects need to remain constant when merging chunks.
  20121. *
  20122. * In contrast, we have the dependency side effects of A, which represents
  20123. * the side effects we trigger if we directly load A. In this example, the
  20124. * dependency side effects are AF.
  20125. * For entry chunks, dependency and correlated side effects are the same.
  20126. *
  20127. * With these concepts, merging chunks is allowed if the correlated side
  20128. * effects of each entry do not change. Thus, we are allowed to merge two
  20129. * chunks if
  20130. *
  20131. * a) the dependency side effects of each chunk are a subset of the correlated
  20132. * side effects of the other chunk, so no additional side effects are
  20133. * triggered for any entry, or
  20134. * b) The dependent entry points of chunk A are a subset of the dependent entry
  20135. * points of chunk B while the dependency side effects of A are a subset of
  20136. * the correlated side effects of B. Because in that scenario, whenever A is
  20137. * loaded, B is loaded as well. But there are cases when B is loaded where A
  20138. * is not loaded. So if we merge the chunks, all dependency side effects of
  20139. * A will be added to the correlated side effects of B, and as the latter is
  20140. * not allowed to change, the former need to be a subset of the latter.
  20141. *
  20142. * Another consideration when merging small chunks into other chunks is to
  20143. * avoid
  20144. * that too much additional code is loaded. This is achieved when the dependent
  20145. * entries of the small chunk are a subset of the dependent entries of the
  20146. * other
  20147. * chunk. Because then when the small chunk is loaded, the other chunk was
  20148. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  20149. * additional size of the small chunk is loaded unnecessarily.
  20150. *
  20151. * So the algorithm performs merges in two passes:
  20152. *
  20153. * 1. First we try to merge small chunks A only into other chunks B if the
  20154. * dependent entries of A are a subset of the dependent entries of B and the
  20155. * dependency side effects of A are a subset of the correlated side effects
  20156. * of B.
  20157. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  20158. * following the rule (a), starting with the smallest chunks to look for
  20159. * possible merge targets.
  20160. */
  20161. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  20162. timeStart('optimize chunks', 3);
  20163. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  20164. if (!chunkPartition) {
  20165. timeEnd('optimize chunks', 3);
  20166. return chunks; // the actual modules
  20167. }
  20168. if (minChunkSize > 1) {
  20169. log('info', parseAst_js.logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  20170. }
  20171. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  20172. if (minChunkSize > 1) {
  20173. log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  20174. }
  20175. timeEnd('optimize chunks', 3);
  20176. return [...chunkPartition.small, ...chunkPartition.big];
  20177. }
  20178. function getPartitionedChunks(chunks, minChunkSize) {
  20179. const smallChunks = [];
  20180. const bigChunks = [];
  20181. for (const chunk of chunks) {
  20182. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  20183. }
  20184. if (smallChunks.length === 0) {
  20185. return null;
  20186. }
  20187. smallChunks.sort(compareChunkSize);
  20188. bigChunks.sort(compareChunkSize);
  20189. return {
  20190. big: new Set(bigChunks),
  20191. small: new Set(smallChunks)
  20192. };
  20193. }
  20194. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  20195. return sizeA - sizeB;
  20196. }
  20197. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  20198. const { small } = chunkPartition;
  20199. for (const mergedChunk of small) {
  20200. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  20201. // In the default case, we do not accept size increases
  20202. minChunkSize <= 1 ? 1 : Infinity);
  20203. if (bestTargetChunk) {
  20204. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  20205. small.delete(mergedChunk);
  20206. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  20207. bestTargetChunk.modules.push(...modules);
  20208. bestTargetChunk.size += size;
  20209. bestTargetChunk.pure &&= pure;
  20210. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  20211. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  20212. bestTargetChunk.containedAtoms |= containedAtoms;
  20213. for (const entry of mergedChunk.dependentEntries) {
  20214. dependentEntries.add(entry);
  20215. }
  20216. for (const dependency of mergedChunk.dependencies) {
  20217. dependencies.add(dependency);
  20218. dependency.dependentChunks.delete(mergedChunk);
  20219. dependency.dependentChunks.add(bestTargetChunk);
  20220. }
  20221. for (const dependentChunk of mergedChunk.dependentChunks) {
  20222. dependentChunks.add(dependentChunk);
  20223. dependentChunk.dependencies.delete(mergedChunk);
  20224. dependentChunk.dependencies.add(bestTargetChunk);
  20225. }
  20226. dependencies.delete(bestTargetChunk);
  20227. dependentChunks.delete(bestTargetChunk);
  20228. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  20229. }
  20230. }
  20231. }
  20232. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  20233. let bestTargetChunk = null;
  20234. // In the default case, we do not accept size increases
  20235. for (const targetChunk of concatLazy([small, big])) {
  20236. if (mergedChunk === targetChunk)
  20237. continue;
  20238. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  20239. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  20240. bestTargetChunk = targetChunk;
  20241. if (additionalSizeAfterMerge === 0)
  20242. break;
  20243. smallestAdditionalSize = additionalSizeAfterMerge;
  20244. }
  20245. }
  20246. return bestTargetChunk;
  20247. }
  20248. /**
  20249. * Determine the additional unused code size that would be added by merging the
  20250. * two chunks. This is not an exact measurement but rather an upper bound. If
  20251. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  20252. * is returned.
  20253. * Merging will not produce cycles if none of the direct non-merged
  20254. * dependencies of a chunk have the other chunk as a transitive dependency.
  20255. */
  20256. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  20257. // The maximum additional unused code size allowed to be added by the merge,
  20258. // taking dependencies into account, needs to be below this number
  20259. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20260. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  20261. return firstSize < currentAdditionalSize
  20262. ? firstSize +
  20263. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  20264. : Infinity;
  20265. }
  20266. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20267. const { correlatedAtoms } = dependencyChunk;
  20268. let dependencyAtoms = dependentChunk.containedAtoms;
  20269. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  20270. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  20271. return Infinity;
  20272. }
  20273. const chunksToCheck = new Set(dependentChunk.dependencies);
  20274. for (const { dependencies, containedAtoms } of chunksToCheck) {
  20275. dependencyAtoms |= containedAtoms;
  20276. const containedSideEffects = containedAtoms & sideEffectAtoms;
  20277. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  20278. return Infinity;
  20279. }
  20280. for (const dependency of dependencies) {
  20281. if (dependency === dependencyChunk) {
  20282. return Infinity;
  20283. }
  20284. chunksToCheck.add(dependency);
  20285. }
  20286. }
  20287. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  20288. }
  20289. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  20290. let size = 0;
  20291. let atomIndex = 0;
  20292. let atomSignature = 1n;
  20293. const { length } = sizeByAtom;
  20294. for (; atomIndex < length; atomIndex++) {
  20295. if ((atoms & atomSignature) === atomSignature) {
  20296. size += sizeByAtom[atomIndex];
  20297. }
  20298. atomSignature <<= 1n;
  20299. if (size >= currentAdditionalSize) {
  20300. return Infinity;
  20301. }
  20302. }
  20303. return size;
  20304. }
  20305. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  20306. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  20307. }
  20308. // ported from https://github.com/substack/node-commondir
  20309. function commondir(files) {
  20310. if (files.length === 0)
  20311. return '/';
  20312. if (files.length === 1)
  20313. return path.dirname(files[0]);
  20314. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  20315. const pathSegments = file.split(/\/+|\\+/);
  20316. let index;
  20317. for (index = 0; commonSegments[index] === pathSegments[index] &&
  20318. index < Math.min(commonSegments.length, pathSegments.length); index++)
  20319. ;
  20320. return commonSegments.slice(0, index);
  20321. }, files[0].split(/\/+|\\+/));
  20322. // Windows correctly handles paths with forward-slashes
  20323. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  20324. }
  20325. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  20326. function sortByExecutionOrder(units) {
  20327. units.sort(compareExecIndex);
  20328. }
  20329. // This process is currently faulty in so far as it only takes the first entry
  20330. // module into account and assumes that dynamic imports are imported in a
  20331. // certain order.
  20332. // A better algorithm would follow every possible execution path and mark which
  20333. // modules are executed before or after which other modules. THen the chunking
  20334. // would need to take care that in each chunk, all modules are always executed
  20335. // in the same sequence.
  20336. function analyseModuleExecution(entryModules) {
  20337. let nextExecIndex = 0;
  20338. const cyclePaths = [];
  20339. const analysedModules = new Set();
  20340. const dynamicImports = new Set();
  20341. const parents = new Map();
  20342. const orderedModules = [];
  20343. const handleSyncLoadedModule = (module, parent) => {
  20344. if (parents.has(module)) {
  20345. if (!analysedModules.has(module)) {
  20346. cyclePaths.push(getCyclePath(module, parent, parents));
  20347. }
  20348. return;
  20349. }
  20350. parents.set(module, parent);
  20351. analyseModule(module);
  20352. };
  20353. const analyseModule = (module) => {
  20354. if (module instanceof Module) {
  20355. for (const dependency of module.dependencies) {
  20356. handleSyncLoadedModule(dependency, module);
  20357. }
  20358. for (const dependency of module.implicitlyLoadedBefore) {
  20359. dynamicImports.add(dependency);
  20360. }
  20361. for (const { resolution, node } of module.dynamicImports) {
  20362. if (resolution instanceof Module) {
  20363. if (node.withinTopLevelAwait) {
  20364. handleSyncLoadedModule(resolution, module);
  20365. }
  20366. else {
  20367. dynamicImports.add(resolution);
  20368. }
  20369. }
  20370. }
  20371. orderedModules.push(module);
  20372. }
  20373. module.execIndex = nextExecIndex++;
  20374. analysedModules.add(module);
  20375. };
  20376. for (const currentEntry of entryModules) {
  20377. if (!parents.has(currentEntry)) {
  20378. parents.set(currentEntry, null);
  20379. analyseModule(currentEntry);
  20380. }
  20381. }
  20382. for (const currentEntry of dynamicImports) {
  20383. if (!parents.has(currentEntry)) {
  20384. parents.set(currentEntry, null);
  20385. analyseModule(currentEntry);
  20386. }
  20387. }
  20388. return { cyclePaths, orderedModules };
  20389. }
  20390. function getCyclePath(module, parent, parents) {
  20391. const cycleSymbol = Symbol(module.id);
  20392. const path = [module.id];
  20393. let nextModule = parent;
  20394. module.cycles.add(cycleSymbol);
  20395. while (nextModule !== module) {
  20396. nextModule.cycles.add(cycleSymbol);
  20397. path.push(nextModule.id);
  20398. nextModule = parents.get(nextModule);
  20399. }
  20400. path.push(path[0]);
  20401. path.reverse();
  20402. return path;
  20403. }
  20404. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  20405. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  20406. const cnst = constBindings ? 'const' : 'var';
  20407. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  20408. const getFunctionIntro = arrowFunctions
  20409. ? (parameters, { isAsync, name }) => {
  20410. const singleParameter = parameters.length === 1;
  20411. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  20412. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  20413. }
  20414. : getNonArrowFunctionIntro;
  20415. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  20416. `${getFunctionIntro(parameters, {
  20417. isAsync: false,
  20418. name
  20419. })}${arrowFunctions
  20420. ? lineBreakIndent
  20421. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  20422. : ''
  20423. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  20424. arrowFunctions
  20425. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  20426. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  20427. ];
  20428. const isValidPropertyName = reservedNamesAsProps
  20429. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  20430. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  20431. return {
  20432. _,
  20433. cnst,
  20434. getDirectReturnFunction,
  20435. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  20436. const [left, right] = getDirectReturnFunction(parameters, {
  20437. functionReturn: true,
  20438. lineBreakIndent: null,
  20439. name: null
  20440. });
  20441. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  20442. },
  20443. getFunctionIntro,
  20444. getNonArrowFunctionIntro,
  20445. getObject(fields, { lineBreakIndent }) {
  20446. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  20447. return `{${fields
  20448. .map(([key, value]) => {
  20449. if (key === null)
  20450. return `${prefix}${value}`;
  20451. const keyInObject = stringifyObjectKeyIfNeeded(key);
  20452. return key === value && objectShorthand && key === keyInObject
  20453. ? prefix + key
  20454. : `${prefix}${keyInObject}:${_}${value}`;
  20455. })
  20456. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  20457. },
  20458. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  20459. n,
  20460. s
  20461. };
  20462. }
  20463. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  20464. class Source {
  20465. constructor(filename, content) {
  20466. this.isOriginal = true;
  20467. this.filename = filename;
  20468. this.content = content;
  20469. }
  20470. traceSegment(line, column, name) {
  20471. return { column, line, name, source: this };
  20472. }
  20473. }
  20474. class Link {
  20475. constructor(map, sources) {
  20476. this.sources = sources;
  20477. this.names = map.names;
  20478. this.mappings = map.mappings;
  20479. }
  20480. traceMappings() {
  20481. const sources = [];
  20482. const sourceIndexMap = new Map();
  20483. const sourcesContent = [];
  20484. const names = [];
  20485. const nameIndexMap = new Map();
  20486. const mappings = [];
  20487. for (const line of this.mappings) {
  20488. const tracedLine = [];
  20489. for (const segment of line) {
  20490. if (segment.length === 1)
  20491. continue;
  20492. const source = this.sources[segment[1]];
  20493. if (!source)
  20494. continue;
  20495. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  20496. if (traced) {
  20497. const { column, line, name, source: { content, filename } } = traced;
  20498. let sourceIndex = sourceIndexMap.get(filename);
  20499. if (sourceIndex === undefined) {
  20500. sourceIndex = sources.length;
  20501. sources.push(filename);
  20502. sourceIndexMap.set(filename, sourceIndex);
  20503. sourcesContent[sourceIndex] = content;
  20504. }
  20505. else if (sourcesContent[sourceIndex] == null) {
  20506. sourcesContent[sourceIndex] = content;
  20507. }
  20508. else if (content != null && sourcesContent[sourceIndex] !== content) {
  20509. return parseAst_js.error(parseAst_js.logConflictingSourcemapSources(filename));
  20510. }
  20511. const tracedSegment = [segment[0], sourceIndex, line, column];
  20512. if (name) {
  20513. let nameIndex = nameIndexMap.get(name);
  20514. if (nameIndex === undefined) {
  20515. nameIndex = names.length;
  20516. names.push(name);
  20517. nameIndexMap.set(name, nameIndex);
  20518. }
  20519. tracedSegment[4] = nameIndex;
  20520. }
  20521. tracedLine.push(tracedSegment);
  20522. }
  20523. }
  20524. mappings.push(tracedLine);
  20525. }
  20526. return { mappings, names, sources, sourcesContent };
  20527. }
  20528. traceSegment(line, column, name) {
  20529. const segments = this.mappings[line];
  20530. if (!segments)
  20531. return null;
  20532. // binary search through segments for the given column
  20533. let searchStart = 0;
  20534. let searchEnd = segments.length - 1;
  20535. while (searchStart <= searchEnd) {
  20536. const m = (searchStart + searchEnd) >> 1;
  20537. const segment = segments[m];
  20538. // If a sourcemap does not have sufficient resolution to contain a
  20539. // necessary mapping, e.g. because it only contains line information, we
  20540. // use the best approximation we could find
  20541. if (segment[0] === column || searchStart === searchEnd) {
  20542. if (segment.length == 1)
  20543. return null;
  20544. const source = this.sources[segment[1]];
  20545. if (!source)
  20546. return null;
  20547. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  20548. }
  20549. if (segment[0] > column) {
  20550. searchEnd = m - 1;
  20551. }
  20552. else {
  20553. searchStart = m + 1;
  20554. }
  20555. }
  20556. return null;
  20557. }
  20558. }
  20559. function getLinkMap(log) {
  20560. return function linkMap(source, map) {
  20561. if (!map.missing) {
  20562. return new Link(map, [source]);
  20563. }
  20564. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logSourcemapBroken(map.plugin));
  20565. return new Link({
  20566. mappings: [],
  20567. names: []
  20568. }, [source]);
  20569. };
  20570. }
  20571. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  20572. let source;
  20573. if (originalSourcemap) {
  20574. const sources = originalSourcemap.sources;
  20575. const sourcesContent = originalSourcemap.sourcesContent || [];
  20576. const directory = path.dirname(id) || '.';
  20577. const sourceRoot = originalSourcemap.sourceRoot || '.';
  20578. const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  20579. source = new Link(originalSourcemap, baseSources);
  20580. }
  20581. else {
  20582. source = new Source(id, originalCode);
  20583. }
  20584. return sourcemapChain.reduce(linkMap, source);
  20585. }
  20586. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  20587. const linkMap = getLinkMap(log);
  20588. const moduleSources = modules
  20589. .filter(module => !module.excludeFromSourcemap)
  20590. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  20591. const link = new Link(map, moduleSources);
  20592. const source = bundleSourcemapChain.reduce(linkMap, link);
  20593. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  20594. if (file) {
  20595. const directory = path.dirname(file);
  20596. sources = sources.map((source) => path.relative(directory, source));
  20597. file = path.basename(file);
  20598. }
  20599. sourcesContent = (excludeContent ? null : sourcesContent);
  20600. for (const module of modules) {
  20601. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  20602. }
  20603. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  20604. }
  20605. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  20606. if (sourcemapChain.length === 0) {
  20607. return originalSourcemap;
  20608. }
  20609. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  20610. const map = source.traceMappings();
  20611. return decodedSourcemap({ version: 3, ...map });
  20612. }
  20613. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  20614. // this for an actual sourceMappingURL
  20615. let SOURCEMAPPING_URL = 'sourceMa';
  20616. SOURCEMAPPING_URL += 'ppingURL';
  20617. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  20618. timeStart('render chunks', 2);
  20619. reserveEntryChunksInBundle(chunks);
  20620. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  20621. timeEnd('render chunks', 2);
  20622. timeStart('transform chunks', 2);
  20623. const getHash = hasherByType[outputOptions.hashCharacters];
  20624. const chunkGraph = getChunkGraph(chunks);
  20625. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  20626. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  20627. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  20628. timeEnd('transform chunks', 2);
  20629. }
  20630. function reserveEntryChunksInBundle(chunks) {
  20631. for (const chunk of chunks) {
  20632. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  20633. // reserves name in bundle as side effect if it does not contain a hash
  20634. chunk.getPreliminaryFileName();
  20635. }
  20636. }
  20637. }
  20638. function getChunkGraph(chunks) {
  20639. return Object.fromEntries(chunks.map(chunk => {
  20640. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  20641. return [renderedChunkInfo.fileName, renderedChunkInfo];
  20642. }));
  20643. }
  20644. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  20645. let map = null;
  20646. const sourcemapChain = [];
  20647. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  20648. if (result == null)
  20649. return code;
  20650. if (typeof result === 'string')
  20651. result = {
  20652. code: result,
  20653. map: undefined
  20654. };
  20655. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  20656. if (result.map !== null) {
  20657. const map = decodedSourcemap(result.map);
  20658. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  20659. }
  20660. return result.code;
  20661. });
  20662. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  20663. if (!compact && code[code.length - 1] !== '\n')
  20664. code += '\n';
  20665. if (sourcemap) {
  20666. timeStart('sourcemaps', 3);
  20667. let resultingFile;
  20668. if (file)
  20669. resultingFile = path.resolve(sourcemapFile || file);
  20670. else if (dir)
  20671. resultingFile = path.resolve(dir, fileName);
  20672. else
  20673. resultingFile = path.resolve(fileName);
  20674. const decodedMap = magicString.generateDecodedMap({});
  20675. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  20676. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  20677. let sourcePath = map.sources[sourcesIndex];
  20678. const sourcemapPath = `${resultingFile}.map`;
  20679. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  20680. if (typeof ignoreList !== 'boolean') {
  20681. parseAst_js.error(parseAst_js.logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  20682. }
  20683. if (ignoreList) {
  20684. if (map.x_google_ignoreList === undefined) {
  20685. map.x_google_ignoreList = [];
  20686. }
  20687. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  20688. map.x_google_ignoreList.push(sourcesIndex);
  20689. }
  20690. }
  20691. if (sourcemapPathTransform) {
  20692. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  20693. if (typeof sourcePath !== 'string') {
  20694. parseAst_js.error(parseAst_js.logFailedValidation(`sourcemapPathTransform function must return a string.`));
  20695. }
  20696. }
  20697. map.sources[sourcesIndex] = parseAst_js.normalize(sourcePath);
  20698. }
  20699. timeEnd('sourcemaps', 3);
  20700. }
  20701. return {
  20702. code,
  20703. map
  20704. };
  20705. }
  20706. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  20707. const nonHashedChunksWithPlaceholders = [];
  20708. const renderedChunksByPlaceholder = new Map();
  20709. const hashDependenciesByPlaceholder = new Map();
  20710. const initialHashesByPlaceholder = new Map();
  20711. const placeholders = new Set();
  20712. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  20713. if (hashPlaceholder)
  20714. placeholders.add(hashPlaceholder);
  20715. }
  20716. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  20717. const transformedChunk = {
  20718. chunk,
  20719. fileName,
  20720. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  20721. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  20722. };
  20723. const { code, map } = transformedChunk;
  20724. if (hashPlaceholder) {
  20725. // To create a reproducible content-only hash, all placeholders are
  20726. // replaced with the same value before hashing
  20727. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  20728. let contentToHash = transformedCode;
  20729. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  20730. if (pluginHash) {
  20731. augmentation += pluginHash;
  20732. }
  20733. return augmentation;
  20734. });
  20735. if (hashAugmentation) {
  20736. contentToHash += hashAugmentation;
  20737. }
  20738. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  20739. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  20740. containedPlaceholders,
  20741. contentHash: getHash(contentToHash)
  20742. });
  20743. }
  20744. else {
  20745. nonHashedChunksWithPlaceholders.push(transformedChunk);
  20746. }
  20747. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  20748. if (map && sourcemapHashPlaceholder) {
  20749. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  20750. }
  20751. }));
  20752. return {
  20753. hashDependenciesByPlaceholder,
  20754. initialHashesByPlaceholder,
  20755. nonHashedChunksWithPlaceholders,
  20756. placeholders,
  20757. renderedChunksByPlaceholder
  20758. };
  20759. }
  20760. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  20761. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  20762. for (const placeholder of placeholders) {
  20763. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  20764. let contentToHash = '';
  20765. const hashDependencyPlaceholders = new Set([placeholder]);
  20766. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  20767. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  20768. contentToHash += contentHash;
  20769. for (const containedPlaceholder of containedPlaceholders) {
  20770. // When looping over a map, setting an entry only causes a new iteration if the key is new
  20771. hashDependencyPlaceholders.add(containedPlaceholder);
  20772. }
  20773. }
  20774. let finalFileName;
  20775. let finalHash;
  20776. do {
  20777. // In case of a hash collision, create a hash of the hash
  20778. if (finalHash) {
  20779. contentToHash = finalHash;
  20780. }
  20781. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  20782. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  20783. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  20784. bundle[finalFileName] = FILE_PLACEHOLDER;
  20785. hashesByPlaceholder.set(placeholder, finalHash);
  20786. }
  20787. return hashesByPlaceholder;
  20788. }
  20789. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  20790. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  20791. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  20792. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  20793. let finalSourcemapFileName = null;
  20794. if (map) {
  20795. if (options.sourcemapDebugIds) {
  20796. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20797. }
  20798. finalSourcemapFileName = sourcemapFileName
  20799. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20800. : `${finalFileName}.map`;
  20801. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  20802. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20803. }
  20804. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  20805. }
  20806. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  20807. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  20808. let finalSourcemapFileName = null;
  20809. if (map) {
  20810. if (options.sourcemapDebugIds) {
  20811. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20812. }
  20813. finalSourcemapFileName = sourcemapFileName
  20814. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20815. : `${fileName}.map`;
  20816. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20817. }
  20818. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  20819. }
  20820. }
  20821. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  20822. let url;
  20823. if (sourcemap === 'inline') {
  20824. url = map.toUrl();
  20825. }
  20826. else {
  20827. const sourcemapFileName = path.basename(fileName);
  20828. url = sourcemapBaseUrl
  20829. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  20830. : sourcemapFileName;
  20831. pluginDriver.emitFile({
  20832. fileName,
  20833. originalFileName: null,
  20834. source: map.toString(),
  20835. type: 'asset'
  20836. });
  20837. }
  20838. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  20839. }
  20840. function calculateDebugIdAndGetComment(code, map) {
  20841. const hash = hasherByType.hex(code);
  20842. const debugId = [
  20843. hash.slice(0, 8),
  20844. hash.slice(8, 12),
  20845. '4' + hash.slice(12, 15),
  20846. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  20847. hash.slice(20, 32)
  20848. ].join('-');
  20849. map.debugId = debugId;
  20850. return '//# debugId=' + debugId + '\n';
  20851. }
  20852. class Bundle {
  20853. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  20854. this.outputOptions = outputOptions;
  20855. this.unsetOptions = unsetOptions;
  20856. this.inputOptions = inputOptions;
  20857. this.pluginDriver = pluginDriver;
  20858. this.graph = graph;
  20859. this.facadeChunkByModule = new Map();
  20860. this.includedNamespaces = new Set();
  20861. }
  20862. async generate(isWrite) {
  20863. timeStart('GENERATE', 1);
  20864. const outputBundleBase = Object.create(null);
  20865. const outputBundle = getOutputBundle(outputBundleBase);
  20866. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  20867. try {
  20868. timeStart('initialize render', 2);
  20869. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  20870. timeEnd('initialize render', 2);
  20871. timeStart('generate chunks', 2);
  20872. const getHashPlaceholder = getHashPlaceholderGenerator();
  20873. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  20874. if (chunks.length > 1) {
  20875. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  20876. }
  20877. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  20878. for (const chunk of chunks) {
  20879. chunk.generateExports();
  20880. chunk.inlineTransitiveImports();
  20881. }
  20882. timeEnd('generate chunks', 2);
  20883. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  20884. }
  20885. catch (error_) {
  20886. await this.pluginDriver.hookParallel('renderError', [error_]);
  20887. throw error_;
  20888. }
  20889. removeUnreferencedAssets(outputBundle);
  20890. timeStart('generate bundle', 2);
  20891. await this.pluginDriver.hookSeq('generateBundle', [
  20892. this.outputOptions,
  20893. outputBundle,
  20894. isWrite
  20895. ]);
  20896. this.finaliseAssets(outputBundle);
  20897. timeEnd('generate bundle', 2);
  20898. timeEnd('GENERATE', 1);
  20899. return outputBundleBase;
  20900. }
  20901. async addManualChunks(manualChunks) {
  20902. const manualChunkAliasByEntry = new Map();
  20903. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  20904. alias,
  20905. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  20906. })));
  20907. for (const { alias, entries } of chunkEntries) {
  20908. for (const entry of entries) {
  20909. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  20910. }
  20911. }
  20912. return manualChunkAliasByEntry;
  20913. }
  20914. assignManualChunks(getManualChunk) {
  20915. const manualChunkAliasesWithEntry = [];
  20916. const manualChunksApi = {
  20917. getModuleIds: () => this.graph.modulesById.keys(),
  20918. getModuleInfo: this.graph.getModuleInfo
  20919. };
  20920. for (const module of this.graph.modulesById.values()) {
  20921. if (module instanceof Module) {
  20922. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  20923. if (typeof manualChunkAlias === 'string') {
  20924. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  20925. }
  20926. }
  20927. }
  20928. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  20929. const manualChunkAliasByEntry = new Map();
  20930. for (const [alias, module] of manualChunkAliasesWithEntry) {
  20931. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  20932. }
  20933. return manualChunkAliasByEntry;
  20934. }
  20935. finaliseAssets(bundle) {
  20936. if (this.outputOptions.validate) {
  20937. for (const file of Object.values(bundle)) {
  20938. if ('code' in file) {
  20939. try {
  20940. parseAst_js.parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  20941. }
  20942. catch (error_) {
  20943. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logChunkInvalid(file, error_));
  20944. }
  20945. }
  20946. }
  20947. }
  20948. this.pluginDriver.finaliseAssets();
  20949. }
  20950. async generateChunks(bundle, getHashPlaceholder) {
  20951. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  20952. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  20953. ? await this.addManualChunks(manualChunks)
  20954. : this.assignManualChunks(manualChunks);
  20955. const snippets = getGenerateCodeSnippets(this.outputOptions);
  20956. const includedModules = getIncludedModules(this.graph.modulesById);
  20957. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  20958. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  20959. const executableModule = inlineDynamicImports
  20960. ? [{ alias: null, modules: includedModules }]
  20961. : preserveModules
  20962. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  20963. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog);
  20964. const chunks = new Array(executableModule.length);
  20965. const chunkByModule = new Map();
  20966. let index = 0;
  20967. for (const { alias, modules } of executableModule) {
  20968. sortByExecutionOrder(modules);
  20969. 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);
  20970. chunks[index++] = chunk;
  20971. }
  20972. for (const chunk of chunks) {
  20973. chunk.link();
  20974. }
  20975. const facades = [];
  20976. for (const chunk of chunks) {
  20977. facades.push(...chunk.generateFacades());
  20978. }
  20979. return [...chunks, ...facades];
  20980. }
  20981. }
  20982. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  20983. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  20984. return parseAst_js.error(parseAst_js.logInvalidOption('output.format', parseAst_js.URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  20985. if (typeof outputOptions.file === 'string')
  20986. return parseAst_js.error(parseAst_js.logInvalidOption('output.file', parseAst_js.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'));
  20987. if (outputOptions.sourcemapFile)
  20988. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapFile', parseAst_js.URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  20989. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  20990. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidOption('output.amd.id', parseAst_js.URL_OUTPUT_AMD_ID, 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  20991. }
  20992. function getIncludedModules(modulesById) {
  20993. const includedModules = [];
  20994. for (const module of modulesById.values()) {
  20995. if (module instanceof Module &&
  20996. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  20997. includedModules.push(module);
  20998. }
  20999. }
  21000. return includedModules;
  21001. }
  21002. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  21003. const absoluteEntryModulePaths = [];
  21004. for (const module of includedModules) {
  21005. if ((module.info.isEntry || preserveModules) && parseAst_js.isAbsolute(module.id)) {
  21006. absoluteEntryModulePaths.push(module.id);
  21007. }
  21008. }
  21009. return absoluteEntryModulePaths;
  21010. }
  21011. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  21012. const externalChunkByModule = new Map();
  21013. for (const module of modulesById.values()) {
  21014. if (module instanceof ExternalModule) {
  21015. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  21016. }
  21017. }
  21018. return externalChunkByModule;
  21019. }
  21020. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  21021. const existingAlias = manualChunkAliasByEntry.get(module);
  21022. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  21023. return parseAst_js.error(parseAst_js.logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  21024. }
  21025. manualChunkAliasByEntry.set(module, alias);
  21026. }
  21027. function flru (max) {
  21028. var num, curr, prev;
  21029. var limit = max;
  21030. function keep(key, value) {
  21031. if (++num > limit) {
  21032. prev = curr;
  21033. reset(1);
  21034. ++num;
  21035. }
  21036. curr[key] = value;
  21037. }
  21038. function reset(isPartial) {
  21039. num = 0;
  21040. curr = Object.create(null);
  21041. isPartial || (prev=Object.create(null));
  21042. }
  21043. reset();
  21044. return {
  21045. clear: reset,
  21046. has: function (key) {
  21047. return curr[key] !== void 0 || prev[key] !== void 0;
  21048. },
  21049. get: function (key) {
  21050. var val = curr[key];
  21051. if (val !== void 0) return val;
  21052. if ((val=prev[key]) !== void 0) {
  21053. keep(key, val);
  21054. return val;
  21055. }
  21056. },
  21057. set: function (key, value) {
  21058. if (curr[key] !== void 0) {
  21059. curr[key] = value;
  21060. } else {
  21061. keep(key, value);
  21062. }
  21063. }
  21064. };
  21065. }
  21066. class GlobalScope extends Scope {
  21067. constructor() {
  21068. super();
  21069. this.parent = null;
  21070. this.variables.set('undefined', new UndefinedVariable());
  21071. }
  21072. findVariable(name) {
  21073. let variable = this.variables.get(name);
  21074. if (!variable) {
  21075. variable = new GlobalVariable(name);
  21076. this.variables.set(name, variable);
  21077. }
  21078. return variable;
  21079. }
  21080. }
  21081. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  21082. let skipped = null;
  21083. let replaceContext = null;
  21084. if (skip) {
  21085. skipped = new Set();
  21086. for (const skippedCall of skip) {
  21087. if (source === skippedCall.source && importer === skippedCall.importer) {
  21088. skipped.add(skippedCall.plugin);
  21089. }
  21090. }
  21091. replaceContext = (pluginContext, plugin) => ({
  21092. ...pluginContext,
  21093. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) => {
  21094. skipSelf ??= true;
  21095. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  21096. }
  21097. });
  21098. }
  21099. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  21100. }
  21101. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  21102. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  21103. if (pluginResult != null) {
  21104. const [resolveIdResult, plugin] = pluginResult;
  21105. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  21106. return {
  21107. ...resolveIdResult,
  21108. resolvedBy: plugin.name
  21109. };
  21110. }
  21111. if (typeof resolveIdResult === 'string') {
  21112. return {
  21113. id: resolveIdResult,
  21114. resolvedBy: plugin.name
  21115. };
  21116. }
  21117. return resolveIdResult;
  21118. }
  21119. // external modules (non-entry modules that start with neither '.' or '/')
  21120. // are skipped at this stage.
  21121. if (importer !== undefined && !parseAst_js.isAbsolute(source) && source[0] !== '.')
  21122. return null;
  21123. // `resolve` processes paths from right to left, prepending them until an
  21124. // absolute path is created. Absolute importees therefore shortcircuit the
  21125. // resolve call and require no special handing on our part.
  21126. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  21127. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
  21128. }
  21129. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  21130. return ((await findFile(file, preserveSymlinks)) ??
  21131. (await findFile(file + '.mjs', preserveSymlinks)) ??
  21132. (await findFile(file + '.js', preserveSymlinks)));
  21133. }
  21134. async function findFile(file, preserveSymlinks) {
  21135. try {
  21136. const stats = await promises.lstat(file);
  21137. if (!preserveSymlinks && stats.isSymbolicLink())
  21138. return await findFile(await promises.realpath(file), preserveSymlinks);
  21139. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  21140. // check case
  21141. const name = path.basename(file);
  21142. const files = await promises.readdir(path.dirname(file));
  21143. if (files.includes(name))
  21144. return file;
  21145. }
  21146. }
  21147. catch {
  21148. // suppress
  21149. }
  21150. }
  21151. function stripBom(content) {
  21152. if (content.charCodeAt(0) === 0xfe_ff) {
  21153. return stripBom(content.slice(1));
  21154. }
  21155. return content;
  21156. }
  21157. async function transform(source, module, pluginDriver, log) {
  21158. const id = module.id;
  21159. const sourcemapChain = [];
  21160. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  21161. const originalCode = source.code;
  21162. let ast = source.ast;
  21163. const transformDependencies = [];
  21164. const emittedFiles = [];
  21165. let customTransformCache = false;
  21166. const useCustomTransformCache = () => (customTransformCache = true);
  21167. let pluginName = '';
  21168. let currentSource = source.code;
  21169. function transformReducer(previousCode, result, plugin) {
  21170. let code;
  21171. let map;
  21172. if (typeof result === 'string') {
  21173. code = result;
  21174. }
  21175. else if (result && typeof result === 'object') {
  21176. module.updateOptions(result);
  21177. if (result.code == null) {
  21178. if (result.map || result.ast) {
  21179. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNoTransformMapOrAstWithoutCode(plugin.name));
  21180. }
  21181. return previousCode;
  21182. }
  21183. ({ code, map, ast } = result);
  21184. }
  21185. else {
  21186. return previousCode;
  21187. }
  21188. // strict null check allows 'null' maps to not be pushed to the chain,
  21189. // while 'undefined' gets the missing map warning
  21190. if (map !== null) {
  21191. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  21192. missing: true,
  21193. plugin: plugin.name
  21194. });
  21195. }
  21196. currentSource = code;
  21197. return code;
  21198. }
  21199. const getLogHandler = (handler) => (log, pos) => {
  21200. log = normalizeLog(log);
  21201. if (pos)
  21202. parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
  21203. log.id = id;
  21204. log.hook = 'transform';
  21205. handler(log);
  21206. };
  21207. let code;
  21208. try {
  21209. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  21210. pluginName = plugin.name;
  21211. return {
  21212. ...pluginContext,
  21213. addWatchFile(id) {
  21214. transformDependencies.push(id);
  21215. pluginContext.addWatchFile(id);
  21216. },
  21217. cache: customTransformCache
  21218. ? pluginContext.cache
  21219. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  21220. debug: getLogHandler(pluginContext.debug),
  21221. emitFile(emittedFile) {
  21222. emittedFiles.push(emittedFile);
  21223. return pluginDriver.emitFile(emittedFile);
  21224. },
  21225. error(error_, pos) {
  21226. if (typeof error_ === 'string')
  21227. error_ = { message: error_ };
  21228. if (pos)
  21229. parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
  21230. error_.id = id;
  21231. error_.hook = 'transform';
  21232. return pluginContext.error(error_);
  21233. },
  21234. getCombinedSourcemap() {
  21235. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  21236. if (!combinedMap) {
  21237. const magicString = new MagicString(originalCode);
  21238. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  21239. }
  21240. if (originalSourcemap !== combinedMap) {
  21241. originalSourcemap = combinedMap;
  21242. sourcemapChain.length = 0;
  21243. }
  21244. return new SourceMap({
  21245. ...combinedMap,
  21246. file: null,
  21247. sourcesContent: combinedMap.sourcesContent
  21248. });
  21249. },
  21250. info: getLogHandler(pluginContext.info),
  21251. setAssetSource() {
  21252. return this.error(parseAst_js.logInvalidSetAssetSourceCall());
  21253. },
  21254. warn: getLogHandler(pluginContext.warn)
  21255. };
  21256. });
  21257. }
  21258. catch (error_) {
  21259. return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
  21260. }
  21261. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  21262. emittedFiles.length > 0)
  21263. module.transformFiles = emittedFiles;
  21264. return {
  21265. ast,
  21266. code,
  21267. customTransformCache,
  21268. originalCode,
  21269. originalSourcemap,
  21270. sourcemapChain,
  21271. transformDependencies
  21272. };
  21273. }
  21274. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  21275. class ModuleLoader {
  21276. constructor(graph, modulesById, options, pluginDriver) {
  21277. this.graph = graph;
  21278. this.modulesById = modulesById;
  21279. this.options = options;
  21280. this.pluginDriver = pluginDriver;
  21281. this.implicitEntryModules = new Set();
  21282. this.indexedEntryModules = [];
  21283. this.latestLoadModulesPromise = Promise.resolve();
  21284. this.moduleLoadPromises = new Map();
  21285. this.modulesWithLoadedDependencies = new Set();
  21286. this.nextChunkNamePriority = 0;
  21287. this.nextEntryModuleIndex = 0;
  21288. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  21289. ? false
  21290. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  21291. this.hasModuleSideEffects = options.treeshake
  21292. ? options.treeshake.moduleSideEffects
  21293. : () => true;
  21294. }
  21295. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  21296. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  21297. await this.awaitLoadModulesPromise();
  21298. return result;
  21299. }
  21300. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  21301. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  21302. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  21303. const firstChunkNamePriority = this.nextChunkNamePriority;
  21304. this.nextChunkNamePriority += unresolvedEntryModules.length;
  21305. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  21306. for (const [index, entryModule] of entryModules.entries()) {
  21307. entryModule.isUserDefinedEntryPoint =
  21308. entryModule.isUserDefinedEntryPoint || isUserDefined;
  21309. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  21310. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  21311. if (existingIndexedModule) {
  21312. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  21313. }
  21314. else {
  21315. this.indexedEntryModules.push({
  21316. index: firstEntryModuleIndex + index,
  21317. module: entryModule
  21318. });
  21319. }
  21320. }
  21321. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  21322. return entryModules;
  21323. }));
  21324. await this.awaitLoadModulesPromise();
  21325. return {
  21326. entryModules: this.indexedEntryModules.map(({ module }) => module),
  21327. implicitEntryModules: [...this.implicitEntryModules],
  21328. newEntryModules
  21329. };
  21330. }
  21331. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  21332. const unresolvedModule = {
  21333. fileName: fileName || null,
  21334. id,
  21335. importer,
  21336. name: name || null
  21337. };
  21338. const module = implicitlyLoadedAfterOneOf
  21339. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  21340. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  21341. if (preserveSignature != null) {
  21342. module.preserveSignature = preserveSignature;
  21343. }
  21344. return module;
  21345. }
  21346. async preloadModule(resolvedId) {
  21347. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  21348. return module.info;
  21349. }
  21350. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  21351. const chunkNamePriority = this.nextChunkNamePriority++;
  21352. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  21353. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  21354. if (!entryModule.info.isEntry) {
  21355. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  21356. // We need to check again if this is still an entry module as these
  21357. // changes need to be performed atomically to avoid race conditions
  21358. // if the same module is re-emitted as an entry module.
  21359. // The inverse changes happen in "handleExistingModule"
  21360. if (!entryModule.info.isEntry) {
  21361. this.implicitEntryModules.add(entryModule);
  21362. for (const module of implicitlyLoadedAfterModules) {
  21363. entryModule.implicitlyLoadedAfter.add(module);
  21364. }
  21365. for (const dependant of entryModule.implicitlyLoadedAfter) {
  21366. dependant.implicitlyLoadedBefore.add(entryModule);
  21367. }
  21368. }
  21369. }
  21370. return entryModule;
  21371. }));
  21372. }
  21373. async addModuleSource(id, importer, module) {
  21374. let source;
  21375. try {
  21376. source = await this.graph.fileOperationQueue.run(async () => {
  21377. const content = await this.pluginDriver.hookFirst('load', [id]);
  21378. if (content !== null)
  21379. return content;
  21380. this.graph.watchFiles[id] = true;
  21381. return await promises.readFile(id, 'utf8');
  21382. });
  21383. }
  21384. catch (error_) {
  21385. let message = `Could not load ${id}`;
  21386. if (importer)
  21387. message += ` (imported by ${parseAst_js.relativeId(importer)})`;
  21388. message += `: ${error_.message}`;
  21389. error_.message = message;
  21390. throw error_;
  21391. }
  21392. const sourceDescription = typeof source === 'string'
  21393. ? { code: source }
  21394. : source != null && typeof source === 'object' && typeof source.code === 'string'
  21395. ? source
  21396. : parseAst_js.error(parseAst_js.logBadLoader(id));
  21397. sourceDescription.code = stripBom(sourceDescription.code);
  21398. const cachedModule = this.graph.cachedModules.get(id);
  21399. if (cachedModule &&
  21400. !cachedModule.customTransformCache &&
  21401. cachedModule.originalCode === sourceDescription.code &&
  21402. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  21403. {
  21404. ast: cachedModule.ast,
  21405. code: cachedModule.code,
  21406. id: cachedModule.id,
  21407. meta: cachedModule.meta,
  21408. moduleSideEffects: cachedModule.moduleSideEffects,
  21409. resolvedSources: cachedModule.resolvedIds,
  21410. syntheticNamedExports: cachedModule.syntheticNamedExports
  21411. }
  21412. ]))) {
  21413. if (cachedModule.transformFiles) {
  21414. for (const emittedFile of cachedModule.transformFiles)
  21415. this.pluginDriver.emitFile(emittedFile);
  21416. }
  21417. await module.setSource(cachedModule);
  21418. }
  21419. else {
  21420. module.updateOptions(sourceDescription);
  21421. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  21422. }
  21423. }
  21424. async awaitLoadModulesPromise() {
  21425. let startingPromise;
  21426. do {
  21427. startingPromise = this.latestLoadModulesPromise;
  21428. await startingPromise;
  21429. } while (startingPromise !== this.latestLoadModulesPromise);
  21430. }
  21431. extendLoadModulesPromise(loadNewModulesPromise) {
  21432. this.latestLoadModulesPromise = Promise.all([
  21433. loadNewModulesPromise,
  21434. this.latestLoadModulesPromise
  21435. ]);
  21436. this.latestLoadModulesPromise.catch(() => {
  21437. /* Avoid unhandled Promise rejections */
  21438. });
  21439. return loadNewModulesPromise;
  21440. }
  21441. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  21442. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  21443. if (resolvedId === null)
  21444. return null;
  21445. if (typeof resolvedId === 'string') {
  21446. dynamicImport.resolution = resolvedId;
  21447. return null;
  21448. }
  21449. return (dynamicImport.resolution = await this.fetchResolvedDependency(parseAst_js.relativeId(resolvedId.id), module.id, resolvedId));
  21450. })));
  21451. for (const dependency of dependencies) {
  21452. if (dependency) {
  21453. module.dynamicDependencies.add(dependency);
  21454. dependency.dynamicImporters.push(module.id);
  21455. }
  21456. }
  21457. }
  21458. // If this is a preload, then this method always waits for the dependencies of
  21459. // the module to be resolved.
  21460. // Otherwise, if the module does not exist, it waits for the module and all
  21461. // its dependencies to be loaded.
  21462. // Otherwise, it returns immediately.
  21463. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  21464. const existingModule = this.modulesById.get(id);
  21465. if (existingModule instanceof Module) {
  21466. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  21467. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  21468. }
  21469. await this.handleExistingModule(existingModule, isEntry, isPreload);
  21470. return existingModule;
  21471. }
  21472. if (existingModule instanceof ExternalModule) {
  21473. return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
  21474. }
  21475. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  21476. this.modulesById.set(id, module);
  21477. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  21478. this.getResolveStaticDependencyPromises(module),
  21479. this.getResolveDynamicImportPromises(module),
  21480. loadAndResolveDependenciesPromise
  21481. ]);
  21482. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  21483. loadAndResolveDependenciesPromise.catch(() => {
  21484. /* avoid unhandled promise rejections */
  21485. });
  21486. this.moduleLoadPromises.set(module, loadPromise);
  21487. const resolveDependencyPromises = await loadPromise;
  21488. if (!isPreload) {
  21489. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  21490. }
  21491. else if (isPreload === RESOLVE_DEPENDENCIES) {
  21492. await loadAndResolveDependenciesPromise;
  21493. }
  21494. return module;
  21495. }
  21496. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  21497. if (this.modulesWithLoadedDependencies.has(module)) {
  21498. return;
  21499. }
  21500. this.modulesWithLoadedDependencies.add(module);
  21501. await Promise.all([
  21502. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  21503. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  21504. ]);
  21505. module.linkImports();
  21506. // To handle errors when resolving dependencies or in moduleParsed
  21507. await loadAndResolveDependenciesPromise;
  21508. }
  21509. fetchResolvedDependency(source, importer, resolvedId) {
  21510. if (resolvedId.external) {
  21511. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  21512. let externalModule = this.modulesById.get(id);
  21513. if (!externalModule) {
  21514. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
  21515. this.modulesById.set(id, externalModule);
  21516. }
  21517. else if (!(externalModule instanceof ExternalModule)) {
  21518. return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
  21519. }
  21520. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  21521. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  21522. }
  21523. return Promise.resolve(externalModule);
  21524. }
  21525. return this.fetchModule(resolvedId, importer, false, false);
  21526. }
  21527. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  21528. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  21529. module.dependencies.add(dependency);
  21530. dependency.importers.push(module.id);
  21531. }
  21532. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  21533. for (const dependency of module.dependencies) {
  21534. if (dependency instanceof Module) {
  21535. dependency.importedFromNotTreeshaken = true;
  21536. }
  21537. }
  21538. }
  21539. }
  21540. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  21541. const { makeAbsoluteExternalsRelative } = this.options;
  21542. if (resolveIdResult) {
  21543. if (typeof resolveIdResult === 'object') {
  21544. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  21545. return {
  21546. ...resolveIdResult,
  21547. external: external &&
  21548. (external === 'relative' ||
  21549. !parseAst_js.isAbsolute(resolveIdResult.id) ||
  21550. (external === true &&
  21551. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  21552. 'absolute')
  21553. };
  21554. }
  21555. const external = this.options.external(resolveIdResult, importer, true);
  21556. return {
  21557. external: external &&
  21558. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  21559. 'absolute'),
  21560. id: external && makeAbsoluteExternalsRelative
  21561. ? normalizeRelativeExternalId(resolveIdResult, importer)
  21562. : resolveIdResult
  21563. };
  21564. }
  21565. const id = makeAbsoluteExternalsRelative
  21566. ? normalizeRelativeExternalId(source, importer)
  21567. : source;
  21568. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  21569. return null;
  21570. }
  21571. return {
  21572. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  21573. id
  21574. };
  21575. }
  21576. getResolveDynamicImportPromises(module) {
  21577. return module.dynamicImports.map(async (dynamicImport) => {
  21578. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  21579. if (resolvedId && typeof resolvedId === 'object') {
  21580. dynamicImport.id = resolvedId.id;
  21581. }
  21582. return [dynamicImport, resolvedId];
  21583. });
  21584. }
  21585. getResolveStaticDependencyPromises(module) {
  21586. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  21587. source,
  21588. (module.resolvedIds[source] =
  21589. module.resolvedIds[source] ||
  21590. this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  21591. ]);
  21592. }
  21593. getResolvedIdWithDefaults(resolvedId, attributes) {
  21594. if (!resolvedId) {
  21595. return null;
  21596. }
  21597. const external = resolvedId.external || false;
  21598. return {
  21599. attributes: resolvedId.attributes || attributes,
  21600. external,
  21601. id: resolvedId.id,
  21602. meta: resolvedId.meta || {},
  21603. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  21604. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  21605. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  21606. };
  21607. }
  21608. async handleExistingModule(module, isEntry, isPreload) {
  21609. const loadPromise = this.moduleLoadPromises.get(module);
  21610. if (isPreload) {
  21611. return isPreload === RESOLVE_DEPENDENCIES
  21612. ? waitForDependencyResolution(loadPromise)
  21613. : loadPromise;
  21614. }
  21615. if (isEntry) {
  21616. // This reverts the changes in addEntryWithImplicitDependants and needs to
  21617. // be performed atomically
  21618. module.info.isEntry = true;
  21619. this.implicitEntryModules.delete(module);
  21620. for (const dependant of module.implicitlyLoadedAfter) {
  21621. dependant.implicitlyLoadedBefore.delete(module);
  21622. }
  21623. module.implicitlyLoadedAfter.clear();
  21624. }
  21625. return this.fetchModuleDependencies(module, ...(await loadPromise));
  21626. }
  21627. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  21628. if (resolvedId === null) {
  21629. if (parseAst_js.isRelative(source)) {
  21630. return parseAst_js.error(parseAst_js.logUnresolvedImport(source, importer));
  21631. }
  21632. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnresolvedImportTreatedAsExternal(source, importer));
  21633. return {
  21634. attributes,
  21635. external: true,
  21636. id: source,
  21637. meta: {},
  21638. moduleSideEffects: this.hasModuleSideEffects(source, true),
  21639. resolvedBy: 'rollup',
  21640. syntheticNamedExports: false
  21641. };
  21642. }
  21643. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  21644. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logExternalSyntheticExports(source, importer));
  21645. }
  21646. return resolvedId;
  21647. }
  21648. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  21649. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT);
  21650. if (resolveIdResult == null) {
  21651. return parseAst_js.error(implicitlyLoadedBefore === null
  21652. ? parseAst_js.logUnresolvedEntry(unresolvedId)
  21653. : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  21654. }
  21655. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  21656. if (resolveIdResult === false || isExternalModules) {
  21657. return parseAst_js.error(implicitlyLoadedBefore === null
  21658. ? isExternalModules && isLoadForManualChunks
  21659. ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  21660. : parseAst_js.logEntryCannotBeExternal(unresolvedId)
  21661. : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  21662. }
  21663. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  21664. ? resolveIdResult
  21665. : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
  21666. }
  21667. async resolveDynamicImport(module, specifier, importer, attributes) {
  21668. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  21669. specifier,
  21670. importer,
  21671. { attributes }
  21672. ]);
  21673. if (typeof specifier !== 'string') {
  21674. if (typeof resolution === 'string') {
  21675. return resolution;
  21676. }
  21677. if (!resolution) {
  21678. return null;
  21679. }
  21680. return this.getResolvedIdWithDefaults(resolution, attributes);
  21681. }
  21682. if (resolution == null) {
  21683. const existingResolution = module.resolvedIds[specifier];
  21684. if (existingResolution) {
  21685. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  21686. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  21687. }
  21688. return existingResolution;
  21689. }
  21690. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  21691. }
  21692. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  21693. }
  21694. }
  21695. function normalizeRelativeExternalId(source, importer) {
  21696. return parseAst_js.isRelative(source)
  21697. ? importer
  21698. ? path.resolve(importer, '..', source)
  21699. : path.resolve(source)
  21700. : source;
  21701. }
  21702. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  21703. if (fileName !== null) {
  21704. module.chunkFileNames.add(fileName);
  21705. }
  21706. else if (name !== null) {
  21707. // Always keep chunkNames sorted by priority
  21708. let namePosition = 0;
  21709. while (module.chunkNames[namePosition]?.priority < priority)
  21710. namePosition++;
  21711. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  21712. }
  21713. }
  21714. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  21715. return (makeAbsoluteExternalsRelative === true ||
  21716. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && parseAst_js.isRelative(source)) ||
  21717. !parseAst_js.isAbsolute(id));
  21718. }
  21719. async function waitForDependencyResolution(loadPromise) {
  21720. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  21721. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  21722. }
  21723. class Queue {
  21724. constructor(maxParallel) {
  21725. this.maxParallel = maxParallel;
  21726. this.queue = [];
  21727. this.workerCount = 0;
  21728. }
  21729. run(task) {
  21730. return new Promise((resolve, reject) => {
  21731. this.queue.push({ reject, resolve, task });
  21732. this.work();
  21733. });
  21734. }
  21735. async work() {
  21736. if (this.workerCount >= this.maxParallel)
  21737. return;
  21738. this.workerCount++;
  21739. let entry;
  21740. while ((entry = this.queue.shift())) {
  21741. const { reject, resolve, task } = entry;
  21742. try {
  21743. const result = await task();
  21744. resolve(result);
  21745. }
  21746. catch (error) {
  21747. reject(error);
  21748. }
  21749. }
  21750. this.workerCount--;
  21751. }
  21752. }
  21753. function normalizeEntryModules(entryModules) {
  21754. if (Array.isArray(entryModules)) {
  21755. return entryModules.map(id => ({
  21756. fileName: null,
  21757. id,
  21758. implicitlyLoadedAfter: [],
  21759. importer: undefined,
  21760. name: null
  21761. }));
  21762. }
  21763. return Object.entries(entryModules).map(([name, id]) => ({
  21764. fileName: null,
  21765. id,
  21766. implicitlyLoadedAfter: [],
  21767. importer: undefined,
  21768. name
  21769. }));
  21770. }
  21771. class Graph {
  21772. constructor(options, watcher) {
  21773. this.options = options;
  21774. this.astLru = flru(5);
  21775. this.cachedModules = new Map();
  21776. this.deoptimizationTracker = new EntityPathTracker();
  21777. this.entryModules = [];
  21778. this.modulesById = new Map();
  21779. this.needsTreeshakingPass = false;
  21780. this.newlyIncludedVariableInits = new Set();
  21781. this.phase = BuildPhase.LOAD_AND_PARSE;
  21782. this.scope = new GlobalScope();
  21783. this.watchFiles = Object.create(null);
  21784. this.watchMode = false;
  21785. this.externalModules = [];
  21786. this.implicitEntryModules = [];
  21787. this.modules = [];
  21788. this.getModuleInfo = (moduleId) => {
  21789. const foundModule = this.modulesById.get(moduleId);
  21790. if (!foundModule)
  21791. return null;
  21792. return foundModule.info;
  21793. };
  21794. if (options.cache !== false) {
  21795. if (options.cache?.modules) {
  21796. for (const module of options.cache.modules)
  21797. this.cachedModules.set(module.id, module);
  21798. }
  21799. this.pluginCache = options.cache?.plugins || Object.create(null);
  21800. // increment access counter
  21801. for (const name in this.pluginCache) {
  21802. const cache = this.pluginCache[name];
  21803. for (const value of Object.values(cache))
  21804. value[0]++;
  21805. }
  21806. }
  21807. if (watcher) {
  21808. this.watchMode = true;
  21809. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  21810. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21811. watcher.onCurrentRun('change', handleChange);
  21812. watcher.onCurrentRun('close', handleClose);
  21813. }
  21814. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21815. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21816. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21817. this.pureFunctions = getPureFunctions(options);
  21818. }
  21819. async build() {
  21820. timeStart('generate module graph', 2);
  21821. await this.generateModuleGraph();
  21822. timeEnd('generate module graph', 2);
  21823. timeStart('sort and bind modules', 2);
  21824. this.phase = BuildPhase.ANALYSE;
  21825. this.sortModules();
  21826. timeEnd('sort and bind modules', 2);
  21827. timeStart('mark included statements', 2);
  21828. this.includeStatements();
  21829. timeEnd('mark included statements', 2);
  21830. this.phase = BuildPhase.GENERATE;
  21831. }
  21832. getCache() {
  21833. // handle plugin cache eviction
  21834. for (const name in this.pluginCache) {
  21835. const cache = this.pluginCache[name];
  21836. let allDeleted = true;
  21837. for (const [key, value] of Object.entries(cache)) {
  21838. if (value[0] >= this.options.experimentalCacheExpiry)
  21839. delete cache[key];
  21840. else
  21841. allDeleted = false;
  21842. }
  21843. if (allDeleted)
  21844. delete this.pluginCache[name];
  21845. }
  21846. return {
  21847. modules: this.modules.map(module => module.toJSON()),
  21848. plugins: this.pluginCache
  21849. };
  21850. }
  21851. async generateModuleGraph() {
  21852. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21853. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21854. if (this.entryModules.length === 0) {
  21855. throw new Error('You must supply options.input to rollup');
  21856. }
  21857. for (const module of this.modulesById.values()) {
  21858. module.cacheInfoGetters();
  21859. if (module instanceof Module) {
  21860. this.modules.push(module);
  21861. }
  21862. else {
  21863. this.externalModules.push(module);
  21864. }
  21865. }
  21866. }
  21867. includeStatements() {
  21868. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  21869. for (const module of entryModules) {
  21870. markModuleAndImpureDependenciesAsExecuted(module);
  21871. }
  21872. if (this.options.treeshake) {
  21873. let treeshakingPass = 1;
  21874. this.newlyIncludedVariableInits.clear();
  21875. do {
  21876. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21877. this.needsTreeshakingPass = false;
  21878. for (const module of this.modules) {
  21879. if (module.isExecuted) {
  21880. module.hasTreeShakingPassStarted = true;
  21881. if (module.info.moduleSideEffects === 'no-treeshake') {
  21882. module.includeAllInBundle();
  21883. }
  21884. else {
  21885. module.include();
  21886. }
  21887. for (const entity of this.newlyIncludedVariableInits) {
  21888. this.newlyIncludedVariableInits.delete(entity);
  21889. entity.include(createInclusionContext(), false);
  21890. }
  21891. }
  21892. }
  21893. if (treeshakingPass === 1) {
  21894. // We only include exports after the first pass to avoid issues with
  21895. // the TDZ detection logic
  21896. for (const module of entryModules) {
  21897. if (module.preserveSignature !== false) {
  21898. module.includeAllExports(false);
  21899. this.needsTreeshakingPass = true;
  21900. }
  21901. }
  21902. }
  21903. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21904. } while (this.needsTreeshakingPass);
  21905. }
  21906. else {
  21907. for (const module of this.modules)
  21908. module.includeAllInBundle();
  21909. }
  21910. for (const externalModule of this.externalModules)
  21911. externalModule.warnUnusedImports();
  21912. for (const module of this.implicitEntryModules) {
  21913. for (const dependant of module.implicitlyLoadedAfter) {
  21914. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21915. parseAst_js.error(parseAst_js.logImplicitDependantIsNotIncluded(dependant));
  21916. }
  21917. }
  21918. }
  21919. }
  21920. sortModules() {
  21921. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21922. for (const cyclePath of cyclePaths) {
  21923. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularDependency(cyclePath));
  21924. }
  21925. this.modules = orderedModules;
  21926. for (const module of this.modules) {
  21927. module.bindReferences();
  21928. }
  21929. this.warnForMissingExports();
  21930. }
  21931. warnForMissingExports() {
  21932. for (const module of this.modules) {
  21933. for (const importDescription of module.importDescriptions.values()) {
  21934. if (importDescription.name !== '*' &&
  21935. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21936. module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  21937. }
  21938. }
  21939. }
  21940. }
  21941. }
  21942. function formatAction([pluginName, hookName, parameters]) {
  21943. const action = `(${pluginName}) ${hookName}`;
  21944. const s = JSON.stringify;
  21945. switch (hookName) {
  21946. case 'resolveId': {
  21947. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  21948. }
  21949. case 'load': {
  21950. return `${action} ${s(parameters[0])}`;
  21951. }
  21952. case 'transform': {
  21953. return `${action} ${s(parameters[1])}`;
  21954. }
  21955. case 'shouldTransformCachedModule': {
  21956. return `${action} ${s(parameters[0].id)}`;
  21957. }
  21958. case 'moduleParsed': {
  21959. return `${action} ${s(parameters[0].id)}`;
  21960. }
  21961. }
  21962. return action;
  21963. }
  21964. let handleBeforeExit = null;
  21965. const rejectByPluginDriver = new Map();
  21966. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21967. const emptyEventLoopPromise = new Promise((_, reject) => {
  21968. rejectByPluginDriver.set(pluginDriver, reject);
  21969. if (!handleBeforeExit) {
  21970. // We only ever create a single event listener to avoid max listener and
  21971. // other issues
  21972. handleBeforeExit = () => {
  21973. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  21974. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21975. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21976. [...unfulfilledActions].map(formatAction).join('\n')));
  21977. }
  21978. };
  21979. process$1.once('beforeExit', handleBeforeExit);
  21980. }
  21981. });
  21982. try {
  21983. return await Promise.race([callback(), emptyEventLoopPromise]);
  21984. }
  21985. finally {
  21986. rejectByPluginDriver.delete(pluginDriver);
  21987. if (rejectByPluginDriver.size === 0) {
  21988. process$1.off('beforeExit', handleBeforeExit);
  21989. handleBeforeExit = null;
  21990. }
  21991. }
  21992. }
  21993. async function initWasm() { }
  21994. async function normalizeInputOptions(config, watchMode) {
  21995. // These are options that may trigger special warnings or behaviour later
  21996. // if the user did not select an explicit value
  21997. const unsetOptions = new Set();
  21998. const context = config.context ?? 'undefined';
  21999. const plugins = await normalizePluginOption(config.plugins);
  22000. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  22001. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  22002. const strictDeprecations = config.strictDeprecations || false;
  22003. const maxParallelFileOps = getMaxParallelFileOps(config);
  22004. const options = {
  22005. cache: getCache(config),
  22006. context,
  22007. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  22008. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  22009. external: getIdMatcher(config.external),
  22010. input: getInput(config),
  22011. jsx: getJsx(config),
  22012. logLevel,
  22013. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  22014. maxParallelFileOps,
  22015. moduleContext: getModuleContext(config, context),
  22016. onLog,
  22017. perf: config.perf || false,
  22018. plugins,
  22019. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  22020. preserveSymlinks: config.preserveSymlinks || false,
  22021. shimMissingExports: config.shimMissingExports || false,
  22022. strictDeprecations,
  22023. treeshake: getTreeshake(config)
  22024. };
  22025. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  22026. return { options, unsetOptions };
  22027. }
  22028. const getCache = (config) => config.cache === true // `true` is the default
  22029. ? undefined
  22030. : config.cache?.cache || config.cache;
  22031. const getIdMatcher = (option) => {
  22032. if (option === true) {
  22033. return () => true;
  22034. }
  22035. if (typeof option === 'function') {
  22036. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  22037. }
  22038. if (option) {
  22039. const ids = new Set();
  22040. const matchers = [];
  22041. for (const value of ensureArray$1(option)) {
  22042. if (value instanceof RegExp) {
  22043. matchers.push(value);
  22044. }
  22045. else {
  22046. ids.add(value);
  22047. }
  22048. }
  22049. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  22050. }
  22051. return () => false;
  22052. };
  22053. const getInput = (config) => {
  22054. const configInput = config.input;
  22055. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  22056. };
  22057. const getJsx = (config) => {
  22058. const configJsx = config.jsx;
  22059. if (!configJsx)
  22060. return false;
  22061. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ');
  22062. const { factory, importSource, mode } = configWithPreset;
  22063. switch (mode) {
  22064. case 'automatic': {
  22065. return {
  22066. factory: factory || 'React.createElement',
  22067. importSource: importSource || 'react',
  22068. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  22069. mode: 'automatic'
  22070. };
  22071. }
  22072. case 'preserve': {
  22073. if (importSource && !(factory || configWithPreset.fragment)) {
  22074. parseAst_js.error(parseAst_js.logInvalidOption('jsx', parseAst_js.URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  22075. }
  22076. return {
  22077. factory: factory || null,
  22078. fragment: configWithPreset.fragment || null,
  22079. importSource: importSource || null,
  22080. mode: 'preserve'
  22081. };
  22082. }
  22083. // case 'classic':
  22084. default: {
  22085. if (mode && mode !== 'classic') {
  22086. parseAst_js.error(parseAst_js.logInvalidOption('jsx.mode', parseAst_js.URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  22087. }
  22088. return {
  22089. factory: factory || 'React.createElement',
  22090. fragment: configWithPreset.fragment || 'React.Fragment',
  22091. importSource: importSource || null,
  22092. mode: 'classic'
  22093. };
  22094. }
  22095. }
  22096. };
  22097. const getMaxParallelFileOps = (config) => {
  22098. const maxParallelFileOps = config.maxParallelFileOps;
  22099. if (typeof maxParallelFileOps === 'number') {
  22100. if (maxParallelFileOps <= 0)
  22101. return Infinity;
  22102. return maxParallelFileOps;
  22103. }
  22104. return 20;
  22105. };
  22106. const getModuleContext = (config, context) => {
  22107. const configModuleContext = config.moduleContext;
  22108. if (typeof configModuleContext === 'function') {
  22109. return id => configModuleContext(id) ?? context;
  22110. }
  22111. if (configModuleContext) {
  22112. const contextByModuleId = Object.create(null);
  22113. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  22114. contextByModuleId[path.resolve(key)] = moduleContext;
  22115. }
  22116. return id => contextByModuleId[id] ?? context;
  22117. }
  22118. return () => context;
  22119. };
  22120. const getTreeshake = (config) => {
  22121. const configTreeshake = config.treeshake;
  22122. if (configTreeshake === false) {
  22123. return false;
  22124. }
  22125. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ');
  22126. return {
  22127. annotations: configWithPreset.annotations !== false,
  22128. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  22129. manualPureFunctions: configWithPreset.manualPureFunctions ?? parseAst_js.EMPTY_ARRAY,
  22130. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  22131. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  22132. ? 'always'
  22133. : configWithPreset.propertyReadSideEffects !== false,
  22134. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  22135. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  22136. };
  22137. };
  22138. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  22139. if (typeof moduleSideEffectsOption === 'boolean') {
  22140. return () => moduleSideEffectsOption;
  22141. }
  22142. if (moduleSideEffectsOption === 'no-external') {
  22143. return (_id, external) => !external;
  22144. }
  22145. if (typeof moduleSideEffectsOption === 'function') {
  22146. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  22147. }
  22148. if (Array.isArray(moduleSideEffectsOption)) {
  22149. const ids = new Set(moduleSideEffectsOption);
  22150. return id => ids.has(id);
  22151. }
  22152. if (moduleSideEffectsOption) {
  22153. parseAst_js.error(parseAst_js.logInvalidOption('treeshake.moduleSideEffects', parseAst_js.URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  22154. }
  22155. return () => true;
  22156. };
  22157. // https://datatracker.ietf.org/doc/html/rfc2396
  22158. // eslint-disable-next-line no-control-regex
  22159. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  22160. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  22161. function sanitizeFileName(name) {
  22162. const match = DRIVE_LETTER_REGEX.exec(name);
  22163. const driveLetter = match ? match[0] : '';
  22164. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  22165. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  22166. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  22167. }
  22168. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  22169. // These are options that may trigger special warnings or behaviour later
  22170. // if the user did not select an explicit value
  22171. const unsetOptions = new Set(unsetInputOptions);
  22172. const compact = config.compact || false;
  22173. const format = getFormat(config);
  22174. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  22175. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  22176. const file = getFile(config, preserveModules, inputOptions);
  22177. const generatedCode = getGeneratedCode(config);
  22178. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  22179. const outputOptions = {
  22180. amd: getAmd(config),
  22181. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  22182. banner: getAddon(config, 'banner'),
  22183. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  22184. compact,
  22185. dir: getDir(config, file),
  22186. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  22187. entryFileNames: getEntryFileNames(config, unsetOptions),
  22188. esModule: config.esModule ?? 'if-default-prop',
  22189. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  22190. exports: getExports(config, unsetOptions),
  22191. extend: config.extend || false,
  22192. externalImportAssertions: externalImportAttributes,
  22193. externalImportAttributes,
  22194. externalLiveBindings: config.externalLiveBindings ?? true,
  22195. file,
  22196. footer: getAddon(config, 'footer'),
  22197. format,
  22198. freeze: config.freeze ?? true,
  22199. generatedCode,
  22200. globals: config.globals || {},
  22201. hashCharacters: config.hashCharacters ?? 'base64',
  22202. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  22203. importAttributesKey: config.importAttributesKey ?? 'assert',
  22204. indent: getIndent(config, compact),
  22205. inlineDynamicImports,
  22206. interop: getInterop(config),
  22207. intro: getAddon(config, 'intro'),
  22208. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  22209. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  22210. name: config.name,
  22211. noConflict: config.noConflict || false,
  22212. outro: getAddon(config, 'outro'),
  22213. paths: config.paths || {},
  22214. plugins: await normalizePluginOption(config.plugins),
  22215. preserveModules,
  22216. preserveModulesRoot: getPreserveModulesRoot(config),
  22217. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  22218. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  22219. ? config.sanitizeFileName
  22220. : config.sanitizeFileName === false
  22221. ? id => id
  22222. : sanitizeFileName,
  22223. sourcemap: config.sourcemap || false,
  22224. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  22225. sourcemapDebugIds: config.sourcemapDebugIds || false,
  22226. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  22227. sourcemapFile: config.sourcemapFile,
  22228. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  22229. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  22230. ? config.sourcemapIgnoreList
  22231. : config.sourcemapIgnoreList === false
  22232. ? () => false
  22233. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  22234. sourcemapPathTransform: config.sourcemapPathTransform,
  22235. strict: config.strict ?? true,
  22236. systemNullSetters: config.systemNullSetters ?? true,
  22237. validate: config.validate || false,
  22238. virtualDirname: config.virtualDirname || '_virtual'
  22239. };
  22240. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  22241. return { options: outputOptions, unsetOptions };
  22242. }
  22243. const getFile = (config, preserveModules, inputOptions) => {
  22244. const { file } = config;
  22245. if (typeof file === 'string') {
  22246. if (preserveModules) {
  22247. return parseAst_js.error(parseAst_js.logInvalidOption('output.file', parseAst_js.URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  22248. }
  22249. if (!Array.isArray(inputOptions.input))
  22250. return parseAst_js.error(parseAst_js.logInvalidOption('output.file', parseAst_js.URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  22251. }
  22252. return file;
  22253. };
  22254. const getFormat = (config) => {
  22255. const configFormat = config.format;
  22256. switch (configFormat) {
  22257. case undefined:
  22258. case 'es':
  22259. case 'esm':
  22260. case 'module': {
  22261. return 'es';
  22262. }
  22263. case 'cjs':
  22264. case 'commonjs': {
  22265. return 'cjs';
  22266. }
  22267. case 'system':
  22268. case 'systemjs': {
  22269. return 'system';
  22270. }
  22271. case 'amd':
  22272. case 'iife':
  22273. case 'umd': {
  22274. return configFormat;
  22275. }
  22276. default: {
  22277. return parseAst_js.error(parseAst_js.logInvalidOption('output.format', parseAst_js.URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  22278. }
  22279. }
  22280. };
  22281. const getInlineDynamicImports = (config, inputOptions) => {
  22282. const inlineDynamicImports = config.inlineDynamicImports || false;
  22283. const { input } = inputOptions;
  22284. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22285. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22286. }
  22287. return inlineDynamicImports;
  22288. };
  22289. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22290. const preserveModules = config.preserveModules || false;
  22291. if (preserveModules) {
  22292. if (inlineDynamicImports) {
  22293. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  22294. }
  22295. if (inputOptions.preserveEntrySignatures === false) {
  22296. return parseAst_js.error(parseAst_js.logInvalidOption('preserveEntrySignatures', parseAst_js.URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  22297. }
  22298. }
  22299. return preserveModules;
  22300. };
  22301. const getPreserveModulesRoot = (config) => {
  22302. const { preserveModulesRoot } = config;
  22303. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22304. return undefined;
  22305. }
  22306. return path.resolve(preserveModulesRoot);
  22307. };
  22308. const getAmd = (config) => {
  22309. const mergedOption = {
  22310. autoId: false,
  22311. basePath: '',
  22312. define: 'define',
  22313. forceJsExtensionForImports: false,
  22314. ...config.amd
  22315. };
  22316. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22317. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.id', parseAst_js.URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22318. }
  22319. if (mergedOption.basePath && !mergedOption.autoId) {
  22320. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.basePath', parseAst_js.URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  22321. }
  22322. return mergedOption.autoId
  22323. ? {
  22324. autoId: true,
  22325. basePath: mergedOption.basePath,
  22326. define: mergedOption.define,
  22327. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22328. }
  22329. : {
  22330. autoId: false,
  22331. define: mergedOption.define,
  22332. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22333. id: mergedOption.id
  22334. };
  22335. };
  22336. const getAddon = (config, name) => {
  22337. const configAddon = config[name];
  22338. if (typeof configAddon === 'function') {
  22339. return configAddon;
  22340. }
  22341. return () => configAddon || '';
  22342. };
  22343. const getDir = (config, file) => {
  22344. const { dir } = config;
  22345. if (typeof dir === 'string' && typeof file === 'string') {
  22346. return parseAst_js.error(parseAst_js.logInvalidOption('output.dir', parseAst_js.URL_OUTPUT_DIR, 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  22347. }
  22348. return dir;
  22349. };
  22350. const getEntryFileNames = (config, unsetOptions) => {
  22351. const configEntryFileNames = config.entryFileNames;
  22352. if (configEntryFileNames == null) {
  22353. unsetOptions.add('entryFileNames');
  22354. }
  22355. return configEntryFileNames ?? '[name].js';
  22356. };
  22357. function getExports(config, unsetOptions) {
  22358. const configExports = config.exports;
  22359. if (configExports == null) {
  22360. unsetOptions.add('exports');
  22361. }
  22362. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22363. return parseAst_js.error(parseAst_js.logInvalidExportOptionValue(configExports));
  22364. }
  22365. return configExports || 'auto';
  22366. }
  22367. const getExternalImportAttributes = (config, inputOptions) => {
  22368. if (config.externalImportAssertions != undefined) {
  22369. parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22370. }
  22371. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22372. };
  22373. const getGeneratedCode = (config) => {
  22374. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
  22375. return {
  22376. arrowFunctions: configWithPreset.arrowFunctions === true,
  22377. constBindings: configWithPreset.constBindings === true,
  22378. objectShorthand: configWithPreset.objectShorthand === true,
  22379. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22380. symbols: configWithPreset.symbols === true
  22381. };
  22382. };
  22383. const getIndent = (config, compact) => {
  22384. if (compact) {
  22385. return '';
  22386. }
  22387. const configIndent = config.indent;
  22388. return configIndent === false ? '' : (configIndent ?? true);
  22389. };
  22390. const ALLOWED_INTEROP_TYPES = new Set([
  22391. 'compat',
  22392. 'auto',
  22393. 'esModule',
  22394. 'default',
  22395. 'defaultOnly'
  22396. ]);
  22397. const getInterop = (config) => {
  22398. const configInterop = config.interop;
  22399. if (typeof configInterop === 'function') {
  22400. const interopPerId = Object.create(null);
  22401. let defaultInterop = null;
  22402. return id => id === null
  22403. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22404. : id in interopPerId
  22405. ? interopPerId[id]
  22406. : validateInterop((interopPerId[id] = configInterop(id)));
  22407. }
  22408. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22409. };
  22410. const validateInterop = (interop) => {
  22411. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22412. return parseAst_js.error(parseAst_js.logInvalidOption('output.interop', parseAst_js.URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22413. }
  22414. return interop;
  22415. };
  22416. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22417. const configManualChunks = config.manualChunks;
  22418. if (configManualChunks) {
  22419. if (inlineDynamicImports) {
  22420. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22421. }
  22422. if (preserveModules) {
  22423. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22424. }
  22425. }
  22426. return configManualChunks || {};
  22427. };
  22428. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22429. const getSourcemapFileNames = (config, unsetOptions) => {
  22430. const configSourcemapFileNames = config.sourcemapFileNames;
  22431. if (configSourcemapFileNames == null) {
  22432. unsetOptions.add('sourcemapFileNames');
  22433. }
  22434. return configSourcemapFileNames;
  22435. };
  22436. const getSourcemapBaseUrl = (config) => {
  22437. const { sourcemapBaseUrl } = config;
  22438. if (sourcemapBaseUrl) {
  22439. if (parseAst_js.isValidUrl(sourcemapBaseUrl)) {
  22440. return parseAst_js.addTrailingSlashIfMissed(sourcemapBaseUrl);
  22441. }
  22442. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapBaseUrl', parseAst_js.URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22443. }
  22444. };
  22445. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22446. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22447. function rollup(rawInputOptions) {
  22448. return rollupInternal(rawInputOptions, null);
  22449. }
  22450. async function rollupInternal(rawInputOptions, watcher) {
  22451. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22452. initialiseTimers(inputOptions);
  22453. await initWasm();
  22454. const graph = new Graph(inputOptions, watcher);
  22455. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22456. const useCache = rawInputOptions.cache !== false;
  22457. if (rawInputOptions.cache) {
  22458. inputOptions.cache = undefined;
  22459. rawInputOptions.cache = undefined;
  22460. }
  22461. timeStart('BUILD', 1);
  22462. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22463. try {
  22464. timeStart('initialize', 2);
  22465. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22466. timeEnd('initialize', 2);
  22467. await graph.build();
  22468. }
  22469. catch (error_) {
  22470. const watchFiles = Object.keys(graph.watchFiles);
  22471. if (watchFiles.length > 0) {
  22472. error_.watchFiles = watchFiles;
  22473. }
  22474. try {
  22475. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22476. }
  22477. catch (buildEndError) {
  22478. // Create a compound error object to include both errors, based on the original error
  22479. const compoundError = parseAst_js.getRollupError({
  22480. ...error_,
  22481. message: `There was an error during the build:\n ${error_.message}\nAdditionally, handling the error in the 'buildEnd' hook caused the following error:\n ${buildEndError.message}`
  22482. });
  22483. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22484. throw compoundError;
  22485. }
  22486. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22487. throw error_;
  22488. }
  22489. try {
  22490. await graph.pluginDriver.hookParallel('buildEnd', []);
  22491. }
  22492. catch (buildEndError) {
  22493. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22494. throw buildEndError;
  22495. }
  22496. });
  22497. timeEnd('BUILD', 1);
  22498. const result = {
  22499. cache: useCache ? graph.getCache() : undefined,
  22500. async close() {
  22501. if (result.closed)
  22502. return;
  22503. result.closed = true;
  22504. await graph.pluginDriver.hookParallel('closeBundle', []);
  22505. },
  22506. closed: false,
  22507. async [Symbol.asyncDispose]() {
  22508. await this.close();
  22509. },
  22510. async generate(rawOutputOptions) {
  22511. if (result.closed)
  22512. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22513. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22514. },
  22515. get watchFiles() {
  22516. return Object.keys(graph.watchFiles);
  22517. },
  22518. async write(rawOutputOptions) {
  22519. if (result.closed)
  22520. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22521. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22522. }
  22523. };
  22524. if (inputOptions.perf)
  22525. result.getTimings = getTimings;
  22526. return result;
  22527. }
  22528. async function getInputOptions(initialInputOptions, watchMode) {
  22529. if (!initialInputOptions) {
  22530. throw new Error('You must supply an options object to rollup');
  22531. }
  22532. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22533. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22534. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22535. return { options, unsetOptions };
  22536. }
  22537. async function getProcessedInputOptions(inputOptions, watchMode) {
  22538. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22539. const logLevel = inputOptions.logLevel || parseAst_js.LOGLEVEL_INFO;
  22540. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22541. for (const plugin of plugins) {
  22542. const { name, options } = plugin;
  22543. const handler = 'handler' in options ? options.handler : options;
  22544. const processedOptions = await handler.call({
  22545. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22546. error: (error_) => parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22547. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22548. meta: { rollupVersion: version, watchMode },
  22549. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22550. }, inputOptions);
  22551. if (processedOptions) {
  22552. inputOptions = processedOptions;
  22553. }
  22554. }
  22555. return inputOptions;
  22556. }
  22557. function normalizePlugins(plugins, anonymousPrefix) {
  22558. for (const [index, plugin] of plugins.entries()) {
  22559. if (!plugin.name) {
  22560. plugin.name = `${anonymousPrefix}${index + 1}`;
  22561. }
  22562. }
  22563. }
  22564. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22565. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22566. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22567. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22568. const generated = await bundle.generate(isWrite);
  22569. if (isWrite) {
  22570. timeStart('WRITE', 1);
  22571. if (!outputOptions.dir && !outputOptions.file) {
  22572. return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
  22573. }
  22574. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22575. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22576. timeEnd('WRITE', 1);
  22577. }
  22578. return createOutput(generated);
  22579. });
  22580. }
  22581. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22582. if (!rawOutputOptions) {
  22583. throw new Error('You must supply an options object');
  22584. }
  22585. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22586. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22587. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22588. return {
  22589. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22590. outputPluginDriver
  22591. };
  22592. }
  22593. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22594. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22595. const emitError = () => pluginContext.error(parseAst_js.logCannotEmitFromOptionsHook());
  22596. return {
  22597. ...pluginContext,
  22598. emitFile: emitError,
  22599. setAssetSource: emitError
  22600. };
  22601. }), inputOptions, unsetInputOptions);
  22602. }
  22603. function createOutput(outputBundle) {
  22604. return {
  22605. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22606. };
  22607. }
  22608. var SortingFileType;
  22609. (function (SortingFileType) {
  22610. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22611. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22612. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22613. })(SortingFileType || (SortingFileType = {}));
  22614. function getSortingFileType(file) {
  22615. if (file.type === 'asset') {
  22616. return SortingFileType.ASSET;
  22617. }
  22618. if (file.isEntry) {
  22619. return SortingFileType.ENTRY_CHUNK;
  22620. }
  22621. return SortingFileType.SECONDARY_CHUNK;
  22622. }
  22623. async function writeOutputFile(outputFile, outputOptions) {
  22624. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  22625. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22626. await promises.mkdir(path.dirname(fileName), { recursive: true });
  22627. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22628. }
  22629. /**
  22630. * Auxiliary function for defining rollup configuration
  22631. * Mainly to facilitate IDE code prompts, after all, export default does not
  22632. * prompt, even if you add @type annotations, it is not accurate
  22633. * @param options
  22634. */
  22635. function defineConfig(options) {
  22636. return options;
  22637. }
  22638. exports.bold = bold;
  22639. exports.commandAliases = commandAliases;
  22640. exports.createFilter = createFilter;
  22641. exports.cyan = cyan;
  22642. exports.defineConfig = defineConfig;
  22643. exports.ensureArray = ensureArray$1;
  22644. exports.getAugmentedNamespace = getAugmentedNamespace;
  22645. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  22646. exports.getNewArray = getNewArray;
  22647. exports.getOrCreate = getOrCreate;
  22648. exports.gray = gray;
  22649. exports.green = green;
  22650. exports.handleError = handleError;
  22651. exports.isWatchEnabled = isWatchEnabled;
  22652. exports.mergeOptions = mergeOptions;
  22653. exports.normalizePluginOption = normalizePluginOption;
  22654. exports.pc = pc;
  22655. exports.rollup = rollup;
  22656. exports.rollupInternal = rollupInternal;
  22657. exports.stderr = stderr;
  22658. exports.underline = underline;
  22659. exports.version = version;
  22660. exports.yellow = yellow;
  22661. //# sourceMappingURL=rollup.js.map