rollup.js 922 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385
  1. /*
  2. @license
  3. Rollup.js v4.60.1
  4. Mon, 30 Mar 2026 04:32:12 GMT - commit ae871d762f6bbeb4320d28fe179211168f27a434
  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. function _interopNamespaceDefault(e) {
  17. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  18. if (e) {
  19. for (const k in e) {
  20. n[k] = e[k];
  21. }
  22. }
  23. n.default = e;
  24. return n;
  25. }
  26. function _mergeNamespaces(n, m) {
  27. for (var i = 0; i < m.length; i++) {
  28. const e = m[i];
  29. if (typeof e !== 'string' && !Array.isArray(e)) { for (const k in e) {
  30. if (k !== 'default' && !(k in n)) {
  31. n[k] = e[k];
  32. }
  33. } }
  34. }
  35. return Object.defineProperty(n, Symbol.toStringTag, { value: 'Module' });
  36. }
  37. const promises__namespace = /*#__PURE__*/_interopNamespaceDefault(promises);
  38. var version = "4.60.1";
  39. function ensureArray$1(items) {
  40. if (Array.isArray(items)) {
  41. return items.filter(Boolean);
  42. }
  43. if (items) {
  44. return [items];
  45. }
  46. return [];
  47. }
  48. var BuildPhase;
  49. (function (BuildPhase) {
  50. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  51. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  52. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  53. })(BuildPhase || (BuildPhase = {}));
  54. let textEncoder;
  55. const getHash64 = input => native_js.xxhashBase64Url(ensureBuffer(input));
  56. const getHash36 = input => native_js.xxhashBase36(ensureBuffer(input));
  57. const getHash16 = input => native_js.xxhashBase16(ensureBuffer(input));
  58. const hasherByType = {
  59. base36: getHash36,
  60. base64: getHash64,
  61. hex: getHash16
  62. };
  63. function ensureBuffer(input) {
  64. if (typeof input === 'string') {
  65. if (typeof Buffer === 'undefined') {
  66. textEncoder ??= new TextEncoder();
  67. return textEncoder.encode(input);
  68. }
  69. return Buffer.from(input);
  70. }
  71. return input;
  72. }
  73. function getOrCreate(map, key, init) {
  74. const existing = map.get(key);
  75. if (existing !== undefined) {
  76. return existing;
  77. }
  78. const value = init();
  79. map.set(key, value);
  80. return value;
  81. }
  82. function getNewSet() {
  83. return new Set();
  84. }
  85. function getNewArray() {
  86. return [];
  87. }
  88. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  89. const base = 64;
  90. function toBase64(value) {
  91. let outString = '';
  92. do {
  93. const currentDigit = value % base;
  94. value = (value / base) | 0;
  95. outString = chars$1[currentDigit] + outString;
  96. } while (value !== 0);
  97. return outString;
  98. }
  99. // Four random characters from the private use area to minimize risk of
  100. // conflicts
  101. const hashPlaceholderLeft = '!~{';
  102. const hashPlaceholderRight = '}~';
  103. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  104. // This is the size of a 128-bits xxhash with base64url encoding
  105. const MAX_HASH_SIZE = 21;
  106. const DEFAULT_HASH_SIZE = 8;
  107. const getHashPlaceholderGenerator = () => {
  108. let nextIndex = 0;
  109. return (optionName, hashSize) => {
  110. if (hashSize > MAX_HASH_SIZE) {
  111. return parseAst_js.error(parseAst_js.logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  112. }
  113. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  114. if (placeholder.length > hashSize) {
  115. 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.`));
  116. }
  117. return placeholder;
  118. };
  119. };
  120. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  121. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  122. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  123. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  124. const containedPlaceholders = new Set();
  125. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  126. if (placeholders.has(placeholder)) {
  127. containedPlaceholders.add(placeholder);
  128. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  129. }
  130. return placeholder;
  131. });
  132. return { containedPlaceholders, transformedCode };
  133. };
  134. const lowercaseBundleKeys = Symbol('bundleKeys');
  135. const FILE_PLACEHOLDER = {
  136. type: 'placeholder'
  137. };
  138. const getOutputBundle = (outputBundleBase) => {
  139. const reservedLowercaseBundleKeys = new Set();
  140. return new Proxy(outputBundleBase, {
  141. deleteProperty(target, key) {
  142. if (typeof key === 'string') {
  143. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  144. }
  145. return Reflect.deleteProperty(target, key);
  146. },
  147. get(target, key) {
  148. if (key === lowercaseBundleKeys) {
  149. return reservedLowercaseBundleKeys;
  150. }
  151. return Reflect.get(target, key);
  152. },
  153. set(target, key, value) {
  154. if (typeof key === 'string') {
  155. reservedLowercaseBundleKeys.add(key.toLowerCase());
  156. }
  157. return Reflect.set(target, key, value);
  158. }
  159. });
  160. };
  161. const removeUnreferencedAssets = (outputBundle) => {
  162. const unreferencedAssets = new Set();
  163. const bundleEntries = Object.values(outputBundle);
  164. for (const asset of bundleEntries) {
  165. if (asset.type === 'asset' && asset.needsCodeReference) {
  166. unreferencedAssets.add(asset.fileName);
  167. }
  168. }
  169. for (const chunk of bundleEntries) {
  170. if (chunk.type === 'chunk') {
  171. for (const referencedFile of chunk.referencedFiles) {
  172. if (unreferencedAssets.has(referencedFile)) {
  173. unreferencedAssets.delete(referencedFile);
  174. }
  175. }
  176. }
  177. }
  178. for (const file of unreferencedAssets) {
  179. delete outputBundle[file];
  180. }
  181. };
  182. function renderNamePattern(pattern, patternName, replacements) {
  183. if (parseAst_js.isPathFragment(pattern))
  184. 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.`));
  185. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  186. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  187. return parseAst_js.error(parseAst_js.logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  188. }
  189. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  190. if (parseAst_js.isPathFragment(replacement))
  191. return parseAst_js.error(parseAst_js.logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  192. return replacement;
  193. });
  194. }
  195. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  196. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  197. return name;
  198. const extension = path.extname(name);
  199. name = name.slice(0, Math.max(0, name.length - extension.length));
  200. let uniqueName, uniqueIndex = 1;
  201. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  202. ;
  203. return uniqueName;
  204. }
  205. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  206. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  207. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  208. ? outputOptions.assetFileNames({
  209. // Additionally, this should be non-enumerable in the next major
  210. get name() {
  211. 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);
  212. return name;
  213. },
  214. names,
  215. // Additionally, this should be non-enumerable in the next major
  216. get originalFileName() {
  217. 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);
  218. return originalFileName;
  219. },
  220. originalFileNames,
  221. source,
  222. type: 'asset'
  223. })
  224. : outputOptions.assetFileNames, 'output.assetFileNames', {
  225. ext: () => path.extname(emittedName).slice(1),
  226. extname: () => path.extname(emittedName),
  227. hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
  228. name: () => emittedName.slice(0, Math.max(0, emittedName.length - path.extname(emittedName).length))
  229. }), bundle);
  230. }
  231. function reserveFileNameInBundle(fileName, { bundle }, log) {
  232. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  233. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logFileNameConflict(fileName));
  234. }
  235. else {
  236. bundle[fileName] = FILE_PLACEHOLDER;
  237. }
  238. }
  239. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  240. function hasValidType(emittedFile) {
  241. return Boolean(emittedFile &&
  242. emittedFileTypes.has(emittedFile.type));
  243. }
  244. function hasValidName(emittedFile) {
  245. const validatedName = emittedFile.fileName || emittedFile.name;
  246. return !validatedName || (typeof validatedName === 'string' && !parseAst_js.isPathFragment(validatedName));
  247. }
  248. function getValidSource(source, emittedFile, fileReferenceId) {
  249. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  250. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  251. 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.`));
  252. }
  253. return source;
  254. }
  255. function getAssetFileName(file, referenceId) {
  256. if (typeof file.fileName !== 'string') {
  257. return parseAst_js.error(parseAst_js.logAssetNotFinalisedForFileName(file.name || referenceId));
  258. }
  259. return file.fileName;
  260. }
  261. function getChunkFileName(file, facadeChunkByModule) {
  262. if (file.fileName) {
  263. return file.fileName;
  264. }
  265. if (facadeChunkByModule) {
  266. return facadeChunkByModule.get(file.module).getFileName();
  267. }
  268. return parseAst_js.error(parseAst_js.logChunkNotGeneratedForFileName(file.fileName || file.name));
  269. }
  270. class FileEmitter {
  271. constructor(graph, options, baseFileEmitter) {
  272. this.graph = graph;
  273. this.options = options;
  274. this.facadeChunkByModule = null;
  275. this.nextIdBase = 1;
  276. this.output = null;
  277. this.outputFileEmitters = [];
  278. this.emitFile = (emittedFile) => {
  279. if (!hasValidType(emittedFile)) {
  280. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  281. }
  282. if (emittedFile.type === 'prebuilt-chunk') {
  283. return this.emitPrebuiltChunk(emittedFile);
  284. }
  285. if (!hasValidName(emittedFile)) {
  286. 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}".`));
  287. }
  288. if (emittedFile.type === 'chunk') {
  289. return this.emitChunk(emittedFile);
  290. }
  291. return this.emitAsset(emittedFile);
  292. };
  293. this.finaliseAssets = () => {
  294. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  295. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  296. return parseAst_js.error(parseAst_js.logNoAssetSourceSet(emittedFile.name || referenceId));
  297. }
  298. };
  299. this.getFileName = (fileReferenceId) => {
  300. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  301. if (!emittedFile)
  302. return parseAst_js.error(parseAst_js.logFileReferenceIdNotFoundForFilename(fileReferenceId));
  303. if (emittedFile.type === 'chunk') {
  304. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  305. }
  306. if (emittedFile.type === 'prebuilt-chunk') {
  307. return emittedFile.fileName;
  308. }
  309. return getAssetFileName(emittedFile, fileReferenceId);
  310. };
  311. this.setAssetSource = (referenceId, requestedSource) => {
  312. const consumedFile = this.filesByReferenceId.get(referenceId);
  313. if (!consumedFile)
  314. return parseAst_js.error(parseAst_js.logAssetReferenceIdNotFoundForSetSource(referenceId));
  315. if (consumedFile.type !== 'asset') {
  316. return parseAst_js.error(parseAst_js.logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  317. }
  318. if (consumedFile.source !== undefined) {
  319. return parseAst_js.error(parseAst_js.logAssetSourceAlreadySet(consumedFile.name || referenceId));
  320. }
  321. const source = getValidSource(requestedSource, consumedFile, referenceId);
  322. if (this.output) {
  323. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  324. }
  325. else {
  326. consumedFile.source = source;
  327. for (const emitter of this.outputFileEmitters) {
  328. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  329. }
  330. }
  331. };
  332. this.setChunkInformation = (facadeChunkByModule) => {
  333. this.facadeChunkByModule = facadeChunkByModule;
  334. };
  335. this.setOutputBundle = (bundle, outputOptions) => {
  336. const getHash = hasherByType[outputOptions.hashCharacters];
  337. const output = (this.output = {
  338. bundle,
  339. fileNamesBySourceHash: new Map(),
  340. getHash,
  341. outputOptions
  342. });
  343. for (const emittedFile of this.filesByReferenceId.values()) {
  344. if (emittedFile.fileName) {
  345. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  346. }
  347. }
  348. const consumedAssetsByHash = new Map();
  349. for (const consumedFile of this.filesByReferenceId.values()) {
  350. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  351. if (consumedFile.fileName) {
  352. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  353. }
  354. else {
  355. const sourceHash = getHash(consumedFile.source);
  356. getOrCreate(consumedAssetsByHash, sourceHash, getNewArray).push(consumedFile);
  357. }
  358. }
  359. else if (consumedFile.type === 'prebuilt-chunk') {
  360. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  361. }
  362. }
  363. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  364. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  365. }
  366. };
  367. this.filesByReferenceId = baseFileEmitter
  368. ? new Map(baseFileEmitter.filesByReferenceId)
  369. : new Map();
  370. baseFileEmitter?.addOutputFileEmitter(this);
  371. }
  372. addOutputFileEmitter(outputFileEmitter) {
  373. this.outputFileEmitters.push(outputFileEmitter);
  374. }
  375. assignReferenceId(file, idBase) {
  376. let referenceId = idBase;
  377. do {
  378. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  379. } while (this.filesByReferenceId.has(referenceId) ||
  380. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  381. file.referenceId = referenceId;
  382. this.filesByReferenceId.set(referenceId, file);
  383. for (const { filesByReferenceId } of this.outputFileEmitters) {
  384. filesByReferenceId.set(referenceId, file);
  385. }
  386. return referenceId;
  387. }
  388. createPrebuiltChunk(prebuiltChunk) {
  389. return {
  390. code: prebuiltChunk.code,
  391. dynamicImports: [],
  392. exports: prebuiltChunk.exports || [],
  393. facadeModuleId: null,
  394. fileName: prebuiltChunk.fileName,
  395. implicitlyLoadedBefore: [],
  396. importedBindings: {},
  397. imports: [],
  398. isDynamicEntry: false,
  399. isEntry: false,
  400. isImplicitEntry: false,
  401. map: prebuiltChunk.map || null,
  402. moduleIds: [],
  403. modules: {},
  404. name: prebuiltChunk.fileName,
  405. preliminaryFileName: prebuiltChunk.fileName,
  406. referencedFiles: [],
  407. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  408. type: 'chunk'
  409. };
  410. }
  411. emitAsset(emittedAsset) {
  412. const source = emittedAsset.source === undefined
  413. ? undefined
  414. : getValidSource(emittedAsset.source, emittedAsset, null);
  415. const originalFileName = emittedAsset.originalFileName || null;
  416. if (typeof originalFileName === 'string') {
  417. this.graph.watchFiles[originalFileName] = true;
  418. }
  419. const consumedAsset = {
  420. fileName: emittedAsset.fileName,
  421. name: emittedAsset.name,
  422. needsCodeReference: !!emittedAsset.needsCodeReference,
  423. originalFileName,
  424. referenceId: '',
  425. source,
  426. type: 'asset'
  427. };
  428. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  429. if (this.output) {
  430. this.emitAssetWithReferenceId(consumedAsset, this.output);
  431. }
  432. else {
  433. for (const fileEmitter of this.outputFileEmitters) {
  434. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  435. }
  436. }
  437. return referenceId;
  438. }
  439. emitAssetWithReferenceId(consumedAsset, output) {
  440. const { fileName, source } = consumedAsset;
  441. if (fileName) {
  442. reserveFileNameInBundle(fileName, output, this.options.onLog);
  443. }
  444. if (source !== undefined) {
  445. this.finalizeAdditionalAsset(consumedAsset, source, output);
  446. }
  447. }
  448. emitChunk(emittedChunk) {
  449. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  450. return parseAst_js.error(parseAst_js.logInvalidRollupPhaseForChunkEmission());
  451. }
  452. if (typeof emittedChunk.id !== 'string') {
  453. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  454. }
  455. const consumedChunk = {
  456. fileName: emittedChunk.fileName,
  457. module: null,
  458. name: emittedChunk.name || emittedChunk.id,
  459. referenceId: '',
  460. type: 'chunk'
  461. };
  462. this.graph.moduleLoader
  463. .emitChunk(emittedChunk)
  464. .then(module => (consumedChunk.module = module))
  465. .catch(() => {
  466. // Avoid unhandled Promise rejection as the error will be thrown later
  467. // once module loading has finished
  468. });
  469. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  470. }
  471. emitPrebuiltChunk(emitPrebuiltChunk) {
  472. if (typeof emitPrebuiltChunk.code !== 'string') {
  473. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  474. }
  475. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  476. parseAst_js.isPathFragment(emitPrebuiltChunk.fileName)) {
  477. 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}".`));
  478. }
  479. const consumedPrebuiltChunk = {
  480. code: emitPrebuiltChunk.code,
  481. exports: emitPrebuiltChunk.exports,
  482. fileName: emitPrebuiltChunk.fileName,
  483. map: emitPrebuiltChunk.map,
  484. referenceId: '',
  485. type: 'prebuilt-chunk'
  486. };
  487. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  488. if (this.output) {
  489. this.output.bundle[consumedPrebuiltChunk.fileName] =
  490. this.createPrebuiltChunk(consumedPrebuiltChunk);
  491. }
  492. return referenceId;
  493. }
  494. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  495. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  496. // Deduplicate assets if an explicit fileName is not provided
  497. if (!fileName) {
  498. const sourceHash = getHash(source);
  499. fileName = fileNamesBySourceHash.get(sourceHash);
  500. if (!fileName) {
  501. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  502. fileNamesBySourceHash.set(sourceHash, fileName);
  503. }
  504. }
  505. // We must not modify the original assets to avoid interaction between outputs
  506. const assetWithFileName = { ...consumedFile, fileName, source };
  507. this.filesByReferenceId.set(referenceId, assetWithFileName);
  508. const existingAsset = bundle[fileName];
  509. if (existingAsset?.type === 'asset') {
  510. existingAsset.needsCodeReference &&= needsCodeReference;
  511. if (name) {
  512. existingAsset.names.push(name);
  513. }
  514. if (originalFileName) {
  515. existingAsset.originalFileNames.push(originalFileName);
  516. }
  517. }
  518. else {
  519. const { options } = this;
  520. bundle[fileName] = {
  521. fileName,
  522. get name() {
  523. // Additionally, this should be non-enumerable in the next major
  524. 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);
  525. return name;
  526. },
  527. names: name ? [name] : [],
  528. needsCodeReference,
  529. get originalFileName() {
  530. // Additionally, this should be non-enumerable in the next major
  531. 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);
  532. return originalFileName;
  533. },
  534. originalFileNames: originalFileName ? [originalFileName] : [],
  535. source,
  536. type: 'asset'
  537. };
  538. }
  539. }
  540. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  541. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  542. let fileName = '';
  543. let usedConsumedFile;
  544. let needsCodeReference = true;
  545. for (const consumedFile of consumedFiles) {
  546. needsCodeReference &&= consumedFile.needsCodeReference;
  547. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  548. if (!fileName ||
  549. assetFileName.length < fileName.length ||
  550. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  551. fileName = assetFileName;
  552. usedConsumedFile = consumedFile;
  553. }
  554. }
  555. fileNamesBySourceHash.set(sourceHash, fileName);
  556. for (const consumedFile of consumedFiles) {
  557. // We must not modify the original assets to avoid interaction between outputs
  558. const assetWithFileName = { ...consumedFile, fileName };
  559. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  560. }
  561. const { options } = this;
  562. bundle[fileName] = {
  563. fileName,
  564. get name() {
  565. // Additionally, this should be non-enumerable in the next major
  566. 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);
  567. return usedConsumedFile.name;
  568. },
  569. names,
  570. needsCodeReference,
  571. get originalFileName() {
  572. // Additionally, this should be non-enumerable in the next major
  573. 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);
  574. return usedConsumedFile.originalFileName;
  575. },
  576. originalFileNames,
  577. source: usedConsumedFile.source,
  578. type: 'asset'
  579. };
  580. }
  581. }
  582. function getNamesFromAssets(consumedFiles) {
  583. const names = [];
  584. const originalFileNames = [];
  585. for (const { name, originalFileName } of consumedFiles) {
  586. if (typeof name === 'string') {
  587. names.push(name);
  588. }
  589. if (originalFileName) {
  590. originalFileNames.push(originalFileName);
  591. }
  592. }
  593. originalFileNames.sort();
  594. // Sort by length first and then alphabetically so that the order is stable
  595. // and the shortest names come first
  596. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  597. return { names, originalFileNames };
  598. }
  599. const doNothing = () => { };
  600. async function asyncFlatten(array) {
  601. do {
  602. array = (await Promise.all(array)).flat(Infinity);
  603. } while (array.some((v) => v?.then));
  604. return array;
  605. }
  606. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  607. const { onwarn, onLog } = config;
  608. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  609. if (onLog) {
  610. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  611. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  612. if (level === parseAst_js.LOGLEVEL_ERROR) {
  613. return parseAst_js.error(normalizeLog(handledLog));
  614. }
  615. if (parseAst_js.logLevelPriority[level] >= minimalPriority) {
  616. defaultOnLog(level, normalizeLog(handledLog));
  617. }
  618. });
  619. }
  620. return defaultOnLog;
  621. };
  622. const getDefaultOnLog = (printLog, onwarn) => onwarn
  623. ? (level, log) => {
  624. if (level === parseAst_js.LOGLEVEL_WARN) {
  625. onwarn(addLogToString(log), warning => printLog(parseAst_js.LOGLEVEL_WARN, normalizeLog(warning)));
  626. }
  627. else {
  628. printLog(level, log);
  629. }
  630. }
  631. : printLog;
  632. const addLogToString = (log) => {
  633. Object.defineProperty(log, 'toString', {
  634. value: () => log.message,
  635. writable: true
  636. });
  637. return log;
  638. };
  639. const normalizeLog = (log) => typeof log === 'string'
  640. ? { message: log }
  641. : typeof log === 'function'
  642. ? normalizeLog(log())
  643. : log;
  644. const defaultPrintLog = (level, { message }) => {
  645. switch (level) {
  646. case parseAst_js.LOGLEVEL_WARN: {
  647. return console.warn(message);
  648. }
  649. case parseAst_js.LOGLEVEL_DEBUG: {
  650. return console.debug(message);
  651. }
  652. default: {
  653. return console.info(message);
  654. }
  655. }
  656. };
  657. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  658. const validOptionSet = new Set(validOptions);
  659. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  660. if (unknownOptions.length > 0) {
  661. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  662. }
  663. }
  664. const treeshakePresets = {
  665. recommended: {
  666. annotations: true,
  667. correctVarValueBeforeDeclaration: false,
  668. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  669. moduleSideEffects: () => true,
  670. propertyReadSideEffects: true,
  671. tryCatchDeoptimization: true,
  672. unknownGlobalSideEffects: false
  673. },
  674. safest: {
  675. annotations: true,
  676. correctVarValueBeforeDeclaration: true,
  677. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  678. moduleSideEffects: () => true,
  679. propertyReadSideEffects: true,
  680. tryCatchDeoptimization: true,
  681. unknownGlobalSideEffects: true
  682. },
  683. smallest: {
  684. annotations: true,
  685. correctVarValueBeforeDeclaration: false,
  686. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  687. moduleSideEffects: () => false,
  688. propertyReadSideEffects: false,
  689. tryCatchDeoptimization: false,
  690. unknownGlobalSideEffects: false
  691. }
  692. };
  693. const jsxPresets = {
  694. preserve: {
  695. factory: null,
  696. fragment: null,
  697. importSource: null,
  698. mode: 'preserve'
  699. },
  700. 'preserve-react': {
  701. factory: 'React.createElement',
  702. fragment: 'React.Fragment',
  703. importSource: 'react',
  704. mode: 'preserve'
  705. },
  706. react: {
  707. factory: 'React.createElement',
  708. fragment: 'React.Fragment',
  709. importSource: 'react',
  710. mode: 'classic'
  711. },
  712. 'react-jsx': {
  713. factory: 'React.createElement',
  714. importSource: 'react',
  715. jsxImportSource: 'react/jsx-runtime',
  716. mode: 'automatic'
  717. }
  718. };
  719. const generatedCodePresets = {
  720. es2015: {
  721. arrowFunctions: true,
  722. constBindings: true,
  723. objectShorthand: true,
  724. reservedNamesAsProps: true,
  725. symbols: true
  726. },
  727. es5: {
  728. arrowFunctions: false,
  729. constBindings: false,
  730. objectShorthand: false,
  731. reservedNamesAsProps: true,
  732. symbols: false
  733. }
  734. };
  735. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  736. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  737. if (typeof value === 'string') {
  738. const preset = presets[value];
  739. if (preset) {
  740. return preset;
  741. }
  742. 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));
  743. }
  744. return objectifyOption(value);
  745. };
  746. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  747. const presetName = value?.preset;
  748. if (presetName) {
  749. const preset = presets[presetName];
  750. if (preset) {
  751. return { ...preset, ...value };
  752. }
  753. else {
  754. parseAst_js.error(parseAst_js.logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${parseAst_js.printQuotedStringList(Object.keys(presets))}`, presetName));
  755. }
  756. }
  757. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  758. };
  759. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  760. function getLogHandler(level, code, logger, pluginName, logLevel) {
  761. if (parseAst_js.logLevelPriority[level] < parseAst_js.logLevelPriority[logLevel]) {
  762. return doNothing;
  763. }
  764. return (log, pos) => {
  765. if (pos != null) {
  766. logger(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidLogPosition(pluginName));
  767. }
  768. log = normalizeLog(log);
  769. if (log.code && !log.pluginCode) {
  770. log.pluginCode = log.code;
  771. }
  772. log.code = code;
  773. log.plugin = pluginName;
  774. logger(level, log);
  775. };
  776. }
  777. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  778. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  779. function createPluginCache(cache) {
  780. return {
  781. delete(id) {
  782. return delete cache[id];
  783. },
  784. get(id) {
  785. const item = cache[id];
  786. if (!item)
  787. return;
  788. item[0] = 0;
  789. return item[1];
  790. },
  791. has(id) {
  792. const item = cache[id];
  793. if (!item)
  794. return false;
  795. item[0] = 0;
  796. return true;
  797. },
  798. set(id, value) {
  799. cache[id] = [0, value];
  800. }
  801. };
  802. }
  803. function getTrackedPluginCache(pluginCache, onUse) {
  804. return {
  805. delete(id) {
  806. onUse();
  807. return pluginCache.delete(id);
  808. },
  809. get(id) {
  810. onUse();
  811. return pluginCache.get(id);
  812. },
  813. has(id) {
  814. onUse();
  815. return pluginCache.has(id);
  816. },
  817. set(id, value) {
  818. onUse();
  819. return pluginCache.set(id, value);
  820. }
  821. };
  822. }
  823. const NO_CACHE = {
  824. delete() {
  825. return false;
  826. },
  827. get() {
  828. return undefined;
  829. },
  830. has() {
  831. return false;
  832. },
  833. set() { }
  834. };
  835. function uncacheablePluginError(pluginName) {
  836. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  837. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  838. return parseAst_js.error(parseAst_js.logAnonymousPluginCache());
  839. }
  840. return parseAst_js.error(parseAst_js.logDuplicatePluginName(pluginName));
  841. }
  842. function getCacheForUncacheablePlugin(pluginName) {
  843. return {
  844. delete() {
  845. return uncacheablePluginError(pluginName);
  846. },
  847. get() {
  848. return uncacheablePluginError(pluginName);
  849. },
  850. has() {
  851. return uncacheablePluginError(pluginName);
  852. },
  853. set() {
  854. return uncacheablePluginError(pluginName);
  855. }
  856. };
  857. }
  858. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  859. const { logLevel, onLog } = options;
  860. let cacheable = true;
  861. if (typeof plugin.cacheKey !== 'string') {
  862. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  863. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  864. existingPluginNames.has(plugin.name)) {
  865. cacheable = false;
  866. }
  867. else {
  868. existingPluginNames.add(plugin.name);
  869. }
  870. }
  871. let cacheInstance;
  872. if (!pluginCache) {
  873. cacheInstance = NO_CACHE;
  874. }
  875. else if (cacheable) {
  876. const cacheKey = plugin.cacheKey || plugin.name;
  877. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  878. }
  879. else {
  880. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  881. }
  882. return {
  883. addWatchFile(id) {
  884. graph.watchFiles[id] = true;
  885. },
  886. cache: cacheInstance,
  887. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  888. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  889. error(error_) {
  890. return parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), plugin.name));
  891. },
  892. fs: options.fs,
  893. getFileName: fileEmitter.getFileName,
  894. getModuleIds: () => graph.modulesById.keys(),
  895. getModuleInfo: graph.getModuleInfo,
  896. getWatchFiles: () => Object.keys(graph.watchFiles),
  897. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  898. load(resolvedId) {
  899. return graph.moduleLoader.preloadModule(resolvedId);
  900. },
  901. meta: {
  902. rollupVersion: version,
  903. watchMode: graph.watchMode
  904. },
  905. parse: parseAst_js.parseAst,
  906. resolve(source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = parseAst_js.BLANK) {
  907. skipSelf ??= true;
  908. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes, skipSelf ? [{ importer, plugin, source }] : null);
  909. },
  910. setAssetSource: fileEmitter.setAssetSource,
  911. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  912. };
  913. }
  914. function getDefaultExportFromCjs (x) {
  915. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  916. }
  917. function getAugmentedNamespace(n) {
  918. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  919. var f = n.default;
  920. if (typeof f == "function") {
  921. var a = function a () {
  922. var isInstance = false;
  923. try {
  924. isInstance = this instanceof a;
  925. } catch {}
  926. if (isInstance) {
  927. return Reflect.construct(f, arguments, this.constructor);
  928. }
  929. return f.apply(this, arguments);
  930. };
  931. a.prototype = f.prototype;
  932. } else a = {};
  933. Object.defineProperty(a, '__esModule', {value: true});
  934. Object.keys(n).forEach(function (k) {
  935. var d = Object.getOwnPropertyDescriptor(n, k);
  936. Object.defineProperty(a, k, d.get ? d : {
  937. enumerable: true,
  938. get: function () {
  939. return n[k];
  940. }
  941. });
  942. });
  943. return a;
  944. }
  945. var utils = {};
  946. var constants;
  947. var hasRequiredConstants;
  948. function requireConstants () {
  949. if (hasRequiredConstants) return constants;
  950. hasRequiredConstants = 1;
  951. const WIN_SLASH = '\\\\/';
  952. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  953. const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
  954. /**
  955. * Posix glob regex
  956. */
  957. const DOT_LITERAL = '\\.';
  958. const PLUS_LITERAL = '\\+';
  959. const QMARK_LITERAL = '\\?';
  960. const SLASH_LITERAL = '\\/';
  961. const ONE_CHAR = '(?=.)';
  962. const QMARK = '[^/]';
  963. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  964. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  965. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  966. const NO_DOT = `(?!${DOT_LITERAL})`;
  967. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  968. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  969. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  970. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  971. const STAR = `${QMARK}*?`;
  972. const SEP = '/';
  973. const POSIX_CHARS = {
  974. DOT_LITERAL,
  975. PLUS_LITERAL,
  976. QMARK_LITERAL,
  977. SLASH_LITERAL,
  978. ONE_CHAR,
  979. QMARK,
  980. END_ANCHOR,
  981. DOTS_SLASH,
  982. NO_DOT,
  983. NO_DOTS,
  984. NO_DOT_SLASH,
  985. NO_DOTS_SLASH,
  986. QMARK_NO_DOT,
  987. STAR,
  988. START_ANCHOR,
  989. SEP
  990. };
  991. /**
  992. * Windows glob regex
  993. */
  994. const WINDOWS_CHARS = {
  995. ...POSIX_CHARS,
  996. SLASH_LITERAL: `[${WIN_SLASH}]`,
  997. QMARK: WIN_NO_SLASH,
  998. STAR: `${WIN_NO_SLASH}*?`,
  999. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  1000. NO_DOT: `(?!${DOT_LITERAL})`,
  1001. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1002. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1003. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1004. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1005. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1006. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  1007. SEP: '\\'
  1008. };
  1009. /**
  1010. * POSIX Bracket Regex
  1011. */
  1012. const POSIX_REGEX_SOURCE = {
  1013. __proto__: null,
  1014. alnum: 'a-zA-Z0-9',
  1015. alpha: 'a-zA-Z',
  1016. ascii: '\\x00-\\x7F',
  1017. blank: ' \\t',
  1018. cntrl: '\\x00-\\x1F\\x7F',
  1019. digit: '0-9',
  1020. graph: '\\x21-\\x7E',
  1021. lower: 'a-z',
  1022. print: '\\x20-\\x7E ',
  1023. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1024. space: ' \\t\\r\\n\\v\\f',
  1025. upper: 'A-Z',
  1026. word: 'A-Za-z0-9_',
  1027. xdigit: 'A-Fa-f0-9'
  1028. };
  1029. constants = {
  1030. DEFAULT_MAX_EXTGLOB_RECURSION,
  1031. MAX_LENGTH: 1024 * 64,
  1032. POSIX_REGEX_SOURCE,
  1033. // regular expressions
  1034. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1035. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1036. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1037. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1038. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1039. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1040. // Replace globs with equivalent patterns to reduce parsing time.
  1041. REPLACEMENTS: {
  1042. __proto__: null,
  1043. '***': '*',
  1044. '**/**': '**',
  1045. '**/**/**': '**'
  1046. },
  1047. // Digits
  1048. CHAR_0: 48, /* 0 */
  1049. CHAR_9: 57, /* 9 */
  1050. // Alphabet chars.
  1051. CHAR_UPPERCASE_A: 65, /* A */
  1052. CHAR_LOWERCASE_A: 97, /* a */
  1053. CHAR_UPPERCASE_Z: 90, /* Z */
  1054. CHAR_LOWERCASE_Z: 122, /* z */
  1055. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1056. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1057. CHAR_ASTERISK: 42, /* * */
  1058. // Non-alphabetic chars.
  1059. CHAR_AMPERSAND: 38, /* & */
  1060. CHAR_AT: 64, /* @ */
  1061. CHAR_BACKWARD_SLASH: 92, /* \ */
  1062. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1063. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1064. CHAR_COLON: 58, /* : */
  1065. CHAR_COMMA: 44, /* , */
  1066. CHAR_DOT: 46, /* . */
  1067. CHAR_DOUBLE_QUOTE: 34, /* " */
  1068. CHAR_EQUAL: 61, /* = */
  1069. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1070. CHAR_FORM_FEED: 12, /* \f */
  1071. CHAR_FORWARD_SLASH: 47, /* / */
  1072. CHAR_GRAVE_ACCENT: 96, /* ` */
  1073. CHAR_HASH: 35, /* # */
  1074. CHAR_HYPHEN_MINUS: 45, /* - */
  1075. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1076. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1077. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1078. CHAR_LINE_FEED: 10, /* \n */
  1079. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1080. CHAR_PERCENT: 37, /* % */
  1081. CHAR_PLUS: 43, /* + */
  1082. CHAR_QUESTION_MARK: 63, /* ? */
  1083. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1084. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1085. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1086. CHAR_SEMICOLON: 59, /* ; */
  1087. CHAR_SINGLE_QUOTE: 39, /* ' */
  1088. CHAR_SPACE: 32, /* */
  1089. CHAR_TAB: 9, /* \t */
  1090. CHAR_UNDERSCORE: 95, /* _ */
  1091. CHAR_VERTICAL_LINE: 124, /* | */
  1092. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1093. /**
  1094. * Create EXTGLOB_CHARS
  1095. */
  1096. extglobChars(chars) {
  1097. return {
  1098. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1099. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1100. '+': { type: 'plus', open: '(?:', close: ')+' },
  1101. '*': { type: 'star', open: '(?:', close: ')*' },
  1102. '@': { type: 'at', open: '(?:', close: ')' }
  1103. };
  1104. },
  1105. /**
  1106. * Create GLOB_CHARS
  1107. */
  1108. globChars(win32) {
  1109. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1110. }
  1111. };
  1112. return constants;
  1113. }
  1114. /*global navigator*/
  1115. var hasRequiredUtils;
  1116. function requireUtils () {
  1117. if (hasRequiredUtils) return utils;
  1118. hasRequiredUtils = 1;
  1119. (function (exports$1) {
  1120. const {
  1121. REGEX_BACKSLASH,
  1122. REGEX_REMOVE_BACKSLASH,
  1123. REGEX_SPECIAL_CHARS,
  1124. REGEX_SPECIAL_CHARS_GLOBAL
  1125. } = /*@__PURE__*/ requireConstants();
  1126. exports$1.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1127. exports$1.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1128. exports$1.isRegexChar = str => str.length === 1 && exports$1.hasRegexChars(str);
  1129. exports$1.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1130. exports$1.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1131. exports$1.isWindows = () => {
  1132. if (typeof navigator !== 'undefined' && navigator.platform) {
  1133. const platform = navigator.platform.toLowerCase();
  1134. return platform === 'win32' || platform === 'windows';
  1135. }
  1136. if (typeof process !== 'undefined' && process.platform) {
  1137. return process.platform === 'win32';
  1138. }
  1139. return false;
  1140. };
  1141. exports$1.removeBackslashes = str => {
  1142. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1143. return match === '\\' ? '' : match;
  1144. });
  1145. };
  1146. exports$1.escapeLast = (input, char, lastIdx) => {
  1147. const idx = input.lastIndexOf(char, lastIdx);
  1148. if (idx === -1) return input;
  1149. if (input[idx - 1] === '\\') return exports$1.escapeLast(input, char, idx - 1);
  1150. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1151. };
  1152. exports$1.removePrefix = (input, state = {}) => {
  1153. let output = input;
  1154. if (output.startsWith('./')) {
  1155. output = output.slice(2);
  1156. state.prefix = './';
  1157. }
  1158. return output;
  1159. };
  1160. exports$1.wrapOutput = (input, state = {}, options = {}) => {
  1161. const prepend = options.contains ? '' : '^';
  1162. const append = options.contains ? '' : '$';
  1163. let output = `${prepend}(?:${input})${append}`;
  1164. if (state.negated === true) {
  1165. output = `(?:^(?!${output}).*$)`;
  1166. }
  1167. return output;
  1168. };
  1169. exports$1.basename = (path, { windows } = {}) => {
  1170. const segs = path.split(windows ? /[\\/]/ : '/');
  1171. const last = segs[segs.length - 1];
  1172. if (last === '') {
  1173. return segs[segs.length - 2];
  1174. }
  1175. return last;
  1176. };
  1177. } (utils));
  1178. return utils;
  1179. }
  1180. var scan_1;
  1181. var hasRequiredScan;
  1182. function requireScan () {
  1183. if (hasRequiredScan) return scan_1;
  1184. hasRequiredScan = 1;
  1185. const utils = /*@__PURE__*/ requireUtils();
  1186. const {
  1187. CHAR_ASTERISK, /* * */
  1188. CHAR_AT, /* @ */
  1189. CHAR_BACKWARD_SLASH, /* \ */
  1190. CHAR_COMMA, /* , */
  1191. CHAR_DOT, /* . */
  1192. CHAR_EXCLAMATION_MARK, /* ! */
  1193. CHAR_FORWARD_SLASH, /* / */
  1194. CHAR_LEFT_CURLY_BRACE, /* { */
  1195. CHAR_LEFT_PARENTHESES, /* ( */
  1196. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1197. CHAR_PLUS, /* + */
  1198. CHAR_QUESTION_MARK, /* ? */
  1199. CHAR_RIGHT_CURLY_BRACE, /* } */
  1200. CHAR_RIGHT_PARENTHESES, /* ) */
  1201. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1202. } = /*@__PURE__*/ requireConstants();
  1203. const isPathSeparator = code => {
  1204. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1205. };
  1206. const depth = token => {
  1207. if (token.isPrefix !== true) {
  1208. token.depth = token.isGlobstar ? Infinity : 1;
  1209. }
  1210. };
  1211. /**
  1212. * Quickly scans a glob pattern and returns an object with a handful of
  1213. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1214. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1215. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1216. *
  1217. * ```js
  1218. * const pm = require('picomatch');
  1219. * console.log(pm.scan('foo/bar/*.js'));
  1220. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1221. * ```
  1222. * @param {String} `str`
  1223. * @param {Object} `options`
  1224. * @return {Object} Returns an object with tokens and regex source string.
  1225. * @api public
  1226. */
  1227. const scan = (input, options) => {
  1228. const opts = options || {};
  1229. const length = input.length - 1;
  1230. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1231. const slashes = [];
  1232. const tokens = [];
  1233. const parts = [];
  1234. let str = input;
  1235. let index = -1;
  1236. let start = 0;
  1237. let lastIndex = 0;
  1238. let isBrace = false;
  1239. let isBracket = false;
  1240. let isGlob = false;
  1241. let isExtglob = false;
  1242. let isGlobstar = false;
  1243. let braceEscaped = false;
  1244. let backslashes = false;
  1245. let negated = false;
  1246. let negatedExtglob = false;
  1247. let finished = false;
  1248. let braces = 0;
  1249. let prev;
  1250. let code;
  1251. let token = { value: '', depth: 0, isGlob: false };
  1252. const eos = () => index >= length;
  1253. const peek = () => str.charCodeAt(index + 1);
  1254. const advance = () => {
  1255. prev = code;
  1256. return str.charCodeAt(++index);
  1257. };
  1258. while (index < length) {
  1259. code = advance();
  1260. let next;
  1261. if (code === CHAR_BACKWARD_SLASH) {
  1262. backslashes = token.backslashes = true;
  1263. code = advance();
  1264. if (code === CHAR_LEFT_CURLY_BRACE) {
  1265. braceEscaped = true;
  1266. }
  1267. continue;
  1268. }
  1269. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1270. braces++;
  1271. while (eos() !== true && (code = advance())) {
  1272. if (code === CHAR_BACKWARD_SLASH) {
  1273. backslashes = token.backslashes = true;
  1274. advance();
  1275. continue;
  1276. }
  1277. if (code === CHAR_LEFT_CURLY_BRACE) {
  1278. braces++;
  1279. continue;
  1280. }
  1281. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1282. isBrace = token.isBrace = true;
  1283. isGlob = token.isGlob = true;
  1284. finished = true;
  1285. if (scanToEnd === true) {
  1286. continue;
  1287. }
  1288. break;
  1289. }
  1290. if (braceEscaped !== true && code === CHAR_COMMA) {
  1291. isBrace = token.isBrace = true;
  1292. isGlob = token.isGlob = true;
  1293. finished = true;
  1294. if (scanToEnd === true) {
  1295. continue;
  1296. }
  1297. break;
  1298. }
  1299. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1300. braces--;
  1301. if (braces === 0) {
  1302. braceEscaped = false;
  1303. isBrace = token.isBrace = true;
  1304. finished = true;
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. if (scanToEnd === true) {
  1310. continue;
  1311. }
  1312. break;
  1313. }
  1314. if (code === CHAR_FORWARD_SLASH) {
  1315. slashes.push(index);
  1316. tokens.push(token);
  1317. token = { value: '', depth: 0, isGlob: false };
  1318. if (finished === true) continue;
  1319. if (prev === CHAR_DOT && index === (start + 1)) {
  1320. start += 2;
  1321. continue;
  1322. }
  1323. lastIndex = index + 1;
  1324. continue;
  1325. }
  1326. if (opts.noext !== true) {
  1327. const isExtglobChar = code === CHAR_PLUS
  1328. || code === CHAR_AT
  1329. || code === CHAR_ASTERISK
  1330. || code === CHAR_QUESTION_MARK
  1331. || code === CHAR_EXCLAMATION_MARK;
  1332. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1333. isGlob = token.isGlob = true;
  1334. isExtglob = token.isExtglob = true;
  1335. finished = true;
  1336. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1337. negatedExtglob = true;
  1338. }
  1339. if (scanToEnd === true) {
  1340. while (eos() !== true && (code = advance())) {
  1341. if (code === CHAR_BACKWARD_SLASH) {
  1342. backslashes = token.backslashes = true;
  1343. code = advance();
  1344. continue;
  1345. }
  1346. if (code === CHAR_RIGHT_PARENTHESES) {
  1347. isGlob = token.isGlob = true;
  1348. finished = true;
  1349. break;
  1350. }
  1351. }
  1352. continue;
  1353. }
  1354. break;
  1355. }
  1356. }
  1357. if (code === CHAR_ASTERISK) {
  1358. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1359. isGlob = token.isGlob = true;
  1360. finished = true;
  1361. if (scanToEnd === true) {
  1362. continue;
  1363. }
  1364. break;
  1365. }
  1366. if (code === CHAR_QUESTION_MARK) {
  1367. isGlob = token.isGlob = true;
  1368. finished = true;
  1369. if (scanToEnd === true) {
  1370. continue;
  1371. }
  1372. break;
  1373. }
  1374. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1375. while (eos() !== true && (next = advance())) {
  1376. if (next === CHAR_BACKWARD_SLASH) {
  1377. backslashes = token.backslashes = true;
  1378. advance();
  1379. continue;
  1380. }
  1381. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1382. isBracket = token.isBracket = true;
  1383. isGlob = token.isGlob = true;
  1384. finished = true;
  1385. break;
  1386. }
  1387. }
  1388. if (scanToEnd === true) {
  1389. continue;
  1390. }
  1391. break;
  1392. }
  1393. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1394. negated = token.negated = true;
  1395. start++;
  1396. continue;
  1397. }
  1398. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1399. isGlob = token.isGlob = true;
  1400. if (scanToEnd === true) {
  1401. while (eos() !== true && (code = advance())) {
  1402. if (code === CHAR_LEFT_PARENTHESES) {
  1403. backslashes = token.backslashes = true;
  1404. code = advance();
  1405. continue;
  1406. }
  1407. if (code === CHAR_RIGHT_PARENTHESES) {
  1408. finished = true;
  1409. break;
  1410. }
  1411. }
  1412. continue;
  1413. }
  1414. break;
  1415. }
  1416. if (isGlob === true) {
  1417. finished = true;
  1418. if (scanToEnd === true) {
  1419. continue;
  1420. }
  1421. break;
  1422. }
  1423. }
  1424. if (opts.noext === true) {
  1425. isExtglob = false;
  1426. isGlob = false;
  1427. }
  1428. let base = str;
  1429. let prefix = '';
  1430. let glob = '';
  1431. if (start > 0) {
  1432. prefix = str.slice(0, start);
  1433. str = str.slice(start);
  1434. lastIndex -= start;
  1435. }
  1436. if (base && isGlob === true && lastIndex > 0) {
  1437. base = str.slice(0, lastIndex);
  1438. glob = str.slice(lastIndex);
  1439. } else if (isGlob === true) {
  1440. base = '';
  1441. glob = str;
  1442. } else {
  1443. base = str;
  1444. }
  1445. if (base && base !== '' && base !== '/' && base !== str) {
  1446. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1447. base = base.slice(0, -1);
  1448. }
  1449. }
  1450. if (opts.unescape === true) {
  1451. if (glob) glob = utils.removeBackslashes(glob);
  1452. if (base && backslashes === true) {
  1453. base = utils.removeBackslashes(base);
  1454. }
  1455. }
  1456. const state = {
  1457. prefix,
  1458. input,
  1459. start,
  1460. base,
  1461. glob,
  1462. isBrace,
  1463. isBracket,
  1464. isGlob,
  1465. isExtglob,
  1466. isGlobstar,
  1467. negated,
  1468. negatedExtglob
  1469. };
  1470. if (opts.tokens === true) {
  1471. state.maxDepth = 0;
  1472. if (!isPathSeparator(code)) {
  1473. tokens.push(token);
  1474. }
  1475. state.tokens = tokens;
  1476. }
  1477. if (opts.parts === true || opts.tokens === true) {
  1478. let prevIndex;
  1479. for (let idx = 0; idx < slashes.length; idx++) {
  1480. const n = prevIndex ? prevIndex + 1 : start;
  1481. const i = slashes[idx];
  1482. const value = input.slice(n, i);
  1483. if (opts.tokens) {
  1484. if (idx === 0 && start !== 0) {
  1485. tokens[idx].isPrefix = true;
  1486. tokens[idx].value = prefix;
  1487. } else {
  1488. tokens[idx].value = value;
  1489. }
  1490. depth(tokens[idx]);
  1491. state.maxDepth += tokens[idx].depth;
  1492. }
  1493. if (idx !== 0 || value !== '') {
  1494. parts.push(value);
  1495. }
  1496. prevIndex = i;
  1497. }
  1498. if (prevIndex && prevIndex + 1 < input.length) {
  1499. const value = input.slice(prevIndex + 1);
  1500. parts.push(value);
  1501. if (opts.tokens) {
  1502. tokens[tokens.length - 1].value = value;
  1503. depth(tokens[tokens.length - 1]);
  1504. state.maxDepth += tokens[tokens.length - 1].depth;
  1505. }
  1506. }
  1507. state.slashes = slashes;
  1508. state.parts = parts;
  1509. }
  1510. return state;
  1511. };
  1512. scan_1 = scan;
  1513. return scan_1;
  1514. }
  1515. var parse_1;
  1516. var hasRequiredParse;
  1517. function requireParse () {
  1518. if (hasRequiredParse) return parse_1;
  1519. hasRequiredParse = 1;
  1520. const constants = /*@__PURE__*/ requireConstants();
  1521. const utils = /*@__PURE__*/ requireUtils();
  1522. /**
  1523. * Constants
  1524. */
  1525. const {
  1526. MAX_LENGTH,
  1527. POSIX_REGEX_SOURCE,
  1528. REGEX_NON_SPECIAL_CHARS,
  1529. REGEX_SPECIAL_CHARS_BACKREF,
  1530. REPLACEMENTS
  1531. } = constants;
  1532. /**
  1533. * Helpers
  1534. */
  1535. const expandRange = (args, options) => {
  1536. if (typeof options.expandRange === 'function') {
  1537. return options.expandRange(...args, options);
  1538. }
  1539. args.sort();
  1540. const value = `[${args.join('-')}]`;
  1541. return value;
  1542. };
  1543. /**
  1544. * Create the message for a syntax error
  1545. */
  1546. const syntaxError = (type, char) => {
  1547. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1548. };
  1549. const splitTopLevel = input => {
  1550. const parts = [];
  1551. let bracket = 0;
  1552. let paren = 0;
  1553. let quote = 0;
  1554. let value = '';
  1555. let escaped = false;
  1556. for (const ch of input) {
  1557. if (escaped === true) {
  1558. value += ch;
  1559. escaped = false;
  1560. continue;
  1561. }
  1562. if (ch === '\\') {
  1563. value += ch;
  1564. escaped = true;
  1565. continue;
  1566. }
  1567. if (ch === '"') {
  1568. quote = quote === 1 ? 0 : 1;
  1569. value += ch;
  1570. continue;
  1571. }
  1572. if (quote === 0) {
  1573. if (ch === '[') {
  1574. bracket++;
  1575. } else if (ch === ']' && bracket > 0) {
  1576. bracket--;
  1577. } else if (bracket === 0) {
  1578. if (ch === '(') {
  1579. paren++;
  1580. } else if (ch === ')' && paren > 0) {
  1581. paren--;
  1582. } else if (ch === '|' && paren === 0) {
  1583. parts.push(value);
  1584. value = '';
  1585. continue;
  1586. }
  1587. }
  1588. }
  1589. value += ch;
  1590. }
  1591. parts.push(value);
  1592. return parts;
  1593. };
  1594. const isPlainBranch = branch => {
  1595. let escaped = false;
  1596. for (const ch of branch) {
  1597. if (escaped === true) {
  1598. escaped = false;
  1599. continue;
  1600. }
  1601. if (ch === '\\') {
  1602. escaped = true;
  1603. continue;
  1604. }
  1605. if (/[?*+@!()[\]{}]/.test(ch)) {
  1606. return false;
  1607. }
  1608. }
  1609. return true;
  1610. };
  1611. const normalizeSimpleBranch = branch => {
  1612. let value = branch.trim();
  1613. let changed = true;
  1614. while (changed === true) {
  1615. changed = false;
  1616. if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
  1617. value = value.slice(2, -1);
  1618. changed = true;
  1619. }
  1620. }
  1621. if (!isPlainBranch(value)) {
  1622. return;
  1623. }
  1624. return value.replace(/\\(.)/g, '$1');
  1625. };
  1626. const hasRepeatedCharPrefixOverlap = branches => {
  1627. const values = branches.map(normalizeSimpleBranch).filter(Boolean);
  1628. for (let i = 0; i < values.length; i++) {
  1629. for (let j = i + 1; j < values.length; j++) {
  1630. const a = values[i];
  1631. const b = values[j];
  1632. const char = a[0];
  1633. if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
  1634. continue;
  1635. }
  1636. if (a === b || a.startsWith(b) || b.startsWith(a)) {
  1637. return true;
  1638. }
  1639. }
  1640. }
  1641. return false;
  1642. };
  1643. const parseRepeatedExtglob = (pattern, requireEnd = true) => {
  1644. if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') {
  1645. return;
  1646. }
  1647. let bracket = 0;
  1648. let paren = 0;
  1649. let quote = 0;
  1650. let escaped = false;
  1651. for (let i = 1; i < pattern.length; i++) {
  1652. const ch = pattern[i];
  1653. if (escaped === true) {
  1654. escaped = false;
  1655. continue;
  1656. }
  1657. if (ch === '\\') {
  1658. escaped = true;
  1659. continue;
  1660. }
  1661. if (ch === '"') {
  1662. quote = quote === 1 ? 0 : 1;
  1663. continue;
  1664. }
  1665. if (quote === 1) {
  1666. continue;
  1667. }
  1668. if (ch === '[') {
  1669. bracket++;
  1670. continue;
  1671. }
  1672. if (ch === ']' && bracket > 0) {
  1673. bracket--;
  1674. continue;
  1675. }
  1676. if (bracket > 0) {
  1677. continue;
  1678. }
  1679. if (ch === '(') {
  1680. paren++;
  1681. continue;
  1682. }
  1683. if (ch === ')') {
  1684. paren--;
  1685. if (paren === 0) {
  1686. if (requireEnd === true && i !== pattern.length - 1) {
  1687. return;
  1688. }
  1689. return {
  1690. type: pattern[0],
  1691. body: pattern.slice(2, i),
  1692. end: i
  1693. };
  1694. }
  1695. }
  1696. }
  1697. };
  1698. const getStarExtglobSequenceOutput = pattern => {
  1699. let index = 0;
  1700. const chars = [];
  1701. while (index < pattern.length) {
  1702. const match = parseRepeatedExtglob(pattern.slice(index), false);
  1703. if (!match || match.type !== '*') {
  1704. return;
  1705. }
  1706. const branches = splitTopLevel(match.body).map(branch => branch.trim());
  1707. if (branches.length !== 1) {
  1708. return;
  1709. }
  1710. const branch = normalizeSimpleBranch(branches[0]);
  1711. if (!branch || branch.length !== 1) {
  1712. return;
  1713. }
  1714. chars.push(branch);
  1715. index += match.end + 1;
  1716. }
  1717. if (chars.length < 1) {
  1718. return;
  1719. }
  1720. const source = chars.length === 1
  1721. ? utils.escapeRegex(chars[0])
  1722. : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`;
  1723. return `${source}*`;
  1724. };
  1725. const repeatedExtglobRecursion = pattern => {
  1726. let depth = 0;
  1727. let value = pattern.trim();
  1728. let match = parseRepeatedExtglob(value);
  1729. while (match) {
  1730. depth++;
  1731. value = match.body.trim();
  1732. match = parseRepeatedExtglob(value);
  1733. }
  1734. return depth;
  1735. };
  1736. const analyzeRepeatedExtglob = (body, options) => {
  1737. if (options.maxExtglobRecursion === false) {
  1738. return { risky: false };
  1739. }
  1740. const max =
  1741. typeof options.maxExtglobRecursion === 'number'
  1742. ? options.maxExtglobRecursion
  1743. : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
  1744. const branches = splitTopLevel(body).map(branch => branch.trim());
  1745. if (branches.length > 1) {
  1746. if (
  1747. branches.some(branch => branch === '') ||
  1748. branches.some(branch => /^[*?]+$/.test(branch)) ||
  1749. hasRepeatedCharPrefixOverlap(branches)
  1750. ) {
  1751. return { risky: true };
  1752. }
  1753. }
  1754. for (const branch of branches) {
  1755. const safeOutput = getStarExtglobSequenceOutput(branch);
  1756. if (safeOutput) {
  1757. return { risky: true, safeOutput };
  1758. }
  1759. if (repeatedExtglobRecursion(branch) > max) {
  1760. return { risky: true };
  1761. }
  1762. }
  1763. return { risky: false };
  1764. };
  1765. /**
  1766. * Parse the given input string.
  1767. * @param {String} input
  1768. * @param {Object} options
  1769. * @return {Object}
  1770. */
  1771. const parse = (input, options) => {
  1772. if (typeof input !== 'string') {
  1773. throw new TypeError('Expected a string');
  1774. }
  1775. input = REPLACEMENTS[input] || input;
  1776. const opts = { ...options };
  1777. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1778. let len = input.length;
  1779. if (len > max) {
  1780. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1781. }
  1782. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1783. const tokens = [bos];
  1784. const capture = opts.capture ? '' : '?:';
  1785. // create constants based on platform, for windows or posix
  1786. const PLATFORM_CHARS = constants.globChars(opts.windows);
  1787. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  1788. const {
  1789. DOT_LITERAL,
  1790. PLUS_LITERAL,
  1791. SLASH_LITERAL,
  1792. ONE_CHAR,
  1793. DOTS_SLASH,
  1794. NO_DOT,
  1795. NO_DOT_SLASH,
  1796. NO_DOTS_SLASH,
  1797. QMARK,
  1798. QMARK_NO_DOT,
  1799. STAR,
  1800. START_ANCHOR
  1801. } = PLATFORM_CHARS;
  1802. const globstar = opts => {
  1803. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1804. };
  1805. const nodot = opts.dot ? '' : NO_DOT;
  1806. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1807. let star = opts.bash === true ? globstar(opts) : STAR;
  1808. if (opts.capture) {
  1809. star = `(${star})`;
  1810. }
  1811. // minimatch options support
  1812. if (typeof opts.noext === 'boolean') {
  1813. opts.noextglob = opts.noext;
  1814. }
  1815. const state = {
  1816. input,
  1817. index: -1,
  1818. start: 0,
  1819. dot: opts.dot === true,
  1820. consumed: '',
  1821. output: '',
  1822. prefix: '',
  1823. backtrack: false,
  1824. negated: false,
  1825. brackets: 0,
  1826. braces: 0,
  1827. parens: 0,
  1828. quotes: 0,
  1829. globstar: false,
  1830. tokens
  1831. };
  1832. input = utils.removePrefix(input, state);
  1833. len = input.length;
  1834. const extglobs = [];
  1835. const braces = [];
  1836. const stack = [];
  1837. let prev = bos;
  1838. let value;
  1839. /**
  1840. * Tokenizing helpers
  1841. */
  1842. const eos = () => state.index === len - 1;
  1843. const peek = state.peek = (n = 1) => input[state.index + n];
  1844. const advance = state.advance = () => input[++state.index] || '';
  1845. const remaining = () => input.slice(state.index + 1);
  1846. const consume = (value = '', num = 0) => {
  1847. state.consumed += value;
  1848. state.index += num;
  1849. };
  1850. const append = token => {
  1851. state.output += token.output != null ? token.output : token.value;
  1852. consume(token.value);
  1853. };
  1854. const negate = () => {
  1855. let count = 1;
  1856. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1857. advance();
  1858. state.start++;
  1859. count++;
  1860. }
  1861. if (count % 2 === 0) {
  1862. return false;
  1863. }
  1864. state.negated = true;
  1865. state.start++;
  1866. return true;
  1867. };
  1868. const increment = type => {
  1869. state[type]++;
  1870. stack.push(type);
  1871. };
  1872. const decrement = type => {
  1873. state[type]--;
  1874. stack.pop();
  1875. };
  1876. /**
  1877. * Push tokens onto the tokens array. This helper speeds up
  1878. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1879. * and 2) helping us avoid creating extra tokens when consecutive
  1880. * characters are plain text. This improves performance and simplifies
  1881. * lookbehinds.
  1882. */
  1883. const push = tok => {
  1884. if (prev.type === 'globstar') {
  1885. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1886. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1887. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1888. state.output = state.output.slice(0, -prev.output.length);
  1889. prev.type = 'star';
  1890. prev.value = '*';
  1891. prev.output = star;
  1892. state.output += prev.output;
  1893. }
  1894. }
  1895. if (extglobs.length && tok.type !== 'paren') {
  1896. extglobs[extglobs.length - 1].inner += tok.value;
  1897. }
  1898. if (tok.value || tok.output) append(tok);
  1899. if (prev && prev.type === 'text' && tok.type === 'text') {
  1900. prev.output = (prev.output || prev.value) + tok.value;
  1901. prev.value += tok.value;
  1902. return;
  1903. }
  1904. tok.prev = prev;
  1905. tokens.push(tok);
  1906. prev = tok;
  1907. };
  1908. const extglobOpen = (type, value) => {
  1909. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1910. token.prev = prev;
  1911. token.parens = state.parens;
  1912. token.output = state.output;
  1913. token.startIndex = state.index;
  1914. token.tokensIndex = tokens.length;
  1915. const output = (opts.capture ? '(' : '') + token.open;
  1916. increment('parens');
  1917. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1918. push({ type: 'paren', extglob: true, value: advance(), output });
  1919. extglobs.push(token);
  1920. };
  1921. const extglobClose = token => {
  1922. const literal = input.slice(token.startIndex, state.index + 1);
  1923. const body = input.slice(token.startIndex + 2, state.index);
  1924. const analysis = analyzeRepeatedExtglob(body, opts);
  1925. if ((token.type === 'plus' || token.type === 'star') && analysis.risky) {
  1926. const safeOutput = analysis.safeOutput
  1927. ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput)
  1928. : undefined;
  1929. const open = tokens[token.tokensIndex];
  1930. open.type = 'text';
  1931. open.value = literal;
  1932. open.output = safeOutput || utils.escapeRegex(literal);
  1933. for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
  1934. tokens[i].value = '';
  1935. tokens[i].output = '';
  1936. delete tokens[i].suffix;
  1937. }
  1938. state.output = token.output + open.output;
  1939. state.backtrack = true;
  1940. push({ type: 'paren', extglob: true, value, output: '' });
  1941. decrement('parens');
  1942. return;
  1943. }
  1944. let output = token.close + (opts.capture ? ')' : '');
  1945. let rest;
  1946. if (token.type === 'negate') {
  1947. let extglobStar = star;
  1948. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1949. extglobStar = globstar(opts);
  1950. }
  1951. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1952. output = token.close = `)$))${extglobStar}`;
  1953. }
  1954. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1955. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1956. // In this case, we need to parse the string and use it in the output of the original pattern.
  1957. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1958. //
  1959. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1960. const expression = parse(rest, { ...options, fastpaths: false }).output;
  1961. output = token.close = `)${expression})${extglobStar})`;
  1962. }
  1963. if (token.prev.type === 'bos') {
  1964. state.negatedExtglob = true;
  1965. }
  1966. }
  1967. push({ type: 'paren', extglob: true, value, output });
  1968. decrement('parens');
  1969. };
  1970. /**
  1971. * Fast paths
  1972. */
  1973. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1974. let backslashes = false;
  1975. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1976. if (first === '\\') {
  1977. backslashes = true;
  1978. return m;
  1979. }
  1980. if (first === '?') {
  1981. if (esc) {
  1982. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1983. }
  1984. if (index === 0) {
  1985. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1986. }
  1987. return QMARK.repeat(chars.length);
  1988. }
  1989. if (first === '.') {
  1990. return DOT_LITERAL.repeat(chars.length);
  1991. }
  1992. if (first === '*') {
  1993. if (esc) {
  1994. return esc + first + (rest ? star : '');
  1995. }
  1996. return star;
  1997. }
  1998. return esc ? m : `\\${m}`;
  1999. });
  2000. if (backslashes === true) {
  2001. if (opts.unescape === true) {
  2002. output = output.replace(/\\/g, '');
  2003. } else {
  2004. output = output.replace(/\\+/g, m => {
  2005. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2006. });
  2007. }
  2008. }
  2009. if (output === input && opts.contains === true) {
  2010. state.output = input;
  2011. return state;
  2012. }
  2013. state.output = utils.wrapOutput(output, state, options);
  2014. return state;
  2015. }
  2016. /**
  2017. * Tokenize input until we reach end-of-string
  2018. */
  2019. while (!eos()) {
  2020. value = advance();
  2021. if (value === '\u0000') {
  2022. continue;
  2023. }
  2024. /**
  2025. * Escaped characters
  2026. */
  2027. if (value === '\\') {
  2028. const next = peek();
  2029. if (next === '/' && opts.bash !== true) {
  2030. continue;
  2031. }
  2032. if (next === '.' || next === ';') {
  2033. continue;
  2034. }
  2035. if (!next) {
  2036. value += '\\';
  2037. push({ type: 'text', value });
  2038. continue;
  2039. }
  2040. // collapse slashes to reduce potential for exploits
  2041. const match = /^\\+/.exec(remaining());
  2042. let slashes = 0;
  2043. if (match && match[0].length > 2) {
  2044. slashes = match[0].length;
  2045. state.index += slashes;
  2046. if (slashes % 2 !== 0) {
  2047. value += '\\';
  2048. }
  2049. }
  2050. if (opts.unescape === true) {
  2051. value = advance();
  2052. } else {
  2053. value += advance();
  2054. }
  2055. if (state.brackets === 0) {
  2056. push({ type: 'text', value });
  2057. continue;
  2058. }
  2059. }
  2060. /**
  2061. * If we're inside a regex character class, continue
  2062. * until we reach the closing bracket.
  2063. */
  2064. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2065. if (opts.posix !== false && value === ':') {
  2066. const inner = prev.value.slice(1);
  2067. if (inner.includes('[')) {
  2068. prev.posix = true;
  2069. if (inner.includes(':')) {
  2070. const idx = prev.value.lastIndexOf('[');
  2071. const pre = prev.value.slice(0, idx);
  2072. const rest = prev.value.slice(idx + 2);
  2073. const posix = POSIX_REGEX_SOURCE[rest];
  2074. if (posix) {
  2075. prev.value = pre + posix;
  2076. state.backtrack = true;
  2077. advance();
  2078. if (!bos.output && tokens.indexOf(prev) === 1) {
  2079. bos.output = ONE_CHAR;
  2080. }
  2081. continue;
  2082. }
  2083. }
  2084. }
  2085. }
  2086. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2087. value = `\\${value}`;
  2088. }
  2089. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2090. value = `\\${value}`;
  2091. }
  2092. if (opts.posix === true && value === '!' && prev.value === '[') {
  2093. value = '^';
  2094. }
  2095. prev.value += value;
  2096. append({ value });
  2097. continue;
  2098. }
  2099. /**
  2100. * If we're inside a quoted string, continue
  2101. * until we reach the closing double quote.
  2102. */
  2103. if (state.quotes === 1 && value !== '"') {
  2104. value = utils.escapeRegex(value);
  2105. prev.value += value;
  2106. append({ value });
  2107. continue;
  2108. }
  2109. /**
  2110. * Double quotes
  2111. */
  2112. if (value === '"') {
  2113. state.quotes = state.quotes === 1 ? 0 : 1;
  2114. if (opts.keepQuotes === true) {
  2115. push({ type: 'text', value });
  2116. }
  2117. continue;
  2118. }
  2119. /**
  2120. * Parentheses
  2121. */
  2122. if (value === '(') {
  2123. increment('parens');
  2124. push({ type: 'paren', value });
  2125. continue;
  2126. }
  2127. if (value === ')') {
  2128. if (state.parens === 0 && opts.strictBrackets === true) {
  2129. throw new SyntaxError(syntaxError('opening', '('));
  2130. }
  2131. const extglob = extglobs[extglobs.length - 1];
  2132. if (extglob && state.parens === extglob.parens + 1) {
  2133. extglobClose(extglobs.pop());
  2134. continue;
  2135. }
  2136. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  2137. decrement('parens');
  2138. continue;
  2139. }
  2140. /**
  2141. * Square brackets
  2142. */
  2143. if (value === '[') {
  2144. if (opts.nobracket === true || !remaining().includes(']')) {
  2145. if (opts.nobracket !== true && opts.strictBrackets === true) {
  2146. throw new SyntaxError(syntaxError('closing', ']'));
  2147. }
  2148. value = `\\${value}`;
  2149. } else {
  2150. increment('brackets');
  2151. }
  2152. push({ type: 'bracket', value });
  2153. continue;
  2154. }
  2155. if (value === ']') {
  2156. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  2157. push({ type: 'text', value, output: `\\${value}` });
  2158. continue;
  2159. }
  2160. if (state.brackets === 0) {
  2161. if (opts.strictBrackets === true) {
  2162. throw new SyntaxError(syntaxError('opening', '['));
  2163. }
  2164. push({ type: 'text', value, output: `\\${value}` });
  2165. continue;
  2166. }
  2167. decrement('brackets');
  2168. const prevValue = prev.value.slice(1);
  2169. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  2170. value = `/${value}`;
  2171. }
  2172. prev.value += value;
  2173. append({ value });
  2174. // when literal brackets are explicitly disabled
  2175. // assume we should match with a regex character class
  2176. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  2177. continue;
  2178. }
  2179. const escaped = utils.escapeRegex(prev.value);
  2180. state.output = state.output.slice(0, -prev.value.length);
  2181. // when literal brackets are explicitly enabled
  2182. // assume we should escape the brackets to match literal characters
  2183. if (opts.literalBrackets === true) {
  2184. state.output += escaped;
  2185. prev.value = escaped;
  2186. continue;
  2187. }
  2188. // when the user specifies nothing, try to match both
  2189. prev.value = `(${capture}${escaped}|${prev.value})`;
  2190. state.output += prev.value;
  2191. continue;
  2192. }
  2193. /**
  2194. * Braces
  2195. */
  2196. if (value === '{' && opts.nobrace !== true) {
  2197. increment('braces');
  2198. const open = {
  2199. type: 'brace',
  2200. value,
  2201. output: '(',
  2202. outputIndex: state.output.length,
  2203. tokensIndex: state.tokens.length
  2204. };
  2205. braces.push(open);
  2206. push(open);
  2207. continue;
  2208. }
  2209. if (value === '}') {
  2210. const brace = braces[braces.length - 1];
  2211. if (opts.nobrace === true || !brace) {
  2212. push({ type: 'text', value, output: value });
  2213. continue;
  2214. }
  2215. let output = ')';
  2216. if (brace.dots === true) {
  2217. const arr = tokens.slice();
  2218. const range = [];
  2219. for (let i = arr.length - 1; i >= 0; i--) {
  2220. tokens.pop();
  2221. if (arr[i].type === 'brace') {
  2222. break;
  2223. }
  2224. if (arr[i].type !== 'dots') {
  2225. range.unshift(arr[i].value);
  2226. }
  2227. }
  2228. output = expandRange(range, opts);
  2229. state.backtrack = true;
  2230. }
  2231. if (brace.comma !== true && brace.dots !== true) {
  2232. const out = state.output.slice(0, brace.outputIndex);
  2233. const toks = state.tokens.slice(brace.tokensIndex);
  2234. brace.value = brace.output = '\\{';
  2235. value = output = '\\}';
  2236. state.output = out;
  2237. for (const t of toks) {
  2238. state.output += (t.output || t.value);
  2239. }
  2240. }
  2241. push({ type: 'brace', value, output });
  2242. decrement('braces');
  2243. braces.pop();
  2244. continue;
  2245. }
  2246. /**
  2247. * Pipes
  2248. */
  2249. if (value === '|') {
  2250. if (extglobs.length > 0) {
  2251. extglobs[extglobs.length - 1].conditions++;
  2252. }
  2253. push({ type: 'text', value });
  2254. continue;
  2255. }
  2256. /**
  2257. * Commas
  2258. */
  2259. if (value === ',') {
  2260. let output = value;
  2261. const brace = braces[braces.length - 1];
  2262. if (brace && stack[stack.length - 1] === 'braces') {
  2263. brace.comma = true;
  2264. output = '|';
  2265. }
  2266. push({ type: 'comma', value, output });
  2267. continue;
  2268. }
  2269. /**
  2270. * Slashes
  2271. */
  2272. if (value === '/') {
  2273. // if the beginning of the glob is "./", advance the start
  2274. // to the current index, and don't add the "./" characters
  2275. // to the state. This greatly simplifies lookbehinds when
  2276. // checking for BOS characters like "!" and "." (not "./")
  2277. if (prev.type === 'dot' && state.index === state.start + 1) {
  2278. state.start = state.index + 1;
  2279. state.consumed = '';
  2280. state.output = '';
  2281. tokens.pop();
  2282. prev = bos; // reset "prev" to the first token
  2283. continue;
  2284. }
  2285. push({ type: 'slash', value, output: SLASH_LITERAL });
  2286. continue;
  2287. }
  2288. /**
  2289. * Dots
  2290. */
  2291. if (value === '.') {
  2292. if (state.braces > 0 && prev.type === 'dot') {
  2293. if (prev.value === '.') prev.output = DOT_LITERAL;
  2294. const brace = braces[braces.length - 1];
  2295. prev.type = 'dots';
  2296. prev.output += value;
  2297. prev.value += value;
  2298. brace.dots = true;
  2299. continue;
  2300. }
  2301. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2302. push({ type: 'text', value, output: DOT_LITERAL });
  2303. continue;
  2304. }
  2305. push({ type: 'dot', value, output: DOT_LITERAL });
  2306. continue;
  2307. }
  2308. /**
  2309. * Question marks
  2310. */
  2311. if (value === '?') {
  2312. const isGroup = prev && prev.value === '(';
  2313. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2314. extglobOpen('qmark', value);
  2315. continue;
  2316. }
  2317. if (prev && prev.type === 'paren') {
  2318. const next = peek();
  2319. let output = value;
  2320. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2321. output = `\\${value}`;
  2322. }
  2323. push({ type: 'text', value, output });
  2324. continue;
  2325. }
  2326. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2327. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2328. continue;
  2329. }
  2330. push({ type: 'qmark', value, output: QMARK });
  2331. continue;
  2332. }
  2333. /**
  2334. * Exclamation
  2335. */
  2336. if (value === '!') {
  2337. if (opts.noextglob !== true && peek() === '(') {
  2338. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2339. extglobOpen('negate', value);
  2340. continue;
  2341. }
  2342. }
  2343. if (opts.nonegate !== true && state.index === 0) {
  2344. negate();
  2345. continue;
  2346. }
  2347. }
  2348. /**
  2349. * Plus
  2350. */
  2351. if (value === '+') {
  2352. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2353. extglobOpen('plus', value);
  2354. continue;
  2355. }
  2356. if ((prev && prev.value === '(') || opts.regex === false) {
  2357. push({ type: 'plus', value, output: PLUS_LITERAL });
  2358. continue;
  2359. }
  2360. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2361. push({ type: 'plus', value });
  2362. continue;
  2363. }
  2364. push({ type: 'plus', value: PLUS_LITERAL });
  2365. continue;
  2366. }
  2367. /**
  2368. * Plain text
  2369. */
  2370. if (value === '@') {
  2371. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2372. push({ type: 'at', extglob: true, value, output: '' });
  2373. continue;
  2374. }
  2375. push({ type: 'text', value });
  2376. continue;
  2377. }
  2378. /**
  2379. * Plain text
  2380. */
  2381. if (value !== '*') {
  2382. if (value === '$' || value === '^') {
  2383. value = `\\${value}`;
  2384. }
  2385. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2386. if (match) {
  2387. value += match[0];
  2388. state.index += match[0].length;
  2389. }
  2390. push({ type: 'text', value });
  2391. continue;
  2392. }
  2393. /**
  2394. * Stars
  2395. */
  2396. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2397. prev.type = 'star';
  2398. prev.star = true;
  2399. prev.value += value;
  2400. prev.output = star;
  2401. state.backtrack = true;
  2402. state.globstar = true;
  2403. consume(value);
  2404. continue;
  2405. }
  2406. let rest = remaining();
  2407. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2408. extglobOpen('star', value);
  2409. continue;
  2410. }
  2411. if (prev.type === 'star') {
  2412. if (opts.noglobstar === true) {
  2413. consume(value);
  2414. continue;
  2415. }
  2416. const prior = prev.prev;
  2417. const before = prior.prev;
  2418. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2419. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2420. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2421. push({ type: 'star', value, output: '' });
  2422. continue;
  2423. }
  2424. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2425. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2426. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2427. push({ type: 'star', value, output: '' });
  2428. continue;
  2429. }
  2430. // strip consecutive `/**/`
  2431. while (rest.slice(0, 3) === '/**') {
  2432. const after = input[state.index + 4];
  2433. if (after && after !== '/') {
  2434. break;
  2435. }
  2436. rest = rest.slice(3);
  2437. consume('/**', 3);
  2438. }
  2439. if (prior.type === 'bos' && eos()) {
  2440. prev.type = 'globstar';
  2441. prev.value += value;
  2442. prev.output = globstar(opts);
  2443. state.output = prev.output;
  2444. state.globstar = true;
  2445. consume(value);
  2446. continue;
  2447. }
  2448. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2449. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2450. prior.output = `(?:${prior.output}`;
  2451. prev.type = 'globstar';
  2452. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2453. prev.value += value;
  2454. state.globstar = true;
  2455. state.output += prior.output + prev.output;
  2456. consume(value);
  2457. continue;
  2458. }
  2459. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2460. const end = rest[1] !== void 0 ? '|$' : '';
  2461. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2462. prior.output = `(?:${prior.output}`;
  2463. prev.type = 'globstar';
  2464. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2465. prev.value += value;
  2466. state.output += prior.output + prev.output;
  2467. state.globstar = true;
  2468. consume(value + advance());
  2469. push({ type: 'slash', value: '/', output: '' });
  2470. continue;
  2471. }
  2472. if (prior.type === 'bos' && rest[0] === '/') {
  2473. prev.type = 'globstar';
  2474. prev.value += value;
  2475. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2476. state.output = prev.output;
  2477. state.globstar = true;
  2478. consume(value + advance());
  2479. push({ type: 'slash', value: '/', output: '' });
  2480. continue;
  2481. }
  2482. // remove single star from output
  2483. state.output = state.output.slice(0, -prev.output.length);
  2484. // reset previous token to globstar
  2485. prev.type = 'globstar';
  2486. prev.output = globstar(opts);
  2487. prev.value += value;
  2488. // reset output with globstar
  2489. state.output += prev.output;
  2490. state.globstar = true;
  2491. consume(value);
  2492. continue;
  2493. }
  2494. const token = { type: 'star', value, output: star };
  2495. if (opts.bash === true) {
  2496. token.output = '.*?';
  2497. if (prev.type === 'bos' || prev.type === 'slash') {
  2498. token.output = nodot + token.output;
  2499. }
  2500. push(token);
  2501. continue;
  2502. }
  2503. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2504. token.output = value;
  2505. push(token);
  2506. continue;
  2507. }
  2508. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2509. if (prev.type === 'dot') {
  2510. state.output += NO_DOT_SLASH;
  2511. prev.output += NO_DOT_SLASH;
  2512. } else if (opts.dot === true) {
  2513. state.output += NO_DOTS_SLASH;
  2514. prev.output += NO_DOTS_SLASH;
  2515. } else {
  2516. state.output += nodot;
  2517. prev.output += nodot;
  2518. }
  2519. if (peek() !== '*') {
  2520. state.output += ONE_CHAR;
  2521. prev.output += ONE_CHAR;
  2522. }
  2523. }
  2524. push(token);
  2525. }
  2526. while (state.brackets > 0) {
  2527. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2528. state.output = utils.escapeLast(state.output, '[');
  2529. decrement('brackets');
  2530. }
  2531. while (state.parens > 0) {
  2532. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2533. state.output = utils.escapeLast(state.output, '(');
  2534. decrement('parens');
  2535. }
  2536. while (state.braces > 0) {
  2537. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2538. state.output = utils.escapeLast(state.output, '{');
  2539. decrement('braces');
  2540. }
  2541. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2542. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2543. }
  2544. // rebuild the output if we had to backtrack at any point
  2545. if (state.backtrack === true) {
  2546. state.output = '';
  2547. for (const token of state.tokens) {
  2548. state.output += token.output != null ? token.output : token.value;
  2549. if (token.suffix) {
  2550. state.output += token.suffix;
  2551. }
  2552. }
  2553. }
  2554. return state;
  2555. };
  2556. /**
  2557. * Fast paths for creating regular expressions for common glob patterns.
  2558. * This can significantly speed up processing and has very little downside
  2559. * impact when none of the fast paths match.
  2560. */
  2561. parse.fastpaths = (input, options) => {
  2562. const opts = { ...options };
  2563. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2564. const len = input.length;
  2565. if (len > max) {
  2566. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2567. }
  2568. input = REPLACEMENTS[input] || input;
  2569. // create constants based on platform, for windows or posix
  2570. const {
  2571. DOT_LITERAL,
  2572. SLASH_LITERAL,
  2573. ONE_CHAR,
  2574. DOTS_SLASH,
  2575. NO_DOT,
  2576. NO_DOTS,
  2577. NO_DOTS_SLASH,
  2578. STAR,
  2579. START_ANCHOR
  2580. } = constants.globChars(opts.windows);
  2581. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2582. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2583. const capture = opts.capture ? '' : '?:';
  2584. const state = { negated: false, prefix: '' };
  2585. let star = opts.bash === true ? '.*?' : STAR;
  2586. if (opts.capture) {
  2587. star = `(${star})`;
  2588. }
  2589. const globstar = opts => {
  2590. if (opts.noglobstar === true) return star;
  2591. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2592. };
  2593. const create = str => {
  2594. switch (str) {
  2595. case '*':
  2596. return `${nodot}${ONE_CHAR}${star}`;
  2597. case '.*':
  2598. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2599. case '*.*':
  2600. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2601. case '*/*':
  2602. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2603. case '**':
  2604. return nodot + globstar(opts);
  2605. case '**/*':
  2606. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2607. case '**/*.*':
  2608. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2609. case '**/.*':
  2610. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2611. default: {
  2612. const match = /^(.*?)\.(\w+)$/.exec(str);
  2613. if (!match) return;
  2614. const source = create(match[1]);
  2615. if (!source) return;
  2616. return source + DOT_LITERAL + match[2];
  2617. }
  2618. }
  2619. };
  2620. const output = utils.removePrefix(input, state);
  2621. let source = create(output);
  2622. if (source && opts.strictSlashes !== true) {
  2623. source += `${SLASH_LITERAL}?`;
  2624. }
  2625. return source;
  2626. };
  2627. parse_1 = parse;
  2628. return parse_1;
  2629. }
  2630. var picomatch_1$1;
  2631. var hasRequiredPicomatch$1;
  2632. function requirePicomatch$1 () {
  2633. if (hasRequiredPicomatch$1) return picomatch_1$1;
  2634. hasRequiredPicomatch$1 = 1;
  2635. const scan = /*@__PURE__*/ requireScan();
  2636. const parse = /*@__PURE__*/ requireParse();
  2637. const utils = /*@__PURE__*/ requireUtils();
  2638. const constants = /*@__PURE__*/ requireConstants();
  2639. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  2640. /**
  2641. * Creates a matcher function from one or more glob patterns. The
  2642. * returned function takes a string to match as its first argument,
  2643. * and returns true if the string is a match. The returned matcher
  2644. * function also takes a boolean as the second argument that, when true,
  2645. * returns an object with additional information.
  2646. *
  2647. * ```js
  2648. * const picomatch = require('picomatch');
  2649. * // picomatch(glob[, options]);
  2650. *
  2651. * const isMatch = picomatch('*.!(*a)');
  2652. * console.log(isMatch('a.a')); //=> false
  2653. * console.log(isMatch('a.b')); //=> true
  2654. * ```
  2655. * @name picomatch
  2656. * @param {String|Array} `globs` One or more glob patterns.
  2657. * @param {Object=} `options`
  2658. * @return {Function=} Returns a matcher function.
  2659. * @api public
  2660. */
  2661. const picomatch = (glob, options, returnState = false) => {
  2662. if (Array.isArray(glob)) {
  2663. const fns = glob.map(input => picomatch(input, options, returnState));
  2664. const arrayMatcher = str => {
  2665. for (const isMatch of fns) {
  2666. const state = isMatch(str);
  2667. if (state) return state;
  2668. }
  2669. return false;
  2670. };
  2671. return arrayMatcher;
  2672. }
  2673. const isState = isObject(glob) && glob.tokens && glob.input;
  2674. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2675. throw new TypeError('Expected pattern to be a non-empty string');
  2676. }
  2677. const opts = options || {};
  2678. const posix = opts.windows;
  2679. const regex = isState
  2680. ? picomatch.compileRe(glob, options)
  2681. : picomatch.makeRe(glob, options, false, true);
  2682. const state = regex.state;
  2683. delete regex.state;
  2684. let isIgnored = () => false;
  2685. if (opts.ignore) {
  2686. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2687. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  2688. }
  2689. const matcher = (input, returnObject = false) => {
  2690. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  2691. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2692. if (typeof opts.onResult === 'function') {
  2693. opts.onResult(result);
  2694. }
  2695. if (isMatch === false) {
  2696. result.isMatch = false;
  2697. return returnObject ? result : false;
  2698. }
  2699. if (isIgnored(input)) {
  2700. if (typeof opts.onIgnore === 'function') {
  2701. opts.onIgnore(result);
  2702. }
  2703. result.isMatch = false;
  2704. return returnObject ? result : false;
  2705. }
  2706. if (typeof opts.onMatch === 'function') {
  2707. opts.onMatch(result);
  2708. }
  2709. return returnObject ? result : true;
  2710. };
  2711. if (returnState) {
  2712. matcher.state = state;
  2713. }
  2714. return matcher;
  2715. };
  2716. /**
  2717. * Test `input` with the given `regex`. This is used by the main
  2718. * `picomatch()` function to test the input string.
  2719. *
  2720. * ```js
  2721. * const picomatch = require('picomatch');
  2722. * // picomatch.test(input, regex[, options]);
  2723. *
  2724. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2725. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2726. * ```
  2727. * @param {String} `input` String to test.
  2728. * @param {RegExp} `regex`
  2729. * @return {Object} Returns an object with matching info.
  2730. * @api public
  2731. */
  2732. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  2733. if (typeof input !== 'string') {
  2734. throw new TypeError('Expected input to be a string');
  2735. }
  2736. if (input === '') {
  2737. return { isMatch: false, output: '' };
  2738. }
  2739. const opts = options || {};
  2740. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  2741. let match = input === glob;
  2742. let output = (match && format) ? format(input) : input;
  2743. if (match === false) {
  2744. output = format ? format(input) : input;
  2745. match = output === glob;
  2746. }
  2747. if (match === false || opts.capture === true) {
  2748. if (opts.matchBase === true || opts.basename === true) {
  2749. match = picomatch.matchBase(input, regex, options, posix);
  2750. } else {
  2751. match = regex.exec(output);
  2752. }
  2753. }
  2754. return { isMatch: Boolean(match), match, output };
  2755. };
  2756. /**
  2757. * Match the basename of a filepath.
  2758. *
  2759. * ```js
  2760. * const picomatch = require('picomatch');
  2761. * // picomatch.matchBase(input, glob[, options]);
  2762. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2763. * ```
  2764. * @param {String} `input` String to test.
  2765. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2766. * @return {Boolean}
  2767. * @api public
  2768. */
  2769. picomatch.matchBase = (input, glob, options) => {
  2770. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  2771. return regex.test(utils.basename(input));
  2772. };
  2773. /**
  2774. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2775. *
  2776. * ```js
  2777. * const picomatch = require('picomatch');
  2778. * // picomatch.isMatch(string, patterns[, options]);
  2779. *
  2780. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2781. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2782. * ```
  2783. * @param {String|Array} str The string to test.
  2784. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2785. * @param {Object} [options] See available [options](#options).
  2786. * @return {Boolean} Returns true if any patterns match `str`
  2787. * @api public
  2788. */
  2789. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  2790. /**
  2791. * Parse a glob pattern to create the source string for a regular
  2792. * expression.
  2793. *
  2794. * ```js
  2795. * const picomatch = require('picomatch');
  2796. * const result = picomatch.parse(pattern[, options]);
  2797. * ```
  2798. * @param {String} `pattern`
  2799. * @param {Object} `options`
  2800. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2801. * @api public
  2802. */
  2803. picomatch.parse = (pattern, options) => {
  2804. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  2805. return parse(pattern, { ...options, fastpaths: false });
  2806. };
  2807. /**
  2808. * Scan a glob pattern to separate the pattern into segments.
  2809. *
  2810. * ```js
  2811. * const picomatch = require('picomatch');
  2812. * // picomatch.scan(input[, options]);
  2813. *
  2814. * const result = picomatch.scan('!./foo/*.js');
  2815. * console.log(result);
  2816. * { prefix: '!./',
  2817. * input: '!./foo/*.js',
  2818. * start: 3,
  2819. * base: 'foo',
  2820. * glob: '*.js',
  2821. * isBrace: false,
  2822. * isBracket: false,
  2823. * isGlob: true,
  2824. * isExtglob: false,
  2825. * isGlobstar: false,
  2826. * negated: true }
  2827. * ```
  2828. * @param {String} `input` Glob pattern to scan.
  2829. * @param {Object} `options`
  2830. * @return {Object} Returns an object with
  2831. * @api public
  2832. */
  2833. picomatch.scan = (input, options) => scan(input, options);
  2834. /**
  2835. * Compile a regular expression from the `state` object returned by the
  2836. * [parse()](#parse) method.
  2837. *
  2838. * ```js
  2839. * const picomatch = require('picomatch');
  2840. * const state = picomatch.parse('*.js');
  2841. * // picomatch.compileRe(state[, options]);
  2842. *
  2843. * console.log(picomatch.compileRe(state));
  2844. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2845. * ```
  2846. * @param {Object} `state`
  2847. * @param {Object} `options`
  2848. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2849. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2850. * @return {RegExp}
  2851. * @api public
  2852. */
  2853. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2854. if (returnOutput === true) {
  2855. return state.output;
  2856. }
  2857. const opts = options || {};
  2858. const prepend = opts.contains ? '' : '^';
  2859. const append = opts.contains ? '' : '$';
  2860. let source = `${prepend}(?:${state.output})${append}`;
  2861. if (state && state.negated === true) {
  2862. source = `^(?!${source}).*$`;
  2863. }
  2864. const regex = picomatch.toRegex(source, options);
  2865. if (returnState === true) {
  2866. regex.state = state;
  2867. }
  2868. return regex;
  2869. };
  2870. /**
  2871. * Create a regular expression from a parsed glob pattern.
  2872. *
  2873. * ```js
  2874. * const picomatch = require('picomatch');
  2875. * // picomatch.makeRe(state[, options]);
  2876. *
  2877. * const result = picomatch.makeRe('*.js');
  2878. * console.log(result);
  2879. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2880. * ```
  2881. * @param {String} `state` The object returned from the `.parse` method.
  2882. * @param {Object} `options`
  2883. * @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.
  2884. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2885. * @return {RegExp} Returns a regex created from the given pattern.
  2886. * @api public
  2887. */
  2888. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2889. if (!input || typeof input !== 'string') {
  2890. throw new TypeError('Expected a non-empty string');
  2891. }
  2892. let parsed = { negated: false, fastpaths: true };
  2893. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2894. parsed.output = parse.fastpaths(input, options);
  2895. }
  2896. if (!parsed.output) {
  2897. parsed = parse(input, options);
  2898. }
  2899. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  2900. };
  2901. /**
  2902. * Create a regular expression from the given regex source string.
  2903. *
  2904. * ```js
  2905. * const picomatch = require('picomatch');
  2906. * // picomatch.toRegex(source[, options]);
  2907. *
  2908. * const { output } = picomatch.parse('*.js');
  2909. * console.log(picomatch.toRegex(output));
  2910. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2911. * ```
  2912. * @param {String} `source` Regular expression source string.
  2913. * @param {Object} `options`
  2914. * @return {RegExp}
  2915. * @api public
  2916. */
  2917. picomatch.toRegex = (source, options) => {
  2918. try {
  2919. const opts = options || {};
  2920. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2921. } catch (err) {
  2922. if (options && options.debug === true) throw err;
  2923. return /$^/;
  2924. }
  2925. };
  2926. /**
  2927. * Picomatch constants.
  2928. * @return {Object}
  2929. */
  2930. picomatch.constants = constants;
  2931. /**
  2932. * Expose "picomatch"
  2933. */
  2934. picomatch_1$1 = picomatch;
  2935. return picomatch_1$1;
  2936. }
  2937. var picomatch_1;
  2938. var hasRequiredPicomatch;
  2939. function requirePicomatch () {
  2940. if (hasRequiredPicomatch) return picomatch_1;
  2941. hasRequiredPicomatch = 1;
  2942. const pico = /*@__PURE__*/ requirePicomatch$1();
  2943. const utils = /*@__PURE__*/ requireUtils();
  2944. function picomatch(glob, options, returnState = false) {
  2945. // default to os.platform()
  2946. if (options && (options.windows === null || options.windows === undefined)) {
  2947. // don't mutate the original options object
  2948. options = { ...options, windows: utils.isWindows() };
  2949. }
  2950. return pico(glob, options, returnState);
  2951. }
  2952. Object.assign(picomatch, pico);
  2953. picomatch_1 = picomatch;
  2954. return picomatch_1;
  2955. }
  2956. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  2957. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  2958. function getMatcherString$1(glob, cwd) {
  2959. if (glob.startsWith('**') || parseAst_js.isAbsolute(glob)) {
  2960. return parseAst_js.normalize(glob);
  2961. }
  2962. const resolved = path.resolve(cwd, glob);
  2963. return parseAst_js.normalize(resolved);
  2964. }
  2965. function patternToIdFilter(pattern) {
  2966. if (pattern instanceof RegExp) {
  2967. return (id) => {
  2968. const normalizedId = parseAst_js.normalize(id);
  2969. const result = pattern.test(normalizedId);
  2970. pattern.lastIndex = 0;
  2971. return result;
  2972. };
  2973. }
  2974. const cwd = process.cwd();
  2975. const glob = getMatcherString$1(pattern, cwd);
  2976. const matcher = pm(glob, { dot: true });
  2977. return (id) => {
  2978. const normalizedId = parseAst_js.normalize(id);
  2979. return matcher(normalizedId);
  2980. };
  2981. }
  2982. function patternToCodeFilter(pattern) {
  2983. if (pattern instanceof RegExp) {
  2984. return (code) => {
  2985. const result = pattern.test(code);
  2986. pattern.lastIndex = 0;
  2987. return result;
  2988. };
  2989. }
  2990. return (code) => code.includes(pattern);
  2991. }
  2992. function createFilter$1(exclude, include) {
  2993. if (!exclude && !include) {
  2994. return;
  2995. }
  2996. return input => {
  2997. if (exclude?.some(filter => filter(input))) {
  2998. return false;
  2999. }
  3000. if (include?.some(filter => filter(input))) {
  3001. return true;
  3002. }
  3003. return !(include && include.length > 0);
  3004. };
  3005. }
  3006. function normalizeFilter(filter) {
  3007. if (typeof filter === 'string' || filter instanceof RegExp) {
  3008. return {
  3009. include: [filter]
  3010. };
  3011. }
  3012. if (Array.isArray(filter)) {
  3013. return {
  3014. include: filter
  3015. };
  3016. }
  3017. return {
  3018. exclude: filter.exclude ? ensureArray$1(filter.exclude) : undefined,
  3019. include: filter.include ? ensureArray$1(filter.include) : undefined
  3020. };
  3021. }
  3022. function createIdFilter(filter) {
  3023. if (!filter)
  3024. return;
  3025. const { exclude, include } = normalizeFilter(filter);
  3026. const excludeFilter = exclude?.map(patternToIdFilter);
  3027. const includeFilter = include?.map(patternToIdFilter);
  3028. return createFilter$1(excludeFilter, includeFilter);
  3029. }
  3030. function createCodeFilter(filter) {
  3031. if (!filter)
  3032. return;
  3033. const { exclude, include } = normalizeFilter(filter);
  3034. const excludeFilter = exclude?.map(patternToCodeFilter);
  3035. const includeFilter = include?.map(patternToCodeFilter);
  3036. return createFilter$1(excludeFilter, includeFilter);
  3037. }
  3038. function createFilterForId(filter) {
  3039. const filterFunction = createIdFilter(filter);
  3040. return filterFunction ? id => !!filterFunction(id) : undefined;
  3041. }
  3042. function createFilterForTransform(idFilter, codeFilter) {
  3043. if (!idFilter && !codeFilter)
  3044. return;
  3045. const idFilterFunction = createIdFilter(idFilter);
  3046. const codeFilterFunction = createCodeFilter(codeFilter);
  3047. return (id, code) => {
  3048. let fallback = true;
  3049. if (idFilterFunction) {
  3050. fallback &&= idFilterFunction(id);
  3051. }
  3052. if (!fallback) {
  3053. return false;
  3054. }
  3055. if (codeFilterFunction) {
  3056. fallback &&= codeFilterFunction(code);
  3057. }
  3058. return fallback;
  3059. };
  3060. }
  3061. // This will make sure no input hook is omitted
  3062. const inputHookNames = {
  3063. buildEnd: 1,
  3064. buildStart: 1,
  3065. closeBundle: 1,
  3066. closeWatcher: 1,
  3067. load: 1,
  3068. moduleParsed: 1,
  3069. onLog: 1,
  3070. options: 1,
  3071. resolveDynamicImport: 1,
  3072. resolveId: 1,
  3073. shouldTransformCachedModule: 1,
  3074. transform: 1,
  3075. watchChange: 1
  3076. };
  3077. const inputHooks = Object.keys(inputHookNames);
  3078. class PluginDriver {
  3079. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  3080. this.graph = graph;
  3081. this.options = options;
  3082. this.pluginCache = pluginCache;
  3083. this.sortedPlugins = new Map();
  3084. this.unfulfilledActions = new Set();
  3085. this.compiledPluginFilters = {
  3086. idOnlyFilter: new WeakMap(),
  3087. transformFilter: new WeakMap()
  3088. };
  3089. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  3090. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  3091. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  3092. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  3093. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  3094. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  3095. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  3096. const existingPluginNames = new Set();
  3097. this.pluginContexts = new Map(this.plugins.map(plugin => [
  3098. plugin,
  3099. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  3100. ]));
  3101. if (basePluginDriver) {
  3102. for (const plugin of userPlugins) {
  3103. for (const hook of inputHooks) {
  3104. if (hook in plugin) {
  3105. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInputHookInOutputPlugin(plugin.name, hook));
  3106. }
  3107. }
  3108. }
  3109. }
  3110. }
  3111. createOutputPluginDriver(plugins) {
  3112. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  3113. }
  3114. getUnfulfilledHookActions() {
  3115. return this.unfulfilledActions;
  3116. }
  3117. // chains, first non-null result stops and returns
  3118. hookFirst(hookName, parameters, replaceContext, skipped) {
  3119. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  3120. }
  3121. // chains, first non-null result stops and returns result and last plugin
  3122. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  3123. for (const plugin of this.getSortedPlugins(hookName)) {
  3124. if (skipped?.has(plugin))
  3125. continue;
  3126. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  3127. if (result != null)
  3128. return [result, plugin];
  3129. }
  3130. return null;
  3131. }
  3132. // chains synchronously, first non-null result stops and returns
  3133. hookFirstSync(hookName, parameters, replaceContext) {
  3134. for (const plugin of this.getSortedPlugins(hookName)) {
  3135. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  3136. if (result != null)
  3137. return result;
  3138. }
  3139. return null;
  3140. }
  3141. // parallel, ignores returns
  3142. async hookParallel(hookName, parameters, replaceContext) {
  3143. const parallelPromises = [];
  3144. for (const plugin of this.getSortedPlugins(hookName)) {
  3145. if (plugin[hookName].sequential) {
  3146. await Promise.all(parallelPromises);
  3147. parallelPromises.length = 0;
  3148. await this.runHook(hookName, parameters, plugin, replaceContext);
  3149. }
  3150. else {
  3151. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  3152. }
  3153. }
  3154. await Promise.all(parallelPromises);
  3155. }
  3156. // chains, reduces returned value, handling the reduced value as the first hook argument
  3157. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  3158. let promise = Promise.resolve(argument0);
  3159. for (const plugin of this.getSortedPlugins(hookName)) {
  3160. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  3161. }
  3162. return promise;
  3163. }
  3164. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  3165. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  3166. for (const plugin of this.getSortedPlugins(hookName)) {
  3167. const parameters = [argument0, ...rest];
  3168. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  3169. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  3170. }
  3171. return argument0;
  3172. }
  3173. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  3174. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  3175. const results = [];
  3176. const parallelResults = [];
  3177. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  3178. if (plugin[hookName].sequential) {
  3179. results.push(...(await Promise.all(parallelResults)));
  3180. parallelResults.length = 0;
  3181. results.push(await this.runHook(hookName, parameters, plugin));
  3182. }
  3183. else {
  3184. parallelResults.push(this.runHook(hookName, parameters, plugin));
  3185. }
  3186. }
  3187. results.push(...(await Promise.all(parallelResults)));
  3188. return results.reduce(reducer, await initialValue);
  3189. }
  3190. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  3191. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  3192. let accumulator = initialValue;
  3193. for (const plugin of this.getSortedPlugins(hookName)) {
  3194. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  3195. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  3196. }
  3197. return accumulator;
  3198. }
  3199. // chains, ignores returns
  3200. hookSeq(hookName, parameters, replaceContext) {
  3201. let promise = Promise.resolve();
  3202. for (const plugin of this.getSortedPlugins(hookName)) {
  3203. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  3204. }
  3205. return promise.then(noReturn);
  3206. }
  3207. getSortedPlugins(hookName, validateHandler) {
  3208. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  3209. }
  3210. // Implementation signature
  3211. runHook(hookName, parameters, plugin, replaceContext) {
  3212. // We always filter for plugins that support the hook before running it
  3213. const hook = plugin[hookName];
  3214. const handler = typeof hook === 'object' ? hook.handler : hook;
  3215. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  3216. if (hookName === 'transform') {
  3217. const filter = hook.filter;
  3218. const hookParameters = parameters;
  3219. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  3220. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  3221. return Promise.resolve();
  3222. }
  3223. }
  3224. else if (hookName === 'resolveId' || hookName === 'load') {
  3225. const filter = hook.filter;
  3226. const hookParameters = parameters;
  3227. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  3228. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  3229. return Promise.resolve();
  3230. }
  3231. }
  3232. }
  3233. let context = this.pluginContexts.get(plugin);
  3234. if (replaceContext) {
  3235. context = replaceContext(context, plugin);
  3236. }
  3237. let action = null;
  3238. return Promise.resolve()
  3239. .then(() => {
  3240. if (typeof handler !== 'function') {
  3241. return handler;
  3242. }
  3243. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  3244. const hookResult = handler.apply(context, parameters);
  3245. if (!hookResult?.then) {
  3246. // short circuit for non-thenables and non-Promises
  3247. return hookResult;
  3248. }
  3249. // Track pending hook actions to properly error out when
  3250. // unfulfilled promises cause rollup to abruptly and confusingly
  3251. // exit with a successful 0 return code but without producing any
  3252. // output, errors or warnings.
  3253. action = [plugin.name, hookName, parameters];
  3254. this.unfulfilledActions.add(action);
  3255. // Although it would be more elegant to just return hookResult here
  3256. // and put the .then() handler just above the .catch() handler below,
  3257. // doing so would subtly change the defacto async event dispatch order
  3258. // which at least one test and some plugins in the wild may depend on.
  3259. return Promise.resolve(hookResult).then(result => {
  3260. // action was fulfilled
  3261. this.unfulfilledActions.delete(action);
  3262. return result;
  3263. });
  3264. })
  3265. .catch(error_ => {
  3266. if (action !== null) {
  3267. // action considered to be fulfilled since error being handled
  3268. this.unfulfilledActions.delete(action);
  3269. }
  3270. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  3271. });
  3272. }
  3273. /**
  3274. * Run a sync plugin hook and return the result.
  3275. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  3276. * @param args Arguments passed to the plugin hook.
  3277. * @param plugin The acutal plugin
  3278. * @param replaceContext When passed, the plugin context can be overridden.
  3279. */
  3280. runHookSync(hookName, parameters, plugin, replaceContext) {
  3281. const hook = plugin[hookName];
  3282. const handler = typeof hook === 'object' ? hook.handler : hook;
  3283. let context = this.pluginContexts.get(plugin);
  3284. if (replaceContext) {
  3285. context = replaceContext(context, plugin);
  3286. }
  3287. try {
  3288. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  3289. return handler.apply(context, parameters);
  3290. }
  3291. catch (error_) {
  3292. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  3293. }
  3294. }
  3295. }
  3296. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  3297. const pre = [];
  3298. const normal = [];
  3299. const post = [];
  3300. for (const plugin of plugins) {
  3301. const hook = plugin[hookName];
  3302. if (hook) {
  3303. if (typeof hook === 'object') {
  3304. validateHandler(hook.handler, hookName, plugin);
  3305. if (hook.order === 'pre') {
  3306. pre.push(plugin);
  3307. continue;
  3308. }
  3309. if (hook.order === 'post') {
  3310. post.push(plugin);
  3311. continue;
  3312. }
  3313. }
  3314. else {
  3315. validateHandler(hook, hookName, plugin);
  3316. }
  3317. normal.push(plugin);
  3318. }
  3319. }
  3320. return [...pre, ...normal, ...post];
  3321. }
  3322. function validateFunctionPluginHandler(handler, hookName, plugin) {
  3323. if (typeof handler !== 'function') {
  3324. parseAst_js.error(parseAst_js.logInvalidFunctionPluginHook(hookName, plugin.name));
  3325. }
  3326. }
  3327. function validateAddonPluginHandler(handler, hookName, plugin) {
  3328. if (typeof handler !== 'string' && typeof handler !== 'function') {
  3329. return parseAst_js.error(parseAst_js.logInvalidAddonPluginHook(hookName, plugin.name));
  3330. }
  3331. }
  3332. function noReturn() { }
  3333. function getLogger(plugins, onLog, watchMode, logLevel) {
  3334. plugins = getSortedValidatedPlugins('onLog', plugins);
  3335. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  3336. const logger = (level, log, skipped = parseAst_js.EMPTY_SET) => {
  3337. parseAst_js.augmentLogMessage(log);
  3338. const logPriority = parseAst_js.logLevelPriority[level];
  3339. if (logPriority < minimalPriority) {
  3340. return;
  3341. }
  3342. for (const plugin of plugins) {
  3343. if (skipped.has(plugin))
  3344. continue;
  3345. const { onLog: pluginOnLog } = plugin;
  3346. const getLogHandler = (level) => {
  3347. if (parseAst_js.logLevelPriority[level] < minimalPriority) {
  3348. return doNothing;
  3349. }
  3350. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  3351. };
  3352. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  3353. if (handler.call({
  3354. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG),
  3355. error: (log) => parseAst_js.error(normalizeLog(log)),
  3356. info: getLogHandler(parseAst_js.LOGLEVEL_INFO),
  3357. meta: { rollupVersion: version, watchMode },
  3358. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN)
  3359. }, level, log) === false) {
  3360. return;
  3361. }
  3362. }
  3363. onLog(level, log);
  3364. };
  3365. return logger;
  3366. }
  3367. const commandAliases = {
  3368. c: 'config',
  3369. d: 'dir',
  3370. e: 'external',
  3371. f: 'format',
  3372. g: 'globals',
  3373. h: 'help',
  3374. i: 'input',
  3375. m: 'sourcemap',
  3376. n: 'name',
  3377. o: 'file',
  3378. p: 'plugin',
  3379. v: 'version',
  3380. w: 'watch'
  3381. };
  3382. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  3383. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  3384. const command = getCommandOptions(rawCommandOptions);
  3385. const plugins = await normalizePluginOption(config.plugins);
  3386. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  3387. const onLog = getOnLog(config, logLevel, printLog);
  3388. const log = getLogger(plugins, onLog, watchMode, logLevel);
  3389. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  3390. if (command.output) {
  3391. Object.assign(command, command.output);
  3392. }
  3393. const outputOptionsArray = ensureArray$1(config.output);
  3394. if (outputOptionsArray.length === 0)
  3395. outputOptionsArray.push({});
  3396. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  3397. warnUnknownOptions(command, [
  3398. ...Object.keys(inputOptions).filter(option => option !== 'fs'),
  3399. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  3400. ...Object.keys(commandAliases),
  3401. 'bundleConfigAsCjs',
  3402. 'config',
  3403. 'configImportAttributesKey',
  3404. 'configPlugin',
  3405. 'environment',
  3406. 'failAfterWarnings',
  3407. 'filterLogs',
  3408. 'forceExit',
  3409. 'plugin',
  3410. 'silent',
  3411. 'stdin',
  3412. 'waitForBundleInput'
  3413. ], 'CLI flags', log, /^_$|output$|config/);
  3414. inputOptions.output = outputOptions;
  3415. return inputOptions;
  3416. }
  3417. function getCommandOptions(rawCommandOptions) {
  3418. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  3419. ? rawCommandOptions.external.split(',')
  3420. : [];
  3421. return {
  3422. ...rawCommandOptions,
  3423. external,
  3424. globals: typeof rawCommandOptions.globals === 'string'
  3425. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  3426. const [id, variableName] = globalDefinition.split(':');
  3427. globals[id] = variableName;
  3428. if (!external.includes(id)) {
  3429. external.push(id);
  3430. }
  3431. return globals;
  3432. }, Object.create(null))
  3433. : undefined
  3434. };
  3435. }
  3436. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  3437. const getOption = (name) => overrides[name] ?? config[name];
  3438. const inputOptions = {
  3439. cache: config.cache,
  3440. context: getOption('context'),
  3441. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  3442. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  3443. external: getExternal(config, overrides),
  3444. fs: getOption('fs'),
  3445. input: getOption('input') || [],
  3446. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ')),
  3447. logLevel: getOption('logLevel'),
  3448. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  3449. maxParallelFileOps: getOption('maxParallelFileOps'),
  3450. moduleContext: getOption('moduleContext'),
  3451. onLog,
  3452. onwarn: undefined,
  3453. perf: getOption('perf'),
  3454. plugins,
  3455. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  3456. preserveSymlinks: getOption('preserveSymlinks'),
  3457. shimMissingExports: getOption('shimMissingExports'),
  3458. strictDeprecations: getOption('strictDeprecations'),
  3459. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ')),
  3460. watch: getWatch(config, overrides)
  3461. };
  3462. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  3463. return inputOptions;
  3464. }
  3465. const getExternal = (config, overrides) => {
  3466. const configExternal = config.external;
  3467. return typeof configExternal === 'function'
  3468. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  3469. : [...ensureArray$1(configExternal), ...overrides.external];
  3470. };
  3471. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  3472. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  3473. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  3474. if (commandOption !== undefined) {
  3475. return commandOption && { ...configOption, ...commandOption };
  3476. }
  3477. return configOption;
  3478. };
  3479. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  3480. const isWatchEnabled = (optionValue) => {
  3481. if (Array.isArray(optionValue)) {
  3482. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  3483. }
  3484. return optionValue === true;
  3485. };
  3486. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  3487. if (!optionValue) {
  3488. return optionValue;
  3489. }
  3490. if (Array.isArray(optionValue)) {
  3491. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  3492. }
  3493. return objectifyValue(optionValue);
  3494. };
  3495. async function mergeOutputOptions(config, overrides, log) {
  3496. const getOption = (name) => overrides[name] ?? config[name];
  3497. const outputOptions = {
  3498. amd: getObjectOption(config, overrides, 'amd'),
  3499. assetFileNames: getOption('assetFileNames'),
  3500. banner: getOption('banner'),
  3501. chunkFileNames: getOption('chunkFileNames'),
  3502. compact: getOption('compact'),
  3503. dir: getOption('dir'),
  3504. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  3505. entryFileNames: getOption('entryFileNames'),
  3506. esModule: getOption('esModule'),
  3507. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  3508. exports: getOption('exports'),
  3509. extend: getOption('extend'),
  3510. externalImportAssertions: getOption('externalImportAssertions'),
  3511. externalImportAttributes: getOption('externalImportAttributes'),
  3512. externalLiveBindings: getOption('externalLiveBindings'),
  3513. file: getOption('file'),
  3514. footer: getOption('footer'),
  3515. format: getOption('format'),
  3516. freeze: getOption('freeze'),
  3517. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '')),
  3518. globals: getOption('globals'),
  3519. hashCharacters: getOption('hashCharacters'),
  3520. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  3521. importAttributesKey: getOption('importAttributesKey'),
  3522. indent: getOption('indent'),
  3523. inlineDynamicImports: getOption('inlineDynamicImports'),
  3524. interop: getOption('interop'),
  3525. intro: getOption('intro'),
  3526. manualChunks: getOption('manualChunks'),
  3527. minifyInternalExports: getOption('minifyInternalExports'),
  3528. name: getOption('name'),
  3529. noConflict: getOption('noConflict'),
  3530. onlyExplicitManualChunks: getOption('onlyExplicitManualChunks'),
  3531. outro: getOption('outro'),
  3532. paths: getOption('paths'),
  3533. plugins: await normalizePluginOption(config.plugins),
  3534. preserveModules: getOption('preserveModules'),
  3535. preserveModulesRoot: getOption('preserveModulesRoot'),
  3536. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  3537. sanitizeFileName: getOption('sanitizeFileName'),
  3538. sourcemap: getOption('sourcemap'),
  3539. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  3540. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  3541. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  3542. sourcemapFile: getOption('sourcemapFile'),
  3543. sourcemapFileNames: getOption('sourcemapFileNames'),
  3544. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  3545. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  3546. strict: getOption('strict'),
  3547. systemNullSetters: getOption('systemNullSetters'),
  3548. validate: getOption('validate'),
  3549. virtualDirname: getOption('virtualDirname')
  3550. };
  3551. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  3552. return outputOptions;
  3553. }
  3554. var picocolors = {exports: {}};
  3555. var hasRequiredPicocolors;
  3556. function requirePicocolors () {
  3557. if (hasRequiredPicocolors) return picocolors.exports;
  3558. hasRequiredPicocolors = 1;
  3559. let p = process || {}, argv = p.argv || [], env = p.env || {};
  3560. let isColorSupported =
  3561. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  3562. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  3563. let formatter = (open, close, replace = open) =>
  3564. input => {
  3565. let string = "" + input, index = string.indexOf(close, open.length);
  3566. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  3567. };
  3568. let replaceClose = (string, close, replace, index) => {
  3569. let result = "", cursor = 0;
  3570. do {
  3571. result += string.substring(cursor, index) + replace;
  3572. cursor = index + close.length;
  3573. index = string.indexOf(close, cursor);
  3574. } while (~index)
  3575. return result + string.substring(cursor)
  3576. };
  3577. let createColors = (enabled = isColorSupported) => {
  3578. let f = enabled ? formatter : () => String;
  3579. return {
  3580. isColorSupported: enabled,
  3581. reset: f("\x1b[0m", "\x1b[0m"),
  3582. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  3583. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  3584. italic: f("\x1b[3m", "\x1b[23m"),
  3585. underline: f("\x1b[4m", "\x1b[24m"),
  3586. inverse: f("\x1b[7m", "\x1b[27m"),
  3587. hidden: f("\x1b[8m", "\x1b[28m"),
  3588. strikethrough: f("\x1b[9m", "\x1b[29m"),
  3589. black: f("\x1b[30m", "\x1b[39m"),
  3590. red: f("\x1b[31m", "\x1b[39m"),
  3591. green: f("\x1b[32m", "\x1b[39m"),
  3592. yellow: f("\x1b[33m", "\x1b[39m"),
  3593. blue: f("\x1b[34m", "\x1b[39m"),
  3594. magenta: f("\x1b[35m", "\x1b[39m"),
  3595. cyan: f("\x1b[36m", "\x1b[39m"),
  3596. white: f("\x1b[37m", "\x1b[39m"),
  3597. gray: f("\x1b[90m", "\x1b[39m"),
  3598. bgBlack: f("\x1b[40m", "\x1b[49m"),
  3599. bgRed: f("\x1b[41m", "\x1b[49m"),
  3600. bgGreen: f("\x1b[42m", "\x1b[49m"),
  3601. bgYellow: f("\x1b[43m", "\x1b[49m"),
  3602. bgBlue: f("\x1b[44m", "\x1b[49m"),
  3603. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  3604. bgCyan: f("\x1b[46m", "\x1b[49m"),
  3605. bgWhite: f("\x1b[47m", "\x1b[49m"),
  3606. blackBright: f("\x1b[90m", "\x1b[39m"),
  3607. redBright: f("\x1b[91m", "\x1b[39m"),
  3608. greenBright: f("\x1b[92m", "\x1b[39m"),
  3609. yellowBright: f("\x1b[93m", "\x1b[39m"),
  3610. blueBright: f("\x1b[94m", "\x1b[39m"),
  3611. magentaBright: f("\x1b[95m", "\x1b[39m"),
  3612. cyanBright: f("\x1b[96m", "\x1b[39m"),
  3613. whiteBright: f("\x1b[97m", "\x1b[39m"),
  3614. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  3615. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  3616. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  3617. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  3618. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  3619. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  3620. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  3621. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  3622. }
  3623. };
  3624. picocolors.exports = createColors();
  3625. picocolors.exports.createColors = createColors;
  3626. return picocolors.exports;
  3627. }
  3628. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  3629. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  3630. // @see https://no-color.org
  3631. // @see https://www.npmjs.com/package/chalk
  3632. const { bold, cyan, dim, gray, green, red, underline, yellow } = pc.createColors(process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR);
  3633. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  3634. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  3635. function handleError(error, recover = false) {
  3636. const name = error.name || error.cause?.name;
  3637. const nameSection = name ? `${name}: ` : '';
  3638. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  3639. const message = `${pluginSection}${nameSection}${error.message}`;
  3640. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  3641. if (error.url) {
  3642. outputLines.push(cyan(error.url));
  3643. }
  3644. if (error.loc) {
  3645. outputLines.push(`${parseAst_js.relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  3646. }
  3647. else if (error.id) {
  3648. outputLines.push(parseAst_js.relativeId(error.id));
  3649. }
  3650. if (error.frame) {
  3651. outputLines.push(dim(error.frame));
  3652. }
  3653. if (error.stack) {
  3654. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  3655. }
  3656. // ES2022: Error.prototype.cause is optional
  3657. if (error.cause) {
  3658. let cause = error.cause;
  3659. const causeErrorLines = [];
  3660. let indent = '';
  3661. while (cause) {
  3662. indent += ' ';
  3663. const message = cause.stack || cause;
  3664. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  3665. cause = cause.cause;
  3666. }
  3667. outputLines.push(dim(causeErrorLines.join('\n')));
  3668. }
  3669. outputLines.push('', '');
  3670. stderr(outputLines.join('\n'));
  3671. if (!recover)
  3672. process$1.exit(1);
  3673. }
  3674. // src/vlq.ts
  3675. var comma = ",".charCodeAt(0);
  3676. var semicolon = ";".charCodeAt(0);
  3677. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3678. var intToChar = new Uint8Array(64);
  3679. var charToInt = new Uint8Array(128);
  3680. for (let i = 0; i < chars.length; i++) {
  3681. const c = chars.charCodeAt(i);
  3682. intToChar[i] = c;
  3683. charToInt[c] = i;
  3684. }
  3685. function decodeInteger(reader, relative) {
  3686. let value = 0;
  3687. let shift = 0;
  3688. let integer = 0;
  3689. do {
  3690. const c = reader.next();
  3691. integer = charToInt[c];
  3692. value |= (integer & 31) << shift;
  3693. shift += 5;
  3694. } while (integer & 32);
  3695. const shouldNegate = value & 1;
  3696. value >>>= 1;
  3697. if (shouldNegate) {
  3698. value = -2147483648 | -value;
  3699. }
  3700. return relative + value;
  3701. }
  3702. function encodeInteger(builder, num, relative) {
  3703. let delta = num - relative;
  3704. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  3705. do {
  3706. let clamped = delta & 31;
  3707. delta >>>= 5;
  3708. if (delta > 0) clamped |= 32;
  3709. builder.write(intToChar[clamped]);
  3710. } while (delta > 0);
  3711. return num;
  3712. }
  3713. function hasMoreVlq(reader, max) {
  3714. if (reader.pos >= max) return false;
  3715. return reader.peek() !== comma;
  3716. }
  3717. // src/strings.ts
  3718. var bufLength = 1024 * 16;
  3719. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  3720. decode(buf) {
  3721. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  3722. return out.toString();
  3723. }
  3724. } : {
  3725. decode(buf) {
  3726. let out = "";
  3727. for (let i = 0; i < buf.length; i++) {
  3728. out += String.fromCharCode(buf[i]);
  3729. }
  3730. return out;
  3731. }
  3732. };
  3733. var StringWriter = class {
  3734. constructor() {
  3735. this.pos = 0;
  3736. this.out = "";
  3737. this.buffer = new Uint8Array(bufLength);
  3738. }
  3739. write(v) {
  3740. const { buffer } = this;
  3741. buffer[this.pos++] = v;
  3742. if (this.pos === bufLength) {
  3743. this.out += td.decode(buffer);
  3744. this.pos = 0;
  3745. }
  3746. }
  3747. flush() {
  3748. const { buffer, out, pos } = this;
  3749. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  3750. }
  3751. };
  3752. var StringReader = class {
  3753. constructor(buffer) {
  3754. this.pos = 0;
  3755. this.buffer = buffer;
  3756. }
  3757. next() {
  3758. return this.buffer.charCodeAt(this.pos++);
  3759. }
  3760. peek() {
  3761. return this.buffer.charCodeAt(this.pos);
  3762. }
  3763. indexOf(char) {
  3764. const { buffer, pos } = this;
  3765. const idx = buffer.indexOf(char, pos);
  3766. return idx === -1 ? buffer.length : idx;
  3767. }
  3768. };
  3769. // src/sourcemap-codec.ts
  3770. function decode(mappings) {
  3771. const { length } = mappings;
  3772. const reader = new StringReader(mappings);
  3773. const decoded = [];
  3774. let genColumn = 0;
  3775. let sourcesIndex = 0;
  3776. let sourceLine = 0;
  3777. let sourceColumn = 0;
  3778. let namesIndex = 0;
  3779. do {
  3780. const semi = reader.indexOf(";");
  3781. const line = [];
  3782. let sorted = true;
  3783. let lastCol = 0;
  3784. genColumn = 0;
  3785. while (reader.pos < semi) {
  3786. let seg;
  3787. genColumn = decodeInteger(reader, genColumn);
  3788. if (genColumn < lastCol) sorted = false;
  3789. lastCol = genColumn;
  3790. if (hasMoreVlq(reader, semi)) {
  3791. sourcesIndex = decodeInteger(reader, sourcesIndex);
  3792. sourceLine = decodeInteger(reader, sourceLine);
  3793. sourceColumn = decodeInteger(reader, sourceColumn);
  3794. if (hasMoreVlq(reader, semi)) {
  3795. namesIndex = decodeInteger(reader, namesIndex);
  3796. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  3797. } else {
  3798. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  3799. }
  3800. } else {
  3801. seg = [genColumn];
  3802. }
  3803. line.push(seg);
  3804. reader.pos++;
  3805. }
  3806. if (!sorted) sort(line);
  3807. decoded.push(line);
  3808. reader.pos = semi + 1;
  3809. } while (reader.pos <= length);
  3810. return decoded;
  3811. }
  3812. function sort(line) {
  3813. line.sort(sortComparator);
  3814. }
  3815. function sortComparator(a, b) {
  3816. return a[0] - b[0];
  3817. }
  3818. function encode(decoded) {
  3819. const writer = new StringWriter();
  3820. let sourcesIndex = 0;
  3821. let sourceLine = 0;
  3822. let sourceColumn = 0;
  3823. let namesIndex = 0;
  3824. for (let i = 0; i < decoded.length; i++) {
  3825. const line = decoded[i];
  3826. if (i > 0) writer.write(semicolon);
  3827. if (line.length === 0) continue;
  3828. let genColumn = 0;
  3829. for (let j = 0; j < line.length; j++) {
  3830. const segment = line[j];
  3831. if (j > 0) writer.write(comma);
  3832. genColumn = encodeInteger(writer, segment[0], genColumn);
  3833. if (segment.length === 1) continue;
  3834. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  3835. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  3836. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  3837. if (segment.length === 4) continue;
  3838. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  3839. }
  3840. }
  3841. return writer.flush();
  3842. }
  3843. class BitSet {
  3844. constructor(arg) {
  3845. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3846. }
  3847. add(n) {
  3848. this.bits[n >> 5] |= 1 << (n & 31);
  3849. }
  3850. has(n) {
  3851. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  3852. }
  3853. }
  3854. let Chunk$1 = class Chunk {
  3855. constructor(start, end, content) {
  3856. this.start = start;
  3857. this.end = end;
  3858. this.original = content;
  3859. this.intro = '';
  3860. this.outro = '';
  3861. this.content = content;
  3862. this.storeName = false;
  3863. this.edited = false;
  3864. {
  3865. this.previous = null;
  3866. this.next = null;
  3867. }
  3868. }
  3869. appendLeft(content) {
  3870. this.outro += content;
  3871. }
  3872. appendRight(content) {
  3873. this.intro = this.intro + content;
  3874. }
  3875. clone() {
  3876. const chunk = new Chunk(this.start, this.end, this.original);
  3877. chunk.intro = this.intro;
  3878. chunk.outro = this.outro;
  3879. chunk.content = this.content;
  3880. chunk.storeName = this.storeName;
  3881. chunk.edited = this.edited;
  3882. return chunk;
  3883. }
  3884. contains(index) {
  3885. return this.start < index && index < this.end;
  3886. }
  3887. eachNext(fn) {
  3888. let chunk = this;
  3889. while (chunk) {
  3890. fn(chunk);
  3891. chunk = chunk.next;
  3892. }
  3893. }
  3894. eachPrevious(fn) {
  3895. let chunk = this;
  3896. while (chunk) {
  3897. fn(chunk);
  3898. chunk = chunk.previous;
  3899. }
  3900. }
  3901. edit(content, storeName, contentOnly) {
  3902. this.content = content;
  3903. if (!contentOnly) {
  3904. this.intro = '';
  3905. this.outro = '';
  3906. }
  3907. this.storeName = storeName;
  3908. this.edited = true;
  3909. return this;
  3910. }
  3911. prependLeft(content) {
  3912. this.outro = content + this.outro;
  3913. }
  3914. prependRight(content) {
  3915. this.intro = content + this.intro;
  3916. }
  3917. reset() {
  3918. this.intro = '';
  3919. this.outro = '';
  3920. if (this.edited) {
  3921. this.content = this.original;
  3922. this.storeName = false;
  3923. this.edited = false;
  3924. }
  3925. }
  3926. split(index) {
  3927. const sliceIndex = index - this.start;
  3928. const originalBefore = this.original.slice(0, sliceIndex);
  3929. const originalAfter = this.original.slice(sliceIndex);
  3930. this.original = originalBefore;
  3931. const newChunk = new Chunk(index, this.end, originalAfter);
  3932. newChunk.outro = this.outro;
  3933. this.outro = '';
  3934. this.end = index;
  3935. if (this.edited) {
  3936. // after split we should save the edit content record into the correct chunk
  3937. // to make sure sourcemap correct
  3938. // For example:
  3939. // ' test'.trim()
  3940. // split -> ' ' + 'test'
  3941. // ✔️ edit -> '' + 'test'
  3942. // ✖️ edit -> 'test' + ''
  3943. // TODO is this block necessary?...
  3944. newChunk.edit('', false);
  3945. this.content = '';
  3946. } else {
  3947. this.content = originalBefore;
  3948. }
  3949. newChunk.next = this.next;
  3950. if (newChunk.next) newChunk.next.previous = newChunk;
  3951. newChunk.previous = this;
  3952. this.next = newChunk;
  3953. return newChunk;
  3954. }
  3955. toString() {
  3956. return this.intro + this.content + this.outro;
  3957. }
  3958. trimEnd(rx) {
  3959. this.outro = this.outro.replace(rx, '');
  3960. if (this.outro.length) return true;
  3961. const trimmed = this.content.replace(rx, '');
  3962. if (trimmed.length) {
  3963. if (trimmed !== this.content) {
  3964. this.split(this.start + trimmed.length).edit('', undefined, true);
  3965. if (this.edited) {
  3966. // save the change, if it has been edited
  3967. this.edit(trimmed, this.storeName, true);
  3968. }
  3969. }
  3970. return true;
  3971. } else {
  3972. this.edit('', undefined, true);
  3973. this.intro = this.intro.replace(rx, '');
  3974. if (this.intro.length) return true;
  3975. }
  3976. }
  3977. trimStart(rx) {
  3978. this.intro = this.intro.replace(rx, '');
  3979. if (this.intro.length) return true;
  3980. const trimmed = this.content.replace(rx, '');
  3981. if (trimmed.length) {
  3982. if (trimmed !== this.content) {
  3983. const newChunk = this.split(this.end - trimmed.length);
  3984. if (this.edited) {
  3985. // save the change, if it has been edited
  3986. newChunk.edit(trimmed, this.storeName, true);
  3987. }
  3988. this.edit('', undefined, true);
  3989. }
  3990. return true;
  3991. } else {
  3992. this.edit('', undefined, true);
  3993. this.outro = this.outro.replace(rx, '');
  3994. if (this.outro.length) return true;
  3995. }
  3996. }
  3997. };
  3998. function getBtoa() {
  3999. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  4000. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  4001. } else if (typeof Buffer === 'function') {
  4002. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  4003. } else {
  4004. return () => {
  4005. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  4006. };
  4007. }
  4008. }
  4009. const btoa = /*#__PURE__*/ getBtoa();
  4010. class SourceMap {
  4011. constructor(properties) {
  4012. this.version = 3;
  4013. this.file = properties.file;
  4014. this.sources = properties.sources;
  4015. this.sourcesContent = properties.sourcesContent;
  4016. this.names = properties.names;
  4017. this.mappings = encode(properties.mappings);
  4018. if (typeof properties.x_google_ignoreList !== 'undefined') {
  4019. this.x_google_ignoreList = properties.x_google_ignoreList;
  4020. }
  4021. if (typeof properties.debugId !== 'undefined') {
  4022. this.debugId = properties.debugId;
  4023. }
  4024. }
  4025. toString() {
  4026. return JSON.stringify(this);
  4027. }
  4028. toUrl() {
  4029. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  4030. }
  4031. }
  4032. function guessIndent(code) {
  4033. const lines = code.split('\n');
  4034. const tabbed = lines.filter((line) => /^\t+/.test(line));
  4035. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  4036. if (tabbed.length === 0 && spaced.length === 0) {
  4037. return null;
  4038. }
  4039. // More lines tabbed than spaced? Assume tabs, and
  4040. // default to tabs in the case of a tie (or nothing
  4041. // to go on)
  4042. if (tabbed.length >= spaced.length) {
  4043. return '\t';
  4044. }
  4045. // Otherwise, we need to guess the multiple
  4046. const min = spaced.reduce((previous, current) => {
  4047. const numSpaces = /^ +/.exec(current)[0].length;
  4048. return Math.min(numSpaces, previous);
  4049. }, Infinity);
  4050. return new Array(min + 1).join(' ');
  4051. }
  4052. function getRelativePath(from, to) {
  4053. const fromParts = from.split(/[/\\]/);
  4054. const toParts = to.split(/[/\\]/);
  4055. fromParts.pop(); // get dirname
  4056. while (fromParts[0] === toParts[0]) {
  4057. fromParts.shift();
  4058. toParts.shift();
  4059. }
  4060. if (fromParts.length) {
  4061. let i = fromParts.length;
  4062. while (i--) fromParts[i] = '..';
  4063. }
  4064. return fromParts.concat(toParts).join('/');
  4065. }
  4066. const toString = Object.prototype.toString;
  4067. function isObject(thing) {
  4068. return toString.call(thing) === '[object Object]';
  4069. }
  4070. function getLocator(source) {
  4071. const originalLines = source.split('\n');
  4072. const lineOffsets = [];
  4073. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  4074. lineOffsets.push(pos);
  4075. pos += originalLines[i].length + 1;
  4076. }
  4077. return function locate(index) {
  4078. let i = 0;
  4079. let j = lineOffsets.length;
  4080. while (i < j) {
  4081. const m = (i + j) >> 1;
  4082. if (index < lineOffsets[m]) {
  4083. j = m;
  4084. } else {
  4085. i = m + 1;
  4086. }
  4087. }
  4088. const line = i - 1;
  4089. const column = index - lineOffsets[line];
  4090. return { line, column };
  4091. };
  4092. }
  4093. const wordRegex = /\w/;
  4094. class Mappings {
  4095. constructor(hires) {
  4096. this.hires = hires;
  4097. this.generatedCodeLine = 0;
  4098. this.generatedCodeColumn = 0;
  4099. this.raw = [];
  4100. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  4101. this.pending = null;
  4102. }
  4103. addEdit(sourceIndex, content, loc, nameIndex) {
  4104. if (content.length) {
  4105. const contentLengthMinusOne = content.length - 1;
  4106. let contentLineEnd = content.indexOf('\n', 0);
  4107. let previousContentLineEnd = -1;
  4108. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  4109. // else code afterwards would fill one line too many
  4110. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  4111. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  4112. if (nameIndex >= 0) {
  4113. segment.push(nameIndex);
  4114. }
  4115. this.rawSegments.push(segment);
  4116. this.generatedCodeLine += 1;
  4117. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4118. this.generatedCodeColumn = 0;
  4119. previousContentLineEnd = contentLineEnd;
  4120. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  4121. }
  4122. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  4123. if (nameIndex >= 0) {
  4124. segment.push(nameIndex);
  4125. }
  4126. this.rawSegments.push(segment);
  4127. this.advance(content.slice(previousContentLineEnd + 1));
  4128. } else if (this.pending) {
  4129. this.rawSegments.push(this.pending);
  4130. this.advance(content);
  4131. }
  4132. this.pending = null;
  4133. }
  4134. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  4135. let originalCharIndex = chunk.start;
  4136. let first = true;
  4137. // when iterating each char, check if it's in a word boundary
  4138. let charInHiresBoundary = false;
  4139. while (originalCharIndex < chunk.end) {
  4140. if (original[originalCharIndex] === '\n') {
  4141. loc.line += 1;
  4142. loc.column = 0;
  4143. this.generatedCodeLine += 1;
  4144. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4145. this.generatedCodeColumn = 0;
  4146. first = true;
  4147. charInHiresBoundary = false;
  4148. } else {
  4149. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  4150. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  4151. if (this.hires === 'boundary') {
  4152. // in hires "boundary", group segments per word boundary than per char
  4153. if (wordRegex.test(original[originalCharIndex])) {
  4154. // for first char in the boundary found, start the boundary by pushing a segment
  4155. if (!charInHiresBoundary) {
  4156. this.rawSegments.push(segment);
  4157. charInHiresBoundary = true;
  4158. }
  4159. } else {
  4160. // for non-word char, end the boundary by pushing a segment
  4161. this.rawSegments.push(segment);
  4162. charInHiresBoundary = false;
  4163. }
  4164. } else {
  4165. this.rawSegments.push(segment);
  4166. }
  4167. }
  4168. loc.column += 1;
  4169. this.generatedCodeColumn += 1;
  4170. first = false;
  4171. }
  4172. originalCharIndex += 1;
  4173. }
  4174. this.pending = null;
  4175. }
  4176. advance(str) {
  4177. if (!str) return;
  4178. const lines = str.split('\n');
  4179. if (lines.length > 1) {
  4180. for (let i = 0; i < lines.length - 1; i++) {
  4181. this.generatedCodeLine++;
  4182. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  4183. }
  4184. this.generatedCodeColumn = 0;
  4185. }
  4186. this.generatedCodeColumn += lines[lines.length - 1].length;
  4187. }
  4188. }
  4189. const n = '\n';
  4190. const warned = {
  4191. insertLeft: false,
  4192. insertRight: false,
  4193. storeName: false,
  4194. };
  4195. class MagicString {
  4196. constructor(string, options = {}) {
  4197. const chunk = new Chunk$1(0, string.length, string);
  4198. Object.defineProperties(this, {
  4199. original: { writable: true, value: string },
  4200. outro: { writable: true, value: '' },
  4201. intro: { writable: true, value: '' },
  4202. firstChunk: { writable: true, value: chunk },
  4203. lastChunk: { writable: true, value: chunk },
  4204. lastSearchedChunk: { writable: true, value: chunk },
  4205. byStart: { writable: true, value: {} },
  4206. byEnd: { writable: true, value: {} },
  4207. filename: { writable: true, value: options.filename },
  4208. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  4209. sourcemapLocations: { writable: true, value: new BitSet() },
  4210. storedNames: { writable: true, value: {} },
  4211. indentStr: { writable: true, value: undefined },
  4212. ignoreList: { writable: true, value: options.ignoreList },
  4213. offset: { writable: true, value: options.offset || 0 },
  4214. });
  4215. this.byStart[0] = chunk;
  4216. this.byEnd[string.length] = chunk;
  4217. }
  4218. addSourcemapLocation(char) {
  4219. this.sourcemapLocations.add(char);
  4220. }
  4221. append(content) {
  4222. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  4223. this.outro += content;
  4224. return this;
  4225. }
  4226. appendLeft(index, content) {
  4227. index = index + this.offset;
  4228. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4229. this._split(index);
  4230. const chunk = this.byEnd[index];
  4231. if (chunk) {
  4232. chunk.appendLeft(content);
  4233. } else {
  4234. this.intro += content;
  4235. }
  4236. return this;
  4237. }
  4238. appendRight(index, content) {
  4239. index = index + this.offset;
  4240. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4241. this._split(index);
  4242. const chunk = this.byStart[index];
  4243. if (chunk) {
  4244. chunk.appendRight(content);
  4245. } else {
  4246. this.outro += content;
  4247. }
  4248. return this;
  4249. }
  4250. clone() {
  4251. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  4252. let originalChunk = this.firstChunk;
  4253. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  4254. while (originalChunk) {
  4255. cloned.byStart[clonedChunk.start] = clonedChunk;
  4256. cloned.byEnd[clonedChunk.end] = clonedChunk;
  4257. const nextOriginalChunk = originalChunk.next;
  4258. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  4259. if (nextClonedChunk) {
  4260. clonedChunk.next = nextClonedChunk;
  4261. nextClonedChunk.previous = clonedChunk;
  4262. clonedChunk = nextClonedChunk;
  4263. }
  4264. originalChunk = nextOriginalChunk;
  4265. }
  4266. cloned.lastChunk = clonedChunk;
  4267. if (this.indentExclusionRanges) {
  4268. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4269. }
  4270. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4271. cloned.intro = this.intro;
  4272. cloned.outro = this.outro;
  4273. return cloned;
  4274. }
  4275. generateDecodedMap(options) {
  4276. options = options || {};
  4277. const sourceIndex = 0;
  4278. const names = Object.keys(this.storedNames);
  4279. const mappings = new Mappings(options.hires);
  4280. const locate = getLocator(this.original);
  4281. if (this.intro) {
  4282. mappings.advance(this.intro);
  4283. }
  4284. this.firstChunk.eachNext((chunk) => {
  4285. const loc = locate(chunk.start);
  4286. if (chunk.intro.length) mappings.advance(chunk.intro);
  4287. if (chunk.edited) {
  4288. mappings.addEdit(
  4289. sourceIndex,
  4290. chunk.content,
  4291. loc,
  4292. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4293. );
  4294. } else {
  4295. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  4296. }
  4297. if (chunk.outro.length) mappings.advance(chunk.outro);
  4298. });
  4299. if (this.outro) {
  4300. mappings.advance(this.outro);
  4301. }
  4302. return {
  4303. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4304. sources: [
  4305. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  4306. ],
  4307. sourcesContent: options.includeContent ? [this.original] : undefined,
  4308. names,
  4309. mappings: mappings.raw,
  4310. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  4311. };
  4312. }
  4313. generateMap(options) {
  4314. return new SourceMap(this.generateDecodedMap(options));
  4315. }
  4316. _ensureindentStr() {
  4317. if (this.indentStr === undefined) {
  4318. this.indentStr = guessIndent(this.original);
  4319. }
  4320. }
  4321. _getRawIndentString() {
  4322. this._ensureindentStr();
  4323. return this.indentStr;
  4324. }
  4325. getIndentString() {
  4326. this._ensureindentStr();
  4327. return this.indentStr === null ? '\t' : this.indentStr;
  4328. }
  4329. indent(indentStr, options) {
  4330. const pattern = /^[^\r\n]/gm;
  4331. if (isObject(indentStr)) {
  4332. options = indentStr;
  4333. indentStr = undefined;
  4334. }
  4335. if (indentStr === undefined) {
  4336. this._ensureindentStr();
  4337. indentStr = this.indentStr || '\t';
  4338. }
  4339. if (indentStr === '') return this; // noop
  4340. options = options || {};
  4341. // Process exclusion ranges
  4342. const isExcluded = {};
  4343. if (options.exclude) {
  4344. const exclusions =
  4345. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  4346. exclusions.forEach((exclusion) => {
  4347. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  4348. isExcluded[i] = true;
  4349. }
  4350. });
  4351. }
  4352. let shouldIndentNextCharacter = options.indentStart !== false;
  4353. const replacer = (match) => {
  4354. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4355. shouldIndentNextCharacter = true;
  4356. return match;
  4357. };
  4358. this.intro = this.intro.replace(pattern, replacer);
  4359. let charIndex = 0;
  4360. let chunk = this.firstChunk;
  4361. while (chunk) {
  4362. const end = chunk.end;
  4363. if (chunk.edited) {
  4364. if (!isExcluded[charIndex]) {
  4365. chunk.content = chunk.content.replace(pattern, replacer);
  4366. if (chunk.content.length) {
  4367. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  4368. }
  4369. }
  4370. } else {
  4371. charIndex = chunk.start;
  4372. while (charIndex < end) {
  4373. if (!isExcluded[charIndex]) {
  4374. const char = this.original[charIndex];
  4375. if (char === '\n') {
  4376. shouldIndentNextCharacter = true;
  4377. } else if (char !== '\r' && shouldIndentNextCharacter) {
  4378. shouldIndentNextCharacter = false;
  4379. if (charIndex === chunk.start) {
  4380. chunk.prependRight(indentStr);
  4381. } else {
  4382. this._splitChunk(chunk, charIndex);
  4383. chunk = chunk.next;
  4384. chunk.prependRight(indentStr);
  4385. }
  4386. }
  4387. }
  4388. charIndex += 1;
  4389. }
  4390. }
  4391. charIndex = chunk.end;
  4392. chunk = chunk.next;
  4393. }
  4394. this.outro = this.outro.replace(pattern, replacer);
  4395. return this;
  4396. }
  4397. insert() {
  4398. throw new Error(
  4399. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  4400. );
  4401. }
  4402. insertLeft(index, content) {
  4403. if (!warned.insertLeft) {
  4404. console.warn(
  4405. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  4406. );
  4407. warned.insertLeft = true;
  4408. }
  4409. return this.appendLeft(index, content);
  4410. }
  4411. insertRight(index, content) {
  4412. if (!warned.insertRight) {
  4413. console.warn(
  4414. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  4415. );
  4416. warned.insertRight = true;
  4417. }
  4418. return this.prependRight(index, content);
  4419. }
  4420. move(start, end, index) {
  4421. start = start + this.offset;
  4422. end = end + this.offset;
  4423. index = index + this.offset;
  4424. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  4425. this._split(start);
  4426. this._split(end);
  4427. this._split(index);
  4428. const first = this.byStart[start];
  4429. const last = this.byEnd[end];
  4430. const oldLeft = first.previous;
  4431. const oldRight = last.next;
  4432. const newRight = this.byStart[index];
  4433. if (!newRight && last === this.lastChunk) return this;
  4434. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4435. if (oldLeft) oldLeft.next = oldRight;
  4436. if (oldRight) oldRight.previous = oldLeft;
  4437. if (newLeft) newLeft.next = first;
  4438. if (newRight) newRight.previous = last;
  4439. if (!first.previous) this.firstChunk = last.next;
  4440. if (!last.next) {
  4441. this.lastChunk = first.previous;
  4442. this.lastChunk.next = null;
  4443. }
  4444. first.previous = newLeft;
  4445. last.next = newRight || null;
  4446. if (!newLeft) this.firstChunk = first;
  4447. if (!newRight) this.lastChunk = last;
  4448. return this;
  4449. }
  4450. overwrite(start, end, content, options) {
  4451. options = options || {};
  4452. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  4453. }
  4454. update(start, end, content, options) {
  4455. start = start + this.offset;
  4456. end = end + this.offset;
  4457. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  4458. if (this.original.length !== 0) {
  4459. while (start < 0) start += this.original.length;
  4460. while (end < 0) end += this.original.length;
  4461. }
  4462. if (end > this.original.length) throw new Error('end is out of bounds');
  4463. if (start === end)
  4464. throw new Error(
  4465. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  4466. );
  4467. this._split(start);
  4468. this._split(end);
  4469. if (options === true) {
  4470. if (!warned.storeName) {
  4471. console.warn(
  4472. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  4473. );
  4474. warned.storeName = true;
  4475. }
  4476. options = { storeName: true };
  4477. }
  4478. const storeName = options !== undefined ? options.storeName : false;
  4479. const overwrite = options !== undefined ? options.overwrite : false;
  4480. if (storeName) {
  4481. const original = this.original.slice(start, end);
  4482. Object.defineProperty(this.storedNames, original, {
  4483. writable: true,
  4484. value: true,
  4485. enumerable: true,
  4486. });
  4487. }
  4488. const first = this.byStart[start];
  4489. const last = this.byEnd[end];
  4490. if (first) {
  4491. let chunk = first;
  4492. while (chunk !== last) {
  4493. if (chunk.next !== this.byStart[chunk.end]) {
  4494. throw new Error('Cannot overwrite across a split point');
  4495. }
  4496. chunk = chunk.next;
  4497. chunk.edit('', false);
  4498. }
  4499. first.edit(content, storeName, !overwrite);
  4500. } else {
  4501. // must be inserting at the end
  4502. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  4503. // TODO last chunk in the array may not be the last chunk, if it's moved...
  4504. last.next = newChunk;
  4505. newChunk.previous = last;
  4506. }
  4507. return this;
  4508. }
  4509. prepend(content) {
  4510. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  4511. this.intro = content + this.intro;
  4512. return this;
  4513. }
  4514. prependLeft(index, content) {
  4515. index = index + this.offset;
  4516. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4517. this._split(index);
  4518. const chunk = this.byEnd[index];
  4519. if (chunk) {
  4520. chunk.prependLeft(content);
  4521. } else {
  4522. this.intro = content + this.intro;
  4523. }
  4524. return this;
  4525. }
  4526. prependRight(index, content) {
  4527. index = index + this.offset;
  4528. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4529. this._split(index);
  4530. const chunk = this.byStart[index];
  4531. if (chunk) {
  4532. chunk.prependRight(content);
  4533. } else {
  4534. this.outro = content + this.outro;
  4535. }
  4536. return this;
  4537. }
  4538. remove(start, end) {
  4539. start = start + this.offset;
  4540. end = end + this.offset;
  4541. if (this.original.length !== 0) {
  4542. while (start < 0) start += this.original.length;
  4543. while (end < 0) end += this.original.length;
  4544. }
  4545. if (start === end) return this;
  4546. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4547. if (start > end) throw new Error('end must be greater than start');
  4548. this._split(start);
  4549. this._split(end);
  4550. let chunk = this.byStart[start];
  4551. while (chunk) {
  4552. chunk.intro = '';
  4553. chunk.outro = '';
  4554. chunk.edit('');
  4555. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4556. }
  4557. return this;
  4558. }
  4559. reset(start, end) {
  4560. start = start + this.offset;
  4561. end = end + this.offset;
  4562. if (this.original.length !== 0) {
  4563. while (start < 0) start += this.original.length;
  4564. while (end < 0) end += this.original.length;
  4565. }
  4566. if (start === end) return this;
  4567. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4568. if (start > end) throw new Error('end must be greater than start');
  4569. this._split(start);
  4570. this._split(end);
  4571. let chunk = this.byStart[start];
  4572. while (chunk) {
  4573. chunk.reset();
  4574. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4575. }
  4576. return this;
  4577. }
  4578. lastChar() {
  4579. if (this.outro.length) return this.outro[this.outro.length - 1];
  4580. let chunk = this.lastChunk;
  4581. do {
  4582. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4583. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4584. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4585. } while ((chunk = chunk.previous));
  4586. if (this.intro.length) return this.intro[this.intro.length - 1];
  4587. return '';
  4588. }
  4589. lastLine() {
  4590. let lineIndex = this.outro.lastIndexOf(n);
  4591. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4592. let lineStr = this.outro;
  4593. let chunk = this.lastChunk;
  4594. do {
  4595. if (chunk.outro.length > 0) {
  4596. lineIndex = chunk.outro.lastIndexOf(n);
  4597. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4598. lineStr = chunk.outro + lineStr;
  4599. }
  4600. if (chunk.content.length > 0) {
  4601. lineIndex = chunk.content.lastIndexOf(n);
  4602. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4603. lineStr = chunk.content + lineStr;
  4604. }
  4605. if (chunk.intro.length > 0) {
  4606. lineIndex = chunk.intro.lastIndexOf(n);
  4607. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4608. lineStr = chunk.intro + lineStr;
  4609. }
  4610. } while ((chunk = chunk.previous));
  4611. lineIndex = this.intro.lastIndexOf(n);
  4612. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4613. return this.intro + lineStr;
  4614. }
  4615. slice(start = 0, end = this.original.length - this.offset) {
  4616. start = start + this.offset;
  4617. end = end + this.offset;
  4618. if (this.original.length !== 0) {
  4619. while (start < 0) start += this.original.length;
  4620. while (end < 0) end += this.original.length;
  4621. }
  4622. let result = '';
  4623. // find start chunk
  4624. let chunk = this.firstChunk;
  4625. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4626. // found end chunk before start
  4627. if (chunk.start < end && chunk.end >= end) {
  4628. return result;
  4629. }
  4630. chunk = chunk.next;
  4631. }
  4632. if (chunk && chunk.edited && chunk.start !== start)
  4633. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4634. const startChunk = chunk;
  4635. while (chunk) {
  4636. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  4637. result += chunk.intro;
  4638. }
  4639. const containsEnd = chunk.start < end && chunk.end >= end;
  4640. if (containsEnd && chunk.edited && chunk.end !== end)
  4641. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4642. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4643. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4644. result += chunk.content.slice(sliceStart, sliceEnd);
  4645. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  4646. result += chunk.outro;
  4647. }
  4648. if (containsEnd) {
  4649. break;
  4650. }
  4651. chunk = chunk.next;
  4652. }
  4653. return result;
  4654. }
  4655. // TODO deprecate this? not really very useful
  4656. snip(start, end) {
  4657. const clone = this.clone();
  4658. clone.remove(0, start);
  4659. clone.remove(end, clone.original.length);
  4660. return clone;
  4661. }
  4662. _split(index) {
  4663. if (this.byStart[index] || this.byEnd[index]) return;
  4664. let chunk = this.lastSearchedChunk;
  4665. let previousChunk = chunk;
  4666. const searchForward = index > chunk.end;
  4667. while (chunk) {
  4668. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4669. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4670. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  4671. if (chunk === previousChunk) return;
  4672. previousChunk = chunk;
  4673. }
  4674. }
  4675. _splitChunk(chunk, index) {
  4676. if (chunk.edited && chunk.content.length) {
  4677. // zero-length edited chunks are a special case (overlapping replacements)
  4678. const loc = getLocator(this.original)(index);
  4679. throw new Error(
  4680. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  4681. );
  4682. }
  4683. const newChunk = chunk.split(index);
  4684. this.byEnd[index] = chunk;
  4685. this.byStart[index] = newChunk;
  4686. this.byEnd[newChunk.end] = newChunk;
  4687. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4688. this.lastSearchedChunk = chunk;
  4689. return true;
  4690. }
  4691. toString() {
  4692. let str = this.intro;
  4693. let chunk = this.firstChunk;
  4694. while (chunk) {
  4695. str += chunk.toString();
  4696. chunk = chunk.next;
  4697. }
  4698. return str + this.outro;
  4699. }
  4700. isEmpty() {
  4701. let chunk = this.firstChunk;
  4702. do {
  4703. if (
  4704. (chunk.intro.length && chunk.intro.trim()) ||
  4705. (chunk.content.length && chunk.content.trim()) ||
  4706. (chunk.outro.length && chunk.outro.trim())
  4707. )
  4708. return false;
  4709. } while ((chunk = chunk.next));
  4710. return true;
  4711. }
  4712. length() {
  4713. let chunk = this.firstChunk;
  4714. let length = 0;
  4715. do {
  4716. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4717. } while ((chunk = chunk.next));
  4718. return length;
  4719. }
  4720. trimLines() {
  4721. return this.trim('[\\r\\n]');
  4722. }
  4723. trim(charType) {
  4724. return this.trimStart(charType).trimEnd(charType);
  4725. }
  4726. trimEndAborted(charType) {
  4727. const rx = new RegExp((charType || '\\s') + '+$');
  4728. this.outro = this.outro.replace(rx, '');
  4729. if (this.outro.length) return true;
  4730. let chunk = this.lastChunk;
  4731. do {
  4732. const end = chunk.end;
  4733. const aborted = chunk.trimEnd(rx);
  4734. // if chunk was trimmed, we have a new lastChunk
  4735. if (chunk.end !== end) {
  4736. if (this.lastChunk === chunk) {
  4737. this.lastChunk = chunk.next;
  4738. }
  4739. this.byEnd[chunk.end] = chunk;
  4740. this.byStart[chunk.next.start] = chunk.next;
  4741. this.byEnd[chunk.next.end] = chunk.next;
  4742. }
  4743. if (aborted) return true;
  4744. chunk = chunk.previous;
  4745. } while (chunk);
  4746. return false;
  4747. }
  4748. trimEnd(charType) {
  4749. this.trimEndAborted(charType);
  4750. return this;
  4751. }
  4752. trimStartAborted(charType) {
  4753. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4754. this.intro = this.intro.replace(rx, '');
  4755. if (this.intro.length) return true;
  4756. let chunk = this.firstChunk;
  4757. do {
  4758. const end = chunk.end;
  4759. const aborted = chunk.trimStart(rx);
  4760. if (chunk.end !== end) {
  4761. // special case...
  4762. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4763. this.byEnd[chunk.end] = chunk;
  4764. this.byStart[chunk.next.start] = chunk.next;
  4765. this.byEnd[chunk.next.end] = chunk.next;
  4766. }
  4767. if (aborted) return true;
  4768. chunk = chunk.next;
  4769. } while (chunk);
  4770. return false;
  4771. }
  4772. trimStart(charType) {
  4773. this.trimStartAborted(charType);
  4774. return this;
  4775. }
  4776. hasChanged() {
  4777. return this.original !== this.toString();
  4778. }
  4779. _replaceRegexp(searchValue, replacement) {
  4780. function getReplacement(match, str) {
  4781. if (typeof replacement === 'string') {
  4782. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4783. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  4784. if (i === '$') return '$';
  4785. if (i === '&') return match[0];
  4786. const num = +i;
  4787. if (num < match.length) return match[+i];
  4788. return `$${i}`;
  4789. });
  4790. } else {
  4791. return replacement(...match, match.index, str, match.groups);
  4792. }
  4793. }
  4794. function matchAll(re, str) {
  4795. let match;
  4796. const matches = [];
  4797. while ((match = re.exec(str))) {
  4798. matches.push(match);
  4799. }
  4800. return matches;
  4801. }
  4802. if (searchValue.global) {
  4803. const matches = matchAll(searchValue, this.original);
  4804. matches.forEach((match) => {
  4805. if (match.index != null) {
  4806. const replacement = getReplacement(match, this.original);
  4807. if (replacement !== match[0]) {
  4808. this.overwrite(match.index, match.index + match[0].length, replacement);
  4809. }
  4810. }
  4811. });
  4812. } else {
  4813. const match = this.original.match(searchValue);
  4814. if (match && match.index != null) {
  4815. const replacement = getReplacement(match, this.original);
  4816. if (replacement !== match[0]) {
  4817. this.overwrite(match.index, match.index + match[0].length, replacement);
  4818. }
  4819. }
  4820. }
  4821. return this;
  4822. }
  4823. _replaceString(string, replacement) {
  4824. const { original } = this;
  4825. const index = original.indexOf(string);
  4826. if (index !== -1) {
  4827. if (typeof replacement === 'function') {
  4828. replacement = replacement(string, index, original);
  4829. }
  4830. if (string !== replacement) {
  4831. this.overwrite(index, index + string.length, replacement);
  4832. }
  4833. }
  4834. return this;
  4835. }
  4836. replace(searchValue, replacement) {
  4837. if (typeof searchValue === 'string') {
  4838. return this._replaceString(searchValue, replacement);
  4839. }
  4840. return this._replaceRegexp(searchValue, replacement);
  4841. }
  4842. _replaceAllString(string, replacement) {
  4843. const { original } = this;
  4844. const stringLength = string.length;
  4845. for (
  4846. let index = original.indexOf(string);
  4847. index !== -1;
  4848. index = original.indexOf(string, index + stringLength)
  4849. ) {
  4850. const previous = original.slice(index, index + stringLength);
  4851. let _replacement = replacement;
  4852. if (typeof replacement === 'function') {
  4853. _replacement = replacement(previous, index, original);
  4854. }
  4855. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  4856. }
  4857. return this;
  4858. }
  4859. replaceAll(searchValue, replacement) {
  4860. if (typeof searchValue === 'string') {
  4861. return this._replaceAllString(searchValue, replacement);
  4862. }
  4863. if (!searchValue.global) {
  4864. throw new TypeError(
  4865. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  4866. );
  4867. }
  4868. return this._replaceRegexp(searchValue, replacement);
  4869. }
  4870. }
  4871. const hasOwnProp = Object.prototype.hasOwnProperty;
  4872. let Bundle$1 = class Bundle {
  4873. constructor(options = {}) {
  4874. this.intro = options.intro || '';
  4875. this.separator = options.separator !== undefined ? options.separator : '\n';
  4876. this.sources = [];
  4877. this.uniqueSources = [];
  4878. this.uniqueSourceIndexByFilename = {};
  4879. }
  4880. addSource(source) {
  4881. if (source instanceof MagicString) {
  4882. return this.addSource({
  4883. content: source,
  4884. filename: source.filename,
  4885. separator: this.separator,
  4886. });
  4887. }
  4888. if (!isObject(source) || !source.content) {
  4889. throw new Error(
  4890. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  4891. );
  4892. }
  4893. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  4894. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  4895. });
  4896. if (source.separator === undefined) {
  4897. // TODO there's a bunch of this sort of thing, needs cleaning up
  4898. source.separator = this.separator;
  4899. }
  4900. if (source.filename) {
  4901. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  4902. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  4903. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  4904. } else {
  4905. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  4906. if (source.content.original !== uniqueSource.content) {
  4907. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  4908. }
  4909. }
  4910. }
  4911. this.sources.push(source);
  4912. return this;
  4913. }
  4914. append(str, options) {
  4915. this.addSource({
  4916. content: new MagicString(str),
  4917. separator: (options && options.separator) || '',
  4918. });
  4919. return this;
  4920. }
  4921. clone() {
  4922. const bundle = new Bundle({
  4923. intro: this.intro,
  4924. separator: this.separator,
  4925. });
  4926. this.sources.forEach((source) => {
  4927. bundle.addSource({
  4928. filename: source.filename,
  4929. content: source.content.clone(),
  4930. separator: source.separator,
  4931. });
  4932. });
  4933. return bundle;
  4934. }
  4935. generateDecodedMap(options = {}) {
  4936. const names = [];
  4937. let x_google_ignoreList = undefined;
  4938. this.sources.forEach((source) => {
  4939. Object.keys(source.content.storedNames).forEach((name) => {
  4940. if (!~names.indexOf(name)) names.push(name);
  4941. });
  4942. });
  4943. const mappings = new Mappings(options.hires);
  4944. if (this.intro) {
  4945. mappings.advance(this.intro);
  4946. }
  4947. this.sources.forEach((source, i) => {
  4948. if (i > 0) {
  4949. mappings.advance(this.separator);
  4950. }
  4951. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  4952. const magicString = source.content;
  4953. const locate = getLocator(magicString.original);
  4954. if (magicString.intro) {
  4955. mappings.advance(magicString.intro);
  4956. }
  4957. magicString.firstChunk.eachNext((chunk) => {
  4958. const loc = locate(chunk.start);
  4959. if (chunk.intro.length) mappings.advance(chunk.intro);
  4960. if (source.filename) {
  4961. if (chunk.edited) {
  4962. mappings.addEdit(
  4963. sourceIndex,
  4964. chunk.content,
  4965. loc,
  4966. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4967. );
  4968. } else {
  4969. mappings.addUneditedChunk(
  4970. sourceIndex,
  4971. chunk,
  4972. magicString.original,
  4973. loc,
  4974. magicString.sourcemapLocations,
  4975. );
  4976. }
  4977. } else {
  4978. mappings.advance(chunk.content);
  4979. }
  4980. if (chunk.outro.length) mappings.advance(chunk.outro);
  4981. });
  4982. if (magicString.outro) {
  4983. mappings.advance(magicString.outro);
  4984. }
  4985. if (source.ignoreList && sourceIndex !== -1) {
  4986. if (x_google_ignoreList === undefined) {
  4987. x_google_ignoreList = [];
  4988. }
  4989. x_google_ignoreList.push(sourceIndex);
  4990. }
  4991. });
  4992. return {
  4993. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4994. sources: this.uniqueSources.map((source) => {
  4995. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  4996. }),
  4997. sourcesContent: this.uniqueSources.map((source) => {
  4998. return options.includeContent ? source.content : null;
  4999. }),
  5000. names,
  5001. mappings: mappings.raw,
  5002. x_google_ignoreList,
  5003. };
  5004. }
  5005. generateMap(options) {
  5006. return new SourceMap(this.generateDecodedMap(options));
  5007. }
  5008. getIndentString() {
  5009. const indentStringCounts = {};
  5010. this.sources.forEach((source) => {
  5011. const indentStr = source.content._getRawIndentString();
  5012. if (indentStr === null) return;
  5013. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  5014. indentStringCounts[indentStr] += 1;
  5015. });
  5016. return (
  5017. Object.keys(indentStringCounts).sort((a, b) => {
  5018. return indentStringCounts[a] - indentStringCounts[b];
  5019. })[0] || '\t'
  5020. );
  5021. }
  5022. indent(indentStr) {
  5023. if (!arguments.length) {
  5024. indentStr = this.getIndentString();
  5025. }
  5026. if (indentStr === '') return this; // noop
  5027. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  5028. this.sources.forEach((source, i) => {
  5029. const separator = source.separator !== undefined ? source.separator : this.separator;
  5030. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  5031. source.content.indent(indentStr, {
  5032. exclude: source.indentExclusionRanges,
  5033. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  5034. });
  5035. trailingNewline = source.content.lastChar() === '\n';
  5036. });
  5037. if (this.intro) {
  5038. this.intro =
  5039. indentStr +
  5040. this.intro.replace(/^[^\n]/gm, (match, index) => {
  5041. return index > 0 ? indentStr + match : match;
  5042. });
  5043. }
  5044. return this;
  5045. }
  5046. prepend(str) {
  5047. this.intro = str + this.intro;
  5048. return this;
  5049. }
  5050. toString() {
  5051. const body = this.sources
  5052. .map((source, i) => {
  5053. const separator = source.separator !== undefined ? source.separator : this.separator;
  5054. const str = (i > 0 ? separator : '') + source.content.toString();
  5055. return str;
  5056. })
  5057. .join('');
  5058. return this.intro + body;
  5059. }
  5060. isEmpty() {
  5061. if (this.intro.length && this.intro.trim()) return false;
  5062. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  5063. return true;
  5064. }
  5065. length() {
  5066. return this.sources.reduce(
  5067. (length, source) => length + source.content.length(),
  5068. this.intro.length,
  5069. );
  5070. }
  5071. trimLines() {
  5072. return this.trim('[\\r\\n]');
  5073. }
  5074. trim(charType) {
  5075. return this.trimStart(charType).trimEnd(charType);
  5076. }
  5077. trimStart(charType) {
  5078. const rx = new RegExp('^' + (charType || '\\s') + '+');
  5079. this.intro = this.intro.replace(rx, '');
  5080. if (!this.intro) {
  5081. let source;
  5082. let i = 0;
  5083. do {
  5084. source = this.sources[i++];
  5085. if (!source) {
  5086. break;
  5087. }
  5088. } while (!source.content.trimStartAborted(charType));
  5089. }
  5090. return this;
  5091. }
  5092. trimEnd(charType) {
  5093. const rx = new RegExp((charType || '\\s') + '+$');
  5094. let source;
  5095. let i = this.sources.length - 1;
  5096. do {
  5097. source = this.sources[i--];
  5098. if (!source) {
  5099. this.intro = this.intro.replace(rx, '');
  5100. break;
  5101. }
  5102. } while (!source.content.trimEndAborted(charType));
  5103. return this;
  5104. }
  5105. };
  5106. function treeshakeNode(node, code, start, end) {
  5107. code.remove(start, end);
  5108. node.removeAnnotations(code);
  5109. }
  5110. const NO_SEMICOLON = { isNoStatement: true };
  5111. // This assumes there are only white-space and comments between start and the string we are looking for
  5112. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  5113. let searchPos, charCodeAfterSlash;
  5114. searchPos = code.indexOf(searchString, start);
  5115. while (true) {
  5116. start = code.indexOf('/', start);
  5117. if (start === -1 || start >= searchPos)
  5118. return searchPos;
  5119. charCodeAfterSlash = code.charCodeAt(++start);
  5120. ++start;
  5121. // With our assumption, '/' always starts a comment. Determine comment type:
  5122. start =
  5123. charCodeAfterSlash === 47 /*"/"*/
  5124. ? code.indexOf('\n', start) + 1
  5125. : code.indexOf('*/', start) + 2;
  5126. if (start > searchPos) {
  5127. searchPos = code.indexOf(searchString, start);
  5128. }
  5129. }
  5130. }
  5131. const NON_WHITESPACE = /\S/g;
  5132. function findNonWhiteSpace(code, index) {
  5133. NON_WHITESPACE.lastIndex = index;
  5134. const result = NON_WHITESPACE.exec(code);
  5135. return result.index;
  5136. }
  5137. const WHITESPACE = /\s/;
  5138. function findLastWhiteSpaceReverse(code, start, end) {
  5139. while (true) {
  5140. if (start >= end) {
  5141. return end;
  5142. }
  5143. if (WHITESPACE.test(code[end - 1])) {
  5144. end--;
  5145. }
  5146. else {
  5147. return end;
  5148. }
  5149. }
  5150. }
  5151. // This assumes "code" only contains white-space and comments
  5152. // Returns position of line-comment if applicable
  5153. function findFirstLineBreakOutsideComment(code) {
  5154. let lineBreakPos, charCodeAfterSlash, start = 0;
  5155. lineBreakPos = code.indexOf('\n', start);
  5156. while (true) {
  5157. start = code.indexOf('/', start);
  5158. if (start === -1 || start > lineBreakPos)
  5159. return [lineBreakPos, lineBreakPos + 1];
  5160. // With our assumption, '/' always starts a comment. Determine comment type:
  5161. charCodeAfterSlash = code.charCodeAt(start + 1);
  5162. if (charCodeAfterSlash === 47 /*"/"*/)
  5163. return [start, lineBreakPos + 1];
  5164. start = code.indexOf('*/', start + 2) + 2;
  5165. if (start > lineBreakPos) {
  5166. lineBreakPos = code.indexOf('\n', start);
  5167. }
  5168. }
  5169. }
  5170. function renderStatementList(statements, code, start, end, options) {
  5171. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  5172. let nextNode = statements[0];
  5173. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  5174. if (nextNodeNeedsBoundaries) {
  5175. nextNodeStart =
  5176. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  5177. }
  5178. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  5179. currentNode = nextNode;
  5180. currentNodeStart = nextNodeStart;
  5181. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  5182. nextNode = statements[nextIndex];
  5183. nextNodeNeedsBoundaries =
  5184. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  5185. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  5186. nextNodeStart =
  5187. currentNode.end +
  5188. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  5189. if (currentNode.included) {
  5190. if (currentNodeNeedsBoundaries) {
  5191. currentNode.render(code, options, {
  5192. end: nextNodeStart,
  5193. start: currentNodeStart
  5194. });
  5195. }
  5196. else {
  5197. currentNode.render(code, options);
  5198. }
  5199. }
  5200. else {
  5201. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  5202. }
  5203. }
  5204. else {
  5205. currentNode.render(code, options);
  5206. }
  5207. }
  5208. }
  5209. // This assumes that the first character is not part of the first node
  5210. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  5211. const splitUpNodes = [];
  5212. let node, nextNodeStart, contentEnd, char;
  5213. let separator = start - 1;
  5214. for (const nextNode of nodes) {
  5215. if (node !== undefined) {
  5216. separator =
  5217. node.end +
  5218. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  5219. }
  5220. nextNodeStart = contentEnd =
  5221. separator +
  5222. 1 +
  5223. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  5224. while (((char = code.original.charCodeAt(nextNodeStart)),
  5225. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  5226. nextNodeStart++;
  5227. if (node !== undefined) {
  5228. splitUpNodes.push({
  5229. contentEnd,
  5230. end: nextNodeStart,
  5231. node,
  5232. separator,
  5233. start
  5234. });
  5235. }
  5236. node = nextNode;
  5237. start = nextNodeStart;
  5238. }
  5239. splitUpNodes.push({
  5240. contentEnd: end,
  5241. end,
  5242. node: node,
  5243. separator: null,
  5244. start
  5245. });
  5246. return splitUpNodes;
  5247. }
  5248. // This assumes there are only white-space and comments between start and end
  5249. function removeLineBreaks(code, start, end) {
  5250. while (true) {
  5251. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  5252. if (removeStart === -1) {
  5253. break;
  5254. }
  5255. code.remove(start + removeStart, (start += removeEnd));
  5256. }
  5257. }
  5258. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  5259. if (exportedVariables.length === 1 &&
  5260. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  5261. const variable = exportedVariables[0];
  5262. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  5263. }
  5264. else {
  5265. const fields = [];
  5266. for (const variable of exportedVariables) {
  5267. for (const exportName of exportNamesByVariable.get(variable)) {
  5268. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  5269. }
  5270. }
  5271. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  5272. }
  5273. }
  5274. // This is only invoked if there is exactly one export name
  5275. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  5276. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  5277. code.appendLeft(expressionEnd, ')');
  5278. }
  5279. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  5280. const { _, getDirectReturnIifeLeft } = options.snippets;
  5281. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  5282. code.appendLeft(expressionEnd, ')');
  5283. }
  5284. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  5285. const { _, getPropertyAccess } = options.snippets;
  5286. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  5287. if (needsParens) {
  5288. code.prependRight(expressionStart, '(');
  5289. code.appendLeft(expressionEnd, ')');
  5290. }
  5291. }
  5292. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  5293. const { _ } = options.snippets;
  5294. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  5295. if (needsParens) {
  5296. code.prependRight(expressionStart, '(');
  5297. code.appendLeft(expressionEnd, ')');
  5298. }
  5299. }
  5300. const UnknownKey = Symbol('Unknown Key');
  5301. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  5302. const UnknownInteger = Symbol('Unknown Integer');
  5303. const UnknownWellKnown = Symbol('Unknown Well-Known');
  5304. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  5305. const SymbolDispose = Symbol('Symbol.asyncDispose');
  5306. const SymbolAsyncDispose = Symbol('Symbol.dispose');
  5307. const SymbolHasInstance = Symbol('Symbol.hasInstance');
  5308. const WELL_KNOWN_SYMBOLS_LIST = [
  5309. SymbolToStringTag,
  5310. SymbolDispose,
  5311. SymbolAsyncDispose,
  5312. SymbolHasInstance
  5313. ];
  5314. const WELL_KNOWN_SYMBOLS = new Set(WELL_KNOWN_SYMBOLS_LIST);
  5315. const isAnyWellKnown = (v) => WELL_KNOWN_SYMBOLS.has(v) || v === UnknownWellKnown;
  5316. const TREE_SHAKEABLE_SYMBOLS_LIST = [SymbolHasInstance, SymbolDispose, SymbolAsyncDispose];
  5317. const TREE_SHAKEABLE_SYMBOLS = new Set(TREE_SHAKEABLE_SYMBOLS_LIST);
  5318. const isConcreteKey = (v) => typeof v === 'string' || WELL_KNOWN_SYMBOLS.has(v);
  5319. const EMPTY_PATH = [];
  5320. const UNKNOWN_PATH = [UnknownKey];
  5321. // For deoptimizations, this means we are modifying an unknown property but did
  5322. // not lose track of the object or are creating a setter/getter;
  5323. // For assignment effects it means we do not check for setter/getter effects
  5324. // but only if something is mutated that is included, which is relevant for
  5325. // Object.defineProperty
  5326. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  5327. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  5328. const INSTANCEOF_PATH = [SymbolHasInstance];
  5329. const EntitiesKey = Symbol('Entities');
  5330. class EntityPathTracker {
  5331. constructor() {
  5332. this.entityPaths = Object.create(null, {
  5333. [EntitiesKey]: { value: new Set() }
  5334. });
  5335. }
  5336. trackEntityAtPathAndGetIfTracked(path, entity) {
  5337. const trackedEntities = this.getEntities(path);
  5338. if (trackedEntities.has(entity))
  5339. return true;
  5340. trackedEntities.add(entity);
  5341. return false;
  5342. }
  5343. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  5344. const trackedEntities = this.getEntities(path);
  5345. if (trackedEntities.has(entity))
  5346. return returnIfTracked;
  5347. trackedEntities.add(entity);
  5348. const result = onUntracked();
  5349. trackedEntities.delete(entity);
  5350. return result;
  5351. }
  5352. getEntities(path) {
  5353. let currentPaths = this.entityPaths;
  5354. for (const pathSegment of path) {
  5355. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5356. [EntitiesKey]: { value: new Set() }
  5357. });
  5358. }
  5359. return currentPaths[EntitiesKey];
  5360. }
  5361. }
  5362. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  5363. class DiscriminatedPathTracker {
  5364. constructor() {
  5365. this.entityPaths = Object.create(null, {
  5366. [EntitiesKey]: { value: new Map() }
  5367. });
  5368. }
  5369. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  5370. let currentPaths = this.entityPaths;
  5371. for (const pathSegment of path) {
  5372. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5373. [EntitiesKey]: { value: new Map() }
  5374. });
  5375. }
  5376. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  5377. if (trackedEntities.has(entity))
  5378. return true;
  5379. trackedEntities.add(entity);
  5380. return false;
  5381. }
  5382. }
  5383. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: parseAst_js.EMPTY_OBJECT });
  5384. class IncludedFullPathTracker {
  5385. constructor() {
  5386. this.includedPaths = null;
  5387. }
  5388. includePathAndGetIfIncluded(path) {
  5389. let included = true;
  5390. let parent = this;
  5391. let parentSegment = 'includedPaths';
  5392. let currentPaths = (this.includedPaths ||=
  5393. ((included = false), Object.create(null)));
  5394. for (const pathSegment of path) {
  5395. // This means from here, all paths are included
  5396. if (currentPaths[UnknownKey]) {
  5397. return true;
  5398. }
  5399. // Including UnknownKey automatically includes all nested paths.
  5400. // From above, we know that UnknownKey is not included yet.
  5401. if (!isConcreteKey(pathSegment)) {
  5402. // Hopefully, this saves some memory over just setting
  5403. // currentPaths[UnknownKey] = EMPTY_OBJECT
  5404. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  5405. return false;
  5406. }
  5407. parent = currentPaths;
  5408. parentSegment = pathSegment;
  5409. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  5410. }
  5411. return included;
  5412. }
  5413. }
  5414. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  5415. [UnknownKey]: true
  5416. });
  5417. class IncludedTopLevelPathTracker {
  5418. constructor() {
  5419. this.includedPaths = null;
  5420. }
  5421. includePathAndGetIfIncluded(path) {
  5422. let included = true;
  5423. const includedPaths = (this.includedPaths ||=
  5424. ((included = false), Object.create(null)));
  5425. if (includedPaths[UnknownKey]) {
  5426. return true;
  5427. }
  5428. const [firstPathSegment, secondPathSegment] = path;
  5429. if (!firstPathSegment) {
  5430. return included;
  5431. }
  5432. if (!isConcreteKey(firstPathSegment)) {
  5433. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  5434. return false;
  5435. }
  5436. if (secondPathSegment) {
  5437. if (includedPaths[firstPathSegment] === UnknownKey) {
  5438. return true;
  5439. }
  5440. includedPaths[firstPathSegment] = UnknownKey;
  5441. return false;
  5442. }
  5443. if (includedPaths[firstPathSegment]) {
  5444. return true;
  5445. }
  5446. includedPaths[firstPathSegment] = true;
  5447. return false;
  5448. }
  5449. includeAllPaths(entity, context, basePath) {
  5450. const { includedPaths } = this;
  5451. if (includedPaths) {
  5452. if (includedPaths[UnknownKey]) {
  5453. entity.includePath([...basePath, UnknownKey], context);
  5454. }
  5455. else {
  5456. const inclusionEntries = Object.entries(includedPaths);
  5457. if (inclusionEntries.length === 0) {
  5458. entity.includePath(basePath, context);
  5459. }
  5460. else {
  5461. for (const [key, value] of inclusionEntries) {
  5462. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  5463. }
  5464. }
  5465. }
  5466. }
  5467. }
  5468. }
  5469. /** @import { Node } from 'estree' */
  5470. /**
  5471. * @param {Node} node
  5472. * @param {Node} parent
  5473. * @returns {boolean}
  5474. */
  5475. function is_reference(node, parent) {
  5476. if (node.type === 'MemberExpression') {
  5477. return !node.computed && is_reference(node.object, node);
  5478. }
  5479. if (node.type !== 'Identifier') return false;
  5480. switch (parent?.type) {
  5481. // disregard `bar` in `foo.bar`
  5482. case 'MemberExpression':
  5483. return parent.computed || node === parent.object;
  5484. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5485. case 'MethodDefinition':
  5486. return parent.computed;
  5487. // disregard the `meta` in `import.meta`
  5488. case 'MetaProperty':
  5489. return parent.meta === node;
  5490. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5491. case 'PropertyDefinition':
  5492. return parent.computed || node === parent.value;
  5493. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5494. case 'Property':
  5495. return parent.computed || node === parent.value;
  5496. // disregard the `bar` in `export { foo as bar }` or
  5497. // the foo in `import { foo as bar }`
  5498. case 'ExportSpecifier':
  5499. case 'ImportSpecifier':
  5500. return node === parent.local;
  5501. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5502. case 'LabeledStatement':
  5503. case 'BreakStatement':
  5504. case 'ContinueStatement':
  5505. return false;
  5506. default:
  5507. return true;
  5508. }
  5509. }
  5510. function createInclusionContext() {
  5511. return {
  5512. brokenFlow: false,
  5513. hasBreak: false,
  5514. hasContinue: false,
  5515. includedCallArguments: new Set(),
  5516. includedLabels: new Set()
  5517. };
  5518. }
  5519. function createHasEffectsContext() {
  5520. return {
  5521. accessed: new EntityPathTracker(),
  5522. assigned: new EntityPathTracker(),
  5523. brokenFlow: false,
  5524. called: new DiscriminatedPathTracker(),
  5525. hasBreak: false,
  5526. hasContinue: false,
  5527. ignore: {
  5528. breaks: false,
  5529. continues: false,
  5530. labels: new Set(),
  5531. returnYield: false,
  5532. this: false
  5533. },
  5534. includedLabels: new Set(),
  5535. instantiated: new DiscriminatedPathTracker(),
  5536. replacedVariableInits: new Map()
  5537. };
  5538. }
  5539. function isFlagSet(flags, flag) {
  5540. return (flags & flag) !== 0;
  5541. }
  5542. function setFlag(flags, flag, value) {
  5543. return (flags & ~flag) | (-value & flag);
  5544. }
  5545. const UnknownValue = Symbol('Unknown Value');
  5546. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  5547. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  5548. class ExpressionEntity {
  5549. constructor() {
  5550. this.flags = 0;
  5551. }
  5552. get included() {
  5553. return isFlagSet(this.flags, 1 /* Flag.included */);
  5554. }
  5555. set included(value) {
  5556. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  5557. }
  5558. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  5559. deoptimizeInteraction(interaction);
  5560. }
  5561. deoptimizePath(_path) { }
  5562. /**
  5563. * If possible it returns a stringifyable literal value for this node that
  5564. * can be used for inlining or comparing values. Otherwise, it should return
  5565. * UnknownValue.
  5566. */
  5567. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  5568. return UnknownValue;
  5569. }
  5570. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  5571. return UNKNOWN_RETURN_EXPRESSION;
  5572. }
  5573. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  5574. return true;
  5575. }
  5576. include(context, _includeChildrenRecursively, _options) {
  5577. if (!this.included)
  5578. this.includeNode(context);
  5579. }
  5580. includeNode(_context) {
  5581. this.included = true;
  5582. }
  5583. includePath(_path, context) {
  5584. if (!this.included)
  5585. this.includeNode(context);
  5586. }
  5587. /* We are both including and including an unknown path here as the former
  5588. * ensures that nested nodes are included while the latter ensures that all
  5589. * paths of the expression are included.
  5590. * */
  5591. includeCallArguments(interaction, context) {
  5592. includeInteraction(interaction, context);
  5593. }
  5594. shouldBeIncluded(_context) {
  5595. return true;
  5596. }
  5597. }
  5598. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  5599. })();
  5600. const UNKNOWN_RETURN_EXPRESSION = [
  5601. UNKNOWN_EXPRESSION,
  5602. false
  5603. ];
  5604. const deoptimizeInteraction = (interaction) => {
  5605. for (const argument of interaction.args) {
  5606. argument?.deoptimizePath(UNKNOWN_PATH);
  5607. }
  5608. };
  5609. const includeInteraction = (interaction, context) => {
  5610. // We do not re-include the "this" argument as we expect this is already
  5611. // re-included at the call site
  5612. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  5613. includeInteractionWithoutThis(interaction, context);
  5614. };
  5615. const includeInteractionWithoutThis = ({ args }, context) => {
  5616. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5617. const argument = args[argumentIndex];
  5618. if (argument) {
  5619. argument.includePath(UNKNOWN_PATH, context);
  5620. argument.include(context, false);
  5621. }
  5622. }
  5623. };
  5624. const INTERACTION_ACCESSED = 0;
  5625. const INTERACTION_ASSIGNED = 1;
  5626. const INTERACTION_CALLED = 2;
  5627. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  5628. args: [null],
  5629. type: INTERACTION_ACCESSED
  5630. };
  5631. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  5632. args: [null, UNKNOWN_EXPRESSION],
  5633. type: INTERACTION_ASSIGNED
  5634. };
  5635. // While this is technically a call without arguments, we can compare against
  5636. // this reference in places where precise values or this argument would make a
  5637. // difference
  5638. const NODE_INTERACTION_UNKNOWN_CALL = {
  5639. args: [null],
  5640. type: INTERACTION_CALLED,
  5641. withNew: false
  5642. };
  5643. const PureFunctionKey = Symbol('PureFunction');
  5644. const getPureFunctions = ({ treeshake }) => {
  5645. const pureFunctions = Object.create(null);
  5646. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  5647. let currentFunctions = pureFunctions;
  5648. for (const pathSegment of functionName.split('.')) {
  5649. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  5650. }
  5651. currentFunctions[PureFunctionKey] = true;
  5652. }
  5653. return pureFunctions;
  5654. };
  5655. class Variable extends ExpressionEntity {
  5656. markReassigned() {
  5657. this.isReassigned = true;
  5658. }
  5659. constructor(name) {
  5660. super();
  5661. this.name = name;
  5662. this.alwaysRendered = false;
  5663. this.forbiddenNames = null;
  5664. this.globalName = null;
  5665. this.initReached = false;
  5666. this.isId = false;
  5667. this.kind = null;
  5668. this.renderBaseName = null;
  5669. this.renderName = null;
  5670. this.isReassigned = false;
  5671. this.onlyFunctionCallUsed = true;
  5672. }
  5673. /**
  5674. * Binds identifiers that reference this variable to this variable.
  5675. * Necessary to be able to change variable names.
  5676. */
  5677. addReference(_identifier) { }
  5678. /**
  5679. * Check if the identifier variable is only used as function call
  5680. * @returns true if the variable is only used as function call
  5681. */
  5682. getOnlyFunctionCallUsed() {
  5683. return this.onlyFunctionCallUsed;
  5684. }
  5685. /**
  5686. * Collect the places where the identifier variable is used
  5687. * @param usedPlace Where the variable is used
  5688. */
  5689. addUsedPlace(usedPlace) {
  5690. const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
  5691. usedPlace.parent.callee === usedPlace;
  5692. if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
  5693. this.onlyFunctionCallUsed = false;
  5694. }
  5695. }
  5696. /**
  5697. * Prevent this variable from being renamed to this name to avoid name
  5698. * collisions
  5699. */
  5700. forbidName(name) {
  5701. (this.forbiddenNames ||= new Set()).add(name);
  5702. }
  5703. getBaseVariableName() {
  5704. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  5705. this.renderBaseName ||
  5706. this.renderName ||
  5707. this.name);
  5708. }
  5709. getName(getPropertyAccess, useOriginalName) {
  5710. if (this.globalName) {
  5711. return this.globalName;
  5712. }
  5713. if (useOriginalName?.(this)) {
  5714. return this.name;
  5715. }
  5716. if (this.renderedLikeHoisted) {
  5717. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  5718. }
  5719. const name = this.renderName || this.name;
  5720. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  5721. }
  5722. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  5723. return type !== INTERACTION_ACCESSED || path.length > 0;
  5724. }
  5725. /**
  5726. * Marks this variable as being part of the bundle, which is usually the case
  5727. * when one of its identifiers becomes part of the bundle. Returns true if it
  5728. * has not been included previously. Once a variable is included, it should
  5729. * take care all its declarations are included.
  5730. */
  5731. includePath(path, context) {
  5732. this.included = true;
  5733. this.renderedLikeHoisted?.includePath(path, context);
  5734. }
  5735. /**
  5736. * Links the rendered name of this variable to another variable and includes
  5737. * this variable if the other variable is included.
  5738. */
  5739. renderLikeHoisted(variable) {
  5740. this.renderedLikeHoisted = variable;
  5741. }
  5742. markCalledFromTryStatement() { }
  5743. setRenderNames(baseName, name) {
  5744. this.renderBaseName = baseName;
  5745. this.renderName = name;
  5746. }
  5747. }
  5748. /** Synthetic import name for source phase imports, similar to '*' for namespaces */
  5749. const SOURCE_PHASE_IMPORT = '*source';
  5750. class ExternalVariable extends Variable {
  5751. constructor(module, name) {
  5752. super(name);
  5753. this.referenced = false;
  5754. this.module = module;
  5755. this.isNamespace = name === '*';
  5756. this.isSourcePhase = name === SOURCE_PHASE_IMPORT;
  5757. }
  5758. addReference(identifier) {
  5759. this.referenced = true;
  5760. if (this.name === 'default' || this.name === '*') {
  5761. this.module.suggestName(identifier.name);
  5762. }
  5763. }
  5764. hasEffectsOnInteractionAtPath(path, { type }) {
  5765. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  5766. }
  5767. includePath(path, context) {
  5768. super.includePath(path, context);
  5769. this.module.used = true;
  5770. }
  5771. }
  5772. function cacheObjectGetters(object, getterProperties) {
  5773. for (const property of getterProperties) {
  5774. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  5775. Object.defineProperty(object, property, {
  5776. get() {
  5777. const value = propertyGetter.call(object);
  5778. // This replaces the getter with a fixed value for subsequent calls
  5779. Object.defineProperty(object, property, { value });
  5780. return value;
  5781. }
  5782. });
  5783. }
  5784. }
  5785. const RESERVED_NAMES = new Set([
  5786. 'await',
  5787. 'break',
  5788. 'case',
  5789. 'catch',
  5790. 'class',
  5791. 'const',
  5792. 'continue',
  5793. 'debugger',
  5794. 'default',
  5795. 'delete',
  5796. 'do',
  5797. 'else',
  5798. 'enum',
  5799. 'eval',
  5800. 'export',
  5801. 'exports',
  5802. 'extends',
  5803. 'false',
  5804. 'finally',
  5805. 'for',
  5806. 'function',
  5807. 'if',
  5808. 'implements',
  5809. 'import',
  5810. 'in',
  5811. 'instanceof',
  5812. 'interface',
  5813. 'let',
  5814. 'NaN',
  5815. 'new',
  5816. 'null',
  5817. 'package',
  5818. 'private',
  5819. 'protected',
  5820. 'public',
  5821. 'return',
  5822. 'static',
  5823. 'super',
  5824. 'switch',
  5825. 'this',
  5826. 'throw',
  5827. 'true',
  5828. 'try',
  5829. 'typeof',
  5830. 'undefined',
  5831. 'var',
  5832. 'void',
  5833. 'while',
  5834. 'with',
  5835. 'yield'
  5836. ]);
  5837. const illegalCharacters = /[^\w$]/g;
  5838. const startsWithDigit = (value) => /\d/.test(value[0]);
  5839. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  5840. function isLegal(value) {
  5841. if (needsEscape(value)) {
  5842. return false;
  5843. }
  5844. return !illegalCharacters.test(value);
  5845. }
  5846. function makeLegal(value) {
  5847. value = value
  5848. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  5849. .replace(illegalCharacters, '_');
  5850. if (needsEscape(value))
  5851. value = `_${value}`;
  5852. return value || '_';
  5853. }
  5854. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  5855. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  5856. function stringifyObjectKeyIfNeeded(key) {
  5857. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5858. return key === '__proto__' ? '["__proto__"]' : key;
  5859. }
  5860. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  5861. return key;
  5862. }
  5863. return JSON.stringify(key);
  5864. }
  5865. function stringifyIdentifierIfNeeded(key) {
  5866. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5867. return key;
  5868. }
  5869. return JSON.stringify(key);
  5870. }
  5871. class ExternalModule {
  5872. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  5873. this.options = options;
  5874. this.id = id;
  5875. this.renormalizeRenderPath = renormalizeRenderPath;
  5876. this.dynamicImporters = [];
  5877. this.execIndex = Infinity;
  5878. this.exportedVariables = new Map();
  5879. this.importers = [];
  5880. this.reexported = false;
  5881. this.used = false;
  5882. this.declarations = new Map();
  5883. this.importersByExportedName = new Map();
  5884. this.mostCommonSuggestion = 0;
  5885. this.nameSuggestions = new Map();
  5886. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  5887. const { importers, dynamicImporters } = this;
  5888. this.info = {
  5889. ast: null,
  5890. attributes,
  5891. code: null,
  5892. dynamicallyImportedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5893. dynamicallyImportedIds: parseAst_js.EMPTY_ARRAY,
  5894. get dynamicImporters() {
  5895. return dynamicImporters.sort();
  5896. },
  5897. exportedBindings: null,
  5898. exports: null,
  5899. hasDefaultExport: null,
  5900. id,
  5901. implicitlyLoadedAfterOneOf: parseAst_js.EMPTY_ARRAY,
  5902. implicitlyLoadedBefore: parseAst_js.EMPTY_ARRAY,
  5903. importedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5904. importedIds: parseAst_js.EMPTY_ARRAY,
  5905. get importers() {
  5906. return importers.sort();
  5907. },
  5908. isEntry: false,
  5909. isExternal: true,
  5910. isIncluded: null,
  5911. meta,
  5912. moduleSideEffects,
  5913. safeVariableNames: null,
  5914. syntheticNamedExports: false
  5915. };
  5916. }
  5917. cacheInfoGetters() {
  5918. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  5919. }
  5920. getVariableForExportName(name, { importChain }) {
  5921. const declaration = this.declarations.get(name);
  5922. for (const module of importChain) {
  5923. getOrCreate(this.importersByExportedName, name, getNewSet).add(module);
  5924. }
  5925. if (declaration)
  5926. return [declaration];
  5927. const externalVariable = new ExternalVariable(this, name);
  5928. this.declarations.set(name, externalVariable);
  5929. this.exportedVariables.set(externalVariable, name);
  5930. return [externalVariable];
  5931. }
  5932. suggestName(name) {
  5933. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  5934. this.nameSuggestions.set(name, value);
  5935. if (value > this.mostCommonSuggestion) {
  5936. this.mostCommonSuggestion = value;
  5937. this.suggestedVariableName = name;
  5938. }
  5939. }
  5940. warnUnusedImports() {
  5941. const unused = [...this.declarations]
  5942. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  5943. .map(([name]) => name);
  5944. if (unused.length === 0)
  5945. return;
  5946. const importersSet = new Set();
  5947. for (const name of unused) {
  5948. const importersOfName = this.importersByExportedName.get(name);
  5949. for (const importer of this.importers) {
  5950. if (!importersOfName?.has(importer))
  5951. continue;
  5952. importersSet.add(importer);
  5953. }
  5954. }
  5955. const importersArray = [...importersSet];
  5956. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnusedExternalImports(this.id, unused, importersArray));
  5957. }
  5958. }
  5959. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  5960. baseModule.isExecuted = true;
  5961. const modules = [baseModule];
  5962. const visitedModules = new Set();
  5963. for (const module of modules) {
  5964. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  5965. if (!(dependency instanceof ExternalModule) &&
  5966. !dependency.isExecuted &&
  5967. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  5968. !visitedModules.has(dependency.id)) {
  5969. dependency.isExecuted = true;
  5970. visitedModules.add(dependency.id);
  5971. modules.push(dependency);
  5972. }
  5973. }
  5974. }
  5975. }
  5976. // This file is generated by scripts/generate-child-node-keys.js.
  5977. // Do not edit this file directly.
  5978. const childNodeKeys = {
  5979. ArrayExpression: ['elements'],
  5980. ArrayPattern: ['elements'],
  5981. ArrowFunctionExpression: ['params', 'body'],
  5982. AssignmentExpression: ['left', 'right'],
  5983. AssignmentPattern: ['left', 'right'],
  5984. AwaitExpression: ['argument'],
  5985. BinaryExpression: ['left', 'right'],
  5986. BlockStatement: ['body'],
  5987. BreakStatement: ['label'],
  5988. CallExpression: ['callee', 'arguments'],
  5989. CatchClause: ['param', 'body'],
  5990. ChainExpression: ['expression'],
  5991. ClassBody: ['body'],
  5992. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  5993. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  5994. ConditionalExpression: ['test', 'consequent', 'alternate'],
  5995. ContinueStatement: ['label'],
  5996. DebuggerStatement: [],
  5997. Decorator: ['expression'],
  5998. DoWhileStatement: ['body', 'test'],
  5999. EmptyStatement: [],
  6000. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  6001. ExportDefaultDeclaration: ['declaration'],
  6002. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  6003. ExportSpecifier: ['local', 'exported'],
  6004. ExpressionStatement: ['expression'],
  6005. ForInStatement: ['left', 'right', 'body'],
  6006. ForOfStatement: ['left', 'right', 'body'],
  6007. ForStatement: ['init', 'test', 'update', 'body'],
  6008. FunctionDeclaration: ['id', 'params', 'body'],
  6009. FunctionExpression: ['id', 'params', 'body'],
  6010. Identifier: [],
  6011. IfStatement: ['test', 'consequent', 'alternate'],
  6012. ImportAttribute: ['key', 'value'],
  6013. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  6014. ImportDefaultSpecifier: ['local'],
  6015. ImportExpression: ['source', 'options'],
  6016. ImportNamespaceSpecifier: ['local'],
  6017. ImportSpecifier: ['imported', 'local'],
  6018. JSXAttribute: ['name', 'value'],
  6019. JSXClosingElement: ['name'],
  6020. JSXClosingFragment: [],
  6021. JSXElement: ['openingElement', 'children', 'closingElement'],
  6022. JSXEmptyExpression: [],
  6023. JSXExpressionContainer: ['expression'],
  6024. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  6025. JSXIdentifier: [],
  6026. JSXMemberExpression: ['object', 'property'],
  6027. JSXNamespacedName: ['namespace', 'name'],
  6028. JSXOpeningElement: ['name', 'attributes'],
  6029. JSXOpeningFragment: [],
  6030. JSXSpreadAttribute: ['argument'],
  6031. JSXSpreadChild: ['expression'],
  6032. JSXText: [],
  6033. LabeledStatement: ['label', 'body'],
  6034. Literal: [],
  6035. LogicalExpression: ['left', 'right'],
  6036. MemberExpression: ['object', 'property'],
  6037. MetaProperty: ['meta', 'property'],
  6038. MethodDefinition: ['decorators', 'key', 'value'],
  6039. NewExpression: ['callee', 'arguments'],
  6040. ObjectExpression: ['properties'],
  6041. ObjectPattern: ['properties'],
  6042. PanicError: [],
  6043. ParseError: [],
  6044. PrivateIdentifier: [],
  6045. Program: ['body'],
  6046. Property: ['key', 'value'],
  6047. PropertyDefinition: ['decorators', 'key', 'value'],
  6048. RestElement: ['argument'],
  6049. ReturnStatement: ['argument'],
  6050. SequenceExpression: ['expressions'],
  6051. SpreadElement: ['argument'],
  6052. StaticBlock: ['body'],
  6053. Super: [],
  6054. SwitchCase: ['test', 'consequent'],
  6055. SwitchStatement: ['discriminant', 'cases'],
  6056. TaggedTemplateExpression: ['tag', 'quasi'],
  6057. TemplateElement: [],
  6058. TemplateLiteral: ['quasis', 'expressions'],
  6059. ThisExpression: [],
  6060. ThrowStatement: ['argument'],
  6061. TryStatement: ['block', 'handler', 'finalizer'],
  6062. UnaryExpression: ['argument'],
  6063. UpdateExpression: ['argument'],
  6064. VariableDeclaration: ['declarations'],
  6065. VariableDeclarator: ['id', 'init'],
  6066. WhileStatement: ['test', 'body'],
  6067. YieldExpression: ['argument']
  6068. };
  6069. const INCLUDE_PARAMETERS = 'variables';
  6070. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  6071. class NodeBase extends ExpressionEntity {
  6072. /**
  6073. * Nodes can apply custom deoptimizations once they become part of the
  6074. * executed code. To do this, they must initialize this as false, implement
  6075. * applyDeoptimizations and call this from include and hasEffects if they have
  6076. * custom handlers
  6077. */
  6078. get deoptimized() {
  6079. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  6080. }
  6081. set deoptimized(value) {
  6082. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  6083. }
  6084. constructor(parent, parentScope) {
  6085. super();
  6086. this.parent = parent;
  6087. this.scope = parentScope;
  6088. this.createScope(parentScope);
  6089. }
  6090. addExportedVariables(_variables, _exportNamesByVariable) { }
  6091. /**
  6092. * Override this to bind assignments to variables and do any initialisations
  6093. * that require the scopes to be populated with variables.
  6094. */
  6095. bind() {
  6096. for (const key of childNodeKeys[this.type]) {
  6097. const value = this[key];
  6098. if (Array.isArray(value)) {
  6099. for (const child of value) {
  6100. child?.bind();
  6101. }
  6102. }
  6103. else if (value) {
  6104. value.bind();
  6105. }
  6106. }
  6107. }
  6108. /**
  6109. * Override if this node should receive a different scope than the parent
  6110. * scope.
  6111. */
  6112. createScope(parentScope) {
  6113. this.scope = parentScope;
  6114. }
  6115. hasEffects(context) {
  6116. if (!this.deoptimized)
  6117. this.applyDeoptimizations();
  6118. for (const key of childNodeKeys[this.type]) {
  6119. const value = this[key];
  6120. if (value === null)
  6121. continue;
  6122. if (Array.isArray(value)) {
  6123. for (const child of value) {
  6124. if (child?.hasEffects(context))
  6125. return true;
  6126. }
  6127. }
  6128. else if (value.hasEffects(context))
  6129. return true;
  6130. }
  6131. return false;
  6132. }
  6133. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  6134. return (this.hasEffects(context) ||
  6135. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  6136. }
  6137. include(context, includeChildrenRecursively, _options) {
  6138. if (!this.included)
  6139. this.includeNode(context);
  6140. for (const key of childNodeKeys[this.type]) {
  6141. const value = this[key];
  6142. if (value === null)
  6143. continue;
  6144. if (Array.isArray(value)) {
  6145. for (const child of value) {
  6146. child?.include(context, includeChildrenRecursively);
  6147. }
  6148. }
  6149. else {
  6150. value.include(context, includeChildrenRecursively);
  6151. }
  6152. }
  6153. }
  6154. includeNode(context) {
  6155. this.included = true;
  6156. if (!this.deoptimized)
  6157. this.applyDeoptimizations();
  6158. for (const key of childNodeKeys[this.type]) {
  6159. const value = this[key];
  6160. if (value === null)
  6161. continue;
  6162. if (Array.isArray(value)) {
  6163. for (const child of value) {
  6164. child?.includePath(UNKNOWN_PATH, context);
  6165. }
  6166. }
  6167. else {
  6168. value.includePath(UNKNOWN_PATH, context);
  6169. }
  6170. }
  6171. }
  6172. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  6173. this.include(context, includeChildrenRecursively);
  6174. }
  6175. /**
  6176. * Override to perform special initialisation steps after the scope is
  6177. * initialised
  6178. */
  6179. initialise() {
  6180. this.scope.context.magicString.addSourcemapLocation(this.start);
  6181. this.scope.context.magicString.addSourcemapLocation(this.end);
  6182. }
  6183. parseNode(esTreeNode) {
  6184. for (const [key, value] of Object.entries(esTreeNode)) {
  6185. // Skip properties defined on the class already.
  6186. // This way, we can override this function to add custom initialisation and then call super.parseNode
  6187. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  6188. // in bitfields. Those are still assigned from the value in the esTreeNode.
  6189. if (this.hasOwnProperty(key))
  6190. continue;
  6191. if (key.charCodeAt(0) === 95 /* _ */) {
  6192. if (key === parseAst_js.ANNOTATION_KEY) {
  6193. this.annotations = value;
  6194. }
  6195. else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
  6196. this.invalidAnnotations = value;
  6197. }
  6198. }
  6199. else if (typeof value !== 'object' || value === null) {
  6200. this[key] = value;
  6201. }
  6202. else if (Array.isArray(value)) {
  6203. this[key] = new Array(value.length);
  6204. let index = 0;
  6205. for (const child of value) {
  6206. this[key][index++] =
  6207. child === null
  6208. ? null
  6209. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  6210. }
  6211. }
  6212. else {
  6213. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  6214. }
  6215. }
  6216. // extend child keys for unknown node types
  6217. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  6218. this.initialise();
  6219. return this;
  6220. }
  6221. removeAnnotations(code) {
  6222. if (this.annotations) {
  6223. for (const annotation of this.annotations) {
  6224. code.remove(annotation.start, annotation.end);
  6225. }
  6226. }
  6227. }
  6228. render(code, options) {
  6229. for (const key of childNodeKeys[this.type]) {
  6230. const value = this[key];
  6231. if (value === null)
  6232. continue;
  6233. if (Array.isArray(value)) {
  6234. for (const child of value) {
  6235. child?.render(code, options);
  6236. }
  6237. }
  6238. else {
  6239. value.render(code, options);
  6240. }
  6241. }
  6242. }
  6243. setAssignedValue(value) {
  6244. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  6245. }
  6246. shouldBeIncluded(context) {
  6247. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  6248. }
  6249. /**
  6250. * Just deoptimize everything by default so that when e.g. we do not track
  6251. * something properly, it is deoptimized.
  6252. * @protected
  6253. */
  6254. applyDeoptimizations() {
  6255. this.deoptimized = true;
  6256. for (const key of childNodeKeys[this.type]) {
  6257. const value = this[key];
  6258. if (value === null)
  6259. continue;
  6260. if (Array.isArray(value)) {
  6261. for (const child of value) {
  6262. child?.deoptimizePath(UNKNOWN_PATH);
  6263. }
  6264. }
  6265. else {
  6266. value.deoptimizePath(UNKNOWN_PATH);
  6267. }
  6268. }
  6269. this.scope.context.requestTreeshakingPass();
  6270. }
  6271. }
  6272. function createChildNodeKeysForNode(esTreeNode) {
  6273. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  6274. }
  6275. function onlyIncludeSelf() {
  6276. this.included = true;
  6277. if (!this.deoptimized)
  6278. this.applyDeoptimizations();
  6279. }
  6280. function onlyIncludeSelfNoDeoptimize() {
  6281. this.included = true;
  6282. }
  6283. function doNotDeoptimize() {
  6284. this.deoptimized = true;
  6285. }
  6286. function isObjectExpressionNode(node) {
  6287. return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
  6288. }
  6289. function isPropertyNode(node) {
  6290. return node instanceof NodeBase && node.type === parseAst_js.Property;
  6291. }
  6292. function isArrowFunctionExpressionNode(node) {
  6293. return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
  6294. }
  6295. function isFunctionExpressionNode(node) {
  6296. return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
  6297. }
  6298. function isCallExpressionNode(node) {
  6299. return node instanceof NodeBase && node.type === parseAst_js.CallExpression;
  6300. }
  6301. function isMemberExpressionNode(node) {
  6302. return node instanceof NodeBase && node.type === parseAst_js.MemberExpression;
  6303. }
  6304. function isAwaitExpressionNode(node) {
  6305. return node instanceof NodeBase && node.type === parseAst_js.AwaitExpression;
  6306. }
  6307. function isIdentifierNode(node) {
  6308. return node instanceof NodeBase && node.type === parseAst_js.Identifier;
  6309. }
  6310. function isExpressionStatementNode(node) {
  6311. return node instanceof NodeBase && node.type === parseAst_js.ExpressionStatement;
  6312. }
  6313. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  6314. return Object.create(inheritedDescriptions, memberDescriptions);
  6315. }
  6316. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  6317. getLiteralValueAtPath(path) {
  6318. return path.length > 0 ? UnknownValue : undefined;
  6319. }
  6320. })();
  6321. const returnsUnknown = {
  6322. value: {
  6323. hasEffectsWhenCalled: null,
  6324. returns: UNKNOWN_EXPRESSION
  6325. }
  6326. };
  6327. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  6328. getReturnExpressionWhenCalledAtPath(path) {
  6329. if (path.length === 1) {
  6330. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  6331. }
  6332. return UNKNOWN_RETURN_EXPRESSION;
  6333. }
  6334. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6335. if (interaction.type === INTERACTION_ACCESSED) {
  6336. return path.length > 1;
  6337. }
  6338. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6339. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  6340. }
  6341. return true;
  6342. }
  6343. })();
  6344. const returnsBoolean = {
  6345. value: {
  6346. hasEffectsWhenCalled: null,
  6347. returns: UNKNOWN_LITERAL_BOOLEAN
  6348. }
  6349. };
  6350. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  6351. getReturnExpressionWhenCalledAtPath(path) {
  6352. if (path.length === 1) {
  6353. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  6354. }
  6355. return UNKNOWN_RETURN_EXPRESSION;
  6356. }
  6357. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6358. if (interaction.type === INTERACTION_ACCESSED) {
  6359. return path.length > 1;
  6360. }
  6361. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6362. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  6363. }
  6364. return true;
  6365. }
  6366. })();
  6367. const returnsNumber = {
  6368. value: {
  6369. hasEffectsWhenCalled: null,
  6370. returns: UNKNOWN_LITERAL_NUMBER
  6371. }
  6372. };
  6373. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  6374. getReturnExpressionWhenCalledAtPath(path) {
  6375. if (path.length === 1) {
  6376. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  6377. }
  6378. return UNKNOWN_RETURN_EXPRESSION;
  6379. }
  6380. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6381. if (interaction.type === INTERACTION_ACCESSED) {
  6382. return path.length > 1;
  6383. }
  6384. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6385. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  6386. }
  6387. return true;
  6388. }
  6389. })();
  6390. const returnsString = {
  6391. value: {
  6392. hasEffectsWhenCalled: null,
  6393. returns: UNKNOWN_LITERAL_STRING
  6394. }
  6395. };
  6396. const stringReplace = {
  6397. value: {
  6398. hasEffectsWhenCalled({ args }, context) {
  6399. const argument1 = args[2];
  6400. return (args.length < 3 ||
  6401. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  6402. deoptimizeCache() { }
  6403. }) === 'symbol' &&
  6404. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  6405. },
  6406. returns: UNKNOWN_LITERAL_STRING
  6407. }
  6408. };
  6409. const objectMembers = assembleMemberDescriptions({
  6410. hasOwnProperty: returnsBoolean,
  6411. isPrototypeOf: returnsBoolean,
  6412. propertyIsEnumerable: returnsBoolean,
  6413. toLocaleString: returnsString,
  6414. toString: returnsString,
  6415. valueOf: returnsUnknown
  6416. });
  6417. const literalBooleanMembers = assembleMemberDescriptions({
  6418. valueOf: returnsBoolean
  6419. }, objectMembers);
  6420. const literalNumberMembers = assembleMemberDescriptions({
  6421. toExponential: returnsString,
  6422. toFixed: returnsString,
  6423. toLocaleString: returnsString,
  6424. toPrecision: returnsString,
  6425. valueOf: returnsNumber
  6426. }, objectMembers);
  6427. /**
  6428. * RegExp are stateful when they have the global or sticky flags set.
  6429. * But if we actually don't use them, the side effect does not matter.
  6430. * the check logic in `hasEffectsOnInteractionAtPath`.
  6431. */
  6432. const literalRegExpMembers = assembleMemberDescriptions({
  6433. exec: returnsUnknown,
  6434. test: returnsBoolean
  6435. }, objectMembers);
  6436. const literalStringMembers = assembleMemberDescriptions({
  6437. anchor: returnsString,
  6438. at: returnsUnknown,
  6439. big: returnsString,
  6440. blink: returnsString,
  6441. bold: returnsString,
  6442. charAt: returnsString,
  6443. charCodeAt: returnsNumber,
  6444. codePointAt: returnsUnknown,
  6445. concat: returnsString,
  6446. endsWith: returnsBoolean,
  6447. fixed: returnsString,
  6448. fontcolor: returnsString,
  6449. fontsize: returnsString,
  6450. includes: returnsBoolean,
  6451. indexOf: returnsNumber,
  6452. italics: returnsString,
  6453. lastIndexOf: returnsNumber,
  6454. link: returnsString,
  6455. localeCompare: returnsNumber,
  6456. match: returnsUnknown,
  6457. matchAll: returnsUnknown,
  6458. normalize: returnsString,
  6459. padEnd: returnsString,
  6460. padStart: returnsString,
  6461. repeat: returnsString,
  6462. replace: stringReplace,
  6463. replaceAll: stringReplace,
  6464. search: returnsNumber,
  6465. slice: returnsString,
  6466. small: returnsString,
  6467. split: returnsUnknown,
  6468. startsWith: returnsBoolean,
  6469. strike: returnsString,
  6470. sub: returnsString,
  6471. substr: returnsString,
  6472. substring: returnsString,
  6473. sup: returnsString,
  6474. toLocaleLowerCase: returnsString,
  6475. toLocaleUpperCase: returnsString,
  6476. toLowerCase: returnsString,
  6477. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  6478. toUpperCase: returnsString,
  6479. trim: returnsString,
  6480. trimEnd: returnsString,
  6481. trimLeft: returnsString,
  6482. trimRight: returnsString,
  6483. trimStart: returnsString,
  6484. valueOf: returnsString
  6485. }, objectMembers);
  6486. function getLiteralMembersForValue(value) {
  6487. if (value instanceof RegExp) {
  6488. return literalRegExpMembers;
  6489. }
  6490. switch (typeof value) {
  6491. case 'boolean': {
  6492. return literalBooleanMembers;
  6493. }
  6494. case 'number': {
  6495. return literalNumberMembers;
  6496. }
  6497. case 'string': {
  6498. return literalStringMembers;
  6499. }
  6500. }
  6501. return Object.create(null);
  6502. }
  6503. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  6504. if (typeof memberName !== 'string' || !members[memberName]) {
  6505. return true;
  6506. }
  6507. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  6508. }
  6509. function getMemberReturnExpressionWhenCalled(members, memberName) {
  6510. if (typeof memberName !== 'string' || !members[memberName])
  6511. return UNKNOWN_RETURN_EXPRESSION;
  6512. return [members[memberName].returns, false];
  6513. }
  6514. class Method extends ExpressionEntity {
  6515. constructor(description) {
  6516. super();
  6517. this.description = description;
  6518. }
  6519. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  6520. if (type === INTERACTION_CALLED && path.length === 0) {
  6521. if (this.description.mutatesSelfAsArray) {
  6522. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6523. }
  6524. if (this.description.mutatesArgs) {
  6525. for (let index = 1; index < args.length; index++) {
  6526. args[index].deoptimizePath(UNKNOWN_PATH);
  6527. }
  6528. }
  6529. }
  6530. }
  6531. getReturnExpressionWhenCalledAtPath(path, { args }) {
  6532. if (path.length > 0) {
  6533. return UNKNOWN_RETURN_EXPRESSION;
  6534. }
  6535. return [
  6536. this.description.returnsPrimitive ||
  6537. (this.description.returns === 'self'
  6538. ? args[0] || UNKNOWN_EXPRESSION
  6539. : this.description.returns()),
  6540. false
  6541. ];
  6542. }
  6543. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  6544. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  6545. return true;
  6546. }
  6547. if (type === INTERACTION_CALLED) {
  6548. if (this.description.mutatesSelfAsArray === true &&
  6549. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  6550. return true;
  6551. }
  6552. if (this.description.callsArgs) {
  6553. for (const argumentIndex of this.description.callsArgs) {
  6554. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  6555. return true;
  6556. }
  6557. }
  6558. }
  6559. }
  6560. return false;
  6561. }
  6562. }
  6563. const METHOD_RETURNS_BOOLEAN = [
  6564. new Method({
  6565. callsArgs: null,
  6566. mutatesArgs: false,
  6567. mutatesSelfAsArray: false,
  6568. returns: null,
  6569. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6570. })
  6571. ];
  6572. const METHOD_RETURNS_STRING = [
  6573. new Method({
  6574. callsArgs: null,
  6575. mutatesArgs: false,
  6576. mutatesSelfAsArray: false,
  6577. returns: null,
  6578. returnsPrimitive: UNKNOWN_LITERAL_STRING
  6579. })
  6580. ];
  6581. const METHOD_RETURNS_NUMBER = [
  6582. new Method({
  6583. callsArgs: null,
  6584. mutatesArgs: false,
  6585. mutatesSelfAsArray: false,
  6586. returns: null,
  6587. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6588. })
  6589. ];
  6590. const METHOD_RETURNS_UNKNOWN = [
  6591. new Method({
  6592. callsArgs: null,
  6593. mutatesArgs: false,
  6594. mutatesSelfAsArray: false,
  6595. returns: null,
  6596. returnsPrimitive: UNKNOWN_EXPRESSION
  6597. })
  6598. ];
  6599. const INTEGER_REG_EXP = /^\d+$/;
  6600. class ObjectEntity extends ExpressionEntity {
  6601. get hasLostTrack() {
  6602. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  6603. }
  6604. set hasLostTrack(value) {
  6605. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  6606. }
  6607. get hasUnknownDeoptimizedInteger() {
  6608. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  6609. }
  6610. set hasUnknownDeoptimizedInteger(value) {
  6611. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  6612. }
  6613. get hasUnknownDeoptimizedProperty() {
  6614. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  6615. }
  6616. set hasUnknownDeoptimizedProperty(value) {
  6617. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  6618. }
  6619. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  6620. // and we assume there are no setters or getters
  6621. constructor(properties, prototypeExpression, immutable = false) {
  6622. super();
  6623. this.prototypeExpression = prototypeExpression;
  6624. this.immutable = immutable;
  6625. this.additionalExpressionsToBeDeoptimized = new Set();
  6626. this.allProperties = [];
  6627. this.alwaysIncludedProperties = new Set();
  6628. this.deoptimizedPaths = new Map();
  6629. this.expressionsToBeDeoptimizedByKey = new Map();
  6630. this.gettersByKey = new Map();
  6631. this.propertiesAndGettersByKey = new Map();
  6632. this.propertiesAndSettersByKey = new Map();
  6633. this.settersByKey = new Map();
  6634. this.unknownIntegerProps = [];
  6635. this.unmatchableGetters = [];
  6636. this.unmatchablePropertiesAndGetters = [];
  6637. this.unmatchablePropertiesAndSetters = [];
  6638. this.unmatchableSetters = [];
  6639. if (Array.isArray(properties)) {
  6640. this.buildPropertyMaps(properties);
  6641. }
  6642. else {
  6643. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  6644. for (const propertiesForKey of properties.values()) {
  6645. this.allProperties.push(...propertiesForKey);
  6646. }
  6647. }
  6648. }
  6649. deoptimizeAllProperties(noAccessors) {
  6650. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  6651. if (noAccessors) {
  6652. this.hasUnknownDeoptimizedProperty = true;
  6653. }
  6654. else {
  6655. this.hasLostTrack = true;
  6656. }
  6657. if (isDeoptimized) {
  6658. return;
  6659. }
  6660. for (const properties of [
  6661. ...this.propertiesAndGettersByKey.values(),
  6662. ...this.settersByKey.values()
  6663. ]) {
  6664. for (const property of properties) {
  6665. property.deoptimizePath(UNKNOWN_PATH);
  6666. }
  6667. }
  6668. // While the prototype itself cannot be mutated, each property can
  6669. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  6670. this.deoptimizeCachedEntities();
  6671. }
  6672. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6673. const [key, ...subPath] = path;
  6674. const { args, type } = interaction;
  6675. if (this.hasLostTrack ||
  6676. // single paths that are deoptimized will not become getters or setters
  6677. ((type === INTERACTION_CALLED || path.length > 1) &&
  6678. (this.hasUnknownDeoptimizedProperty ||
  6679. (isConcreteKey(key) && this.deoptimizedPaths.get(key))))) {
  6680. deoptimizeInteraction(interaction);
  6681. return;
  6682. }
  6683. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  6684. ? [
  6685. this.propertiesAndGettersByKey,
  6686. this.propertiesAndGettersByKey,
  6687. this.unmatchablePropertiesAndGetters
  6688. ]
  6689. : type === INTERACTION_ACCESSED
  6690. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6691. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6692. if (isConcreteKey(key)) {
  6693. if (propertiesForExactMatchByKey.get(key)) {
  6694. const properties = relevantPropertiesByKey.get(key);
  6695. if (properties) {
  6696. for (const property of properties) {
  6697. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6698. }
  6699. }
  6700. if (!this.immutable) {
  6701. for (const argument of args) {
  6702. if (argument) {
  6703. this.additionalExpressionsToBeDeoptimized.add(argument);
  6704. }
  6705. }
  6706. }
  6707. return;
  6708. }
  6709. for (const property of relevantUnmatchableProperties) {
  6710. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6711. }
  6712. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  6713. for (const property of this.unknownIntegerProps) {
  6714. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6715. }
  6716. }
  6717. }
  6718. else {
  6719. for (const properties of [
  6720. ...relevantPropertiesByKey.values(),
  6721. relevantUnmatchableProperties
  6722. ]) {
  6723. for (const property of properties) {
  6724. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6725. }
  6726. }
  6727. for (const property of this.unknownIntegerProps) {
  6728. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6729. }
  6730. }
  6731. if (!this.immutable) {
  6732. for (const argument of args) {
  6733. if (argument) {
  6734. this.additionalExpressionsToBeDeoptimized.add(argument);
  6735. }
  6736. }
  6737. }
  6738. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6739. }
  6740. deoptimizeIntegerProperties() {
  6741. if (this.hasLostTrack ||
  6742. this.hasUnknownDeoptimizedProperty ||
  6743. this.hasUnknownDeoptimizedInteger) {
  6744. return;
  6745. }
  6746. this.hasUnknownDeoptimizedInteger = true;
  6747. // Omits symbol keys but that's unimportant here
  6748. for (const [key, propertiesAndGetters] of this.propertiesAndGettersByKey.entries()) {
  6749. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  6750. for (const property of propertiesAndGetters) {
  6751. property.deoptimizePath(UNKNOWN_PATH);
  6752. }
  6753. }
  6754. }
  6755. this.deoptimizeCachedIntegerEntities();
  6756. }
  6757. // Assumption: If only a specific path is deoptimized, no accessors are created
  6758. deoptimizePath(path) {
  6759. if (this.hasLostTrack || this.immutable) {
  6760. return;
  6761. }
  6762. const key = path[0];
  6763. if (path.length === 1) {
  6764. if (key === UnknownInteger) {
  6765. return this.deoptimizeIntegerProperties();
  6766. }
  6767. else if (!isConcreteKey(key)) {
  6768. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  6769. }
  6770. if (!this.deoptimizedPaths.get(key)) {
  6771. this.deoptimizedPaths.set(key, true);
  6772. // we only deoptimizeCache exact matches as in all other cases,
  6773. // we do not return a literal value or return expression
  6774. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey.get(key);
  6775. if (expressionsToBeDeoptimized) {
  6776. for (const expression of expressionsToBeDeoptimized) {
  6777. expression.deoptimizeCache();
  6778. }
  6779. }
  6780. }
  6781. }
  6782. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  6783. for (const property of isConcreteKey(key)
  6784. ? [
  6785. ...(this.propertiesAndGettersByKey.get(key) || this.unmatchablePropertiesAndGetters),
  6786. ...(this.settersByKey.get(key) || this.unmatchableSetters)
  6787. ]
  6788. : this.allProperties) {
  6789. property.deoptimizePath(subPath);
  6790. }
  6791. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  6792. }
  6793. getLiteralValueAtPath(path, recursionTracker, origin) {
  6794. if (path.length === 0) {
  6795. // This should actually be "UnknownTruthyValue". However, this currently
  6796. // causes an issue with TypeScript enums in files with moduleSideEffects:
  6797. // false because we cannot properly track whether a "var" has been
  6798. // initialized. This should be reverted once we can properly track this.
  6799. // return UnknownTruthyValue;
  6800. return UnknownValue;
  6801. }
  6802. const key = path[0];
  6803. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6804. if (expressionAtPath) {
  6805. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  6806. }
  6807. if (this.prototypeExpression) {
  6808. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6809. }
  6810. if (path.length === 1) {
  6811. return undefined;
  6812. }
  6813. return UnknownValue;
  6814. }
  6815. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6816. if (path.length === 0) {
  6817. return UNKNOWN_RETURN_EXPRESSION;
  6818. }
  6819. const [key, ...subPath] = path;
  6820. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6821. if (expressionAtPath) {
  6822. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  6823. }
  6824. if (this.prototypeExpression) {
  6825. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6826. }
  6827. return UNKNOWN_RETURN_EXPRESSION;
  6828. }
  6829. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6830. const [key, ...subPath] = path;
  6831. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  6832. const expressionAtPath = this.getMemberExpression(key);
  6833. if (expressionAtPath) {
  6834. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  6835. }
  6836. if (this.prototypeExpression) {
  6837. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6838. }
  6839. return true;
  6840. }
  6841. if (key === UnknownNonAccessorKey)
  6842. return false;
  6843. if (this.hasLostTrack)
  6844. return true;
  6845. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  6846. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6847. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6848. if (isConcreteKey(key)) {
  6849. if (propertiesAndAccessorsByKey.get(key)) {
  6850. const accessors = accessorsByKey.get(key);
  6851. if (accessors) {
  6852. for (const accessor of accessors) {
  6853. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6854. return true;
  6855. }
  6856. }
  6857. return false;
  6858. }
  6859. for (const accessor of unmatchableAccessors) {
  6860. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  6861. return true;
  6862. }
  6863. }
  6864. }
  6865. else {
  6866. for (const accessors of [...accessorsByKey.values(), unmatchableAccessors]) {
  6867. for (const accessor of accessors) {
  6868. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6869. return true;
  6870. }
  6871. }
  6872. }
  6873. if (this.prototypeExpression) {
  6874. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6875. }
  6876. return false;
  6877. }
  6878. include(context, includeChildrenRecursively) {
  6879. this.included = true;
  6880. for (const property of this.allProperties) {
  6881. if (includeChildrenRecursively ||
  6882. property.shouldBeIncluded(context) ||
  6883. this.alwaysIncludedProperties.has(property)) {
  6884. property.include(context, includeChildrenRecursively);
  6885. }
  6886. }
  6887. this.prototypeExpression?.include(context, includeChildrenRecursively);
  6888. }
  6889. includePath(path, context) {
  6890. this.included = true;
  6891. for (const property of this.alwaysIncludedProperties) {
  6892. property.includePath(UNKNOWN_PATH, context);
  6893. }
  6894. if (path.length === 0)
  6895. return;
  6896. const [key, ...subPath] = path;
  6897. const [includedMembers, includedPath] = isConcreteKey(key)
  6898. ? [
  6899. new Set([
  6900. ...(this.propertiesAndGettersByKey.get(key) || this.unmatchablePropertiesAndGetters),
  6901. ...(this.propertiesAndSettersByKey.get(key) || this.unmatchablePropertiesAndSetters)
  6902. ]),
  6903. subPath
  6904. ]
  6905. : [this.allProperties, UNKNOWN_PATH];
  6906. for (const property of includedMembers) {
  6907. property.includePath(includedPath, context);
  6908. }
  6909. this.prototypeExpression?.includePath(path, context);
  6910. }
  6911. buildPropertyMaps(properties) {
  6912. const { allProperties, alwaysIncludedProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  6913. for (let index = properties.length - 1; index >= 0; index--) {
  6914. const { key, kind, property } = properties[index];
  6915. allProperties.push(property);
  6916. if (isAnyWellKnown(key) && !TREE_SHAKEABLE_SYMBOLS.has(key)) {
  6917. // Never treeshake well-known symbols (unless Rollup can optimize them)
  6918. // They are most likely called implicitly by language semantics, don't get rid of them
  6919. alwaysIncludedProperties.add(property);
  6920. if (key === UnknownWellKnown)
  6921. continue;
  6922. }
  6923. if (isConcreteKey(key)) {
  6924. if (kind === 'set') {
  6925. if (!propertiesAndSettersByKey.has(key)) {
  6926. propertiesAndSettersByKey.set(key, [property, ...unmatchablePropertiesAndSetters]);
  6927. settersByKey.set(key, [property, ...unmatchableSetters]);
  6928. }
  6929. }
  6930. else if (kind === 'get') {
  6931. if (!propertiesAndGettersByKey.has(key)) {
  6932. propertiesAndGettersByKey.set(key, [property, ...unmatchablePropertiesAndGetters]);
  6933. gettersByKey.set(key, [property, ...unmatchableGetters]);
  6934. }
  6935. }
  6936. else {
  6937. if (!propertiesAndSettersByKey.has(key)) {
  6938. propertiesAndSettersByKey.set(key, [property, ...unmatchablePropertiesAndSetters]);
  6939. }
  6940. if (!propertiesAndGettersByKey.has(key)) {
  6941. propertiesAndGettersByKey.set(key, [property, ...unmatchablePropertiesAndGetters]);
  6942. }
  6943. }
  6944. }
  6945. else {
  6946. if (key === UnknownInteger) {
  6947. unknownIntegerProps.push(property);
  6948. continue;
  6949. }
  6950. if (kind === 'set')
  6951. unmatchableSetters.push(property);
  6952. if (kind === 'get')
  6953. unmatchableGetters.push(property);
  6954. if (kind !== 'get')
  6955. unmatchablePropertiesAndSetters.push(property);
  6956. if (kind !== 'set')
  6957. unmatchablePropertiesAndGetters.push(property);
  6958. }
  6959. }
  6960. }
  6961. deoptimizeCachedEntities() {
  6962. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimizedByKey.values()) {
  6963. for (const expression of expressionsToBeDeoptimized) {
  6964. expression.deoptimizeCache();
  6965. }
  6966. }
  6967. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6968. expression.deoptimizePath(UNKNOWN_PATH);
  6969. }
  6970. }
  6971. deoptimizeCachedIntegerEntities() {
  6972. for (const [key, expressionsToBeDeoptimized] of this.expressionsToBeDeoptimizedByKey.entries()) {
  6973. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  6974. for (const expression of expressionsToBeDeoptimized) {
  6975. expression.deoptimizeCache();
  6976. }
  6977. }
  6978. }
  6979. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6980. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6981. }
  6982. }
  6983. getMemberExpression(key) {
  6984. if (this.hasLostTrack ||
  6985. this.hasUnknownDeoptimizedProperty ||
  6986. !isConcreteKey(key) ||
  6987. (this.hasUnknownDeoptimizedInteger && typeof key === 'string' && INTEGER_REG_EXP.test(key)) ||
  6988. this.deoptimizedPaths.get(key)) {
  6989. return UNKNOWN_EXPRESSION;
  6990. }
  6991. const properties = this.propertiesAndGettersByKey.get(key);
  6992. if (properties?.length === 1) {
  6993. return properties[0];
  6994. }
  6995. if (properties ||
  6996. this.unmatchablePropertiesAndGetters.length > 0 ||
  6997. (this.unknownIntegerProps.length > 0 && typeof key === 'string' && INTEGER_REG_EXP.test(key))) {
  6998. return UNKNOWN_EXPRESSION;
  6999. }
  7000. return null;
  7001. }
  7002. getMemberExpressionAndTrackDeopt(key, origin) {
  7003. if (!isConcreteKey(key)) {
  7004. return UNKNOWN_EXPRESSION;
  7005. }
  7006. const expression = this.getMemberExpression(key);
  7007. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  7008. let expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey.get(key);
  7009. if (!expressionsToBeDeoptimized) {
  7010. this.expressionsToBeDeoptimizedByKey.set(key, (expressionsToBeDeoptimized = []));
  7011. }
  7012. expressionsToBeDeoptimized.push(origin);
  7013. }
  7014. return expression;
  7015. }
  7016. }
  7017. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  7018. // This makes sure unknown properties are not handled as "undefined" but as
  7019. // "unknown" but without access side effects. An exception is done for numeric
  7020. // properties as we do not expect new builtin properties to be numbers, this
  7021. // will improve tree-shaking for out-of-bounds array properties
  7022. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  7023. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7024. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  7025. deoptimizeInteraction(interaction);
  7026. }
  7027. }
  7028. getLiteralValueAtPath(path) {
  7029. // We ignore number properties as we do not expect new properties to be
  7030. // numbers and also want to keep handling out-of-bound array elements as
  7031. // "undefined"
  7032. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  7033. }
  7034. hasEffectsOnInteractionAtPath(path, { type }) {
  7035. return path.length > 1 || type === INTERACTION_CALLED;
  7036. }
  7037. })();
  7038. const OBJECT_PROTOTYPE = new ObjectEntity(new Map([
  7039. ['hasOwnProperty', METHOD_RETURNS_BOOLEAN],
  7040. ['isPrototypeOf', METHOD_RETURNS_BOOLEAN],
  7041. ['propertyIsEnumerable', METHOD_RETURNS_BOOLEAN],
  7042. ['toLocaleString', METHOD_RETURNS_STRING],
  7043. ['toString', METHOD_RETURNS_STRING],
  7044. ['valueOf', METHOD_RETURNS_UNKNOWN]
  7045. ]), OBJECT_PROTOTYPE_FALLBACK, true);
  7046. const NEW_ARRAY_PROPERTIES = [
  7047. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  7048. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7049. ];
  7050. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  7051. new Method({
  7052. callsArgs: [0],
  7053. mutatesArgs: false,
  7054. mutatesSelfAsArray: 'deopt-only',
  7055. returns: null,
  7056. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  7057. })
  7058. ];
  7059. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  7060. new Method({
  7061. callsArgs: [0],
  7062. mutatesArgs: false,
  7063. mutatesSelfAsArray: 'deopt-only',
  7064. returns: null,
  7065. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7066. })
  7067. ];
  7068. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  7069. new Method({
  7070. callsArgs: null,
  7071. mutatesArgs: false,
  7072. mutatesSelfAsArray: true,
  7073. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7074. returnsPrimitive: null
  7075. })
  7076. ];
  7077. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7078. new Method({
  7079. callsArgs: null,
  7080. mutatesArgs: false,
  7081. mutatesSelfAsArray: 'deopt-only',
  7082. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7083. returnsPrimitive: null
  7084. })
  7085. ];
  7086. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7087. new Method({
  7088. callsArgs: [0],
  7089. mutatesArgs: false,
  7090. mutatesSelfAsArray: 'deopt-only',
  7091. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7092. returnsPrimitive: null
  7093. })
  7094. ];
  7095. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  7096. new Method({
  7097. callsArgs: null,
  7098. mutatesArgs: true,
  7099. mutatesSelfAsArray: true,
  7100. returns: null,
  7101. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7102. })
  7103. ];
  7104. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  7105. new Method({
  7106. callsArgs: null,
  7107. mutatesArgs: false,
  7108. mutatesSelfAsArray: true,
  7109. returns: null,
  7110. returnsPrimitive: UNKNOWN_EXPRESSION
  7111. })
  7112. ];
  7113. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7114. new Method({
  7115. callsArgs: null,
  7116. mutatesArgs: false,
  7117. mutatesSelfAsArray: 'deopt-only',
  7118. returns: null,
  7119. returnsPrimitive: UNKNOWN_EXPRESSION
  7120. })
  7121. ];
  7122. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7123. new Method({
  7124. callsArgs: [0],
  7125. mutatesArgs: false,
  7126. mutatesSelfAsArray: 'deopt-only',
  7127. returns: null,
  7128. returnsPrimitive: UNKNOWN_EXPRESSION
  7129. })
  7130. ];
  7131. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  7132. new Method({
  7133. callsArgs: null,
  7134. mutatesArgs: false,
  7135. mutatesSelfAsArray: true,
  7136. returns: 'self',
  7137. returnsPrimitive: null
  7138. })
  7139. ];
  7140. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  7141. new Method({
  7142. callsArgs: [0],
  7143. mutatesArgs: false,
  7144. mutatesSelfAsArray: true,
  7145. returns: 'self',
  7146. returnsPrimitive: null
  7147. })
  7148. ];
  7149. const ARRAY_PROTOTYPE = new ObjectEntity(new Map([
  7150. // We assume that accessors have effects as we do not track the accessed value afterwards
  7151. ['at', METHOD_DEOPTS_SELF_RETURNS_UNKNOWN],
  7152. ['concat', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7153. ['copyWithin', METHOD_MUTATES_SELF_RETURNS_SELF],
  7154. ['entries', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7155. ['every', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN],
  7156. ['fill', METHOD_MUTATES_SELF_RETURNS_SELF],
  7157. ['filter', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7158. ['find', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  7159. ['findIndex', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER],
  7160. ['findLast', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  7161. ['findLastIndex', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER],
  7162. ['flat', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7163. ['flatMap', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7164. ['forEach', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  7165. ['includes', METHOD_RETURNS_BOOLEAN],
  7166. ['indexOf', METHOD_RETURNS_NUMBER],
  7167. ['join', METHOD_RETURNS_STRING],
  7168. ['keys', METHOD_RETURNS_UNKNOWN],
  7169. ['lastIndexOf', METHOD_RETURNS_NUMBER],
  7170. ['map', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7171. ['pop', METHOD_MUTATES_SELF_RETURNS_UNKNOWN],
  7172. ['push', METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER],
  7173. ['reduce', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  7174. ['reduceRight', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  7175. ['reverse', METHOD_MUTATES_SELF_RETURNS_SELF],
  7176. ['shift', METHOD_MUTATES_SELF_RETURNS_UNKNOWN],
  7177. ['slice', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  7178. ['some', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN],
  7179. ['sort', METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF],
  7180. ['splice', METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY],
  7181. ['toLocaleString', METHOD_RETURNS_STRING],
  7182. ['toString', METHOD_RETURNS_STRING],
  7183. ['unshift', METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER],
  7184. ['values', METHOD_DEOPTS_SELF_RETURNS_UNKNOWN]
  7185. ]), OBJECT_PROTOTYPE, true);
  7186. class SpreadElement extends NodeBase {
  7187. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7188. if (path.length > 0) {
  7189. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  7190. }
  7191. }
  7192. hasEffects(context) {
  7193. if (!this.deoptimized)
  7194. this.applyDeoptimizations();
  7195. const { propertyReadSideEffects } = this.scope.context.options
  7196. .treeshake;
  7197. return (this.argument.hasEffects(context) ||
  7198. (propertyReadSideEffects &&
  7199. (propertyReadSideEffects === 'always' ||
  7200. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  7201. }
  7202. includeNode(context) {
  7203. this.included = true;
  7204. if (!this.deoptimized)
  7205. this.applyDeoptimizations();
  7206. this.argument.includePath(UNKNOWN_PATH, context);
  7207. }
  7208. applyDeoptimizations() {
  7209. this.deoptimized = true;
  7210. // Only properties of properties of the argument could become subject to reassignment
  7211. // This will also reassign the return values of iterators
  7212. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  7213. this.scope.context.requestTreeshakingPass();
  7214. }
  7215. }
  7216. class ArrayExpression extends NodeBase {
  7217. constructor() {
  7218. super(...arguments);
  7219. this.objectEntity = null;
  7220. }
  7221. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7222. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7223. }
  7224. deoptimizePath(path) {
  7225. this.getObjectEntity().deoptimizePath(path);
  7226. }
  7227. getLiteralValueAtPath(path, recursionTracker, origin) {
  7228. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7229. }
  7230. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7231. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7232. }
  7233. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7234. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7235. }
  7236. includeNode(context) {
  7237. this.included = true;
  7238. if (!this.deoptimized)
  7239. this.applyDeoptimizations();
  7240. for (const element of this.elements) {
  7241. if (element) {
  7242. element?.includePath(UNKNOWN_PATH, context);
  7243. }
  7244. }
  7245. }
  7246. applyDeoptimizations() {
  7247. this.deoptimized = true;
  7248. let hasSpread = false;
  7249. for (let index = 0; index < this.elements.length; index++) {
  7250. const element = this.elements[index];
  7251. if (element && (hasSpread || element instanceof SpreadElement)) {
  7252. hasSpread = true;
  7253. element.deoptimizePath(UNKNOWN_PATH);
  7254. }
  7255. }
  7256. this.scope.context.requestTreeshakingPass();
  7257. }
  7258. getObjectEntity() {
  7259. if (this.objectEntity !== null) {
  7260. return this.objectEntity;
  7261. }
  7262. const properties = [
  7263. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7264. ];
  7265. let hasSpread = false;
  7266. for (let index = 0; index < this.elements.length; index++) {
  7267. const element = this.elements[index];
  7268. if (hasSpread || element instanceof SpreadElement) {
  7269. if (element) {
  7270. hasSpread = true;
  7271. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  7272. }
  7273. }
  7274. else if (element) {
  7275. properties.push({ key: String(index), kind: 'init', property: element });
  7276. }
  7277. else {
  7278. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  7279. }
  7280. }
  7281. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  7282. }
  7283. }
  7284. /* eslint sort-keys: "off" */
  7285. const ValueProperties = Symbol('Value Properties');
  7286. const getUnknownValue = () => UnknownValue;
  7287. const returnFalse = () => false;
  7288. const returnTrue = () => true;
  7289. const getWellKnownSymbol = (symbol) => ({
  7290. __proto__: null,
  7291. [ValueProperties]: {
  7292. deoptimizeArgumentsOnCall: doNothing,
  7293. getLiteralValue: () => symbol,
  7294. hasEffectsWhenCalled: returnTrue
  7295. }
  7296. });
  7297. const PURE = {
  7298. deoptimizeArgumentsOnCall: doNothing,
  7299. getLiteralValue: getUnknownValue,
  7300. hasEffectsWhenCalled: returnFalse
  7301. };
  7302. const IMPURE = {
  7303. deoptimizeArgumentsOnCall: doNothing,
  7304. getLiteralValue: getUnknownValue,
  7305. hasEffectsWhenCalled: returnTrue
  7306. };
  7307. const PURE_WITH_ARRAY = {
  7308. deoptimizeArgumentsOnCall: doNothing,
  7309. getLiteralValue: getUnknownValue,
  7310. hasEffectsWhenCalled({ args }) {
  7311. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  7312. }
  7313. };
  7314. const GETTER_ACCESS = {
  7315. deoptimizeArgumentsOnCall: doNothing,
  7316. getLiteralValue: getUnknownValue,
  7317. hasEffectsWhenCalled({ args }, context) {
  7318. const [_thisArgument, firstArgument] = args;
  7319. return (!(firstArgument instanceof ExpressionEntity) ||
  7320. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7321. }
  7322. };
  7323. // We use shortened variables to reduce file size here
  7324. /* OBJECT */
  7325. const O = {
  7326. __proto__: null,
  7327. [ValueProperties]: IMPURE
  7328. };
  7329. /* PURE FUNCTION */
  7330. const PF = {
  7331. __proto__: null,
  7332. [ValueProperties]: PURE
  7333. };
  7334. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  7335. const PF_NO_GETTER = {
  7336. __proto__: null,
  7337. [ValueProperties]: GETTER_ACCESS
  7338. };
  7339. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  7340. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  7341. __proto__: null,
  7342. [ValueProperties]: {
  7343. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  7344. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  7345. },
  7346. getLiteralValue: getUnknownValue,
  7347. hasEffectsWhenCalled({ args }, context) {
  7348. return (args.length <= 1 ||
  7349. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  7350. }
  7351. }
  7352. };
  7353. /* CONSTRUCTOR */
  7354. const C = {
  7355. __proto__: null,
  7356. [ValueProperties]: IMPURE,
  7357. prototype: O
  7358. };
  7359. /* PURE CONSTRUCTOR */
  7360. const PC = {
  7361. __proto__: null,
  7362. [ValueProperties]: PURE,
  7363. prototype: O
  7364. };
  7365. const PC_WITH_ARRAY = {
  7366. __proto__: null,
  7367. [ValueProperties]: PURE_WITH_ARRAY,
  7368. prototype: O
  7369. };
  7370. const ARRAY_TYPE = {
  7371. __proto__: null,
  7372. [ValueProperties]: PURE,
  7373. from: O,
  7374. of: PF,
  7375. prototype: O
  7376. };
  7377. const INTL_MEMBER = {
  7378. __proto__: null,
  7379. [ValueProperties]: PURE,
  7380. supportedLocalesOf: PC
  7381. };
  7382. const UNKNOWN_WELL_KNOWN = {
  7383. deoptimizeArgumentsOnCall: doNothing,
  7384. getLiteralValue: () => UnknownWellKnown,
  7385. hasEffectsWhenCalled: returnTrue
  7386. };
  7387. const knownGlobals = {
  7388. // Placeholders for global objects to avoid shape mutations
  7389. global: O,
  7390. globalThis: O,
  7391. self: O,
  7392. window: O,
  7393. // Common globals
  7394. __proto__: null,
  7395. [ValueProperties]: IMPURE,
  7396. Array: {
  7397. __proto__: null,
  7398. [ValueProperties]: IMPURE,
  7399. from: O,
  7400. isArray: PF,
  7401. of: PF,
  7402. prototype: O
  7403. },
  7404. ArrayBuffer: {
  7405. __proto__: null,
  7406. [ValueProperties]: PURE,
  7407. isView: PF,
  7408. prototype: O
  7409. },
  7410. AggregateError: PC_WITH_ARRAY,
  7411. Atomics: O,
  7412. BigInt: C,
  7413. BigInt64Array: C,
  7414. BigUint64Array: C,
  7415. Boolean: PC,
  7416. constructor: C,
  7417. DataView: PC,
  7418. Date: {
  7419. __proto__: null,
  7420. [ValueProperties]: PURE,
  7421. now: PF,
  7422. parse: PF,
  7423. prototype: O,
  7424. UTC: PF
  7425. },
  7426. decodeURI: PF,
  7427. decodeURIComponent: PF,
  7428. encodeURI: PF,
  7429. encodeURIComponent: PF,
  7430. Error: PC,
  7431. escape: PF,
  7432. eval: O,
  7433. EvalError: PC,
  7434. FinalizationRegistry: C,
  7435. Float32Array: ARRAY_TYPE,
  7436. Float64Array: ARRAY_TYPE,
  7437. Function: C,
  7438. hasOwnProperty: O,
  7439. Infinity: O,
  7440. Int16Array: ARRAY_TYPE,
  7441. Int32Array: ARRAY_TYPE,
  7442. Int8Array: ARRAY_TYPE,
  7443. isFinite: PF,
  7444. isNaN: PF,
  7445. isPrototypeOf: O,
  7446. JSON: O,
  7447. Map: PC_WITH_ARRAY,
  7448. Math: {
  7449. __proto__: null,
  7450. [ValueProperties]: IMPURE,
  7451. abs: PF,
  7452. acos: PF,
  7453. acosh: PF,
  7454. asin: PF,
  7455. asinh: PF,
  7456. atan: PF,
  7457. atan2: PF,
  7458. atanh: PF,
  7459. cbrt: PF,
  7460. ceil: PF,
  7461. clz32: PF,
  7462. cos: PF,
  7463. cosh: PF,
  7464. exp: PF,
  7465. expm1: PF,
  7466. floor: PF,
  7467. fround: PF,
  7468. hypot: PF,
  7469. imul: PF,
  7470. log: PF,
  7471. log10: PF,
  7472. log1p: PF,
  7473. log2: PF,
  7474. max: PF,
  7475. min: PF,
  7476. pow: PF,
  7477. random: PF,
  7478. round: PF,
  7479. sign: PF,
  7480. sin: PF,
  7481. sinh: PF,
  7482. sqrt: PF,
  7483. tan: PF,
  7484. tanh: PF,
  7485. trunc: PF
  7486. },
  7487. NaN: O,
  7488. Number: {
  7489. __proto__: null,
  7490. [ValueProperties]: PURE,
  7491. isFinite: PF,
  7492. isInteger: PF,
  7493. isNaN: PF,
  7494. isSafeInteger: PF,
  7495. parseFloat: PF,
  7496. parseInt: PF,
  7497. prototype: O
  7498. },
  7499. Object: {
  7500. __proto__: null,
  7501. [ValueProperties]: PURE,
  7502. create: PF,
  7503. // Technically those can throw in certain situations, but we ignore this as
  7504. // code that relies on this will hopefully wrap this in a try-catch, which
  7505. // deoptimizes everything anyway
  7506. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  7507. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  7508. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  7509. getOwnPropertyDescriptor: PF,
  7510. getOwnPropertyDescriptors: PF,
  7511. getOwnPropertyNames: PF,
  7512. getOwnPropertySymbols: PF,
  7513. getPrototypeOf: PF,
  7514. hasOwn: PF,
  7515. is: PF,
  7516. isExtensible: PF,
  7517. isFrozen: PF,
  7518. isSealed: PF,
  7519. keys: PF,
  7520. fromEntries: O,
  7521. entries: PF_NO_GETTER,
  7522. values: PF_NO_GETTER,
  7523. prototype: O
  7524. },
  7525. parseFloat: PF,
  7526. parseInt: PF,
  7527. Promise: {
  7528. __proto__: null,
  7529. [ValueProperties]: IMPURE,
  7530. all: O,
  7531. allSettled: O,
  7532. any: O,
  7533. prototype: O,
  7534. race: O,
  7535. reject: O,
  7536. resolve: O
  7537. },
  7538. propertyIsEnumerable: O,
  7539. Proxy: {
  7540. __proto__: null,
  7541. [ValueProperties]: {
  7542. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  7543. if (isObjectExpressionNode(parameter)) {
  7544. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  7545. if (!hasSpreadElement) {
  7546. for (const property of parameter.properties) {
  7547. property.deoptimizeArgumentsOnInteractionAtPath({
  7548. args: [null, target],
  7549. type: INTERACTION_CALLED,
  7550. withNew: false
  7551. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  7552. }
  7553. return;
  7554. }
  7555. }
  7556. target.deoptimizePath(UNKNOWN_PATH);
  7557. },
  7558. getLiteralValue: getUnknownValue,
  7559. hasEffectsWhenCalled: returnTrue
  7560. }
  7561. },
  7562. RangeError: PC,
  7563. ReferenceError: PC,
  7564. Reflect: O,
  7565. RegExp: PC,
  7566. Set: PC_WITH_ARRAY,
  7567. SharedArrayBuffer: C,
  7568. String: {
  7569. __proto__: null,
  7570. [ValueProperties]: PURE,
  7571. fromCharCode: PF,
  7572. fromCodePoint: PF,
  7573. prototype: O,
  7574. raw: PF
  7575. },
  7576. Symbol: {
  7577. __proto__: null,
  7578. [ValueProperties]: PURE,
  7579. for: PF,
  7580. keyFor: PF,
  7581. prototype: O,
  7582. asyncDispose: getWellKnownSymbol(SymbolAsyncDispose),
  7583. dispose: getWellKnownSymbol(SymbolDispose),
  7584. hasInstance: getWellKnownSymbol(SymbolHasInstance),
  7585. toStringTag: getWellKnownSymbol(SymbolToStringTag)
  7586. },
  7587. SyntaxError: PC,
  7588. toLocaleString: O,
  7589. toString: O,
  7590. TypeError: PC,
  7591. Uint16Array: ARRAY_TYPE,
  7592. Uint32Array: ARRAY_TYPE,
  7593. Uint8Array: ARRAY_TYPE,
  7594. Uint8ClampedArray: ARRAY_TYPE,
  7595. // Technically, this is a global, but it needs special handling
  7596. // undefined: ?,
  7597. unescape: PF,
  7598. URIError: PC,
  7599. valueOf: O,
  7600. WeakMap: PC_WITH_ARRAY,
  7601. WeakRef: C,
  7602. WeakSet: PC_WITH_ARRAY,
  7603. // Additional globals shared by Node and Browser that are not strictly part of the language
  7604. clearInterval: C,
  7605. clearTimeout: C,
  7606. console: {
  7607. __proto__: null,
  7608. [ValueProperties]: IMPURE,
  7609. assert: C,
  7610. clear: C,
  7611. count: C,
  7612. countReset: C,
  7613. debug: C,
  7614. dir: C,
  7615. dirxml: C,
  7616. error: C,
  7617. exception: C,
  7618. group: C,
  7619. groupCollapsed: C,
  7620. groupEnd: C,
  7621. info: C,
  7622. log: C,
  7623. table: C,
  7624. time: C,
  7625. timeEnd: C,
  7626. timeLog: C,
  7627. trace: C,
  7628. warn: C
  7629. },
  7630. Intl: {
  7631. __proto__: null,
  7632. [ValueProperties]: IMPURE,
  7633. Collator: INTL_MEMBER,
  7634. DateTimeFormat: INTL_MEMBER,
  7635. DisplayNames: INTL_MEMBER,
  7636. ListFormat: INTL_MEMBER,
  7637. Locale: INTL_MEMBER,
  7638. NumberFormat: INTL_MEMBER,
  7639. PluralRules: INTL_MEMBER,
  7640. RelativeTimeFormat: INTL_MEMBER,
  7641. Segmenter: INTL_MEMBER
  7642. },
  7643. setInterval: C,
  7644. setTimeout: C,
  7645. TextDecoder: C,
  7646. TextEncoder: C,
  7647. URL: {
  7648. __proto__: null,
  7649. [ValueProperties]: IMPURE,
  7650. prototype: O,
  7651. canParse: PF
  7652. },
  7653. URLSearchParams: C,
  7654. // Browser specific globals
  7655. AbortController: C,
  7656. AbortSignal: C,
  7657. addEventListener: O,
  7658. alert: O,
  7659. AnalyserNode: C,
  7660. Animation: C,
  7661. AnimationEvent: C,
  7662. applicationCache: O,
  7663. ApplicationCache: C,
  7664. ApplicationCacheErrorEvent: C,
  7665. atob: O,
  7666. Attr: C,
  7667. Audio: C,
  7668. AudioBuffer: C,
  7669. AudioBufferSourceNode: C,
  7670. AudioContext: C,
  7671. AudioDestinationNode: C,
  7672. AudioListener: C,
  7673. AudioNode: C,
  7674. AudioParam: C,
  7675. AudioProcessingEvent: C,
  7676. AudioScheduledSourceNode: C,
  7677. AudioWorkletNode: C,
  7678. BarProp: C,
  7679. BaseAudioContext: C,
  7680. BatteryManager: C,
  7681. BeforeUnloadEvent: C,
  7682. BiquadFilterNode: C,
  7683. Blob: C,
  7684. BlobEvent: C,
  7685. blur: O,
  7686. BroadcastChannel: C,
  7687. btoa: O,
  7688. ByteLengthQueuingStrategy: C,
  7689. Cache: C,
  7690. caches: O,
  7691. CacheStorage: C,
  7692. cancelAnimationFrame: O,
  7693. cancelIdleCallback: O,
  7694. CanvasCaptureMediaStreamTrack: C,
  7695. CanvasGradient: C,
  7696. CanvasPattern: C,
  7697. CanvasRenderingContext2D: C,
  7698. ChannelMergerNode: C,
  7699. ChannelSplitterNode: C,
  7700. CharacterData: C,
  7701. clientInformation: O,
  7702. ClipboardEvent: C,
  7703. close: O,
  7704. closed: O,
  7705. CloseEvent: C,
  7706. Comment: C,
  7707. CompositionEvent: C,
  7708. confirm: O,
  7709. ConstantSourceNode: C,
  7710. ConvolverNode: C,
  7711. CountQueuingStrategy: C,
  7712. createImageBitmap: O,
  7713. Credential: C,
  7714. CredentialsContainer: C,
  7715. crypto: O,
  7716. Crypto: C,
  7717. CryptoKey: C,
  7718. CSS: C,
  7719. CSSConditionRule: C,
  7720. CSSFontFaceRule: C,
  7721. CSSGroupingRule: C,
  7722. CSSImportRule: C,
  7723. CSSKeyframeRule: C,
  7724. CSSKeyframesRule: C,
  7725. CSSMediaRule: C,
  7726. CSSNamespaceRule: C,
  7727. CSSPageRule: C,
  7728. CSSRule: C,
  7729. CSSRuleList: C,
  7730. CSSStyleDeclaration: C,
  7731. CSSStyleRule: C,
  7732. CSSStyleSheet: C,
  7733. CSSSupportsRule: C,
  7734. CustomElementRegistry: C,
  7735. customElements: O,
  7736. CustomEvent: {
  7737. __proto__: null,
  7738. [ValueProperties]: {
  7739. deoptimizeArgumentsOnCall({ args }) {
  7740. args[2]?.deoptimizePath(['detail']);
  7741. },
  7742. getLiteralValue: getUnknownValue,
  7743. hasEffectsWhenCalled: returnFalse
  7744. },
  7745. prototype: O
  7746. },
  7747. DataTransfer: C,
  7748. DataTransferItem: C,
  7749. DataTransferItemList: C,
  7750. defaultstatus: O,
  7751. defaultStatus: O,
  7752. DelayNode: C,
  7753. DeviceMotionEvent: C,
  7754. DeviceOrientationEvent: C,
  7755. devicePixelRatio: O,
  7756. dispatchEvent: O,
  7757. document: O,
  7758. Document: C,
  7759. DocumentFragment: C,
  7760. DocumentType: C,
  7761. DOMError: C,
  7762. DOMException: C,
  7763. DOMImplementation: C,
  7764. DOMMatrix: C,
  7765. DOMMatrixReadOnly: C,
  7766. DOMParser: C,
  7767. DOMPoint: C,
  7768. DOMPointReadOnly: C,
  7769. DOMQuad: C,
  7770. DOMRect: C,
  7771. DOMRectReadOnly: C,
  7772. DOMStringList: C,
  7773. DOMStringMap: C,
  7774. DOMTokenList: C,
  7775. DragEvent: C,
  7776. DynamicsCompressorNode: C,
  7777. Element: C,
  7778. ErrorEvent: C,
  7779. Event: C,
  7780. EventSource: C,
  7781. EventTarget: C,
  7782. external: O,
  7783. fetch: O,
  7784. File: C,
  7785. FileList: C,
  7786. FileReader: C,
  7787. find: O,
  7788. focus: O,
  7789. FocusEvent: C,
  7790. FontFace: C,
  7791. FontFaceSetLoadEvent: C,
  7792. FormData: C,
  7793. frames: O,
  7794. GainNode: C,
  7795. Gamepad: C,
  7796. GamepadButton: C,
  7797. GamepadEvent: C,
  7798. getComputedStyle: O,
  7799. getSelection: O,
  7800. HashChangeEvent: C,
  7801. Headers: C,
  7802. history: O,
  7803. History: C,
  7804. HTMLAllCollection: C,
  7805. HTMLAnchorElement: C,
  7806. HTMLAreaElement: C,
  7807. HTMLAudioElement: C,
  7808. HTMLBaseElement: C,
  7809. HTMLBodyElement: C,
  7810. HTMLBRElement: C,
  7811. HTMLButtonElement: C,
  7812. HTMLCanvasElement: C,
  7813. HTMLCollection: C,
  7814. HTMLContentElement: C,
  7815. HTMLDataElement: C,
  7816. HTMLDataListElement: C,
  7817. HTMLDetailsElement: C,
  7818. HTMLDialogElement: C,
  7819. HTMLDirectoryElement: C,
  7820. HTMLDivElement: C,
  7821. HTMLDListElement: C,
  7822. HTMLDocument: C,
  7823. HTMLElement: C,
  7824. HTMLEmbedElement: C,
  7825. HTMLFieldSetElement: C,
  7826. HTMLFontElement: C,
  7827. HTMLFormControlsCollection: C,
  7828. HTMLFormElement: C,
  7829. HTMLFrameElement: C,
  7830. HTMLFrameSetElement: C,
  7831. HTMLHeadElement: C,
  7832. HTMLHeadingElement: C,
  7833. HTMLHRElement: C,
  7834. HTMLHtmlElement: C,
  7835. HTMLIFrameElement: C,
  7836. HTMLImageElement: C,
  7837. HTMLInputElement: C,
  7838. HTMLLabelElement: C,
  7839. HTMLLegendElement: C,
  7840. HTMLLIElement: C,
  7841. HTMLLinkElement: C,
  7842. HTMLMapElement: C,
  7843. HTMLMarqueeElement: C,
  7844. HTMLMediaElement: C,
  7845. HTMLMenuElement: C,
  7846. HTMLMetaElement: C,
  7847. HTMLMeterElement: C,
  7848. HTMLModElement: C,
  7849. HTMLObjectElement: C,
  7850. HTMLOListElement: C,
  7851. HTMLOptGroupElement: C,
  7852. HTMLOptionElement: C,
  7853. HTMLOptionsCollection: C,
  7854. HTMLOutputElement: C,
  7855. HTMLParagraphElement: C,
  7856. HTMLParamElement: C,
  7857. HTMLPictureElement: C,
  7858. HTMLPreElement: C,
  7859. HTMLProgressElement: C,
  7860. HTMLQuoteElement: C,
  7861. HTMLScriptElement: C,
  7862. HTMLSelectElement: C,
  7863. HTMLShadowElement: C,
  7864. HTMLSlotElement: C,
  7865. HTMLSourceElement: C,
  7866. HTMLSpanElement: C,
  7867. HTMLStyleElement: C,
  7868. HTMLTableCaptionElement: C,
  7869. HTMLTableCellElement: C,
  7870. HTMLTableColElement: C,
  7871. HTMLTableElement: C,
  7872. HTMLTableRowElement: C,
  7873. HTMLTableSectionElement: C,
  7874. HTMLTemplateElement: C,
  7875. HTMLTextAreaElement: C,
  7876. HTMLTimeElement: C,
  7877. HTMLTitleElement: C,
  7878. HTMLTrackElement: C,
  7879. HTMLUListElement: C,
  7880. HTMLUnknownElement: C,
  7881. HTMLVideoElement: C,
  7882. IDBCursor: C,
  7883. IDBCursorWithValue: C,
  7884. IDBDatabase: C,
  7885. IDBFactory: C,
  7886. IDBIndex: C,
  7887. IDBKeyRange: C,
  7888. IDBObjectStore: C,
  7889. IDBOpenDBRequest: C,
  7890. IDBRequest: C,
  7891. IDBTransaction: C,
  7892. IDBVersionChangeEvent: C,
  7893. IdleDeadline: C,
  7894. IIRFilterNode: C,
  7895. Image: C,
  7896. ImageBitmap: C,
  7897. ImageBitmapRenderingContext: C,
  7898. ImageCapture: C,
  7899. ImageData: C,
  7900. indexedDB: O,
  7901. innerHeight: O,
  7902. innerWidth: O,
  7903. InputEvent: C,
  7904. IntersectionObserver: C,
  7905. IntersectionObserverEntry: C,
  7906. isSecureContext: O,
  7907. KeyboardEvent: C,
  7908. KeyframeEffect: C,
  7909. length: O,
  7910. localStorage: O,
  7911. location: O,
  7912. Location: C,
  7913. locationbar: O,
  7914. matchMedia: O,
  7915. MediaDeviceInfo: C,
  7916. MediaDevices: C,
  7917. MediaElementAudioSourceNode: C,
  7918. MediaEncryptedEvent: C,
  7919. MediaError: C,
  7920. MediaKeyMessageEvent: C,
  7921. MediaKeySession: C,
  7922. MediaKeyStatusMap: C,
  7923. MediaKeySystemAccess: C,
  7924. MediaList: C,
  7925. MediaQueryList: C,
  7926. MediaQueryListEvent: C,
  7927. MediaRecorder: C,
  7928. MediaSettingsRange: C,
  7929. MediaSource: C,
  7930. MediaStream: C,
  7931. MediaStreamAudioDestinationNode: C,
  7932. MediaStreamAudioSourceNode: C,
  7933. MediaStreamEvent: C,
  7934. MediaStreamTrack: C,
  7935. MediaStreamTrackEvent: C,
  7936. menubar: O,
  7937. MessageChannel: C,
  7938. MessageEvent: C,
  7939. MessagePort: C,
  7940. MIDIAccess: C,
  7941. MIDIConnectionEvent: C,
  7942. MIDIInput: C,
  7943. MIDIInputMap: C,
  7944. MIDIMessageEvent: C,
  7945. MIDIOutput: C,
  7946. MIDIOutputMap: C,
  7947. MIDIPort: C,
  7948. MimeType: C,
  7949. MimeTypeArray: C,
  7950. MouseEvent: C,
  7951. moveBy: O,
  7952. moveTo: O,
  7953. MutationEvent: C,
  7954. MutationObserver: C,
  7955. MutationRecord: C,
  7956. name: O,
  7957. NamedNodeMap: C,
  7958. NavigationPreloadManager: C,
  7959. navigator: O,
  7960. Navigator: C,
  7961. NetworkInformation: C,
  7962. Node: C,
  7963. NodeFilter: O,
  7964. NodeIterator: C,
  7965. NodeList: C,
  7966. Notification: C,
  7967. OfflineAudioCompletionEvent: C,
  7968. OfflineAudioContext: C,
  7969. offscreenBuffering: O,
  7970. OffscreenCanvas: C,
  7971. open: O,
  7972. openDatabase: O,
  7973. Option: C,
  7974. origin: O,
  7975. OscillatorNode: C,
  7976. outerHeight: O,
  7977. outerWidth: O,
  7978. PageTransitionEvent: C,
  7979. pageXOffset: O,
  7980. pageYOffset: O,
  7981. PannerNode: C,
  7982. parent: O,
  7983. Path2D: C,
  7984. PaymentAddress: C,
  7985. PaymentRequest: C,
  7986. PaymentRequestUpdateEvent: C,
  7987. PaymentResponse: C,
  7988. performance: O,
  7989. Performance: C,
  7990. PerformanceEntry: C,
  7991. PerformanceLongTaskTiming: C,
  7992. PerformanceMark: C,
  7993. PerformanceMeasure: C,
  7994. PerformanceNavigation: C,
  7995. PerformanceNavigationTiming: C,
  7996. PerformanceObserver: C,
  7997. PerformanceObserverEntryList: C,
  7998. PerformancePaintTiming: C,
  7999. PerformanceResourceTiming: C,
  8000. PerformanceTiming: C,
  8001. PeriodicWave: C,
  8002. Permissions: C,
  8003. PermissionStatus: C,
  8004. personalbar: O,
  8005. PhotoCapabilities: C,
  8006. Plugin: C,
  8007. PluginArray: C,
  8008. PointerEvent: C,
  8009. PopStateEvent: C,
  8010. postMessage: O,
  8011. Presentation: C,
  8012. PresentationAvailability: C,
  8013. PresentationConnection: C,
  8014. PresentationConnectionAvailableEvent: C,
  8015. PresentationConnectionCloseEvent: C,
  8016. PresentationConnectionList: C,
  8017. PresentationReceiver: C,
  8018. PresentationRequest: C,
  8019. print: O,
  8020. ProcessingInstruction: C,
  8021. ProgressEvent: C,
  8022. PromiseRejectionEvent: C,
  8023. prompt: O,
  8024. PushManager: C,
  8025. PushSubscription: C,
  8026. PushSubscriptionOptions: C,
  8027. queueMicrotask: O,
  8028. RadioNodeList: C,
  8029. Range: C,
  8030. ReadableStream: C,
  8031. RemotePlayback: C,
  8032. removeEventListener: O,
  8033. Request: C,
  8034. requestAnimationFrame: O,
  8035. requestIdleCallback: O,
  8036. resizeBy: O,
  8037. ResizeObserver: C,
  8038. ResizeObserverEntry: C,
  8039. resizeTo: O,
  8040. Response: C,
  8041. RTCCertificate: C,
  8042. RTCDataChannel: C,
  8043. RTCDataChannelEvent: C,
  8044. RTCDtlsTransport: C,
  8045. RTCIceCandidate: C,
  8046. RTCIceTransport: C,
  8047. RTCPeerConnection: C,
  8048. RTCPeerConnectionIceEvent: C,
  8049. RTCRtpReceiver: C,
  8050. RTCRtpSender: C,
  8051. RTCSctpTransport: C,
  8052. RTCSessionDescription: C,
  8053. RTCStatsReport: C,
  8054. RTCTrackEvent: C,
  8055. screen: O,
  8056. Screen: C,
  8057. screenLeft: O,
  8058. ScreenOrientation: C,
  8059. screenTop: O,
  8060. screenX: O,
  8061. screenY: O,
  8062. ScriptProcessorNode: C,
  8063. scroll: O,
  8064. scrollbars: O,
  8065. scrollBy: O,
  8066. scrollTo: O,
  8067. scrollX: O,
  8068. scrollY: O,
  8069. SecurityPolicyViolationEvent: C,
  8070. Selection: C,
  8071. ServiceWorker: C,
  8072. ServiceWorkerContainer: C,
  8073. ServiceWorkerRegistration: C,
  8074. sessionStorage: O,
  8075. ShadowRoot: C,
  8076. SharedWorker: C,
  8077. SourceBuffer: C,
  8078. SourceBufferList: C,
  8079. speechSynthesis: O,
  8080. SpeechSynthesisEvent: C,
  8081. SpeechSynthesisUtterance: C,
  8082. StaticRange: C,
  8083. status: O,
  8084. statusbar: O,
  8085. StereoPannerNode: C,
  8086. stop: O,
  8087. Storage: C,
  8088. StorageEvent: C,
  8089. StorageManager: C,
  8090. styleMedia: O,
  8091. StyleSheet: C,
  8092. StyleSheetList: C,
  8093. SubtleCrypto: C,
  8094. SVGAElement: C,
  8095. SVGAngle: C,
  8096. SVGAnimatedAngle: C,
  8097. SVGAnimatedBoolean: C,
  8098. SVGAnimatedEnumeration: C,
  8099. SVGAnimatedInteger: C,
  8100. SVGAnimatedLength: C,
  8101. SVGAnimatedLengthList: C,
  8102. SVGAnimatedNumber: C,
  8103. SVGAnimatedNumberList: C,
  8104. SVGAnimatedPreserveAspectRatio: C,
  8105. SVGAnimatedRect: C,
  8106. SVGAnimatedString: C,
  8107. SVGAnimatedTransformList: C,
  8108. SVGAnimateElement: C,
  8109. SVGAnimateMotionElement: C,
  8110. SVGAnimateTransformElement: C,
  8111. SVGAnimationElement: C,
  8112. SVGCircleElement: C,
  8113. SVGClipPathElement: C,
  8114. SVGComponentTransferFunctionElement: C,
  8115. SVGDefsElement: C,
  8116. SVGDescElement: C,
  8117. SVGDiscardElement: C,
  8118. SVGElement: C,
  8119. SVGEllipseElement: C,
  8120. SVGFEBlendElement: C,
  8121. SVGFEColorMatrixElement: C,
  8122. SVGFEComponentTransferElement: C,
  8123. SVGFECompositeElement: C,
  8124. SVGFEConvolveMatrixElement: C,
  8125. SVGFEDiffuseLightingElement: C,
  8126. SVGFEDisplacementMapElement: C,
  8127. SVGFEDistantLightElement: C,
  8128. SVGFEDropShadowElement: C,
  8129. SVGFEFloodElement: C,
  8130. SVGFEFuncAElement: C,
  8131. SVGFEFuncBElement: C,
  8132. SVGFEFuncGElement: C,
  8133. SVGFEFuncRElement: C,
  8134. SVGFEGaussianBlurElement: C,
  8135. SVGFEImageElement: C,
  8136. SVGFEMergeElement: C,
  8137. SVGFEMergeNodeElement: C,
  8138. SVGFEMorphologyElement: C,
  8139. SVGFEOffsetElement: C,
  8140. SVGFEPointLightElement: C,
  8141. SVGFESpecularLightingElement: C,
  8142. SVGFESpotLightElement: C,
  8143. SVGFETileElement: C,
  8144. SVGFETurbulenceElement: C,
  8145. SVGFilterElement: C,
  8146. SVGForeignObjectElement: C,
  8147. SVGGElement: C,
  8148. SVGGeometryElement: C,
  8149. SVGGradientElement: C,
  8150. SVGGraphicsElement: C,
  8151. SVGImageElement: C,
  8152. SVGLength: C,
  8153. SVGLengthList: C,
  8154. SVGLinearGradientElement: C,
  8155. SVGLineElement: C,
  8156. SVGMarkerElement: C,
  8157. SVGMaskElement: C,
  8158. SVGMatrix: C,
  8159. SVGMetadataElement: C,
  8160. SVGMPathElement: C,
  8161. SVGNumber: C,
  8162. SVGNumberList: C,
  8163. SVGPathElement: C,
  8164. SVGPatternElement: C,
  8165. SVGPoint: C,
  8166. SVGPointList: C,
  8167. SVGPolygonElement: C,
  8168. SVGPolylineElement: C,
  8169. SVGPreserveAspectRatio: C,
  8170. SVGRadialGradientElement: C,
  8171. SVGRect: C,
  8172. SVGRectElement: C,
  8173. SVGScriptElement: C,
  8174. SVGSetElement: C,
  8175. SVGStopElement: C,
  8176. SVGStringList: C,
  8177. SVGStyleElement: C,
  8178. SVGSVGElement: C,
  8179. SVGSwitchElement: C,
  8180. SVGSymbolElement: C,
  8181. SVGTextContentElement: C,
  8182. SVGTextElement: C,
  8183. SVGTextPathElement: C,
  8184. SVGTextPositioningElement: C,
  8185. SVGTitleElement: C,
  8186. SVGTransform: C,
  8187. SVGTransformList: C,
  8188. SVGTSpanElement: C,
  8189. SVGUnitTypes: C,
  8190. SVGUseElement: C,
  8191. SVGViewElement: C,
  8192. TaskAttributionTiming: C,
  8193. Text: C,
  8194. TextEvent: C,
  8195. TextMetrics: C,
  8196. TextTrack: C,
  8197. TextTrackCue: C,
  8198. TextTrackCueList: C,
  8199. TextTrackList: C,
  8200. TimeRanges: C,
  8201. toolbar: O,
  8202. top: O,
  8203. Touch: C,
  8204. TouchEvent: C,
  8205. TouchList: C,
  8206. TrackEvent: C,
  8207. TransitionEvent: C,
  8208. TreeWalker: C,
  8209. UIEvent: C,
  8210. ValidityState: C,
  8211. visualViewport: O,
  8212. VisualViewport: C,
  8213. VTTCue: C,
  8214. WaveShaperNode: C,
  8215. WebAssembly: O,
  8216. WebGL2RenderingContext: C,
  8217. WebGLActiveInfo: C,
  8218. WebGLBuffer: C,
  8219. WebGLContextEvent: C,
  8220. WebGLFramebuffer: C,
  8221. WebGLProgram: C,
  8222. WebGLQuery: C,
  8223. WebGLRenderbuffer: C,
  8224. WebGLRenderingContext: C,
  8225. WebGLSampler: C,
  8226. WebGLShader: C,
  8227. WebGLShaderPrecisionFormat: C,
  8228. WebGLSync: C,
  8229. WebGLTexture: C,
  8230. WebGLTransformFeedback: C,
  8231. WebGLUniformLocation: C,
  8232. WebGLVertexArrayObject: C,
  8233. WebSocket: C,
  8234. WheelEvent: C,
  8235. Window: C,
  8236. Worker: C,
  8237. WritableStream: C,
  8238. XMLDocument: C,
  8239. XMLHttpRequest: C,
  8240. XMLHttpRequestEventTarget: C,
  8241. XMLHttpRequestUpload: C,
  8242. XMLSerializer: C,
  8243. XPathEvaluator: C,
  8244. XPathExpression: C,
  8245. XPathResult: C,
  8246. XSLTProcessor: C
  8247. };
  8248. for (const global of ['window', 'global', 'self', 'globalThis']) {
  8249. knownGlobals[global] = knownGlobals;
  8250. }
  8251. function getGlobalAtPath(path) {
  8252. let currentGlobal = knownGlobals;
  8253. for (const pathSegment of path) {
  8254. if (typeof pathSegment !== 'string') {
  8255. return null;
  8256. }
  8257. currentGlobal = currentGlobal[pathSegment];
  8258. if (!currentGlobal) {
  8259. // Well-known symbols very often have a complex meaning and are invoked implicitly by the language.
  8260. // Resolve them to a special value so they can be distinguished and excluded from treeshaking.
  8261. return path[0] === 'Symbol' && path.length === 2 ? UNKNOWN_WELL_KNOWN : null;
  8262. }
  8263. }
  8264. return currentGlobal[ValueProperties];
  8265. }
  8266. class GlobalVariable extends Variable {
  8267. constructor(name) {
  8268. super(name);
  8269. // Ensure we use live-bindings for globals as we do not know if they have
  8270. // been reassigned
  8271. this.markReassigned();
  8272. }
  8273. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8274. switch (interaction.type) {
  8275. // While there is no point in testing these cases as at the moment, they
  8276. // are also covered via other means, we keep them for completeness
  8277. case INTERACTION_ACCESSED:
  8278. case INTERACTION_ASSIGNED: {
  8279. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  8280. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8281. }
  8282. return;
  8283. }
  8284. case INTERACTION_CALLED: {
  8285. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8286. if (globalAtPath) {
  8287. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  8288. }
  8289. else {
  8290. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8291. }
  8292. return;
  8293. }
  8294. }
  8295. }
  8296. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  8297. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8298. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  8299. }
  8300. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8301. switch (interaction.type) {
  8302. case INTERACTION_ACCESSED: {
  8303. if (path.length === 0) {
  8304. // Technically, "undefined" is a global variable of sorts
  8305. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  8306. }
  8307. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  8308. }
  8309. case INTERACTION_ASSIGNED: {
  8310. return true;
  8311. }
  8312. case INTERACTION_CALLED: {
  8313. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8314. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  8315. }
  8316. }
  8317. }
  8318. }
  8319. // To avoid infinite recursions
  8320. const MAX_PATH_DEPTH = 6;
  8321. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  8322. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  8323. const limitConcatenatedPathDepth = (path1, path2) => {
  8324. const { length: length1 } = path1;
  8325. const { length: length2 } = path2;
  8326. return length1 === 0
  8327. ? path2
  8328. : length2 === 0
  8329. ? path1
  8330. : length1 + length2 > MAX_PATH_DEPTH
  8331. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  8332. : [...path1, ...path2];
  8333. };
  8334. class LocalVariable extends Variable {
  8335. constructor(name, declarator, init,
  8336. /** if this is non-empty, the actual init is this path of this.init */
  8337. initPath, context, kind) {
  8338. super(name);
  8339. this.init = init;
  8340. this.initPath = initPath;
  8341. this.kind = kind;
  8342. this.calledFromTryStatement = false;
  8343. this.additionalInitializers = null;
  8344. this.includedPathTracker = new IncludedFullPathTracker();
  8345. this.expressionsToBeDeoptimized = [];
  8346. this.declarations = declarator ? [declarator] : [];
  8347. this.deoptimizationTracker = context.deoptimizationTracker;
  8348. this.module = context.module;
  8349. }
  8350. addDeclaration(identifier, init) {
  8351. this.declarations.push(identifier);
  8352. this.markInitializersForDeoptimization().push(init);
  8353. }
  8354. consolidateInitializers() {
  8355. if (this.additionalInitializers) {
  8356. for (const initializer of this.additionalInitializers) {
  8357. initializer.deoptimizePath(UNKNOWN_PATH);
  8358. }
  8359. }
  8360. }
  8361. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8362. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8363. deoptimizeInteraction(interaction);
  8364. return;
  8365. }
  8366. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8367. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  8368. }, undefined);
  8369. }
  8370. deoptimizePath(path) {
  8371. if (this.isReassigned ||
  8372. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8373. return;
  8374. }
  8375. if (path.length === 0) {
  8376. this.markReassigned();
  8377. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  8378. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  8379. for (const expression of expressionsToBeDeoptimized) {
  8380. expression.deoptimizeCache();
  8381. }
  8382. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  8383. }
  8384. else {
  8385. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  8386. }
  8387. }
  8388. getLiteralValueAtPath(path, recursionTracker, origin) {
  8389. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8390. return UnknownValue;
  8391. }
  8392. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8393. this.expressionsToBeDeoptimized.push(origin);
  8394. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  8395. }, UnknownValue);
  8396. }
  8397. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8398. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8399. return UNKNOWN_RETURN_EXPRESSION;
  8400. }
  8401. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8402. this.expressionsToBeDeoptimized.push(origin);
  8403. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  8404. }, UNKNOWN_RETURN_EXPRESSION);
  8405. }
  8406. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8407. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8408. return true;
  8409. }
  8410. switch (interaction.type) {
  8411. case INTERACTION_ACCESSED: {
  8412. if (this.isReassigned)
  8413. return true;
  8414. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  8415. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8416. }
  8417. case INTERACTION_ASSIGNED: {
  8418. if (this.included)
  8419. return true;
  8420. if (path.length === 0)
  8421. return false;
  8422. // if (this.isReassigned || this.init.included) return true;
  8423. if (this.isReassigned)
  8424. return true;
  8425. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  8426. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8427. }
  8428. case INTERACTION_CALLED: {
  8429. if (this.isReassigned)
  8430. return true;
  8431. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  8432. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8433. }
  8434. }
  8435. }
  8436. includePath(path, context) {
  8437. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  8438. this.module.scope.context.requestTreeshakingPass();
  8439. if (!this.included) {
  8440. // This will reduce the number of tree-shaking passes by eagerly
  8441. // including inits. By pushing this here instead of directly including
  8442. // we avoid deep call stacks.
  8443. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  8444. }
  8445. super.includePath(path, context);
  8446. for (const declaration of this.declarations) {
  8447. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  8448. if (!declaration.included)
  8449. declaration.include(context, false);
  8450. let node = declaration.parent;
  8451. while (!node.included) {
  8452. // We do not want to properly include parents in case they are part of a dead branch
  8453. // in which case .include() might pull in more dead code
  8454. node.includeNode(context);
  8455. if (node.type === parseAst_js.Program)
  8456. break;
  8457. node = node.parent;
  8458. }
  8459. }
  8460. // We need to make sure we include the correct path of the init
  8461. if (path.length > 0) {
  8462. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  8463. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  8464. }
  8465. }
  8466. }
  8467. includeCallArguments(interaction, context) {
  8468. if (this.isReassigned ||
  8469. context.includedCallArguments.has(this.init) ||
  8470. // This can be removed again once we can include arguments when called at
  8471. // a specific path
  8472. this.initPath.length > 0) {
  8473. includeInteraction(interaction, context);
  8474. }
  8475. else {
  8476. context.includedCallArguments.add(this.init);
  8477. this.init.includeCallArguments(interaction, context);
  8478. context.includedCallArguments.delete(this.init);
  8479. }
  8480. }
  8481. markCalledFromTryStatement() {
  8482. this.calledFromTryStatement = true;
  8483. }
  8484. markInitializersForDeoptimization() {
  8485. if (this.additionalInitializers === null) {
  8486. this.additionalInitializers = [this.init];
  8487. this.init = UNKNOWN_EXPRESSION;
  8488. this.markReassigned();
  8489. }
  8490. return this.additionalInitializers;
  8491. }
  8492. }
  8493. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  8494. class IdentifierBase extends NodeBase {
  8495. constructor() {
  8496. super(...arguments);
  8497. this.variable = null;
  8498. this.isVariableReference = false;
  8499. }
  8500. get isTDZAccess() {
  8501. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  8502. return null;
  8503. }
  8504. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  8505. }
  8506. set isTDZAccess(value) {
  8507. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  8508. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  8509. }
  8510. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8511. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8512. }
  8513. deoptimizePath(path) {
  8514. if (path.length === 0 && !this.scope.contains(this.name)) {
  8515. this.disallowImportReassignment();
  8516. }
  8517. // We keep conditional chaining because an unknown Node could have an
  8518. // Identifier as property that might be deoptimized by default
  8519. this.variable?.deoptimizePath(path);
  8520. }
  8521. getLiteralValueAtPath(path, recursionTracker, origin) {
  8522. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  8523. }
  8524. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8525. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8526. return [expression, isPure || this.isPureFunction(path)];
  8527. }
  8528. hasEffects(context) {
  8529. if (!this.deoptimized)
  8530. this.applyDeoptimizations();
  8531. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  8532. return true;
  8533. }
  8534. return (this.scope.context.options.treeshake
  8535. .unknownGlobalSideEffects &&
  8536. this.variable instanceof GlobalVariable &&
  8537. !this.isPureFunction(EMPTY_PATH) &&
  8538. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8539. }
  8540. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8541. switch (interaction.type) {
  8542. case INTERACTION_ACCESSED: {
  8543. return (this.variable !== null &&
  8544. !this.isPureFunction(path) &&
  8545. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8546. }
  8547. case INTERACTION_ASSIGNED: {
  8548. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  8549. }
  8550. case INTERACTION_CALLED: {
  8551. return (!this.isPureFunction(path) &&
  8552. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8553. }
  8554. }
  8555. }
  8556. include(context, includeChildrenRecursively) {
  8557. if (!this.included)
  8558. this.includeNode(context);
  8559. if (includeChildrenRecursively) {
  8560. this.variable?.includePath(UNKNOWN_PATH, context);
  8561. }
  8562. }
  8563. includeNode(context) {
  8564. this.included = true;
  8565. if (!this.deoptimized)
  8566. this.applyDeoptimizations();
  8567. if (this.variable !== null) {
  8568. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8569. }
  8570. }
  8571. includePath(path, context) {
  8572. if (!this.included) {
  8573. this.included = true;
  8574. if (!this.deoptimized)
  8575. this.applyDeoptimizations();
  8576. if (this.variable !== null) {
  8577. this.scope.context.includeVariableInModule(this.variable, path, context);
  8578. }
  8579. }
  8580. else if (path.length > 0) {
  8581. this.variable?.includePath(path, context);
  8582. }
  8583. }
  8584. includeCallArguments(interaction, context) {
  8585. this.variable.includeCallArguments(interaction, context);
  8586. }
  8587. isPossibleTDZ() {
  8588. // return cached value to avoid issues with the next tree-shaking pass
  8589. const cachedTdzAccess = this.isTDZAccess;
  8590. if (cachedTdzAccess !== null)
  8591. return cachedTdzAccess;
  8592. if (!(this.variable instanceof LocalVariable &&
  8593. this.variable.kind &&
  8594. tdzVariableKinds.has(this.variable.kind) &&
  8595. // We ignore modules that did not receive a treeshaking pass yet as that
  8596. // causes many false positives due to circular dependencies or disabled
  8597. // moduleSideEffects.
  8598. this.variable.module.hasTreeShakingPassStarted)) {
  8599. return (this.isTDZAccess = false);
  8600. }
  8601. let decl_id;
  8602. if (this.variable.declarations &&
  8603. this.variable.declarations.length === 1 &&
  8604. (decl_id = this.variable.declarations[0]) &&
  8605. this.start < decl_id.start &&
  8606. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  8607. // a variable accessed before its declaration
  8608. // in the same function or at top level of module
  8609. return (this.isTDZAccess = true);
  8610. }
  8611. if (!this.variable.initReached) {
  8612. // Either a const/let TDZ violation or
  8613. // var use before declaration was encountered.
  8614. return (this.isTDZAccess = true);
  8615. }
  8616. return (this.isTDZAccess = false);
  8617. }
  8618. applyDeoptimizations() {
  8619. this.deoptimized = true;
  8620. if (this.variable instanceof LocalVariable) {
  8621. // When accessing a variable from a module without side effects, this
  8622. // means we use an export of that module and therefore need to potentially
  8623. // include it in the bundle.
  8624. if (!this.variable.module.isExecuted) {
  8625. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  8626. }
  8627. this.variable.consolidateInitializers();
  8628. this.scope.context.requestTreeshakingPass();
  8629. }
  8630. if (this.isVariableReference) {
  8631. this.variable.addUsedPlace(this);
  8632. this.scope.context.requestTreeshakingPass();
  8633. }
  8634. }
  8635. disallowImportReassignment() {
  8636. return this.scope.context.error(parseAst_js.logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  8637. }
  8638. getVariableRespectingTDZ() {
  8639. if (this.isPossibleTDZ()) {
  8640. return UNKNOWN_EXPRESSION;
  8641. }
  8642. return this.variable;
  8643. }
  8644. isPureFunction(path) {
  8645. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  8646. for (const segment of path) {
  8647. if (currentPureFunction) {
  8648. if (currentPureFunction[PureFunctionKey]) {
  8649. return true;
  8650. }
  8651. currentPureFunction = currentPureFunction[segment];
  8652. }
  8653. else {
  8654. return false;
  8655. }
  8656. }
  8657. return currentPureFunction?.[PureFunctionKey];
  8658. }
  8659. }
  8660. function closestParentFunctionOrProgram(node) {
  8661. while (node && !/^Program|Function/.test(node.type)) {
  8662. node = node.parent;
  8663. }
  8664. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  8665. return node;
  8666. }
  8667. class ObjectMember extends ExpressionEntity {
  8668. constructor(object, path) {
  8669. super();
  8670. this.object = object;
  8671. this.path = path;
  8672. }
  8673. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8674. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  8675. }
  8676. deoptimizePath(path) {
  8677. this.object.deoptimizePath([...this.path, ...path]);
  8678. }
  8679. getLiteralValueAtPath(path, recursionTracker, origin) {
  8680. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  8681. }
  8682. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8683. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  8684. }
  8685. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8686. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  8687. }
  8688. }
  8689. class Identifier extends IdentifierBase {
  8690. constructor() {
  8691. super(...arguments);
  8692. this.variable = null;
  8693. }
  8694. get isDestructuringDeoptimized() {
  8695. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  8696. }
  8697. set isDestructuringDeoptimized(value) {
  8698. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  8699. }
  8700. addExportedVariables(variables, exportNamesByVariable) {
  8701. if (exportNamesByVariable.has(this.variable)) {
  8702. variables.push(this.variable);
  8703. }
  8704. }
  8705. bind() {
  8706. if (!this.variable && is_reference(this, this.parent)) {
  8707. this.variable = this.scope.findVariable(this.name);
  8708. this.variable.addReference(this);
  8709. this.isVariableReference = true;
  8710. }
  8711. }
  8712. declare(kind, destructuredInitPath, init) {
  8713. let variable;
  8714. const { treeshake } = this.scope.context.options;
  8715. if (kind === 'parameter') {
  8716. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  8717. }
  8718. else {
  8719. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  8720. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  8721. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  8722. variable.markInitializersForDeoptimization();
  8723. }
  8724. }
  8725. return [(this.variable = variable)];
  8726. }
  8727. deoptimizeAssignment(destructuredInitPath, init) {
  8728. this.deoptimizePath(EMPTY_PATH);
  8729. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  8730. }
  8731. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  8732. return (destructuredInitPath.length > 0 &&
  8733. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8734. }
  8735. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  8736. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  8737. this.isDestructuringDeoptimized = true;
  8738. init.deoptimizeArgumentsOnInteractionAtPath({
  8739. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  8740. type: INTERACTION_ACCESSED
  8741. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  8742. }
  8743. const { propertyReadSideEffects } = this.scope.context.options
  8744. .treeshake;
  8745. let included = this.included;
  8746. if ((included ||=
  8747. destructuredInitPath.length > 0 &&
  8748. !context.brokenFlow &&
  8749. propertyReadSideEffects &&
  8750. (propertyReadSideEffects === 'always' ||
  8751. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  8752. if (this.variable && !this.variable.included) {
  8753. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8754. }
  8755. init.includePath(destructuredInitPath, context);
  8756. }
  8757. if (!this.included && included) {
  8758. this.includeNode(context);
  8759. }
  8760. return this.included;
  8761. }
  8762. markDeclarationReached() {
  8763. this.variable.initReached = true;
  8764. }
  8765. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = parseAst_js.BLANK) {
  8766. if (this.variable) {
  8767. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  8768. if (name !== this.name) {
  8769. code.overwrite(this.start, this.end, name, {
  8770. contentOnly: true,
  8771. storeName: true
  8772. });
  8773. if (isShorthandProperty) {
  8774. code.prependRight(this.start, `${this.name}: `);
  8775. }
  8776. }
  8777. // In strict mode, any variable named "eval" must be the actual "eval" function
  8778. if (name === 'eval' &&
  8779. renderedParentType === parseAst_js.CallExpression &&
  8780. isCalleeOfRenderedParent) {
  8781. code.appendRight(this.start, '0, ');
  8782. }
  8783. }
  8784. }
  8785. }
  8786. function getSafeName(baseName, usedNames, forbiddenNames) {
  8787. let safeName = baseName;
  8788. let count = 1;
  8789. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  8790. safeName = `${baseName}$${toBase64(count++)}`;
  8791. }
  8792. usedNames.add(safeName);
  8793. return safeName;
  8794. }
  8795. class Scope {
  8796. constructor() {
  8797. this.children = [];
  8798. this.variables = new Map();
  8799. }
  8800. /*
  8801. Redeclaration rules:
  8802. - var can redeclare var
  8803. - in function scopes, function and var can redeclare function and var
  8804. - var is hoisted across scopes, function remains in the scope it is declared
  8805. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  8806. - function cannot redeclare catch scope parameters
  8807. - var can redeclare catch scope parameters in a way
  8808. - if the parameter is an identifier and not a pattern
  8809. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  8810. - const, let, class, and function except in the cases above cannot redeclare anything
  8811. */
  8812. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  8813. const name = identifier.name;
  8814. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  8815. if (existingVariable) {
  8816. if (kind === 'var' && existingVariable.kind === 'var') {
  8817. existingVariable.addDeclaration(identifier, init);
  8818. return existingVariable;
  8819. }
  8820. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  8821. }
  8822. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  8823. this.variables.set(name, newVariable);
  8824. return newVariable;
  8825. }
  8826. addHoistedVariable(name, variable) {
  8827. (this.hoistedVariables ||= new Map()).set(name, variable);
  8828. }
  8829. contains(name) {
  8830. return this.variables.has(name);
  8831. }
  8832. findVariable(_name) {
  8833. /* istanbul ignore next */
  8834. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  8835. }
  8836. }
  8837. class ChildScope extends Scope {
  8838. constructor(parent, context) {
  8839. super();
  8840. this.parent = parent;
  8841. this.context = context;
  8842. this.accessedOutsideVariables = new Map();
  8843. parent.children.push(this);
  8844. }
  8845. addAccessedDynamicImport(importExpression) {
  8846. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  8847. if (this.parent instanceof ChildScope) {
  8848. this.parent.addAccessedDynamicImport(importExpression);
  8849. }
  8850. }
  8851. addAccessedGlobals(globals, accessedGlobalsByScope) {
  8852. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  8853. for (const name of globals) {
  8854. accessedGlobals.add(name);
  8855. }
  8856. accessedGlobalsByScope.set(this, accessedGlobals);
  8857. if (this.parent instanceof ChildScope) {
  8858. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  8859. }
  8860. }
  8861. addNamespaceMemberAccess(name, variable) {
  8862. this.accessedOutsideVariables.set(name, variable);
  8863. this.parent.addNamespaceMemberAccess(name, variable);
  8864. }
  8865. addReturnExpression(expression) {
  8866. if (this.parent instanceof ChildScope) {
  8867. this.parent.addReturnExpression(expression);
  8868. }
  8869. }
  8870. addUsedOutsideNames(usedNames, accessedGlobalsByScope) {
  8871. for (const variable of this.accessedOutsideVariables.values()) {
  8872. if (variable.included) {
  8873. usedNames.add(variable.getBaseVariableName());
  8874. }
  8875. }
  8876. const accessedGlobals = accessedGlobalsByScope.get(this);
  8877. if (accessedGlobals) {
  8878. for (const name of accessedGlobals) {
  8879. usedNames.add(name);
  8880. }
  8881. }
  8882. }
  8883. contains(name) {
  8884. return this.variables.has(name) || this.parent.contains(name);
  8885. }
  8886. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8887. const usedNames = new Set();
  8888. this.addUsedOutsideNames(usedNames, accessedGlobalsByScope);
  8889. if (this.accessedDynamicImports) {
  8890. for (const importExpression of this.accessedDynamicImports) {
  8891. if (importExpression.inlineNamespace) {
  8892. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  8893. }
  8894. }
  8895. }
  8896. for (const [name, variable] of this.variables) {
  8897. if (variable.included || variable.alwaysRendered) {
  8898. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  8899. }
  8900. }
  8901. for (const scope of this.children) {
  8902. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8903. }
  8904. }
  8905. findLexicalBoundary() {
  8906. return this.parent.findLexicalBoundary();
  8907. }
  8908. findGlobal(name) {
  8909. const variable = this.parent.findVariable(name);
  8910. this.accessedOutsideVariables.set(name, variable);
  8911. return variable;
  8912. }
  8913. findVariable(name) {
  8914. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8915. if (knownVariable) {
  8916. return knownVariable;
  8917. }
  8918. const variable = this.parent.findVariable(name);
  8919. this.accessedOutsideVariables.set(name, variable);
  8920. return variable;
  8921. }
  8922. }
  8923. function checkEffectForNodes(nodes, context) {
  8924. for (const node of nodes) {
  8925. if (node.hasEffects(context)) {
  8926. return true;
  8927. }
  8928. }
  8929. return false;
  8930. }
  8931. class MethodBase extends NodeBase {
  8932. constructor() {
  8933. super(...arguments);
  8934. this.accessedValue = null;
  8935. }
  8936. get computed() {
  8937. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  8938. }
  8939. set computed(value) {
  8940. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  8941. }
  8942. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8943. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8944. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8945. args: interaction.args,
  8946. type: INTERACTION_CALLED,
  8947. withNew: false
  8948. }, EMPTY_PATH, recursionTracker);
  8949. }
  8950. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8951. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8952. args: interaction.args,
  8953. type: INTERACTION_CALLED,
  8954. withNew: false
  8955. }, EMPTY_PATH, recursionTracker);
  8956. }
  8957. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8958. }
  8959. // As getter properties directly receive their values from fixed function
  8960. // expressions, there is no known situation where a getter is deoptimized.
  8961. deoptimizeCache() { }
  8962. deoptimizePath(path) {
  8963. this.getAccessedValue()[0].deoptimizePath(path);
  8964. }
  8965. getLiteralValueAtPath(path, recursionTracker, origin) {
  8966. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  8967. }
  8968. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8969. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8970. }
  8971. hasEffects(context) {
  8972. return this.key.hasEffects(context);
  8973. }
  8974. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8975. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8976. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8977. args: interaction.args,
  8978. type: INTERACTION_CALLED,
  8979. withNew: false
  8980. }, context);
  8981. }
  8982. // setters are only called for empty paths
  8983. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8984. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8985. args: interaction.args,
  8986. type: INTERACTION_CALLED,
  8987. withNew: false
  8988. }, context);
  8989. }
  8990. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  8991. }
  8992. getAccessedValue() {
  8993. if (this.accessedValue === null) {
  8994. if (this.kind === 'get') {
  8995. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  8996. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8997. }
  8998. else {
  8999. return (this.accessedValue = [this.value, false]);
  9000. }
  9001. }
  9002. return this.accessedValue;
  9003. }
  9004. }
  9005. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9006. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  9007. class MethodDefinition extends MethodBase {
  9008. hasEffects(context) {
  9009. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  9010. }
  9011. }
  9012. class BlockScope extends ChildScope {
  9013. constructor(parent) {
  9014. super(parent, parent.context);
  9015. }
  9016. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9017. if (kind === 'var') {
  9018. const name = identifier.name;
  9019. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9020. if (existingVariable) {
  9021. if (existingVariable.kind === 'var' ||
  9022. (kind === 'var' && existingVariable.kind === 'parameter')) {
  9023. existingVariable.addDeclaration(identifier, init);
  9024. return existingVariable;
  9025. }
  9026. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9027. }
  9028. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9029. // Necessary to make sure the init is deoptimized for conditional declarations.
  9030. // We cannot call deoptimizePath here.
  9031. declaredVariable.markInitializersForDeoptimization();
  9032. // We add the variable to this and all parent scopes to reliably detect conflicts
  9033. this.addHoistedVariable(name, declaredVariable);
  9034. return declaredVariable;
  9035. }
  9036. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9037. }
  9038. }
  9039. class StaticBlock extends NodeBase {
  9040. createScope(parentScope) {
  9041. this.scope = new BlockScope(parentScope);
  9042. }
  9043. hasEffects(context) {
  9044. for (const node of this.body) {
  9045. if (node.hasEffects(context))
  9046. return true;
  9047. }
  9048. return false;
  9049. }
  9050. include(context, includeChildrenRecursively) {
  9051. this.included = true;
  9052. for (const node of this.body) {
  9053. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9054. node.include(context, includeChildrenRecursively);
  9055. }
  9056. }
  9057. render(code, options) {
  9058. if (this.body.length > 0) {
  9059. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  9060. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  9061. }
  9062. else {
  9063. super.render(code, options);
  9064. }
  9065. }
  9066. }
  9067. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9068. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  9069. function isStaticBlock(statement) {
  9070. return statement.type === parseAst_js.StaticBlock;
  9071. }
  9072. class ClassNode extends NodeBase {
  9073. constructor() {
  9074. super(...arguments);
  9075. this.objectEntity = null;
  9076. }
  9077. createScope(parentScope) {
  9078. this.scope = new ChildScope(parentScope, parentScope.context);
  9079. }
  9080. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9081. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9082. }
  9083. deoptimizeCache() {
  9084. this.getObjectEntity().deoptimizeAllProperties();
  9085. }
  9086. deoptimizePath(path) {
  9087. this.getObjectEntity().deoptimizePath(path);
  9088. }
  9089. getLiteralValueAtPath(path, recursionTracker, origin) {
  9090. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9091. }
  9092. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9093. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9094. }
  9095. hasEffects(context) {
  9096. if (!this.deoptimized)
  9097. this.applyDeoptimizations();
  9098. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  9099. this.id?.markDeclarationReached();
  9100. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  9101. }
  9102. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9103. return interaction.type === INTERACTION_CALLED && path.length === 0
  9104. ? !interaction.withNew ||
  9105. (this.classConstructor === null
  9106. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  9107. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  9108. false
  9109. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9110. }
  9111. include(context, includeChildrenRecursively) {
  9112. if (!this.included)
  9113. this.includeNode(context);
  9114. this.superClass?.include(context, includeChildrenRecursively);
  9115. this.body.include(context, includeChildrenRecursively);
  9116. for (const decorator of this.decorators)
  9117. decorator.include(context, includeChildrenRecursively);
  9118. if (this.id) {
  9119. this.id.markDeclarationReached();
  9120. this.id.include(context, includeChildrenRecursively);
  9121. }
  9122. }
  9123. initialise() {
  9124. super.initialise();
  9125. this.id?.declare('class', EMPTY_PATH, this);
  9126. for (const method of this.body.body) {
  9127. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  9128. this.classConstructor = method;
  9129. return;
  9130. }
  9131. }
  9132. this.classConstructor = null;
  9133. }
  9134. applyDeoptimizations() {
  9135. this.deoptimized = true;
  9136. for (const definition of this.body.body) {
  9137. if (!isStaticBlock(definition) &&
  9138. !(definition.static ||
  9139. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  9140. // Calls to methods are not tracked, ensure that the return value is deoptimized
  9141. definition.deoptimizePath(UNKNOWN_PATH);
  9142. }
  9143. }
  9144. this.scope.context.requestTreeshakingPass();
  9145. }
  9146. getObjectEntity() {
  9147. if (this.objectEntity !== null) {
  9148. return this.objectEntity;
  9149. }
  9150. const staticProperties = [];
  9151. const dynamicMethods = [];
  9152. for (const definition of this.body.body) {
  9153. if (isStaticBlock(definition))
  9154. continue;
  9155. const properties = definition.static ? staticProperties : dynamicMethods;
  9156. const definitionKind = definition.kind;
  9157. // Note that class fields do not end up on the prototype
  9158. if (properties === dynamicMethods && !definitionKind)
  9159. continue;
  9160. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  9161. let key;
  9162. if (definition.computed) {
  9163. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9164. if (typeof keyValue === 'symbol') {
  9165. properties.push({
  9166. key: isAnyWellKnown(keyValue) ? keyValue : UnknownKey,
  9167. kind,
  9168. property: definition
  9169. });
  9170. continue;
  9171. }
  9172. else {
  9173. key = String(keyValue);
  9174. }
  9175. }
  9176. else {
  9177. key =
  9178. definition.key instanceof Identifier
  9179. ? definition.key.name
  9180. : String(definition.key.value);
  9181. }
  9182. properties.push({ key, kind, property: definition });
  9183. }
  9184. staticProperties.unshift({
  9185. key: 'prototype',
  9186. kind: 'init',
  9187. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  9188. });
  9189. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  9190. }
  9191. }
  9192. ClassNode.prototype.includeNode = onlyIncludeSelf;
  9193. class ClassDeclaration extends ClassNode {
  9194. initialise() {
  9195. super.initialise();
  9196. if (this.id !== null) {
  9197. this.id.variable.isId = true;
  9198. }
  9199. }
  9200. parseNode(esTreeNode) {
  9201. if (esTreeNode.id !== null) {
  9202. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  9203. }
  9204. return super.parseNode(esTreeNode);
  9205. }
  9206. render(code, options) {
  9207. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  9208. if (this.id) {
  9209. const { variable, name } = this.id;
  9210. if (format === 'system' && exportNamesByVariable.has(variable)) {
  9211. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  9212. }
  9213. const renderedVariable = variable.getName(getPropertyAccess);
  9214. if (renderedVariable !== name) {
  9215. this.decorators.map(decorator => decorator.render(code, options));
  9216. this.superClass?.render(code, options);
  9217. this.body.render(code, {
  9218. ...options,
  9219. useOriginalName: (_variable) => _variable === variable
  9220. });
  9221. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  9222. code.prependLeft(this.end, ';');
  9223. return;
  9224. }
  9225. }
  9226. super.render(code, options);
  9227. }
  9228. applyDeoptimizations() {
  9229. super.applyDeoptimizations();
  9230. const { id, scope } = this;
  9231. if (id) {
  9232. const { name, variable } = id;
  9233. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  9234. if (accessedVariable !== variable) {
  9235. accessedVariable.forbidName(name);
  9236. }
  9237. }
  9238. }
  9239. }
  9240. }
  9241. class ArgumentsVariable extends LocalVariable {
  9242. constructor(context) {
  9243. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  9244. }
  9245. addArgumentToBeDeoptimized(_argument) { }
  9246. // Only If there is at least one reference, then we need to track all
  9247. // arguments in order to be able to deoptimize them.
  9248. addReference() {
  9249. this.deoptimizedArguments = [];
  9250. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  9251. }
  9252. hasEffectsOnInteractionAtPath(path, { type }) {
  9253. return type !== INTERACTION_ACCESSED || path.length > 1;
  9254. }
  9255. includePath(path, context) {
  9256. super.includePath(path, context);
  9257. for (const argument of this.deoptimizedArguments) {
  9258. argument.deoptimizePath(UNKNOWN_PATH);
  9259. }
  9260. this.deoptimizedArguments.length = 0;
  9261. }
  9262. }
  9263. function addArgumentToBeDeoptimized(argument) {
  9264. if (this.included) {
  9265. argument.deoptimizePath(UNKNOWN_PATH);
  9266. }
  9267. else {
  9268. this.deoptimizedArguments?.push(argument);
  9269. }
  9270. }
  9271. const MAX_TRACKED_INTERACTIONS = 20;
  9272. const NO_INTERACTIONS = parseAst_js.EMPTY_ARRAY;
  9273. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  9274. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  9275. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  9276. class ParameterVariable extends LocalVariable {
  9277. constructor(name, declarator, argumentPath, context) {
  9278. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  9279. this.includedPathTracker = new IncludedTopLevelPathTracker();
  9280. this.argumentsToBeDeoptimized = new Set();
  9281. this.deoptimizationInteractions = [];
  9282. this.deoptimizations = new EntityPathTracker();
  9283. this.deoptimizedFields = new Set();
  9284. this.expressionsDependingOnKnownValue = [];
  9285. this.knownValue = null;
  9286. this.knownValueLiteral = UnknownValue;
  9287. }
  9288. addArgumentForDeoptimization(entity) {
  9289. this.updateKnownValue(entity);
  9290. if (entity === UNKNOWN_EXPRESSION) {
  9291. // As unknown expressions fully deoptimize all interactions, we can clear
  9292. // the interaction cache at this point provided we keep this optimization
  9293. // in mind when adding new interactions
  9294. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  9295. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  9296. for (const { interaction } of this.deoptimizationInteractions) {
  9297. deoptimizeInteraction(interaction);
  9298. }
  9299. this.deoptimizationInteractions = NO_INTERACTIONS;
  9300. }
  9301. }
  9302. else if (this.deoptimizedFields.has(UnknownKey)) {
  9303. // This means that we already deoptimized all interactions and no longer
  9304. // track them
  9305. entity.deoptimizePath([...this.initPath, UnknownKey]);
  9306. }
  9307. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  9308. this.argumentsToBeDeoptimized.add(entity);
  9309. for (const field of this.deoptimizedFields) {
  9310. entity.deoptimizePath([...this.initPath, field]);
  9311. }
  9312. for (const { interaction, path } of this.deoptimizationInteractions) {
  9313. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  9314. }
  9315. }
  9316. }
  9317. /** This says we should not make assumptions about the value of the parameter.
  9318. * This is different from deoptimization that will also cause argument values
  9319. * to be deoptimized. */
  9320. markReassigned() {
  9321. if (this.isReassigned) {
  9322. return;
  9323. }
  9324. super.markReassigned();
  9325. for (const expression of this.expressionsDependingOnKnownValue) {
  9326. expression.deoptimizeCache();
  9327. }
  9328. this.expressionsDependingOnKnownValue = parseAst_js.EMPTY_ARRAY;
  9329. }
  9330. deoptimizeCache() {
  9331. this.markReassigned();
  9332. }
  9333. /**
  9334. * Update the known value of the parameter variable.
  9335. * Must be called for every function call, so it can track all the arguments,
  9336. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  9337. * @param argument The argument of the function call
  9338. */
  9339. updateKnownValue(argument) {
  9340. if (this.isReassigned) {
  9341. return;
  9342. }
  9343. if (this.knownValue === null) {
  9344. this.knownValue = argument;
  9345. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  9346. return;
  9347. }
  9348. // the same literal or identifier, do nothing
  9349. if (this.knownValue === argument ||
  9350. (this.knownValue instanceof Identifier &&
  9351. argument instanceof Identifier &&
  9352. this.knownValue.variable === argument.variable)) {
  9353. return;
  9354. }
  9355. const { knownValueLiteral } = this;
  9356. if (typeof knownValueLiteral === 'symbol' ||
  9357. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  9358. knownValueLiteral) {
  9359. this.markReassigned();
  9360. }
  9361. }
  9362. /**
  9363. * This function freezes the known value of the parameter variable,
  9364. * so the optimization starts with a certain ExpressionEntity.
  9365. * The optimization can be undone by calling `markReassigned`.
  9366. * @returns the frozen value
  9367. */
  9368. getKnownValue() {
  9369. return this.knownValue || UNKNOWN_EXPRESSION;
  9370. }
  9371. getLiteralValueAtPath(path, recursionTracker, origin) {
  9372. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9373. return UnknownValue;
  9374. }
  9375. const knownValue = this.getKnownValue();
  9376. this.expressionsDependingOnKnownValue.push(origin);
  9377. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  9378. }
  9379. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9380. const { type } = interaction;
  9381. if (this.isReassigned ||
  9382. type === INTERACTION_ASSIGNED ||
  9383. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9384. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  9385. }
  9386. return (!(type === INTERACTION_CALLED
  9387. ? (interaction.withNew
  9388. ? context.instantiated
  9389. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  9390. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  9391. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  9392. }
  9393. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  9394. // For performance reasons, we fully deoptimize all deeper interactions
  9395. if (path.length >= 2 ||
  9396. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  9397. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  9398. (path.length === 1 &&
  9399. (this.deoptimizedFields.has(UnknownKey) ||
  9400. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  9401. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  9402. deoptimizeInteraction(interaction);
  9403. return;
  9404. }
  9405. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  9406. for (const entity of this.argumentsToBeDeoptimized) {
  9407. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  9408. }
  9409. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  9410. this.deoptimizationInteractions.push({
  9411. interaction,
  9412. path
  9413. });
  9414. }
  9415. }
  9416. }
  9417. deoptimizePath(path) {
  9418. if (path.length === 0) {
  9419. this.markReassigned();
  9420. return;
  9421. }
  9422. if (this.deoptimizedFields.has(UnknownKey)) {
  9423. return;
  9424. }
  9425. const key = path[0];
  9426. if (this.deoptimizedFields.has(key)) {
  9427. return;
  9428. }
  9429. this.deoptimizedFields.add(key);
  9430. for (const entity of this.argumentsToBeDeoptimized) {
  9431. // We do not need a recursion tracker here as we already track whether
  9432. // this field is deoptimized
  9433. entity.deoptimizePath([...this.initPath, key]);
  9434. }
  9435. if (key === UnknownKey) {
  9436. // save some memory
  9437. this.deoptimizationInteractions = NO_INTERACTIONS;
  9438. this.deoptimizations = EMPTY_PATH_TRACKER;
  9439. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  9440. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  9441. }
  9442. }
  9443. getReturnExpressionWhenCalledAtPath(path) {
  9444. // We deoptimize everything that is called as that will trivially deoptimize
  9445. // the corresponding return expressions as well and avoid badly performing
  9446. // and complicated alternatives
  9447. if (path.length === 0) {
  9448. this.deoptimizePath(UNKNOWN_PATH);
  9449. }
  9450. else if (!this.deoptimizedFields.has(path[0])) {
  9451. this.deoptimizePath([path[0]]);
  9452. }
  9453. return UNKNOWN_RETURN_EXPRESSION;
  9454. }
  9455. includeArgumentPaths(entity, context) {
  9456. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  9457. }
  9458. }
  9459. class ThisVariable extends ParameterVariable {
  9460. constructor(context) {
  9461. super('this', null, EMPTY_PATH, context);
  9462. }
  9463. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9464. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  9465. }
  9466. }
  9467. class CatchBodyScope extends ChildScope {
  9468. constructor(parent) {
  9469. super(parent, parent.context);
  9470. this.parent = parent;
  9471. }
  9472. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9473. if (kind === 'var') {
  9474. const name = identifier.name;
  9475. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9476. if (existingVariable) {
  9477. const existingKind = existingVariable.kind;
  9478. if (existingKind === 'parameter' &&
  9479. // If this is a destructured parameter, it is forbidden to redeclare
  9480. existingVariable.declarations[0].parent.type === parseAst_js.CatchClause) {
  9481. // If this is a var with the same name as the catch scope parameter,
  9482. // the assignment actually goes to the parameter and the var is
  9483. // hoisted without assignment. Locally, it is shadowed by the
  9484. // parameter
  9485. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  9486. // To avoid the need to rewrite the declaration, we link the variable
  9487. // names. If we ever implement a logic that splits initialization and
  9488. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  9489. // removed again.
  9490. // We do not need to check whether there already is a linked
  9491. // variable because then declaredVariable would be that linked
  9492. // variable.
  9493. existingVariable.renderLikeHoisted(declaredVariable);
  9494. this.addHoistedVariable(name, declaredVariable);
  9495. return declaredVariable;
  9496. }
  9497. if (existingKind === 'var') {
  9498. existingVariable.addDeclaration(identifier, init);
  9499. return existingVariable;
  9500. }
  9501. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9502. }
  9503. // We only add parameters to parameter scopes
  9504. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9505. // Necessary to make sure the init is deoptimized for conditional declarations.
  9506. // We cannot call deoptimizePath here.
  9507. declaredVariable.markInitializersForDeoptimization();
  9508. // We add the variable to this and all parent scopes to reliably detect conflicts
  9509. this.addHoistedVariable(name, declaredVariable);
  9510. return declaredVariable;
  9511. }
  9512. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9513. }
  9514. }
  9515. class FunctionBodyScope extends ChildScope {
  9516. constructor(parent) {
  9517. super(parent, parent.context);
  9518. }
  9519. // There is stuff that is only allowed in function scopes, i.e. functions can
  9520. // be redeclared, functions and var can redeclare each other
  9521. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9522. const name = identifier.name;
  9523. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9524. if (existingVariable) {
  9525. const existingKind = existingVariable.kind;
  9526. if ((kind === 'var' || kind === 'function') &&
  9527. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  9528. existingVariable.addDeclaration(identifier, init);
  9529. return existingVariable;
  9530. }
  9531. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9532. }
  9533. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  9534. this.variables.set(name, newVariable);
  9535. return newVariable;
  9536. }
  9537. }
  9538. class ParameterScope extends ChildScope {
  9539. constructor(parent, isCatchScope) {
  9540. super(parent, parent.context);
  9541. this.hasRest = false;
  9542. this.parameters = [];
  9543. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  9544. }
  9545. /**
  9546. * Adds a parameter to this scope. Parameters must be added in the correct
  9547. * order, i.e. from left to right.
  9548. */
  9549. addParameterDeclaration(identifier, argumentPath) {
  9550. const { name, start } = identifier;
  9551. const existingParameter = this.variables.get(name);
  9552. if (existingParameter) {
  9553. return this.context.error(parseAst_js.logDuplicateArgumentNameError(name), start);
  9554. }
  9555. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  9556. this.variables.set(name, variable);
  9557. // We also add it to the body scope to detect name conflicts with local
  9558. // variables. We still need the intermediate scope, though, as parameter
  9559. // defaults are NOT taken from the body scope but from the parameters or
  9560. // outside scope.
  9561. this.bodyScope.addHoistedVariable(name, variable);
  9562. return variable;
  9563. }
  9564. addParameterVariables(parameters, hasRest) {
  9565. this.parameters = parameters;
  9566. for (const parameterList of parameters) {
  9567. for (const parameter of parameterList) {
  9568. parameter.alwaysRendered = true;
  9569. }
  9570. }
  9571. this.hasRest = hasRest;
  9572. }
  9573. includeCallArguments({ args }, context) {
  9574. let calledFromTryStatement = false;
  9575. let argumentIncluded = false;
  9576. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  9577. let lastExplicitlyIncludedIndex = args.length - 1;
  9578. // If there is a SpreadElement, we need to include all arguments after it
  9579. // because we no longer know which argument corresponds to which parameter.
  9580. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9581. const argument = args[argumentIndex];
  9582. if (argument instanceof SpreadElement && !argumentIncluded) {
  9583. argumentIncluded = true;
  9584. lastExplicitlyIncludedIndex = argumentIndex - 1;
  9585. }
  9586. if (argumentIncluded) {
  9587. argument.includePath(UNKNOWN_PATH, context);
  9588. argument.include(context, false);
  9589. }
  9590. }
  9591. // Now we go backwards either starting from the last argument or before the
  9592. // first SpreadElement to ensure all arguments before are included as needed
  9593. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  9594. const parameterVariables = this.parameters[index - 1] || restParameter;
  9595. const argument = args[index];
  9596. if (parameterVariables) {
  9597. calledFromTryStatement = false;
  9598. if (parameterVariables.length === 0) {
  9599. // handle empty destructuring to avoid destructuring undefined
  9600. argumentIncluded = true;
  9601. }
  9602. else {
  9603. for (const parameterVariable of parameterVariables) {
  9604. if (parameterVariable.calledFromTryStatement) {
  9605. calledFromTryStatement = true;
  9606. }
  9607. if (parameterVariable.included) {
  9608. argumentIncluded = true;
  9609. if (calledFromTryStatement) {
  9610. argument.include(context, true);
  9611. }
  9612. else {
  9613. parameterVariable.includeArgumentPaths(argument, context);
  9614. argument.include(context, false);
  9615. }
  9616. }
  9617. }
  9618. }
  9619. }
  9620. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  9621. argumentIncluded = true;
  9622. argument.include(context, calledFromTryStatement);
  9623. }
  9624. }
  9625. }
  9626. }
  9627. class ReturnValueScope extends ParameterScope {
  9628. constructor() {
  9629. super(...arguments);
  9630. this.returnExpression = null;
  9631. this.returnExpressions = [];
  9632. }
  9633. addReturnExpression(expression) {
  9634. this.returnExpressions.push(expression);
  9635. }
  9636. deoptimizeArgumentsOnCall({ args }) {
  9637. const { parameters } = this;
  9638. let position = 0;
  9639. for (; position < args.length - 1; position++) {
  9640. // Only the "this" argument arg[0] can be null
  9641. const argument = args[position + 1];
  9642. if (argument instanceof SpreadElement) {
  9643. // This deoptimizes the current and remaining parameters and arguments
  9644. for (; position < parameters.length; position++) {
  9645. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  9646. for (const variable of parameters[position]) {
  9647. variable.markReassigned();
  9648. }
  9649. }
  9650. break;
  9651. }
  9652. if (this.hasRest && position >= parameters.length - 1) {
  9653. argument.deoptimizePath(UNKNOWN_PATH);
  9654. }
  9655. else {
  9656. const variables = parameters[position];
  9657. if (variables) {
  9658. for (const variable of variables) {
  9659. variable.addArgumentForDeoptimization(argument);
  9660. }
  9661. }
  9662. this.addArgumentToBeDeoptimized(argument);
  9663. }
  9664. }
  9665. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  9666. for (; position < nonRestParameterLength; position++) {
  9667. for (const variable of parameters[position]) {
  9668. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  9669. }
  9670. }
  9671. }
  9672. getReturnExpression() {
  9673. if (this.returnExpression === null)
  9674. this.updateReturnExpression();
  9675. return this.returnExpression;
  9676. }
  9677. deoptimizeAllParameters() {
  9678. for (const parameter of this.parameters) {
  9679. for (const variable of parameter) {
  9680. variable.deoptimizePath(UNKNOWN_PATH);
  9681. variable.markReassigned();
  9682. }
  9683. }
  9684. }
  9685. reassignAllParameters() {
  9686. for (const parameter of this.parameters) {
  9687. for (const variable of parameter) {
  9688. variable.markReassigned();
  9689. }
  9690. }
  9691. }
  9692. addArgumentToBeDeoptimized(_argument) { }
  9693. updateReturnExpression() {
  9694. if (this.returnExpressions.length === 1) {
  9695. this.returnExpression = this.returnExpressions[0];
  9696. }
  9697. else {
  9698. this.returnExpression = UNKNOWN_EXPRESSION;
  9699. for (const expression of this.returnExpressions) {
  9700. expression.deoptimizePath(UNKNOWN_PATH);
  9701. }
  9702. }
  9703. }
  9704. }
  9705. class FunctionScope extends ReturnValueScope {
  9706. constructor(parent, functionNode) {
  9707. super(parent, false);
  9708. this.functionNode = functionNode;
  9709. const { context } = parent;
  9710. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  9711. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  9712. }
  9713. findLexicalBoundary() {
  9714. return this;
  9715. }
  9716. includeCallArguments(interaction, context) {
  9717. super.includeCallArguments(interaction, context);
  9718. if (this.argumentsVariable.included) {
  9719. const { args } = interaction;
  9720. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9721. const argument = args[argumentIndex];
  9722. if (argument) {
  9723. argument.includePath(UNKNOWN_PATH, context);
  9724. argument.include(context, false);
  9725. }
  9726. }
  9727. }
  9728. }
  9729. addArgumentToBeDeoptimized(argument) {
  9730. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  9731. }
  9732. }
  9733. class ExpressionStatement extends NodeBase {
  9734. initialise() {
  9735. super.initialise();
  9736. if (this.directive &&
  9737. this.directive !== 'use strict' &&
  9738. this.parent.type === parseAst_js.Program) {
  9739. this.scope.context.log(parseAst_js.LOGLEVEL_WARN,
  9740. // This is necessary, because either way (deleting or not) can lead to errors.
  9741. parseAst_js.logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  9742. }
  9743. }
  9744. removeAnnotations(code) {
  9745. this.expression.removeAnnotations(code);
  9746. }
  9747. render(code, options) {
  9748. super.render(code, options);
  9749. if (code.original[this.end - 1] !== ';') {
  9750. code.appendLeft(this.end, ';');
  9751. }
  9752. }
  9753. shouldBeIncluded(context) {
  9754. if (this.directive && this.directive !== 'use strict')
  9755. return this.parent.type !== parseAst_js.Program;
  9756. return super.shouldBeIncluded(context);
  9757. }
  9758. }
  9759. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9760. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9761. class BlockStatement extends NodeBase {
  9762. get deoptimizeBody() {
  9763. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  9764. }
  9765. set deoptimizeBody(value) {
  9766. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  9767. }
  9768. get directlyIncluded() {
  9769. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  9770. }
  9771. set directlyIncluded(value) {
  9772. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  9773. }
  9774. addImplicitReturnExpressionToScope() {
  9775. const lastStatement = this.body[this.body.length - 1];
  9776. if (!lastStatement || lastStatement.type !== parseAst_js.ReturnStatement) {
  9777. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  9778. }
  9779. }
  9780. createScope(parentScope) {
  9781. this.scope = this.parent.preventChildBlockScope
  9782. ? parentScope
  9783. : new BlockScope(parentScope);
  9784. }
  9785. hasEffects(context) {
  9786. if (this.deoptimizeBody)
  9787. return true;
  9788. for (const node of this.body) {
  9789. if (context.brokenFlow)
  9790. break;
  9791. if (node.hasEffects(context))
  9792. return true;
  9793. }
  9794. return false;
  9795. }
  9796. include(context, includeChildrenRecursively) {
  9797. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  9798. this.included = true;
  9799. this.directlyIncluded = true;
  9800. if (this.deoptimizeBody)
  9801. includeChildrenRecursively = true;
  9802. for (const node of this.body) {
  9803. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9804. node.include(context, includeChildrenRecursively);
  9805. }
  9806. }
  9807. }
  9808. initialise() {
  9809. super.initialise();
  9810. this.scope.context.magicString.addSourcemapLocation(this.end - 1);
  9811. const firstBodyStatement = this.body[0];
  9812. this.deoptimizeBody =
  9813. firstBodyStatement instanceof ExpressionStatement &&
  9814. firstBodyStatement.directive === 'use asm';
  9815. }
  9816. render(code, options) {
  9817. if (this.body.length > 0) {
  9818. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  9819. }
  9820. else {
  9821. super.render(code, options);
  9822. }
  9823. }
  9824. }
  9825. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9826. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9827. class RestElement extends NodeBase {
  9828. constructor() {
  9829. super(...arguments);
  9830. this.declarationInit = null;
  9831. }
  9832. addExportedVariables(variables, exportNamesByVariable) {
  9833. this.argument.addExportedVariables(variables, exportNamesByVariable);
  9834. }
  9835. declare(kind, destructuredInitPath, init) {
  9836. this.declarationInit = init;
  9837. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  9838. }
  9839. deoptimizeAssignment(destructuredInitPath, init) {
  9840. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  9841. }
  9842. deoptimizePath(path) {
  9843. if (path.length === 0) {
  9844. this.argument.deoptimizePath(EMPTY_PATH);
  9845. }
  9846. }
  9847. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9848. return (path.length > 0 ||
  9849. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9850. }
  9851. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  9852. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  9853. }
  9854. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  9855. const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init);
  9856. if (!this.included && included) {
  9857. this.includeNode(context);
  9858. }
  9859. return this.included;
  9860. }
  9861. include(context, includeChildrenRecursively) {
  9862. if (!this.included)
  9863. this.includeNode(context);
  9864. // This should just include the identifier, its properties should be
  9865. // included where the variable is used.
  9866. this.argument.include(context, includeChildrenRecursively);
  9867. }
  9868. markDeclarationReached() {
  9869. this.argument.markDeclarationReached();
  9870. }
  9871. applyDeoptimizations() {
  9872. this.deoptimized = true;
  9873. if (this.declarationInit !== null) {
  9874. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  9875. this.scope.context.requestTreeshakingPass();
  9876. }
  9877. }
  9878. }
  9879. RestElement.prototype.includeNode = onlyIncludeSelf;
  9880. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  9881. ? destructuredInitPath
  9882. : [...destructuredInitPath, UnknownKey];
  9883. class FunctionBase extends NodeBase {
  9884. constructor() {
  9885. super(...arguments);
  9886. this.parameterVariableValuesDeoptimized = false;
  9887. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  9888. }
  9889. get async() {
  9890. return isFlagSet(this.flags, 256 /* Flag.async */);
  9891. }
  9892. set async(value) {
  9893. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  9894. }
  9895. get deoptimizedReturn() {
  9896. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  9897. }
  9898. set deoptimizedReturn(value) {
  9899. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  9900. }
  9901. get generator() {
  9902. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  9903. }
  9904. set generator(value) {
  9905. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  9906. }
  9907. get hasCachedEffects() {
  9908. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  9909. }
  9910. set hasCachedEffects(value) {
  9911. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  9912. }
  9913. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9914. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  9915. this.scope.deoptimizeArgumentsOnCall(interaction);
  9916. }
  9917. else {
  9918. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9919. }
  9920. }
  9921. deoptimizePath(path) {
  9922. this.getObjectEntity().deoptimizePath(path);
  9923. if (path.length === 1 && path[0] === UnknownKey) {
  9924. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  9925. // which means the return expression and parameters need to be reassigned
  9926. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9927. this.scope.deoptimizeAllParameters();
  9928. }
  9929. }
  9930. getLiteralValueAtPath(path, recursionTracker, origin) {
  9931. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9932. }
  9933. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9934. if (path.length > 0) {
  9935. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9936. }
  9937. if (this.async) {
  9938. if (!this.deoptimizedReturn) {
  9939. this.deoptimizedReturn = true;
  9940. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9941. this.scope.context.requestTreeshakingPass();
  9942. }
  9943. return UNKNOWN_RETURN_EXPRESSION;
  9944. }
  9945. return [this.scope.getReturnExpression(), false];
  9946. }
  9947. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9948. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  9949. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9950. }
  9951. if (this.hasCachedEffects) {
  9952. return true;
  9953. }
  9954. if (this.async) {
  9955. const { propertyReadSideEffects } = this.scope.context.options
  9956. .treeshake;
  9957. const returnExpression = this.scope.getReturnExpression();
  9958. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  9959. (propertyReadSideEffects &&
  9960. (propertyReadSideEffects === 'always' ||
  9961. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  9962. this.hasCachedEffects = true;
  9963. return true;
  9964. }
  9965. }
  9966. const { propertyReadSideEffects } = this.scope.context.options
  9967. .treeshake;
  9968. for (let index = 0; index < this.params.length; index++) {
  9969. const parameter = this.params[index];
  9970. if (parameter.hasEffects(context) ||
  9971. (propertyReadSideEffects &&
  9972. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  9973. this.hasCachedEffects = true;
  9974. return true;
  9975. }
  9976. }
  9977. return false;
  9978. }
  9979. /**
  9980. * If the function (expression or declaration) is only used as function calls
  9981. */
  9982. onlyFunctionCallUsed() {
  9983. let variable = null;
  9984. if (this.parent.type === parseAst_js.VariableDeclarator) {
  9985. variable = this.parent.id.variable ?? null;
  9986. }
  9987. if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
  9988. variable = this.parent.variable;
  9989. }
  9990. return variable?.getOnlyFunctionCallUsed() ?? false;
  9991. }
  9992. include(context, includeChildrenRecursively) {
  9993. if (!this.included)
  9994. this.includeNode(context);
  9995. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  9996. this.parameterVariableValuesDeoptimized = true;
  9997. this.scope.reassignAllParameters();
  9998. }
  9999. const { brokenFlow } = context;
  10000. context.brokenFlow = false;
  10001. this.body.include(context, includeChildrenRecursively);
  10002. context.brokenFlow = brokenFlow;
  10003. }
  10004. initialise() {
  10005. super.initialise();
  10006. if (this.body instanceof BlockStatement) {
  10007. this.body.addImplicitReturnExpressionToScope();
  10008. }
  10009. else {
  10010. this.scope.addReturnExpression(this.body);
  10011. }
  10012. if (this.annotations &&
  10013. this.scope.context.options.treeshake.annotations) {
  10014. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  10015. }
  10016. }
  10017. parseNode(esTreeNode) {
  10018. const { body, params } = esTreeNode;
  10019. const { scope } = this;
  10020. const { bodyScope, context } = scope;
  10021. // We need to ensure that parameters are declared before the body is parsed
  10022. // so that the scope already knows all parameters and can detect conflicts
  10023. // when parsing the body.
  10024. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  10025. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  10026. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  10027. return super.parseNode(esTreeNode);
  10028. }
  10029. }
  10030. FunctionBase.prototype.preventChildBlockScope = true;
  10031. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10032. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  10033. class FunctionNode extends FunctionBase {
  10034. constructor() {
  10035. super(...arguments);
  10036. this.objectEntity = null;
  10037. }
  10038. createScope(parentScope) {
  10039. this.scope = new FunctionScope(parentScope, this);
  10040. this.constructedEntity = new ObjectEntity(new Map(), OBJECT_PROTOTYPE);
  10041. // This makes sure that all deoptimizations of "this" are applied to the
  10042. // constructed entity.
  10043. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  10044. }
  10045. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10046. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10047. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  10048. // args[0] is the "this" argument
  10049. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  10050. }
  10051. }
  10052. hasEffects(context) {
  10053. if (this.annotationNoSideEffects) {
  10054. return false;
  10055. }
  10056. return !!this.id?.hasEffects(context);
  10057. }
  10058. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10059. if (this.annotationNoSideEffects &&
  10060. path.length === 0 &&
  10061. interaction.type === INTERACTION_CALLED) {
  10062. return false;
  10063. }
  10064. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10065. return true;
  10066. }
  10067. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  10068. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  10069. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  10070. const { brokenFlow, ignore, replacedVariableInits } = context;
  10071. context.ignore = {
  10072. breaks: false,
  10073. continues: false,
  10074. labels: new Set(),
  10075. returnYield: true,
  10076. this: interaction.withNew
  10077. };
  10078. if (this.body.hasEffects(context)) {
  10079. this.hasCachedEffects = true;
  10080. return true;
  10081. }
  10082. context.brokenFlow = brokenFlow;
  10083. if (thisInit) {
  10084. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  10085. }
  10086. else {
  10087. replacedVariableInits.delete(this.scope.thisVariable);
  10088. }
  10089. context.ignore = ignore;
  10090. }
  10091. return false;
  10092. }
  10093. include(context, includeChildrenRecursively) {
  10094. super.include(context, includeChildrenRecursively);
  10095. this.id?.include(context, includeChildrenRecursively);
  10096. const hasArguments = this.scope.argumentsVariable.included;
  10097. for (const parameter of this.params) {
  10098. if (!(parameter instanceof Identifier) || hasArguments) {
  10099. parameter.include(context, includeChildrenRecursively);
  10100. }
  10101. }
  10102. }
  10103. includeNode(context) {
  10104. this.included = true;
  10105. const hasArguments = this.scope.argumentsVariable.included;
  10106. for (const parameter of this.params) {
  10107. if (!(parameter instanceof Identifier) || hasArguments) {
  10108. parameter.includePath(UNKNOWN_PATH, context);
  10109. }
  10110. }
  10111. }
  10112. initialise() {
  10113. super.initialise();
  10114. this.id?.declare('function', EMPTY_PATH, this);
  10115. }
  10116. getObjectEntity() {
  10117. if (this.objectEntity !== null) {
  10118. return this.objectEntity;
  10119. }
  10120. return (this.objectEntity = new ObjectEntity([
  10121. {
  10122. key: 'prototype',
  10123. kind: 'init',
  10124. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  10125. }
  10126. ], OBJECT_PROTOTYPE));
  10127. }
  10128. }
  10129. class FunctionDeclaration extends FunctionNode {
  10130. initialise() {
  10131. super.initialise();
  10132. if (this.id !== null) {
  10133. this.id.variable.isId = true;
  10134. }
  10135. }
  10136. onlyFunctionCallUsed() {
  10137. // call super.onlyFunctionCallUsed for export default anonymous function
  10138. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  10139. }
  10140. parseNode(esTreeNode) {
  10141. if (esTreeNode.id !== null) {
  10142. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  10143. }
  10144. return super.parseNode(esTreeNode);
  10145. }
  10146. }
  10147. // The header ends at the first non-white-space after "default"
  10148. function getDeclarationStart(code, start) {
  10149. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  10150. }
  10151. function getFunctionIdInsertPosition(code, start) {
  10152. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  10153. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  10154. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  10155. if (generatorStarPos === -1) {
  10156. return declarationEnd;
  10157. }
  10158. return declarationEnd + generatorStarPos + 1;
  10159. }
  10160. class ExportDefaultDeclaration extends NodeBase {
  10161. bind() {
  10162. super.bind();
  10163. const name = this.declarationName || this.scope.context.getModuleName();
  10164. // Check if there's already a variable with the same name in the scope. This
  10165. // can cause inconsistencies when using the cache.
  10166. this.variable.name = this.scope.variables.get(name) ? `${name}_default` : name;
  10167. }
  10168. include(context, includeChildrenRecursively) {
  10169. this.included = true;
  10170. this.declaration.include(context, includeChildrenRecursively);
  10171. if (includeChildrenRecursively) {
  10172. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  10173. }
  10174. }
  10175. includePath(path, context) {
  10176. this.included = true;
  10177. this.declaration.includePath(path, context);
  10178. }
  10179. initialise() {
  10180. super.initialise();
  10181. const declaration = this.declaration;
  10182. this.declarationName =
  10183. (declaration.id && declaration.id.name) || this.declaration.name;
  10184. this.variable = this.scope.addExportDefaultDeclaration(this, this.scope.context);
  10185. this.scope.context.addExport(this);
  10186. }
  10187. removeAnnotations(code) {
  10188. this.declaration.removeAnnotations(code);
  10189. }
  10190. render(code, options, nodeRenderOptions) {
  10191. const { start, end } = nodeRenderOptions;
  10192. const declarationStart = getDeclarationStart(code.original, this.start);
  10193. if (this.declaration instanceof FunctionDeclaration) {
  10194. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  10195. ? getFunctionIdInsertPosition(code.original, declarationStart)
  10196. : null, options);
  10197. }
  10198. else if (this.declaration instanceof ClassDeclaration) {
  10199. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  10200. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  10201. : null, options);
  10202. }
  10203. else if (this.variable.getOriginalVariable() !== this.variable) {
  10204. // Remove altogether to prevent re-declaring the same variable
  10205. treeshakeNode(this, code, start, end);
  10206. return;
  10207. }
  10208. else if (this.variable.included) {
  10209. this.renderVariableDeclaration(code, declarationStart, options);
  10210. }
  10211. else {
  10212. code.remove(this.start, declarationStart);
  10213. this.declaration.render(code, options, {
  10214. renderedSurroundingElement: parseAst_js.ExpressionStatement
  10215. });
  10216. if (code.original[this.end - 1] !== ';') {
  10217. code.appendLeft(this.end, ';');
  10218. }
  10219. return;
  10220. }
  10221. this.declaration.render(code, options);
  10222. }
  10223. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  10224. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  10225. const name = this.variable.getName(getPropertyAccess);
  10226. // Remove `export default`
  10227. code.remove(this.start, declarationStart);
  10228. if (idInsertPosition !== null) {
  10229. code.appendLeft(idInsertPosition, ` ${name}`);
  10230. }
  10231. if (format === 'system' &&
  10232. this.declaration instanceof ClassDeclaration &&
  10233. exportNamesByVariable.has(this.variable)) {
  10234. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  10235. }
  10236. }
  10237. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  10238. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  10239. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  10240. if (systemExportNames) {
  10241. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  10242. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  10243. }
  10244. else {
  10245. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  10246. if (!hasTrailingSemicolon) {
  10247. code.appendLeft(this.end, ';');
  10248. }
  10249. }
  10250. }
  10251. }
  10252. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  10253. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  10254. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  10255. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  10256. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  10257. const backSlashRegEx = /\\/g;
  10258. function escapeId(id) {
  10259. if (!needsEscapeRegEx.test(id))
  10260. return id;
  10261. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  10262. }
  10263. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  10264. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  10265. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  10266. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  10267. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  10268. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  10269. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  10270. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  10271. const defaultInteropHelpersByInteropType = {
  10272. auto: INTEROP_DEFAULT_VARIABLE,
  10273. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  10274. default: null,
  10275. defaultOnly: null,
  10276. esModule: null
  10277. };
  10278. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  10279. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  10280. const namespaceInteropHelpersByInteropType = {
  10281. auto: INTEROP_NAMESPACE_VARIABLE,
  10282. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  10283. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  10284. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  10285. esModule: null
  10286. };
  10287. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  10288. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  10289. const usedHelpers = new Set(additionalHelpers);
  10290. for (const variable of HELPER_NAMES) {
  10291. if (accessedGlobals.has(variable)) {
  10292. usedHelpers.add(variable);
  10293. }
  10294. }
  10295. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  10296. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  10297. : '').join('');
  10298. };
  10299. const HELPER_GENERATORS = {
  10300. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  10301. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  10302. },
  10303. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  10304. const { _, getDirectReturnFunction, n } = snippets;
  10305. const [left, right] = getDirectReturnFunction(['e'], {
  10306. functionReturn: true,
  10307. lineBreakIndent: null,
  10308. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  10309. });
  10310. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  10311. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10312. },
  10313. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  10314. const { _, getDirectReturnFunction, n } = snippets;
  10315. const [left, right] = getDirectReturnFunction(['e'], {
  10316. functionReturn: true,
  10317. lineBreakIndent: null,
  10318. name: INTEROP_DEFAULT_VARIABLE
  10319. });
  10320. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  10321. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10322. },
  10323. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  10324. const { _, getDirectReturnFunction, n } = snippets;
  10325. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10326. const [left, right] = getDirectReturnFunction(['e'], {
  10327. functionReturn: true,
  10328. lineBreakIndent: null,
  10329. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  10330. });
  10331. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10332. }
  10333. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  10334. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  10335. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10336. `}${n}${n}`);
  10337. },
  10338. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  10339. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  10340. const [left, right] = getDirectReturnFunction(['e'], {
  10341. functionReturn: true,
  10342. lineBreakIndent: null,
  10343. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10344. });
  10345. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  10346. [null, `__proto__:${_}null`],
  10347. ['default', 'e']
  10348. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10349. },
  10350. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10351. const { _, n } = snippets;
  10352. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10353. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10354. `}${n}${n}`);
  10355. },
  10356. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  10357. const { _, getDirectReturnFunction, n } = snippets;
  10358. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10359. const [left, right] = getDirectReturnFunction(['e'], {
  10360. functionReturn: true,
  10361. lineBreakIndent: null,
  10362. name: INTEROP_NAMESPACE_VARIABLE
  10363. });
  10364. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10365. }
  10366. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10367. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10368. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10369. `}${n}${n}`);
  10370. },
  10371. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10372. const { _, cnst, n } = snippets;
  10373. const useForEach = cnst === 'var' && liveBindings;
  10374. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10375. `${t}${loopOverNamespaces(`{${n}` +
  10376. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10377. (liveBindings
  10378. ? useForEach
  10379. ? copyOwnPropertyLiveBinding
  10380. : copyPropertyLiveBinding
  10381. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10382. `${t}${t}${t}}${n}` +
  10383. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10384. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  10385. `}${n}${n}`);
  10386. }
  10387. };
  10388. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10389. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10390. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10391. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  10392. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10393. const copyProperty = `{${n}` +
  10394. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10395. `${index}${t}}`;
  10396. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  10397. `${index}if${_}(e)${_}{${n}` +
  10398. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10399. `${index}}${n}` +
  10400. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10401. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10402. };
  10403. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10404. ? `for${_}(${cnst} k in e)${_}${body}`
  10405. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10406. isAsync: false,
  10407. name: null
  10408. })}${body})${s}`;
  10409. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10410. if (useForEach) {
  10411. const [left, right] = getDirectReturnFunction(['e'], {
  10412. functionReturn: false,
  10413. lineBreakIndent: { base: t, t },
  10414. name: null
  10415. });
  10416. return (`m.forEach(${left}` +
  10417. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10418. isAsync: false,
  10419. name: null
  10420. })}${body})${right});`);
  10421. }
  10422. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10423. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10424. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10425. };
  10426. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10427. const { _, n } = snippets;
  10428. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10429. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10430. `${index}}${n}`);
  10431. };
  10432. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10433. const [left, right] = getDirectReturnFunction([], {
  10434. functionReturn: true,
  10435. lineBreakIndent: null,
  10436. name: null
  10437. });
  10438. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10439. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10440. `${index}${t}enumerable:${_}true,${n}` +
  10441. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10442. `${index}});${n}`);
  10443. };
  10444. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10445. const [left, right] = getDirectReturnFunction([], {
  10446. functionReturn: true,
  10447. lineBreakIndent: null,
  10448. name: null
  10449. });
  10450. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10451. `${index}if${_}(d)${_}{${n}` +
  10452. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10453. `${index}${t}${t}enumerable:${_}true,${n}` +
  10454. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10455. `${index}${t}});${n}` +
  10456. `${index}}${n}`);
  10457. };
  10458. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10459. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10460. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  10461. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10462. : fragment;
  10463. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10464. function getToStringTagValue(getObject) {
  10465. return getObject([['value', "'Module'"]], {
  10466. lineBreakIndent: null
  10467. });
  10468. }
  10469. class Literal extends NodeBase {
  10470. deoptimizeArgumentsOnInteractionAtPath() { }
  10471. getLiteralValueAtPath(path) {
  10472. if (path.length > 0 ||
  10473. // unknown literals can also be null but do not start with an "n"
  10474. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  10475. typeof this.value === 'bigint' ||
  10476. // to support shims for regular expressions
  10477. this.scope.context.code.charCodeAt(this.start) === 47) {
  10478. return UnknownValue;
  10479. }
  10480. return this.value;
  10481. }
  10482. getReturnExpressionWhenCalledAtPath(path) {
  10483. if (path.length !== 1)
  10484. return UNKNOWN_RETURN_EXPRESSION;
  10485. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  10486. }
  10487. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10488. switch (interaction.type) {
  10489. case INTERACTION_ACCESSED: {
  10490. return path.length > (this.value === null ? 0 : 1);
  10491. }
  10492. case INTERACTION_ASSIGNED: {
  10493. return true;
  10494. }
  10495. case INTERACTION_CALLED: {
  10496. if (this.included &&
  10497. this.value instanceof RegExp &&
  10498. (this.value.global || this.value.sticky)) {
  10499. return true;
  10500. }
  10501. return (path.length !== 1 ||
  10502. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  10503. }
  10504. }
  10505. }
  10506. initialise() {
  10507. super.initialise();
  10508. this.members = getLiteralMembersForValue(this.value);
  10509. }
  10510. parseNode(esTreeNode) {
  10511. this.value = esTreeNode.value;
  10512. this.regex = esTreeNode.regex;
  10513. return super.parseNode(esTreeNode);
  10514. }
  10515. render(code) {
  10516. if (typeof this.value === 'string') {
  10517. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  10518. }
  10519. }
  10520. }
  10521. Literal.prototype.includeNode = onlyIncludeSelf;
  10522. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  10523. if ('getLiteralValueAtPathAsChainElement' in object) {
  10524. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  10525. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  10526. return IS_SKIPPED_CHAIN;
  10527. }
  10528. }
  10529. else if (element.optional &&
  10530. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  10531. return IS_SKIPPED_CHAIN;
  10532. }
  10533. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  10534. }
  10535. function getResolvablePropertyKey(memberExpression) {
  10536. return memberExpression.computed
  10537. ? getResolvableComputedPropertyKey(memberExpression.property)
  10538. : memberExpression.property.name;
  10539. }
  10540. function getResolvableComputedPropertyKey(propertyKey) {
  10541. if (propertyKey instanceof Literal) {
  10542. return String(propertyKey.value);
  10543. }
  10544. return null;
  10545. }
  10546. function getPathIfNotComputed(memberExpression) {
  10547. const nextPathKey = memberExpression.propertyKey;
  10548. const object = memberExpression.object;
  10549. if (typeof nextPathKey === 'string') {
  10550. if (object instanceof Identifier) {
  10551. return [
  10552. { key: object.name, pos: object.start },
  10553. { key: nextPathKey, pos: memberExpression.property.start }
  10554. ];
  10555. }
  10556. if (object instanceof MemberExpression) {
  10557. const parentPath = getPathIfNotComputed(object);
  10558. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  10559. }
  10560. }
  10561. return null;
  10562. }
  10563. function getStringFromPath(path) {
  10564. let pathString = path[0].key;
  10565. for (let index = 1; index < path.length; index++) {
  10566. pathString += '.' + path[index].key;
  10567. }
  10568. return pathString;
  10569. }
  10570. class MemberExpression extends NodeBase {
  10571. constructor() {
  10572. super(...arguments);
  10573. this.promiseHandler = null;
  10574. this.variable = null;
  10575. this.expressionsToBeDeoptimized = [];
  10576. }
  10577. get computed() {
  10578. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  10579. }
  10580. set computed(value) {
  10581. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  10582. }
  10583. get optional() {
  10584. return isFlagSet(this.flags, 128 /* Flag.optional */);
  10585. }
  10586. set optional(value) {
  10587. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  10588. }
  10589. get assignmentDeoptimized() {
  10590. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  10591. }
  10592. set assignmentDeoptimized(value) {
  10593. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  10594. }
  10595. get bound() {
  10596. return isFlagSet(this.flags, 32 /* Flag.bound */);
  10597. }
  10598. set bound(value) {
  10599. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  10600. }
  10601. get isUndefined() {
  10602. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  10603. }
  10604. set isUndefined(value) {
  10605. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  10606. }
  10607. bind() {
  10608. this.bound = true;
  10609. const path = getPathIfNotComputed(this);
  10610. const baseVariable = path && this.scope.findVariable(path[0].key);
  10611. if (baseVariable?.isNamespace) {
  10612. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  10613. if (!resolvedVariable) {
  10614. super.bind();
  10615. }
  10616. else if (resolvedVariable === 'undefined') {
  10617. this.isUndefined = true;
  10618. }
  10619. else {
  10620. this.variable = resolvedVariable;
  10621. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  10622. }
  10623. }
  10624. else {
  10625. super.bind();
  10626. }
  10627. }
  10628. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10629. if (this.promiseHandler) {
  10630. this.promiseHandler.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10631. }
  10632. else if (this.variable) {
  10633. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10634. }
  10635. else if (!this.isUndefined) {
  10636. if (path.length < MAX_PATH_DEPTH) {
  10637. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  10638. }
  10639. else {
  10640. deoptimizeInteraction(interaction);
  10641. }
  10642. }
  10643. }
  10644. deoptimizeAssignment(destructuredInitPath, init) {
  10645. this.deoptimizePath(EMPTY_PATH);
  10646. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  10647. }
  10648. deoptimizeCache() {
  10649. if (this.propertyKey === this.dynamicPropertyKey)
  10650. return;
  10651. const { expressionsToBeDeoptimized, object } = this;
  10652. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  10653. this.dynamicPropertyKey = this.propertyKey;
  10654. object.deoptimizePath(UNKNOWN_PATH);
  10655. if (this.included) {
  10656. object.includePath(UNKNOWN_PATH, createInclusionContext());
  10657. }
  10658. for (const expression of expressionsToBeDeoptimized) {
  10659. expression.deoptimizeCache();
  10660. }
  10661. }
  10662. deoptimizePath(path) {
  10663. if (path.length === 0)
  10664. this.disallowNamespaceReassignment();
  10665. if (this.variable) {
  10666. this.variable.deoptimizePath(path);
  10667. }
  10668. else if (!this.isUndefined) {
  10669. const { propertyKey } = this;
  10670. this.object.deoptimizePath([
  10671. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  10672. ...(path.length < MAX_PATH_DEPTH
  10673. ? path
  10674. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10675. ]);
  10676. }
  10677. }
  10678. getLiteralValueAtPath(path, recursionTracker, origin) {
  10679. if (this.variable) {
  10680. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10681. }
  10682. if (this.isUndefined) {
  10683. return undefined;
  10684. }
  10685. const propertyKey = this.getDynamicPropertyKey();
  10686. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10687. if (propertyKey !== this.propertyKey)
  10688. this.expressionsToBeDeoptimized.push(origin);
  10689. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  10690. }
  10691. return UnknownValue;
  10692. }
  10693. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  10694. if (this.variable) {
  10695. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10696. }
  10697. if (this.isUndefined) {
  10698. return undefined;
  10699. }
  10700. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  10701. }
  10702. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10703. if (this.variable) {
  10704. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10705. }
  10706. if (this.isUndefined) {
  10707. return [UNDEFINED_EXPRESSION, false];
  10708. }
  10709. const propertyKey = this.getDynamicPropertyKey();
  10710. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10711. if (propertyKey !== this.propertyKey)
  10712. this.expressionsToBeDeoptimized.push(origin);
  10713. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  10714. }
  10715. return UNKNOWN_RETURN_EXPRESSION;
  10716. }
  10717. hasEffects(context) {
  10718. if (!this.deoptimized)
  10719. this.applyDeoptimizations();
  10720. return (this.property.hasEffects(context) ||
  10721. this.object.hasEffects(context) ||
  10722. this.hasAccessEffect(context));
  10723. }
  10724. hasEffectsAsChainElement(context) {
  10725. if (this.variable || this.isUndefined)
  10726. return this.hasEffects(context);
  10727. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  10728. ? this.object.hasEffectsAsChainElement(context)
  10729. : this.object.hasEffects(context);
  10730. if (objectHasEffects === IS_SKIPPED_CHAIN)
  10731. return IS_SKIPPED_CHAIN;
  10732. if (this.optional &&
  10733. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  10734. return objectHasEffects || IS_SKIPPED_CHAIN;
  10735. }
  10736. // We only apply deoptimizations lazily once we know we are not skipping
  10737. if (!this.deoptimized)
  10738. this.applyDeoptimizations();
  10739. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  10740. }
  10741. hasEffectsAsAssignmentTarget(context, checkAccess) {
  10742. if (checkAccess && !this.deoptimized)
  10743. this.applyDeoptimizations();
  10744. if (!this.assignmentDeoptimized)
  10745. this.applyAssignmentDeoptimization();
  10746. return (this.property.hasEffects(context) ||
  10747. this.object.hasEffects(context) ||
  10748. (checkAccess && this.hasAccessEffect(context)) ||
  10749. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  10750. }
  10751. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10752. if (this.variable) {
  10753. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10754. }
  10755. if (this.isUndefined) {
  10756. return true;
  10757. }
  10758. if (path.length < MAX_PATH_DEPTH) {
  10759. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  10760. }
  10761. return true;
  10762. }
  10763. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10764. return (destructuredInitPath.length > 0 &&
  10765. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  10766. }
  10767. include(context, includeChildrenRecursively) {
  10768. if (!this.included)
  10769. this.includeNode(context);
  10770. this.object.include(context, includeChildrenRecursively);
  10771. this.property.include(context, includeChildrenRecursively);
  10772. if (includeChildrenRecursively) {
  10773. this.variable?.includePath(UNKNOWN_PATH, context);
  10774. }
  10775. }
  10776. includeNode(context) {
  10777. this.included = true;
  10778. if (!this.deoptimized)
  10779. this.applyDeoptimizations();
  10780. if (this.variable) {
  10781. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10782. }
  10783. else if (!this.isUndefined) {
  10784. this.object.includePath([this.propertyKey], context);
  10785. }
  10786. }
  10787. includeNodeAsAssignmentTarget(context) {
  10788. this.included = true;
  10789. if (!this.assignmentDeoptimized)
  10790. this.applyAssignmentDeoptimization();
  10791. if (this.variable) {
  10792. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10793. }
  10794. else if (!this.isUndefined) {
  10795. this.object.includePath([this.propertyKey], context);
  10796. }
  10797. }
  10798. includePath(path, context) {
  10799. if (!this.included)
  10800. this.includeNode(context);
  10801. if (this.variable) {
  10802. this.variable?.includePath(path, context);
  10803. }
  10804. else if (!this.isUndefined) {
  10805. this.object.includePath([
  10806. this.propertyKey,
  10807. ...(path.length < MAX_PATH_DEPTH
  10808. ? path
  10809. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10810. ], context);
  10811. }
  10812. }
  10813. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  10814. if (!this.included)
  10815. this.includeNodeAsAssignmentTarget(context);
  10816. if (deoptimizeAccess && !this.deoptimized)
  10817. this.applyDeoptimizations();
  10818. this.object.include(context, includeChildrenRecursively);
  10819. this.property.include(context, includeChildrenRecursively);
  10820. }
  10821. includeCallArguments(interaction, context) {
  10822. if (this.promiseHandler) {
  10823. this.promiseHandler.includeCallArguments(interaction, context);
  10824. }
  10825. else if (this.variable) {
  10826. this.variable.includeCallArguments(interaction, context);
  10827. }
  10828. else {
  10829. includeInteraction(interaction, context);
  10830. }
  10831. }
  10832. includeDestructuredIfNecessary() {
  10833. /* istanbul ignore next */
  10834. this.scope.context.error({
  10835. message: 'includeDestructuredIfNecessary is currently not supported for MemberExpressions'
  10836. }, this.start);
  10837. }
  10838. initialise() {
  10839. super.initialise();
  10840. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  10841. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  10842. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  10843. }
  10844. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = parseAst_js.BLANK) {
  10845. if (this.variable || this.isUndefined) {
  10846. const { snippets: { getPropertyAccess } } = options;
  10847. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  10848. if (renderedParentType && isCalleeOfRenderedParent)
  10849. replacement = '0, ' + replacement;
  10850. code.overwrite(this.start, this.end, replacement, {
  10851. contentOnly: true,
  10852. storeName: true
  10853. });
  10854. }
  10855. else {
  10856. if (renderedParentType && isCalleeOfRenderedParent) {
  10857. code.appendRight(this.start, '0, ');
  10858. }
  10859. this.object.render(code, options, { renderedSurroundingElement });
  10860. this.property.render(code, options);
  10861. }
  10862. }
  10863. setAssignedValue(value) {
  10864. this.assignmentInteraction = {
  10865. args: [this.object, value],
  10866. type: INTERACTION_ASSIGNED
  10867. };
  10868. }
  10869. applyDeoptimizations() {
  10870. this.deoptimized = true;
  10871. const { propertyReadSideEffects } = this.scope.context.options
  10872. .treeshake;
  10873. if (
  10874. // Namespaces are not bound and should not be deoptimized
  10875. this.bound &&
  10876. propertyReadSideEffects &&
  10877. !(this.variable || this.isUndefined || this.promiseHandler)) {
  10878. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10879. this.scope.context.requestTreeshakingPass();
  10880. }
  10881. if (this.variable) {
  10882. this.variable.addUsedPlace(this);
  10883. this.scope.context.requestTreeshakingPass();
  10884. }
  10885. }
  10886. applyAssignmentDeoptimization() {
  10887. this.assignmentDeoptimized = true;
  10888. const { propertyReadSideEffects } = this.scope.context.options
  10889. .treeshake;
  10890. if (
  10891. // Namespaces are not bound and should not be deoptimized
  10892. this.bound &&
  10893. propertyReadSideEffects &&
  10894. !(this.variable || this.isUndefined)) {
  10895. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10896. this.scope.context.requestTreeshakingPass();
  10897. }
  10898. }
  10899. disallowNamespaceReassignment() {
  10900. if (this.object instanceof Identifier) {
  10901. const variable = this.scope.findVariable(this.object.name);
  10902. if (variable.isNamespace) {
  10903. if (this.variable) {
  10904. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  10905. }
  10906. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  10907. }
  10908. }
  10909. }
  10910. getDynamicPropertyKey() {
  10911. if (this.dynamicPropertyKey === null) {
  10912. this.dynamicPropertyKey = this.propertyKey;
  10913. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10914. return (this.dynamicPropertyKey =
  10915. typeof value === 'symbol'
  10916. ? WELL_KNOWN_SYMBOLS.has(value)
  10917. ? value
  10918. : UnknownKey
  10919. : String(value));
  10920. }
  10921. return this.dynamicPropertyKey;
  10922. }
  10923. hasAccessEffect(context) {
  10924. const { propertyReadSideEffects } = this.scope.context.options
  10925. .treeshake;
  10926. return (!(this.variable || this.isUndefined) &&
  10927. propertyReadSideEffects &&
  10928. (propertyReadSideEffects === 'always' ||
  10929. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  10930. }
  10931. }
  10932. function resolveNamespaceVariables(baseVariable, path, astContext) {
  10933. if (path.length === 0)
  10934. return baseVariable;
  10935. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  10936. return null;
  10937. const exportName = path[0].key;
  10938. const [variable, options] = baseVariable.context.traceExport(exportName);
  10939. if (!variable) {
  10940. if (path.length === 1) {
  10941. const fileName = baseVariable.context.fileName;
  10942. astContext.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(exportName, astContext.module.id, fileName, !!options?.missingButExportExists), path[0].pos);
  10943. return 'undefined';
  10944. }
  10945. return null;
  10946. }
  10947. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  10948. }
  10949. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10950. const FILE_OBJ_PREFIX = 'ROLLUP_FILE_URL_OBJ_';
  10951. const IMPORT = 'import';
  10952. class MetaProperty extends NodeBase {
  10953. constructor() {
  10954. super(...arguments);
  10955. this.metaProperty = null;
  10956. this.preliminaryChunkId = null;
  10957. this.referenceId = null;
  10958. }
  10959. getReferencedFileName(outputPluginDriver) {
  10960. const { meta: { name }, metaProperty } = this;
  10961. if (name === IMPORT) {
  10962. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  10963. return outputPluginDriver.getFileName(metaProperty.slice(FILE_OBJ_PREFIX.length));
  10964. }
  10965. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  10966. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10967. }
  10968. }
  10969. return null;
  10970. }
  10971. hasEffects() {
  10972. return false;
  10973. }
  10974. hasEffectsOnInteractionAtPath(path, { type }) {
  10975. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10976. }
  10977. include() {
  10978. if (!this.included)
  10979. this.includeNode();
  10980. }
  10981. includeNode() {
  10982. this.included = true;
  10983. if (this.meta.name === IMPORT) {
  10984. this.scope.context.addImportMeta(this);
  10985. const parent = this.parent;
  10986. const metaProperty = (this.metaProperty =
  10987. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10988. ? parent.propertyKey
  10989. : null);
  10990. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  10991. this.referenceId = metaProperty.slice(FILE_OBJ_PREFIX.length);
  10992. }
  10993. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  10994. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10995. }
  10996. }
  10997. }
  10998. render(code, renderOptions) {
  10999. const { format, pluginDriver, snippets } = renderOptions;
  11000. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  11001. const { id: moduleId, info: { attributes } } = module;
  11002. if (name !== IMPORT)
  11003. return;
  11004. const chunkId = preliminaryChunkId;
  11005. if (referenceId) {
  11006. const fileName = pluginDriver.getFileName(referenceId);
  11007. const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
  11008. const isUrlObject = !!metaProperty?.startsWith(FILE_OBJ_PREFIX);
  11009. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  11010. { attributes, chunkId, fileName, format, moduleId, referenceId, relativePath }
  11011. ]) || relativeUrlMechanisms[format](relativePath, isUrlObject);
  11012. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  11013. return;
  11014. }
  11015. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  11016. metaProperty,
  11017. { attributes, chunkId, format, moduleId }
  11018. ]);
  11019. if (!replacement) {
  11020. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  11021. renderOptions.accessedDocumentCurrentScript ||=
  11022. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  11023. }
  11024. if (typeof replacement === 'string') {
  11025. if (parent instanceof MemberExpression) {
  11026. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  11027. }
  11028. else {
  11029. code.overwrite(start, end, replacement, { contentOnly: true });
  11030. }
  11031. }
  11032. }
  11033. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  11034. this.preliminaryChunkId = preliminaryChunkId;
  11035. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) || this.metaProperty?.startsWith(FILE_OBJ_PREFIX)
  11036. ? accessedFileUrlGlobals
  11037. : accessedMetaUrlGlobals)[format];
  11038. if (accessedGlobals.length > 0) {
  11039. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  11040. }
  11041. }
  11042. }
  11043. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  11044. const accessedMetaUrlGlobals = {
  11045. amd: ['document', 'module', 'URL'],
  11046. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  11047. es: [],
  11048. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  11049. system: ['module'],
  11050. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  11051. };
  11052. const accessedFileUrlGlobals = {
  11053. amd: ['document', 'require', 'URL'],
  11054. cjs: ['document', 'require', 'URL'],
  11055. es: [],
  11056. iife: ['document', 'URL'],
  11057. system: ['module', 'URL'],
  11058. umd: ['document', 'require', 'URL']
  11059. };
  11060. const getResolveUrl = (path, asObject, URL = 'URL') => `new ${URL}(${path})${asObject ? '' : '.href'}`;
  11061. const getRelativeUrlFromDocument = (relativePath, asObject, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`, asObject);
  11062. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  11063. const urlMechanism = getUrl(chunkId);
  11064. return property === null
  11065. ? `({ url: ${urlMechanism} })`
  11066. : property === 'url'
  11067. ? urlMechanism
  11068. : 'undefined';
  11069. };
  11070. const getFileUrlFromFullPath = (path, asObject) => `require('u' + 'rl').pathToFileURL(${path})${asObject ? '' : '.href'}`;
  11071. const getFileUrlFromRelativePath = (path, asObject) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`, asObject);
  11072. 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)`;
  11073. const relativeUrlMechanisms = {
  11074. amd: (relativePath, asObject) => {
  11075. if (relativePath[0] !== '.')
  11076. relativePath = './' + relativePath;
  11077. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`, asObject);
  11078. },
  11079. cjs: (relativePath, asObject) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject)})`,
  11080. es: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`, asObject),
  11081. iife: (relativePath, asObject) => getRelativeUrlFromDocument(relativePath, asObject),
  11082. system: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`, asObject),
  11083. umd: (relativePath, asObject) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject, true)})`
  11084. };
  11085. const importMetaMechanisms = {
  11086. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`, false)),
  11087. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId)})`),
  11088. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  11089. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  11090. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId, true)})`)
  11091. };
  11092. class UndefinedVariable extends Variable {
  11093. constructor() {
  11094. super('undefined');
  11095. }
  11096. getLiteralValueAtPath() {
  11097. return undefined;
  11098. }
  11099. }
  11100. class ExportDefaultVariable extends LocalVariable {
  11101. constructor(exportDefaultDeclaration, context) {
  11102. super('default', exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  11103. this.hasId = false;
  11104. this.originalId = null;
  11105. this.originalVariable = null;
  11106. const declaration = exportDefaultDeclaration.declaration;
  11107. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  11108. declaration.id) {
  11109. this.hasId = true;
  11110. this.originalId = declaration.id;
  11111. }
  11112. else if (declaration instanceof Identifier) {
  11113. this.originalId = declaration;
  11114. }
  11115. }
  11116. addReference(identifier) {
  11117. if (!this.hasId) {
  11118. this.name = identifier.name;
  11119. }
  11120. }
  11121. addUsedPlace(usedPlace) {
  11122. const original = this.getOriginalVariable();
  11123. if (original === this) {
  11124. super.addUsedPlace(usedPlace);
  11125. }
  11126. else {
  11127. original.addUsedPlace(usedPlace);
  11128. }
  11129. }
  11130. forbidName(name) {
  11131. const original = this.getOriginalVariable();
  11132. if (original === this) {
  11133. super.forbidName(name);
  11134. }
  11135. else {
  11136. original.forbidName(name);
  11137. }
  11138. }
  11139. getAssignedVariableName() {
  11140. return (this.originalId && this.originalId.name) || null;
  11141. }
  11142. getBaseVariableName() {
  11143. const original = this.getOriginalVariable();
  11144. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  11145. }
  11146. getDirectOriginalVariable() {
  11147. return this.originalId &&
  11148. (this.hasId ||
  11149. !(this.originalId.isPossibleTDZ() ||
  11150. this.originalId.variable.isReassigned ||
  11151. this.originalId.variable instanceof UndefinedVariable ||
  11152. // this avoids a circular dependency
  11153. 'syntheticNamespace' in this.originalId.variable))
  11154. ? this.originalId.variable
  11155. : null;
  11156. }
  11157. getName(getPropertyAccess) {
  11158. const original = this.getOriginalVariable();
  11159. return original === this
  11160. ? super.getName(getPropertyAccess)
  11161. : original.getName(getPropertyAccess);
  11162. }
  11163. getOriginalVariable() {
  11164. if (this.originalVariable)
  11165. return this.originalVariable;
  11166. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11167. let original = this;
  11168. let currentVariable;
  11169. const checkedVariables = new Set();
  11170. do {
  11171. checkedVariables.add(original);
  11172. currentVariable = original;
  11173. original = currentVariable.getDirectOriginalVariable();
  11174. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  11175. return (this.originalVariable = original || currentVariable);
  11176. }
  11177. }
  11178. class NamespaceVariable extends Variable {
  11179. constructor(context) {
  11180. super(context.getModuleName());
  11181. this.areAllMembersDeoptimized = false;
  11182. this.mergedNamespaces = [];
  11183. this.nonExplicitNamespacesIncluded = false;
  11184. this.referencedEarly = false;
  11185. this.references = [];
  11186. this.context = context;
  11187. this.module = context.module;
  11188. }
  11189. addReference(identifier) {
  11190. this.references.push(identifier);
  11191. this.name = identifier.name;
  11192. }
  11193. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11194. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  11195. const key = path[0];
  11196. if (typeof key === 'string') {
  11197. this.module
  11198. .getExportedVariablesByName()
  11199. .get(key)
  11200. ?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  11201. }
  11202. else {
  11203. deoptimizeInteraction(interaction);
  11204. }
  11205. }
  11206. }
  11207. deoptimizePath(path) {
  11208. if (path.length > 1) {
  11209. const key = path[0];
  11210. if (typeof key === 'string') {
  11211. this.module.getExportedVariablesByName().get(key)?.deoptimizePath(path.slice(1));
  11212. }
  11213. else if (!this.areAllMembersDeoptimized) {
  11214. this.areAllMembersDeoptimized = true;
  11215. for (const variable of this.module.getExportedVariablesByName().values()) {
  11216. variable.deoptimizePath(UNKNOWN_PATH);
  11217. }
  11218. }
  11219. }
  11220. }
  11221. getLiteralValueAtPath(path) {
  11222. if (path[0] === SymbolToStringTag) {
  11223. return 'Module';
  11224. }
  11225. return UnknownValue;
  11226. }
  11227. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11228. const { type } = interaction;
  11229. if (path.length === 0) {
  11230. // This can only be a call anyway
  11231. return true;
  11232. }
  11233. if (path.length === 1 && type !== INTERACTION_CALLED) {
  11234. return type === INTERACTION_ASSIGNED;
  11235. }
  11236. const key = path[0];
  11237. if (typeof key !== 'string') {
  11238. return true;
  11239. }
  11240. const memberVariable = this.module.getExportedVariablesByName().get(key);
  11241. return (!memberVariable ||
  11242. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  11243. }
  11244. includePath(path, context) {
  11245. super.includePath(path, context);
  11246. this.includeMemberPath(path, context);
  11247. }
  11248. includeMemberPath(path, context) {
  11249. if (path.length > 0) {
  11250. const [name, ...remainingPath] = path;
  11251. if (typeof name === 'string') {
  11252. const variable = this.module.getExportedVariablesByName().get(name);
  11253. if (variable) {
  11254. this.context.includeVariableInModule(variable, remainingPath, context);
  11255. }
  11256. else {
  11257. this.includeNonExplicitNamespaces();
  11258. }
  11259. }
  11260. else if (name) {
  11261. this.module.includeAllExports();
  11262. this.includeNonExplicitNamespaces();
  11263. }
  11264. }
  11265. }
  11266. prepare(accessedGlobalsByScope) {
  11267. if (this.mergedNamespaces.length > 0) {
  11268. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11269. }
  11270. }
  11271. renderBlock(options) {
  11272. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11273. const memberVariables = this.module.getExportedVariablesByName();
  11274. const members = [...memberVariables.entries()]
  11275. .filter(([name, variable]) => !name.startsWith('*') && variable.included)
  11276. .map(([name, variable]) => {
  11277. if (this.referencedEarly || variable.isReassigned || variable === this) {
  11278. return [
  11279. null,
  11280. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  11281. ];
  11282. }
  11283. return [name, variable.getName(getPropertyAccess)];
  11284. });
  11285. members.unshift([null, `__proto__:${_}null`]);
  11286. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11287. if (this.mergedNamespaces.length > 0) {
  11288. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11289. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  11290. }
  11291. else {
  11292. // The helper to merge namespaces will also take care of freezing and toStringTag
  11293. if (symbols) {
  11294. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11295. }
  11296. if (freeze) {
  11297. output = `/*#__PURE__*/Object.freeze(${output})`;
  11298. }
  11299. }
  11300. const name = this.getName(getPropertyAccess);
  11301. output = `${cnst} ${name}${_}=${_}${output};`;
  11302. if (format === 'system' && exportNamesByVariable.has(this)) {
  11303. output += `${n}${getSystemExportStatement([this], options)};`;
  11304. }
  11305. return output;
  11306. }
  11307. renderFirst() {
  11308. return this.referencedEarly;
  11309. }
  11310. setMergedNamespaces(mergedNamespaces) {
  11311. this.mergedNamespaces = mergedNamespaces;
  11312. const moduleExecIndex = this.context.getModuleExecIndex();
  11313. for (const identifier of this.references) {
  11314. const { context } = identifier.scope;
  11315. if (context.getModuleExecIndex() <= moduleExecIndex) {
  11316. this.referencedEarly = true;
  11317. break;
  11318. }
  11319. }
  11320. }
  11321. includeNonExplicitNamespaces() {
  11322. if (!this.nonExplicitNamespacesIncluded) {
  11323. this.nonExplicitNamespacesIncluded = true;
  11324. this.setMergedNamespaces(this.module.includeAndGetAdditionalMergedNamespaces());
  11325. }
  11326. }
  11327. }
  11328. NamespaceVariable.prototype.isNamespace = true;
  11329. // This is a proxy that does not include the namespace object when a path is included
  11330. const getDynamicNamespaceVariable = (namespace) => Object.create(namespace, {
  11331. includePath: {
  11332. value(path, context) {
  11333. namespace.includeMemberPath(path, context);
  11334. }
  11335. }
  11336. });
  11337. class SyntheticNamedExportVariable extends Variable {
  11338. constructor(context, name, syntheticNamespace) {
  11339. super(name);
  11340. this.baseVariable = null;
  11341. this.context = context;
  11342. this.module = context.module;
  11343. this.syntheticNamespace = syntheticNamespace;
  11344. }
  11345. getBaseVariable() {
  11346. if (this.baseVariable)
  11347. return this.baseVariable;
  11348. let baseVariable = this.syntheticNamespace;
  11349. while (baseVariable instanceof ExportDefaultVariable ||
  11350. baseVariable instanceof SyntheticNamedExportVariable) {
  11351. if (baseVariable instanceof ExportDefaultVariable) {
  11352. const original = baseVariable.getOriginalVariable();
  11353. if (original === baseVariable)
  11354. break;
  11355. baseVariable = original;
  11356. }
  11357. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11358. baseVariable = baseVariable.syntheticNamespace;
  11359. }
  11360. }
  11361. return (this.baseVariable = baseVariable);
  11362. }
  11363. getBaseVariableName() {
  11364. return this.syntheticNamespace.getBaseVariableName();
  11365. }
  11366. getName(getPropertyAccess) {
  11367. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11368. }
  11369. includePath(path, context) {
  11370. super.includePath(path, context);
  11371. this.context.includeVariableInModule(this.syntheticNamespace, [this.name, ...path], context);
  11372. }
  11373. setRenderNames(baseName, name) {
  11374. super.setRenderNames(baseName, name);
  11375. }
  11376. }
  11377. class ExternalChunk {
  11378. constructor(module, options, inputBase) {
  11379. this.options = options;
  11380. this.inputBase = inputBase;
  11381. this.defaultVariableName = '';
  11382. this.namespaceVariableName = '';
  11383. this.variableName = '';
  11384. this.fileName = null;
  11385. this.importAttributes = null;
  11386. this.id = module.id;
  11387. this.moduleInfo = module.info;
  11388. this.renormalizeRenderPath = module.renormalizeRenderPath;
  11389. this.suggestedVariableName = module.suggestedVariableName;
  11390. }
  11391. getFileName() {
  11392. if (this.fileName) {
  11393. return this.fileName;
  11394. }
  11395. const { paths } = this.options;
  11396. return (this.fileName =
  11397. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  11398. (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
  11399. }
  11400. getImportAttributes(snippets) {
  11401. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  11402. this.options.externalImportAttributes &&
  11403. this.moduleInfo.attributes, snippets));
  11404. }
  11405. getImportPath(importer) {
  11406. return escapeId(this.renormalizeRenderPath
  11407. ? parseAst_js.getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  11408. : this.getFileName());
  11409. }
  11410. }
  11411. function formatAttributes(attributes, { getObject }) {
  11412. if (!attributes) {
  11413. return null;
  11414. }
  11415. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  11416. if (assertionEntries.length > 0) {
  11417. return getObject(assertionEntries, { lineBreakIndent: null });
  11418. }
  11419. return null;
  11420. }
  11421. function removeJsExtension(name) {
  11422. return name.endsWith('.js') ? name.slice(0, -3) : name;
  11423. }
  11424. function getCompleteAmdId(options, chunkId) {
  11425. if (options.autoId) {
  11426. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  11427. }
  11428. return options.id ?? '';
  11429. }
  11430. function getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  11431. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  11432. if (!namedExportsMode) {
  11433. return `${n}${n}${mechanism}${getSingleDefaultExport(exports$1, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  11434. }
  11435. let exportBlock = '';
  11436. if (namedExportsMode) {
  11437. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11438. if (!reexports) {
  11439. continue;
  11440. }
  11441. for (const specifier of reexports) {
  11442. if (specifier.reexported !== '*') {
  11443. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11444. if (exportBlock)
  11445. exportBlock += n;
  11446. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  11447. const [left, right] = getDirectReturnFunction([], {
  11448. functionReturn: true,
  11449. lineBreakIndent: null,
  11450. name: null
  11451. });
  11452. exportBlock +=
  11453. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  11454. `${t}enumerable:${_}true,${n}` +
  11455. `${t}get:${_}${left}${importName}${right}${n}});`;
  11456. }
  11457. else if (specifier.reexported === '__proto__') {
  11458. exportBlock +=
  11459. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11460. `${t}enumerable:${_}true,${n}` +
  11461. `${t}value:${_}${importName}${n}});`;
  11462. }
  11463. else {
  11464. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  11465. }
  11466. }
  11467. }
  11468. }
  11469. }
  11470. for (const { exported, local } of exports$1) {
  11471. const lhs = `exports${getPropertyAccess(exported)}`;
  11472. const rhs = local;
  11473. if (lhs !== rhs) {
  11474. if (exportBlock)
  11475. exportBlock += n;
  11476. exportBlock +=
  11477. exported === '__proto__'
  11478. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11479. `${t}enumerable:${_}true,${n}` +
  11480. `${t}value:${_}${rhs}${n}});`
  11481. : `${lhs}${_}=${_}${rhs};`;
  11482. }
  11483. }
  11484. if (namedExportsMode) {
  11485. for (const { name, reexports } of dependencies) {
  11486. if (!reexports) {
  11487. continue;
  11488. }
  11489. for (const specifier of reexports) {
  11490. if (specifier.reexported === '*') {
  11491. if (exportBlock)
  11492. exportBlock += n;
  11493. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  11494. const protoString = "'__proto__'";
  11495. exportBlock +=
  11496. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  11497. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  11498. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  11499. `${t}${t}enumerable:${_}true,${n}` +
  11500. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  11501. `${t}});${n}${n}`;
  11502. }
  11503. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  11504. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  11505. isAsync: false,
  11506. name: null
  11507. })}${copyPropertyIfNecessary});`;
  11508. }
  11509. }
  11510. }
  11511. }
  11512. if (exportBlock) {
  11513. return `${n}${n}${exportBlock}`;
  11514. }
  11515. return '';
  11516. }
  11517. function getSingleDefaultExport(exports$1, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  11518. if (exports$1.length > 0) {
  11519. return exports$1[0].local;
  11520. }
  11521. else {
  11522. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11523. if (reexports) {
  11524. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11525. }
  11526. }
  11527. }
  11528. }
  11529. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  11530. if (imported === 'default') {
  11531. if (!isChunk) {
  11532. const moduleInterop = interop(moduleId);
  11533. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  11534. ? defaultVariableName
  11535. : moduleVariableName;
  11536. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  11537. ? `${variableName}${getPropertyAccess('default')}`
  11538. : variableName;
  11539. }
  11540. return depNamedExportsMode
  11541. ? `${moduleVariableName}${getPropertyAccess('default')}`
  11542. : moduleVariableName;
  11543. }
  11544. if (imported === '*') {
  11545. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  11546. ? namespaceVariableName
  11547. : moduleVariableName;
  11548. }
  11549. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  11550. }
  11551. function getEsModuleValue(getObject) {
  11552. return getObject([['value', 'true']], {
  11553. lineBreakIndent: null
  11554. });
  11555. }
  11556. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  11557. if (hasNamedExports) {
  11558. if (addEsModule) {
  11559. if (addNamespaceToStringTag) {
  11560. return `Object.defineProperties(exports,${_}${getObject([
  11561. ['__esModule', getEsModuleValue(getObject)],
  11562. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  11563. ], {
  11564. lineBreakIndent: null
  11565. })});`;
  11566. }
  11567. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  11568. }
  11569. if (addNamespaceToStringTag) {
  11570. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  11571. }
  11572. }
  11573. return '';
  11574. }
  11575. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  11576. if (needsLiveBinding) {
  11577. const [left, right] = getDirectReturnFunction([], {
  11578. functionReturn: true,
  11579. lineBreakIndent: null,
  11580. name: null
  11581. });
  11582. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  11583. `${t}${t}enumerable:${_}true,${n}` +
  11584. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  11585. }
  11586. return `exports[k]${_}=${_}${name}[k]`;
  11587. };
  11588. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  11589. const { _, cnst, n } = snippets;
  11590. const neededInteropHelpers = new Set();
  11591. const interopStatements = [];
  11592. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  11593. neededInteropHelpers.add(helper);
  11594. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  11595. };
  11596. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11597. if (isChunk) {
  11598. for (const { imported, reexported } of [
  11599. ...(imports || []),
  11600. ...(reexports || [])
  11601. ]) {
  11602. if (imported === '*' && reexported !== '*') {
  11603. if (!namedExportsMode) {
  11604. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  11605. }
  11606. break;
  11607. }
  11608. }
  11609. }
  11610. else {
  11611. const moduleInterop = interop(importPath);
  11612. let hasDefault = false;
  11613. let hasNamespace = false;
  11614. for (const { imported, reexported } of [
  11615. ...(imports || []),
  11616. ...(reexports || [])
  11617. ]) {
  11618. let helper;
  11619. let variableName;
  11620. if (imported === 'default') {
  11621. if (!hasDefault) {
  11622. hasDefault = true;
  11623. if (defaultVariableName !== namespaceVariableName) {
  11624. variableName = defaultVariableName;
  11625. helper = defaultInteropHelpersByInteropType[moduleInterop];
  11626. }
  11627. }
  11628. }
  11629. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  11630. hasNamespace = true;
  11631. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  11632. variableName = namespaceVariableName;
  11633. }
  11634. if (helper) {
  11635. addInteropStatement(variableName, helper, name);
  11636. }
  11637. }
  11638. }
  11639. }
  11640. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  11641. }
  11642. function throwOnPhase(outputFormat, chunkId, dependencies) {
  11643. const sourcePhaseDependency = dependencies.find(dependency => dependency.sourcePhaseImport);
  11644. if (sourcePhaseDependency) {
  11645. parseAst_js.error(parseAst_js.logSourcePhaseFormatUnsupported(outputFormat, chunkId, sourcePhaseDependency.importPath));
  11646. }
  11647. }
  11648. function addJsExtension(name) {
  11649. return name.endsWith('.js') ? name : name + '.js';
  11650. }
  11651. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  11652. // The assumption is that this makes sense for all relative ids:
  11653. // https://requirejs.org/docs/api.html#jsfiles
  11654. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  11655. if (id[0] !== '.') {
  11656. return id;
  11657. }
  11658. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  11659. }
  11660. const builtinModules = [
  11661. "node:assert",
  11662. "assert",
  11663. "node:assert/strict",
  11664. "assert/strict",
  11665. "node:async_hooks",
  11666. "async_hooks",
  11667. "node:buffer",
  11668. "buffer",
  11669. "node:child_process",
  11670. "child_process",
  11671. "node:cluster",
  11672. "cluster",
  11673. "node:console",
  11674. "console",
  11675. "node:constants",
  11676. "constants",
  11677. "node:crypto",
  11678. "crypto",
  11679. "node:dgram",
  11680. "dgram",
  11681. "node:diagnostics_channel",
  11682. "diagnostics_channel",
  11683. "node:dns",
  11684. "dns",
  11685. "node:dns/promises",
  11686. "dns/promises",
  11687. "node:domain",
  11688. "domain",
  11689. "node:events",
  11690. "events",
  11691. "node:fs",
  11692. "fs",
  11693. "node:fs/promises",
  11694. "fs/promises",
  11695. "node:http",
  11696. "http",
  11697. "node:http2",
  11698. "http2",
  11699. "node:https",
  11700. "https",
  11701. "node:inspector",
  11702. "inspector",
  11703. "node:inspector/promises",
  11704. "inspector/promises",
  11705. "node:module",
  11706. "module",
  11707. "node:net",
  11708. "net",
  11709. "node:os",
  11710. "os",
  11711. "node:path",
  11712. "path",
  11713. "node:path/posix",
  11714. "path/posix",
  11715. "node:path/win32",
  11716. "path/win32",
  11717. "node:perf_hooks",
  11718. "perf_hooks",
  11719. "node:process",
  11720. "process",
  11721. "node:querystring",
  11722. "querystring",
  11723. "node:quic",
  11724. "node:readline",
  11725. "readline",
  11726. "node:readline/promises",
  11727. "readline/promises",
  11728. "node:repl",
  11729. "repl",
  11730. "node:sea",
  11731. "node:sqlite",
  11732. "node:stream",
  11733. "stream",
  11734. "node:stream/consumers",
  11735. "stream/consumers",
  11736. "node:stream/promises",
  11737. "stream/promises",
  11738. "node:stream/web",
  11739. "stream/web",
  11740. "node:string_decoder",
  11741. "string_decoder",
  11742. "node:test",
  11743. "node:test/reporters",
  11744. "node:timers",
  11745. "timers",
  11746. "node:timers/promises",
  11747. "timers/promises",
  11748. "node:tls",
  11749. "tls",
  11750. "node:trace_events",
  11751. "trace_events",
  11752. "node:tty",
  11753. "tty",
  11754. "node:url",
  11755. "url",
  11756. "node:util",
  11757. "util",
  11758. "node:util/types",
  11759. "util/types",
  11760. "node:v8",
  11761. "v8",
  11762. "node:vm",
  11763. "vm",
  11764. "node:wasi",
  11765. "wasi",
  11766. "node:worker_threads",
  11767. "worker_threads",
  11768. "node:zlib",
  11769. "zlib"
  11770. ];
  11771. const nodeBuiltins = new Set(builtinModules);
  11772. function warnOnBuiltins(log, dependencies) {
  11773. const externalBuiltins = dependencies
  11774. .map(({ importPath }) => importPath)
  11775. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  11776. if (externalBuiltins.length === 0)
  11777. return;
  11778. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNodeBuiltins(externalBuiltins));
  11779. }
  11780. function amd(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  11781. warnOnBuiltins(log, dependencies);
  11782. throwOnPhase('amd', id, dependencies);
  11783. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  11784. const parameters = dependencies.map(m => m.name);
  11785. const { n, getNonArrowFunctionIntro, _ } = snippets;
  11786. if (hasExports && (namedExportsMode || exports$1[0]?.local === 'exports.default')) {
  11787. parameters.unshift(`exports`);
  11788. deps.unshift(`'exports'`);
  11789. }
  11790. if (accessedGlobals.has('require')) {
  11791. parameters.unshift('require');
  11792. deps.unshift(`'require'`);
  11793. }
  11794. if (accessedGlobals.has('module')) {
  11795. parameters.unshift('module');
  11796. deps.unshift(`'module'`);
  11797. }
  11798. const completeAmdId = getCompleteAmdId(amd, id);
  11799. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  11800. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  11801. const useStrict = strict ? `${_}'use strict';` : '';
  11802. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  11803. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11804. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11805. if (namespaceMarkers) {
  11806. namespaceMarkers = n + n + namespaceMarkers;
  11807. }
  11808. magicString
  11809. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11810. .indent(t)
  11811. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11812. // cf. https://v8.dev/blog/preparser#pife
  11813. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  11814. isAsync: false,
  11815. name: null
  11816. })}{${useStrict}${n}${n}`)
  11817. .append(`${n}${n}}));`);
  11818. }
  11819. function cjs(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  11820. throwOnPhase('cjs', id, dependencies);
  11821. const { _, n } = snippets;
  11822. const useStrict = strict ? `'use strict';${n}${n}` : '';
  11823. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11824. if (namespaceMarkers) {
  11825. namespaceMarkers += n + n;
  11826. }
  11827. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  11828. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  11829. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  11830. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  11831. magicString.append(`${exportBlock}${outro}`);
  11832. }
  11833. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  11834. let importBlock = '';
  11835. let definingVariable = false;
  11836. for (const { importPath, name, reexports, imports } of dependencies) {
  11837. if (!reexports && !imports) {
  11838. if (importBlock) {
  11839. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  11840. }
  11841. definingVariable = false;
  11842. importBlock += `require('${importPath}')`;
  11843. }
  11844. else {
  11845. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  11846. definingVariable = true;
  11847. importBlock += `${name}${_}=${_}require('${importPath}')`;
  11848. }
  11849. }
  11850. if (importBlock) {
  11851. return `${importBlock};${n}${n}`;
  11852. }
  11853. return '';
  11854. }
  11855. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports: exports$1, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  11856. const { n } = snippets;
  11857. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  11858. if (importBlock.length > 0)
  11859. intro += importBlock.join(n) + n + n;
  11860. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  11861. if (intro)
  11862. magicString.prepend(intro);
  11863. const exportBlock = getExportBlock(exports$1, snippets);
  11864. if (exportBlock.length > 0)
  11865. magicString.append(n + n + exportBlock.join(n).trim());
  11866. if (outro)
  11867. magicString.append(outro);
  11868. magicString.trim();
  11869. }
  11870. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  11871. const importBlock = [];
  11872. for (const { importPath, reexports, imports, name, attributes, sourcePhaseImport } of dependencies) {
  11873. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  11874. const pathWithAssertion = `'${importPath}'${assertion};`;
  11875. if (sourcePhaseImport) {
  11876. importBlock.push(`import source ${sourcePhaseImport} from${_}${pathWithAssertion}`);
  11877. }
  11878. if (!reexports && !imports) {
  11879. if (!sourcePhaseImport) {
  11880. importBlock.push(`import${_}${pathWithAssertion}`);
  11881. }
  11882. continue;
  11883. }
  11884. if (imports) {
  11885. let defaultImport = null;
  11886. let starImport = null;
  11887. const importedNames = [];
  11888. for (const specifier of imports) {
  11889. if (specifier.imported === 'default') {
  11890. defaultImport = specifier;
  11891. }
  11892. else if (specifier.imported === '*') {
  11893. starImport = specifier;
  11894. }
  11895. else {
  11896. importedNames.push(specifier);
  11897. }
  11898. }
  11899. if (starImport) {
  11900. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  11901. }
  11902. if (defaultImport && importedNames.length === 0) {
  11903. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  11904. }
  11905. else if (importedNames.length > 0) {
  11906. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  11907. .map(specifier => specifier.imported === specifier.local
  11908. ? specifier.imported
  11909. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  11910. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11911. }
  11912. }
  11913. if (reexports) {
  11914. let starExport = null;
  11915. const namespaceReexports = [];
  11916. const namedReexports = [];
  11917. for (const specifier of reexports) {
  11918. if (specifier.reexported === '*') {
  11919. starExport = specifier;
  11920. }
  11921. else if (specifier.imported === '*') {
  11922. namespaceReexports.push(specifier);
  11923. }
  11924. else {
  11925. namedReexports.push(specifier);
  11926. }
  11927. }
  11928. if (starExport) {
  11929. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  11930. }
  11931. if (namespaceReexports.length > 0) {
  11932. if (!imports ||
  11933. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  11934. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  11935. }
  11936. for (const specifier of namespaceReexports) {
  11937. importBlock.push(`export${_}{${_}${name === specifier.reexported
  11938. ? name
  11939. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  11940. }
  11941. }
  11942. if (namedReexports.length > 0) {
  11943. importBlock.push(`export${_}{${_}${namedReexports
  11944. .map(specifier => specifier.imported === specifier.reexported
  11945. ? stringifyIdentifierIfNeeded(specifier.imported)
  11946. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  11947. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11948. }
  11949. }
  11950. }
  11951. return importBlock;
  11952. }
  11953. function getExportBlock(exports$1, { _, cnst }) {
  11954. const exportBlock = [];
  11955. const exportDeclaration = new Array(exports$1.length);
  11956. let index = 0;
  11957. for (const specifier of exports$1) {
  11958. if (specifier.expression) {
  11959. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  11960. }
  11961. exportDeclaration[index++] =
  11962. specifier.exported === specifier.local
  11963. ? specifier.local
  11964. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  11965. }
  11966. if (exportDeclaration.length > 0) {
  11967. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  11968. }
  11969. return exportBlock;
  11970. }
  11971. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  11972. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  11973. const parts = name.split('.');
  11974. // Check if the key exists in the object's prototype.
  11975. const isReserved = parts[0] in Object.prototype;
  11976. if (log && isReserved) {
  11977. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  11978. }
  11979. parts[0] =
  11980. (typeof globals === 'function'
  11981. ? globals(parts[0])
  11982. : isReserved
  11983. ? parts[0]
  11984. : globals[parts[0]]) || parts[0];
  11985. parts.pop();
  11986. let propertyPath = root;
  11987. return (parts
  11988. .map(part => {
  11989. propertyPath += getPropertyAccess(part);
  11990. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  11991. })
  11992. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  11993. }
  11994. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  11995. const parts = deepName.split('.');
  11996. // Check if the key exists in the object's prototype.
  11997. const isReserved = parts[0] in Object.prototype;
  11998. if (log && isReserved) {
  11999. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  12000. }
  12001. parts[0] =
  12002. (typeof globals === 'function'
  12003. ? globals(parts[0])
  12004. : isReserved
  12005. ? parts[0]
  12006. : globals[parts[0]]) || parts[0];
  12007. const last = parts.pop();
  12008. let propertyPath = root;
  12009. let deepAssignment = [
  12010. ...parts.map(part => {
  12011. propertyPath += getPropertyAccess(part);
  12012. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12013. }),
  12014. `${propertyPath}${getPropertyAccess(last)}`
  12015. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  12016. if (parts.length > 0) {
  12017. deepAssignment = `(${deepAssignment})`;
  12018. }
  12019. return deepAssignment;
  12020. }
  12021. function trimEmptyImports(dependencies) {
  12022. let index = dependencies.length;
  12023. while (index--) {
  12024. const { imports, reexports } = dependencies[index];
  12025. if (imports || reexports) {
  12026. return dependencies.slice(0, index + 1);
  12027. }
  12028. }
  12029. return [];
  12030. }
  12031. function iife(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  12032. throwOnPhase('iife', id, dependencies);
  12033. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12034. const isNamespaced = name && name.includes('.');
  12035. const useVariableAssignment = !extend && !isNamespaced;
  12036. if (name && useVariableAssignment && !isLegal(name)) {
  12037. return parseAst_js.error(parseAst_js.logIllegalIdentifierAsName(name));
  12038. }
  12039. warnOnBuiltins(log, dependencies);
  12040. const external = trimEmptyImports(dependencies);
  12041. const deps = external.map(dep => dep.globalName || 'null');
  12042. const parameters = external.map(m => m.name);
  12043. if (hasExports && !name) {
  12044. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNameOptionForIifeExport());
  12045. }
  12046. if (hasExports && (namedExportsMode || exports$1[0]?.local === 'exports.default')) {
  12047. if (extend) {
  12048. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12049. parameters.unshift('exports');
  12050. }
  12051. else {
  12052. deps.unshift('{}');
  12053. parameters.unshift('exports');
  12054. }
  12055. }
  12056. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12057. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  12058. magicString.prepend(`${intro}${interopBlock}`);
  12059. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  12060. isAsync: false,
  12061. name: null
  12062. })}{${n}${useStrict}${n}`;
  12063. if (hasExports) {
  12064. if (name && !(extend && namedExportsMode)) {
  12065. wrapperIntro =
  12066. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12067. `${_}=${_}${wrapperIntro}`;
  12068. }
  12069. if (isNamespaced) {
  12070. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  12071. }
  12072. }
  12073. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12074. if (hasExports && !extend && namedExportsMode) {
  12075. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12076. }
  12077. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  12078. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  12079. if (namespaceMarkers) {
  12080. namespaceMarkers = n + n + namespaceMarkers;
  12081. }
  12082. magicString
  12083. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  12084. .indent(t)
  12085. .prepend(wrapperIntro)
  12086. .append(wrapperOutro);
  12087. }
  12088. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  12089. function system(magicString, { accessedGlobals, dependencies, exports: exports$1, hasExports, id, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  12090. throwOnPhase('system', id, dependencies);
  12091. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12092. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports$1, t, snippets);
  12093. const registeredName = name ? `'${name}',${_}` : '';
  12094. const wrapperParameters = accessedGlobals.has('module')
  12095. ? ['exports', 'module']
  12096. : hasExports
  12097. ? ['exports']
  12098. : [];
  12099. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12100. // cf. https://v8.dev/blog/preparser#pife
  12101. let wrapperStart = `System.register(${registeredName}[` +
  12102. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  12103. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  12104. isAsync: false,
  12105. name: null
  12106. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12107. getStarExcludesBlock(starExcludes, t, snippets) +
  12108. getImportBindingsBlock(importBindings, t, snippets) +
  12109. `${n}${t}return${_}{${setters.length > 0
  12110. ? `${n}${t}${t}setters:${_}[${setters
  12111. .map(setter => setter
  12112. ? `${getFunctionIntro(['module'], {
  12113. isAsync: false,
  12114. name: null
  12115. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12116. : systemNullSetters
  12117. ? `null`
  12118. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12119. .join(`,${_}`)}],`
  12120. : ''}${n}`;
  12121. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12122. isAsync: usesTopLevelAwait,
  12123. name: null
  12124. })}{${n}${n}`;
  12125. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12126. magicString
  12127. .prepend(intro +
  12128. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  12129. getHoistedExportsBlock(exports$1, t, snippets))
  12130. .append(`${outro}${n}${n}` +
  12131. getSyntheticExportsBlock(exports$1, t, snippets) +
  12132. getMissingExportsBlock(exports$1, t, snippets))
  12133. .indent(`${t}${t}${t}`)
  12134. .append(wrapperEnd)
  12135. .prepend(wrapperStart);
  12136. }
  12137. function analyzeDependencies(dependencies, exports$1, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12138. const importBindings = [];
  12139. const setters = [];
  12140. let starExcludes = null;
  12141. for (const { imports, reexports } of dependencies) {
  12142. const setter = [];
  12143. if (imports) {
  12144. for (const specifier of imports) {
  12145. importBindings.push(specifier.local);
  12146. if (specifier.imported === '*') {
  12147. setter.push(`${specifier.local}${_}=${_}module;`);
  12148. }
  12149. else {
  12150. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12151. }
  12152. }
  12153. }
  12154. if (reexports) {
  12155. const reexportedNames = [];
  12156. let hasStarReexport = false;
  12157. for (const { imported, reexported } of reexports) {
  12158. if (reexported === '*') {
  12159. hasStarReexport = true;
  12160. }
  12161. else {
  12162. reexportedNames.push([
  12163. reexported,
  12164. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  12165. ]);
  12166. }
  12167. }
  12168. if (reexportedNames.length > 1 || hasStarReexport) {
  12169. if (hasStarReexport) {
  12170. if (!starExcludes) {
  12171. starExcludes = getStarExcludes({ dependencies, exports: exports$1 });
  12172. }
  12173. reexportedNames.unshift([null, `__proto__:${_}null`]);
  12174. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12175. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  12176. }
  12177. else {
  12178. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12179. setter.push(`exports(${exportMapping});`);
  12180. }
  12181. }
  12182. else {
  12183. const [key, value] = reexportedNames[0];
  12184. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  12185. }
  12186. }
  12187. setters.push(setter.join(`${n}${t}${t}${t}`));
  12188. }
  12189. return { importBindings, setters, starExcludes };
  12190. }
  12191. const getStarExcludes = ({ dependencies, exports: exports$1 }) => {
  12192. const starExcludes = new Set(exports$1.map(expt => expt.exported));
  12193. starExcludes.add('default');
  12194. for (const { reexports } of dependencies) {
  12195. if (reexports) {
  12196. for (const reexport of reexports) {
  12197. if (reexport.reexported !== '*')
  12198. starExcludes.add(reexport.reexported);
  12199. }
  12200. }
  12201. }
  12202. return starExcludes;
  12203. };
  12204. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  12205. if (starExcludes) {
  12206. const fields = [...starExcludes].map(property => [
  12207. property,
  12208. '1'
  12209. ]);
  12210. fields.unshift([null, `__proto__:${_}null`]);
  12211. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  12212. lineBreakIndent: { base: t, t }
  12213. })};`;
  12214. }
  12215. return '';
  12216. };
  12217. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  12218. const getHoistedExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12219. function getExportsBlock(exports$1, t, { _, n }) {
  12220. if (exports$1.length === 0) {
  12221. return '';
  12222. }
  12223. if (exports$1.length === 1) {
  12224. return `exports(${JSON.stringify(exports$1[0].name)},${_}${exports$1[0].value});${n}${n}`;
  12225. }
  12226. return (`exports({${n}` +
  12227. exports$1
  12228. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  12229. .join(`,${n}`) +
  12230. `${n}});${n}${n}`);
  12231. }
  12232. const getSyntheticExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1
  12233. .filter(expt => expt.expression)
  12234. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12235. const getMissingExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1
  12236. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  12237. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  12238. function globalProperty(name, globalVariable, getPropertyAccess) {
  12239. if (!name)
  12240. return 'null';
  12241. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  12242. }
  12243. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  12244. let propertyPath = globalVariable;
  12245. return name
  12246. .split('.')
  12247. .map(part => (propertyPath += getPropertyAccess(part)))
  12248. .join(`${_}&&${_}`);
  12249. }
  12250. function umd(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  12251. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  12252. const factoryVariable = compact ? 'f' : 'factory';
  12253. const globalVariable = compact ? 'g' : 'global';
  12254. if (hasExports && !name) {
  12255. return parseAst_js.error(parseAst_js.logMissingNameOptionForUmdExport());
  12256. }
  12257. throwOnPhase('umd', id, dependencies);
  12258. warnOnBuiltins(log, dependencies);
  12259. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  12260. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  12261. const trimmedImports = trimEmptyImports(dependencies);
  12262. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  12263. const factoryParameters = trimmedImports.map(m => m.name);
  12264. if ((hasExports || noConflict) &&
  12265. (namedExportsMode || (hasExports && exports$1[0]?.local === 'exports.default'))) {
  12266. amdDeps.unshift(`'exports'`);
  12267. cjsDeps.unshift(`exports`);
  12268. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  12269. factoryParameters.unshift('exports');
  12270. }
  12271. const completeAmdId = getCompleteAmdId(amd, id);
  12272. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12273. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  12274. const define = amd.define;
  12275. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  12276. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  12277. let iifeExport;
  12278. if (noConflict) {
  12279. const noConflictExportsVariable = compact ? 'e' : 'exports';
  12280. let factory;
  12281. if (!namedExportsMode && hasExports) {
  12282. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  12283. }
  12284. else {
  12285. const module = globalDeps.shift();
  12286. factory =
  12287. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  12288. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  12289. }
  12290. iifeExport =
  12291. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  12292. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  12293. `${t}${t}${factory}${n}` +
  12294. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  12295. isAsync: false,
  12296. name: null
  12297. })}{${_}` +
  12298. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  12299. `${t}})()`;
  12300. }
  12301. else {
  12302. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  12303. if (!namedExportsMode && hasExports) {
  12304. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  12305. }
  12306. }
  12307. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  12308. const wrapperParameters = [factoryVariable];
  12309. if (iifeNeedsGlobal) {
  12310. wrapperParameters.unshift(globalVariable);
  12311. }
  12312. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  12313. const iifeStart = iifeNeedsGlobal
  12314. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  12315. : '';
  12316. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  12317. const cjsIntro = iifeNeedsGlobal
  12318. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  12319. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  12320. : '';
  12321. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  12322. cjsIntro +
  12323. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  12324. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  12325. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12326. // cf. https://v8.dev/blog/preparser#pife
  12327. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  12328. isAsync: false,
  12329. name: null
  12330. })}{${useStrict}${n}`;
  12331. const wrapperOutro = n + n + '}));';
  12332. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  12333. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  12334. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  12335. if (namespaceMarkers) {
  12336. namespaceMarkers = n + n + namespaceMarkers;
  12337. }
  12338. magicString
  12339. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  12340. .trim()
  12341. .indent(t)
  12342. .append(wrapperOutro)
  12343. .prepend(wrapperIntro);
  12344. }
  12345. const finalisers = { amd, cjs, es, iife, system, umd };
  12346. const extractors = {
  12347. ArrayPattern(names, param) {
  12348. for (const element of param.elements) {
  12349. if (element)
  12350. extractors[element.type](names, element);
  12351. }
  12352. },
  12353. AssignmentPattern(names, param) {
  12354. extractors[param.left.type](names, param.left);
  12355. },
  12356. Identifier(names, param) {
  12357. names.push(param.name);
  12358. },
  12359. MemberExpression() { },
  12360. ObjectPattern(names, param) {
  12361. for (const prop of param.properties) {
  12362. // @ts-ignore Typescript reports that this is not a valid type
  12363. if (prop.type === 'RestElement') {
  12364. extractors.RestElement(names, prop);
  12365. }
  12366. else {
  12367. extractors[prop.value.type](names, prop.value);
  12368. }
  12369. }
  12370. },
  12371. RestElement(names, param) {
  12372. extractors[param.argument.type](names, param.argument);
  12373. }
  12374. };
  12375. const extractAssignedNames = function extractAssignedNames(param) {
  12376. const names = [];
  12377. extractors[param.type](names, param);
  12378. return names;
  12379. };
  12380. // Helper since Typescript can't detect readonly arrays with Array.isArray
  12381. function isArray(arg) {
  12382. return Array.isArray(arg);
  12383. }
  12384. function ensureArray(thing) {
  12385. if (isArray(thing))
  12386. return thing;
  12387. if (thing == null)
  12388. return [];
  12389. return [thing];
  12390. }
  12391. const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
  12392. const normalizePath = function normalizePath(filename) {
  12393. return filename.replace(normalizePathRegExp, require$$0.posix.sep);
  12394. };
  12395. function getMatcherString(id, resolutionBase) {
  12396. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
  12397. return normalizePath(id);
  12398. }
  12399. // resolve('') is valid and will default to process.cwd()
  12400. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  12401. // escape all possible (posix + win) path characters that might interfere with regex
  12402. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  12403. // Note that we use posix.join because:
  12404. // 1. the basePath has been normalized to use /
  12405. // 2. the incoming glob (id) matcher, also uses /
  12406. // otherwise Node will force backslash (\) on windows
  12407. return require$$0.posix.join(basePath, normalizePath(id));
  12408. }
  12409. const createFilter = function createFilter(include, exclude, options) {
  12410. const resolutionBase = options && options.resolve;
  12411. const getMatcher = (id) => id instanceof RegExp
  12412. ? id
  12413. : {
  12414. test: (what) => {
  12415. // this refactor is a tad overly verbose but makes for easy debugging
  12416. const pattern = getMatcherString(id, resolutionBase);
  12417. const fn = pm(pattern, { dot: true });
  12418. const result = fn(what);
  12419. return result;
  12420. }
  12421. };
  12422. const includeMatchers = ensureArray(include).map(getMatcher);
  12423. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  12424. if (!includeMatchers.length && !excludeMatchers.length)
  12425. return (id) => typeof id === 'string' && !id.includes('\0');
  12426. return function result(id) {
  12427. if (typeof id !== 'string')
  12428. return false;
  12429. if (id.includes('\0'))
  12430. return false;
  12431. const pathId = normalizePath(id);
  12432. for (let i = 0; i < excludeMatchers.length; ++i) {
  12433. const matcher = excludeMatchers[i];
  12434. if (matcher instanceof RegExp) {
  12435. matcher.lastIndex = 0;
  12436. }
  12437. if (matcher.test(pathId))
  12438. return false;
  12439. }
  12440. for (let i = 0; i < includeMatchers.length; ++i) {
  12441. const matcher = includeMatchers[i];
  12442. if (matcher instanceof RegExp) {
  12443. matcher.lastIndex = 0;
  12444. }
  12445. if (matcher.test(pathId))
  12446. return true;
  12447. }
  12448. return !includeMatchers.length;
  12449. };
  12450. };
  12451. 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';
  12452. 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';
  12453. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  12454. forbiddenIdentifiers.add('');
  12455. class ArrayPattern extends NodeBase {
  12456. addExportedVariables(variables, exportNamesByVariable) {
  12457. for (const element of this.elements) {
  12458. element?.addExportedVariables(variables, exportNamesByVariable);
  12459. }
  12460. }
  12461. declare(kind, destructuredInitPath, init) {
  12462. const variables = [];
  12463. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12464. for (const element of this.elements) {
  12465. if (element !== null) {
  12466. variables.push(...element.declare(kind, includedPatternPath, init));
  12467. }
  12468. }
  12469. return variables;
  12470. }
  12471. deoptimizeAssignment(destructuredInitPath, init) {
  12472. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12473. for (const element of this.elements) {
  12474. element?.deoptimizeAssignment(includedPatternPath, init);
  12475. }
  12476. }
  12477. // Patterns can only be deoptimized at the empty path at the moment
  12478. deoptimizePath() {
  12479. for (const element of this.elements) {
  12480. element?.deoptimizePath(EMPTY_PATH);
  12481. }
  12482. }
  12483. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12484. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12485. for (const element of this.elements) {
  12486. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  12487. return true;
  12488. }
  12489. }
  12490. return false;
  12491. }
  12492. // Patterns are only checked at the empty path at the moment
  12493. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  12494. for (const element of this.elements) {
  12495. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12496. return true;
  12497. }
  12498. return false;
  12499. }
  12500. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12501. let included = false;
  12502. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12503. for (const element of [...this.elements].reverse()) {
  12504. if (element) {
  12505. if (included && !element.included) {
  12506. element.includeNode(context);
  12507. }
  12508. included =
  12509. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  12510. }
  12511. }
  12512. if (!this.included && included) {
  12513. this.includeNode(context);
  12514. }
  12515. return this.included;
  12516. }
  12517. render(code, options) {
  12518. let removedStart = this.start + 1;
  12519. for (const element of this.elements) {
  12520. if (!element)
  12521. continue;
  12522. if (element.included) {
  12523. element.render(code, options);
  12524. removedStart = element.end;
  12525. }
  12526. else {
  12527. code.remove(removedStart, this.end - 1);
  12528. break;
  12529. }
  12530. }
  12531. }
  12532. markDeclarationReached() {
  12533. for (const element of this.elements) {
  12534. element?.markDeclarationReached();
  12535. }
  12536. }
  12537. }
  12538. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  12539. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  12540. ? destructuredInitPath
  12541. : [...destructuredInitPath, UnknownInteger];
  12542. class ArrowFunctionExpression extends FunctionBase {
  12543. constructor() {
  12544. super(...arguments);
  12545. this.objectEntity = null;
  12546. }
  12547. get expression() {
  12548. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  12549. }
  12550. set expression(value) {
  12551. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  12552. }
  12553. createScope(parentScope) {
  12554. this.scope = new ReturnValueScope(parentScope, false);
  12555. }
  12556. hasEffects() {
  12557. return false;
  12558. }
  12559. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12560. if (this.annotationNoSideEffects &&
  12561. path.length === 0 &&
  12562. interaction.type === INTERACTION_CALLED) {
  12563. return false;
  12564. }
  12565. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  12566. return true;
  12567. }
  12568. if (interaction.type === INTERACTION_CALLED) {
  12569. const { ignore, brokenFlow } = context;
  12570. context.ignore = {
  12571. breaks: false,
  12572. continues: false,
  12573. labels: new Set(),
  12574. returnYield: true,
  12575. this: false
  12576. };
  12577. if (this.body.hasEffects(context))
  12578. return true;
  12579. context.ignore = ignore;
  12580. context.brokenFlow = brokenFlow;
  12581. }
  12582. return false;
  12583. }
  12584. onlyFunctionCallUsed() {
  12585. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  12586. this.parent.callee === this;
  12587. return isIIFE || super.onlyFunctionCallUsed();
  12588. }
  12589. include(context, includeChildrenRecursively) {
  12590. super.include(context, includeChildrenRecursively);
  12591. for (const parameter of this.params) {
  12592. if (!(parameter instanceof Identifier)) {
  12593. parameter.include(context, includeChildrenRecursively);
  12594. }
  12595. }
  12596. }
  12597. includeNode(context) {
  12598. this.included = true;
  12599. this.body.includePath(UNKNOWN_PATH, context);
  12600. for (const parameter of this.params) {
  12601. if (!(parameter instanceof Identifier)) {
  12602. parameter.includePath(UNKNOWN_PATH, context);
  12603. }
  12604. }
  12605. }
  12606. getObjectEntity() {
  12607. if (this.objectEntity !== null) {
  12608. return this.objectEntity;
  12609. }
  12610. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  12611. }
  12612. }
  12613. class ObjectPattern extends NodeBase {
  12614. addExportedVariables(variables, exportNamesByVariable) {
  12615. for (const property of this.properties) {
  12616. if (property.type === parseAst_js.Property) {
  12617. property.value.addExportedVariables(variables, exportNamesByVariable);
  12618. }
  12619. else {
  12620. property.argument.addExportedVariables(variables, exportNamesByVariable);
  12621. }
  12622. }
  12623. }
  12624. declare(kind, destructuredInitPath, init) {
  12625. const variables = [];
  12626. for (const property of this.properties) {
  12627. variables.push(...property.declare(kind, destructuredInitPath, init));
  12628. }
  12629. return variables;
  12630. }
  12631. deoptimizeAssignment(destructuredInitPath, init) {
  12632. for (const property of this.properties) {
  12633. property.deoptimizeAssignment(destructuredInitPath, init);
  12634. }
  12635. }
  12636. deoptimizePath(path) {
  12637. if (path.length === 0) {
  12638. for (const property of this.properties) {
  12639. property.deoptimizePath(path);
  12640. }
  12641. }
  12642. }
  12643. hasEffectsOnInteractionAtPath(
  12644. // At the moment, this is only triggered for assignment left-hand sides,
  12645. // where the path is empty
  12646. _path, interaction, context) {
  12647. for (const property of this.properties) {
  12648. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12649. return true;
  12650. }
  12651. return false;
  12652. }
  12653. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12654. for (const property of this.properties) {
  12655. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  12656. return true;
  12657. }
  12658. return false;
  12659. }
  12660. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12661. if (!this.properties.length)
  12662. return this.included;
  12663. const lastProperty = this.properties.at(-1);
  12664. let included = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12665. const lastPropertyIsRestElement = lastProperty.type === parseAst_js.RestElement;
  12666. for (const property of this.properties.slice(0, -1)) {
  12667. if (lastPropertyIsRestElement && included && !property.included) {
  12668. property.includeNode(context);
  12669. }
  12670. included =
  12671. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  12672. }
  12673. if (!this.included && included) {
  12674. this.includeNode(context);
  12675. }
  12676. return this.included;
  12677. }
  12678. markDeclarationReached() {
  12679. for (const property of this.properties) {
  12680. property.markDeclarationReached();
  12681. }
  12682. }
  12683. render(code, options) {
  12684. if (this.properties.length > 0) {
  12685. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  12686. let lastSeparatorPos = null;
  12687. for (const { node, separator, start, end } of separatedNodes) {
  12688. if (!node.included) {
  12689. treeshakeNode(node, code, start, end);
  12690. continue;
  12691. }
  12692. lastSeparatorPos = separator;
  12693. node.render(code, options);
  12694. }
  12695. if (lastSeparatorPos) {
  12696. code.remove(lastSeparatorPos, this.end - 1);
  12697. }
  12698. }
  12699. }
  12700. }
  12701. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12702. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  12703. class AssignmentExpression extends NodeBase {
  12704. constructor() {
  12705. super(...arguments);
  12706. this.isConstReassignment = false;
  12707. }
  12708. hasEffects(context) {
  12709. const { deoptimized, isConstReassignment, left, operator, right } = this;
  12710. if (!deoptimized)
  12711. this.applyDeoptimizations();
  12712. // MemberExpressions do not access the property before assignments if the
  12713. // operator is '='.
  12714. return (isConstReassignment ||
  12715. right.hasEffects(context) ||
  12716. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  12717. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  12718. }
  12719. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12720. return ((interaction.type === INTERACTION_ASSIGNED && this.left.included) ||
  12721. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  12722. }
  12723. include(context, includeChildrenRecursively) {
  12724. const { deoptimized, isConstReassignment, left, right, operator } = this;
  12725. if (!deoptimized)
  12726. this.applyDeoptimizations();
  12727. if (!this.included)
  12728. this.includeNode(context);
  12729. const hasEffectsContext = createHasEffectsContext();
  12730. if (includeChildrenRecursively ||
  12731. isConstReassignment ||
  12732. operator !== '=' ||
  12733. left.included ||
  12734. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  12735. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  12736. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  12737. }
  12738. right.include(context, includeChildrenRecursively);
  12739. }
  12740. includeNode(context) {
  12741. this.included = true;
  12742. if (!this.deoptimized)
  12743. this.applyDeoptimizations();
  12744. this.right.includePath(UNKNOWN_PATH, context);
  12745. }
  12746. initialise() {
  12747. super.initialise();
  12748. if (this.left instanceof Identifier) {
  12749. const variable = this.scope.variables.get(this.left.name);
  12750. if (variable?.kind === 'const') {
  12751. this.isConstReassignment = true;
  12752. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logConstVariableReassignError(), this.left.start);
  12753. }
  12754. }
  12755. this.left.setAssignedValue(this.right);
  12756. }
  12757. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12758. const { left, right, start, end, parent } = this;
  12759. if (left.included) {
  12760. left.render(code, options);
  12761. right.render(code, options);
  12762. }
  12763. else {
  12764. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  12765. code.remove(start, inclusionStart);
  12766. if (preventASI) {
  12767. removeLineBreaks(code, inclusionStart, right.start);
  12768. }
  12769. right.render(code, options, {
  12770. renderedParentType: renderedParentType || parent.type,
  12771. renderedSurroundingElement: renderedSurroundingElement || parent.type
  12772. });
  12773. }
  12774. if (options.format === 'system') {
  12775. if (left instanceof Identifier) {
  12776. const variable = left.variable;
  12777. const exportNames = options.exportNamesByVariable.get(variable);
  12778. if (exportNames) {
  12779. if (exportNames.length === 1) {
  12780. renderSystemExportExpression(variable, start, end, code, options);
  12781. }
  12782. else {
  12783. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== parseAst_js.ExpressionStatement, code, options);
  12784. }
  12785. return;
  12786. }
  12787. }
  12788. else {
  12789. const systemPatternExports = [];
  12790. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  12791. if (systemPatternExports.length > 0) {
  12792. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === parseAst_js.ExpressionStatement, code, options);
  12793. return;
  12794. }
  12795. }
  12796. }
  12797. if (left.included &&
  12798. left instanceof ObjectPattern &&
  12799. (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  12800. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression)) {
  12801. code.appendRight(start, '(');
  12802. code.prependLeft(end, ')');
  12803. }
  12804. }
  12805. applyDeoptimizations() {
  12806. this.deoptimized = true;
  12807. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  12808. this.scope.context.requestTreeshakingPass();
  12809. }
  12810. }
  12811. class AssignmentPattern extends NodeBase {
  12812. addExportedVariables(variables, exportNamesByVariable) {
  12813. this.left.addExportedVariables(variables, exportNamesByVariable);
  12814. }
  12815. declare(kind, destructuredInitPath, init) {
  12816. return this.left.declare(kind, destructuredInitPath, init);
  12817. }
  12818. deoptimizeAssignment(destructuredInitPath, init) {
  12819. this.left.deoptimizeAssignment(destructuredInitPath, init);
  12820. }
  12821. deoptimizePath(path) {
  12822. if (path.length === 0) {
  12823. this.left.deoptimizePath(path);
  12824. }
  12825. }
  12826. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12827. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  12828. }
  12829. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12830. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  12831. }
  12832. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12833. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  12834. this.included;
  12835. if ((included ||= this.right.shouldBeIncluded(context))) {
  12836. this.right.include(context, false);
  12837. if (!this.left.included) {
  12838. this.left.includeNode(context);
  12839. // Unfortunately, we need to include the left side again now, so that
  12840. // any declared variables are properly included.
  12841. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12842. }
  12843. }
  12844. if (!this.included && included) {
  12845. this.includeNode(context);
  12846. }
  12847. return this.included;
  12848. }
  12849. includeNode(context) {
  12850. this.included = true;
  12851. if (!this.deoptimized)
  12852. this.applyDeoptimizations();
  12853. this.right.includePath(UNKNOWN_PATH, context);
  12854. }
  12855. markDeclarationReached() {
  12856. this.left.markDeclarationReached();
  12857. }
  12858. render(code, options, { isShorthandProperty } = parseAst_js.BLANK) {
  12859. this.left.render(code, options, { isShorthandProperty });
  12860. this.right.render(code, options);
  12861. }
  12862. applyDeoptimizations() {
  12863. this.deoptimized = true;
  12864. this.left.deoptimizePath(EMPTY_PATH);
  12865. this.right.deoptimizePath(UNKNOWN_PATH);
  12866. this.scope.context.requestTreeshakingPass();
  12867. }
  12868. }
  12869. class AwaitExpression extends NodeBase {
  12870. deoptimizePath(path) {
  12871. this.argument.deoptimizePath(path);
  12872. }
  12873. hasEffects() {
  12874. if (!this.deoptimized)
  12875. this.applyDeoptimizations();
  12876. return true;
  12877. }
  12878. initialise() {
  12879. super.initialise();
  12880. let parent = this.parent;
  12881. do {
  12882. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  12883. return;
  12884. } while ((parent = parent.parent));
  12885. this.scope.context.usesTopLevelAwait = true;
  12886. }
  12887. include(context, includeChildrenRecursively) {
  12888. if (!this.included)
  12889. this.includeNode(context);
  12890. this.argument.include(context, includeChildrenRecursively);
  12891. }
  12892. includeNode(context) {
  12893. this.included = true;
  12894. if (!this.deoptimized)
  12895. this.applyDeoptimizations();
  12896. // Thenables need to be included
  12897. this.argument.includePath(THEN_PATH, context);
  12898. }
  12899. includePath(path, context) {
  12900. if (!this.deoptimized)
  12901. this.applyDeoptimizations();
  12902. if (!this.included)
  12903. this.includeNode(context);
  12904. this.argument.includePath(path, context);
  12905. }
  12906. }
  12907. const THEN_PATH = ['then'];
  12908. function getRenderedLiteralValue(value) {
  12909. if (value === undefined) {
  12910. return 'void 0';
  12911. }
  12912. if (typeof value === 'boolean') {
  12913. return String(value);
  12914. }
  12915. if (typeof value === 'string') {
  12916. return JSON.stringify(value);
  12917. }
  12918. if (typeof value === 'number') {
  12919. return getSimplifiedNumber(value);
  12920. }
  12921. return UnknownValue;
  12922. }
  12923. function getSimplifiedNumber(value) {
  12924. if (Object.is(-0, value)) {
  12925. return '-0';
  12926. }
  12927. const exp = value.toExponential();
  12928. const [base, exponent] = exp.split('e');
  12929. const floatLength = base.split('.')[1]?.length || 0;
  12930. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  12931. const stringifiedValue = String(value).replace('+', '');
  12932. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  12933. }
  12934. const binaryOperators = {
  12935. '!=': (left, right) => left != right,
  12936. '!==': (left, right) => left !== right,
  12937. '%': (left, right) => left % right,
  12938. '&': (left, right) => left & right,
  12939. '*': (left, right) => left * right,
  12940. // At the moment, "**" will be transpiled to Math.pow
  12941. '**': (left, right) => left ** right,
  12942. '+': (left, right) => left + right,
  12943. '-': (left, right) => left - right,
  12944. '/': (left, right) => left / right,
  12945. '<': (left, right) => left < right,
  12946. '<<': (left, right) => left << right,
  12947. '<=': (left, right) => left <= right,
  12948. '==': (left, right) => left == right,
  12949. '===': (left, right) => left === right,
  12950. '>': (left, right) => left > right,
  12951. '>=': (left, right) => left >= right,
  12952. '>>': (left, right) => left >> right,
  12953. '>>>': (left, right) => left >>> right,
  12954. '^': (left, right) => left ^ right,
  12955. '|': (left, right) => left | right
  12956. // We use the fallback for cases where we return something unknown
  12957. // in: () => UnknownValue,
  12958. // instanceof: () => UnknownValue,
  12959. };
  12960. const UNASSIGNED$1 = Symbol('Unassigned');
  12961. class BinaryExpression extends NodeBase {
  12962. constructor() {
  12963. super(...arguments);
  12964. this.renderedLiteralValue = UNASSIGNED$1;
  12965. }
  12966. deoptimizeCache() {
  12967. this.renderedLiteralValue = UnknownValue;
  12968. }
  12969. getLiteralValueAtPath(path, recursionTracker, origin) {
  12970. if (path.length > 0)
  12971. return UnknownValue;
  12972. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12973. if (typeof leftValue === 'symbol')
  12974. return UnknownValue;
  12975. // Optimize `'export' in namespace`
  12976. if (this.operator === 'in' && this.right.variable instanceof NamespaceVariable) {
  12977. const [variable] = this.right.variable.context.traceExport(String(leftValue));
  12978. if (variable instanceof ExternalVariable)
  12979. return UnknownValue;
  12980. if (variable instanceof SyntheticNamedExportVariable)
  12981. return UnknownValue;
  12982. return !!variable;
  12983. }
  12984. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12985. if (typeof rightValue === 'symbol')
  12986. return UnknownValue;
  12987. const operatorFunction = binaryOperators[this.operator];
  12988. if (!operatorFunction)
  12989. return UnknownValue;
  12990. return operatorFunction(leftValue, rightValue);
  12991. }
  12992. getRenderedLiteralValue() {
  12993. // Only optimize `'export' in ns`
  12994. if (this.operator !== 'in' || !(this.right.variable instanceof NamespaceVariable)) {
  12995. return UnknownValue;
  12996. }
  12997. if (this.renderedLiteralValue !== UNASSIGNED$1)
  12998. return this.renderedLiteralValue;
  12999. return (this.renderedLiteralValue = getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  13000. }
  13001. hasEffects(context) {
  13002. // support some implicit type coercion runtime errors
  13003. if (this.operator === '+' &&
  13004. this.parent instanceof ExpressionStatement &&
  13005. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  13006. return true;
  13007. }
  13008. return super.hasEffects(context);
  13009. }
  13010. hasEffectsOnInteractionAtPath(path, { type }) {
  13011. return type !== INTERACTION_ACCESSED || path.length > 1;
  13012. }
  13013. include(context, includeChildrenRecursively, options) {
  13014. if (!this.included)
  13015. this.includeNode(context);
  13016. if (typeof this.getRenderedLiteralValue() === 'symbol') {
  13017. this.left.include(context, includeChildrenRecursively, options);
  13018. this.right.include(context, includeChildrenRecursively, options);
  13019. // `instanceof` will attempt to call RHS's `Symbol.hasInstance` if it exists.
  13020. if (this.operator === 'instanceof')
  13021. this.right.includePath(INSTANCEOF_PATH, context);
  13022. }
  13023. }
  13024. includeNode(context) {
  13025. this.included = true;
  13026. if (this.operator === 'in' && typeof this.getRenderedLiteralValue() === 'symbol') {
  13027. this.right.includePath(UNKNOWN_PATH, context);
  13028. }
  13029. }
  13030. removeAnnotations(code) {
  13031. this.left.removeAnnotations(code);
  13032. }
  13033. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13034. const renderedLiteralValue = this.getRenderedLiteralValue();
  13035. if (typeof renderedLiteralValue !== 'symbol') {
  13036. code.overwrite(this.start, this.end, renderedLiteralValue);
  13037. }
  13038. else {
  13039. this.left.render(code, options, { renderedSurroundingElement });
  13040. this.right.render(code, options);
  13041. }
  13042. }
  13043. }
  13044. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13045. class BreakStatement extends NodeBase {
  13046. hasEffects(context) {
  13047. if (this.label) {
  13048. if (!context.ignore.labels.has(this.label.name))
  13049. return true;
  13050. context.includedLabels.add(this.label.name);
  13051. }
  13052. else {
  13053. if (!context.ignore.breaks)
  13054. return true;
  13055. context.hasBreak = true;
  13056. }
  13057. context.brokenFlow = true;
  13058. return false;
  13059. }
  13060. include(context, includeChildrenRecursively) {
  13061. this.included = true;
  13062. if (this.label) {
  13063. this.label.include(context, includeChildrenRecursively);
  13064. context.includedLabels.add(this.label.name);
  13065. }
  13066. else {
  13067. context.hasBreak = true;
  13068. }
  13069. context.brokenFlow = true;
  13070. }
  13071. }
  13072. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13073. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13074. function renderCallArguments(code, options, node) {
  13075. if (node.arguments.length > 0) {
  13076. if (node.arguments[node.arguments.length - 1].included) {
  13077. for (const argument of node.arguments) {
  13078. argument.render(code, options);
  13079. }
  13080. }
  13081. else {
  13082. let lastIncludedIndex = node.arguments.length - 2;
  13083. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  13084. lastIncludedIndex--;
  13085. }
  13086. if (lastIncludedIndex >= 0) {
  13087. for (let index = 0; index <= lastIncludedIndex; index++) {
  13088. node.arguments[index].render(code, options);
  13089. }
  13090. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  13091. }
  13092. else {
  13093. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  13094. }
  13095. }
  13096. }
  13097. }
  13098. class CallExpressionBase extends NodeBase {
  13099. constructor() {
  13100. super(...arguments);
  13101. this.returnExpression = null;
  13102. this.deoptimizableDependentExpressions = [];
  13103. this.expressionsToBeDeoptimized = new Set();
  13104. }
  13105. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13106. const { args } = interaction;
  13107. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  13108. if (isPure)
  13109. return;
  13110. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  13111. if (deoptimizedExpressions.length === 0)
  13112. return;
  13113. if (returnExpression === UNKNOWN_EXPRESSION) {
  13114. for (const expression of deoptimizedExpressions) {
  13115. expression.deoptimizePath(UNKNOWN_PATH);
  13116. }
  13117. }
  13118. else {
  13119. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  13120. for (const expression of deoptimizedExpressions) {
  13121. this.expressionsToBeDeoptimized.add(expression);
  13122. }
  13123. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13124. }, null);
  13125. }
  13126. }
  13127. deoptimizeCache() {
  13128. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  13129. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13130. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  13131. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_SET;
  13132. this.deoptimizableDependentExpressions = parseAst_js.EMPTY_ARRAY;
  13133. for (const expression of deoptimizableDependentExpressions) {
  13134. expression.deoptimizeCache();
  13135. }
  13136. for (const expression of expressionsToBeDeoptimized) {
  13137. expression.deoptimizePath(UNKNOWN_PATH);
  13138. }
  13139. }
  13140. }
  13141. deoptimizePath(path) {
  13142. if (path.length === 0 ||
  13143. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  13144. return;
  13145. }
  13146. const [returnExpression] = this.getReturnExpression();
  13147. if (returnExpression !== UNKNOWN_EXPRESSION) {
  13148. returnExpression.deoptimizePath(path);
  13149. }
  13150. }
  13151. getLiteralValueAtPath(path, recursionTracker, origin) {
  13152. const [returnExpression] = this.getReturnExpression(recursionTracker);
  13153. if (returnExpression === UNKNOWN_EXPRESSION) {
  13154. return UnknownValue;
  13155. }
  13156. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  13157. this.deoptimizableDependentExpressions.push(origin);
  13158. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  13159. }, UnknownValue);
  13160. }
  13161. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13162. const returnExpression = this.getReturnExpression(recursionTracker);
  13163. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  13164. return returnExpression;
  13165. }
  13166. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  13167. this.deoptimizableDependentExpressions.push(origin);
  13168. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13169. return [expression, isPure || returnExpression[1]];
  13170. }, UNKNOWN_RETURN_EXPRESSION);
  13171. }
  13172. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13173. const { type } = interaction;
  13174. if (type === INTERACTION_CALLED) {
  13175. const { args, withNew } = interaction;
  13176. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  13177. return false;
  13178. }
  13179. }
  13180. else if ((type === INTERACTION_ASSIGNED
  13181. ? context.assigned
  13182. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  13183. return false;
  13184. }
  13185. const [returnExpression, isPure] = this.getReturnExpression();
  13186. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  13187. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  13188. }
  13189. }
  13190. class CallExpression extends CallExpressionBase {
  13191. get hasCheckedForWarnings() {
  13192. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  13193. }
  13194. set hasCheckedForWarnings(value) {
  13195. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  13196. }
  13197. get optional() {
  13198. return isFlagSet(this.flags, 128 /* Flag.optional */);
  13199. }
  13200. set optional(value) {
  13201. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  13202. }
  13203. bind() {
  13204. super.bind();
  13205. this.interaction = {
  13206. args: [
  13207. this.callee instanceof MemberExpression && !this.callee.variable
  13208. ? this.callee.object
  13209. : null,
  13210. ...this.arguments
  13211. ],
  13212. type: INTERACTION_CALLED,
  13213. withNew: false
  13214. };
  13215. }
  13216. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  13217. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  13218. }
  13219. hasEffects(context) {
  13220. if (!this.deoptimized)
  13221. this.applyDeoptimizations();
  13222. for (const argument of this.arguments) {
  13223. if (argument.hasEffects(context))
  13224. return true;
  13225. }
  13226. if (this.annotationPure) {
  13227. return false;
  13228. }
  13229. return (this.callee.hasEffects(context) ||
  13230. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13231. }
  13232. hasEffectsAsChainElement(context) {
  13233. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  13234. ? this.callee.hasEffectsAsChainElement(context)
  13235. : this.callee.hasEffects(context);
  13236. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  13237. return IS_SKIPPED_CHAIN;
  13238. if (this.optional &&
  13239. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  13240. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  13241. }
  13242. // We only apply deoptimizations lazily once we know we are not skipping
  13243. if (!this.deoptimized)
  13244. this.applyDeoptimizations();
  13245. for (const argument of this.arguments) {
  13246. if (argument.hasEffects(context))
  13247. return true;
  13248. }
  13249. return (!this.annotationPure &&
  13250. (calleeHasEffects ||
  13251. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  13252. }
  13253. include(context, includeChildrenRecursively) {
  13254. if (!this.included)
  13255. this.includeNode(context);
  13256. if (includeChildrenRecursively) {
  13257. super.include(context, true);
  13258. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  13259. this.callee instanceof Identifier &&
  13260. this.callee.variable) {
  13261. this.callee.variable.markCalledFromTryStatement();
  13262. }
  13263. }
  13264. else {
  13265. this.callee.include(context, false);
  13266. this.callee.includeCallArguments(this.interaction, context);
  13267. }
  13268. }
  13269. includeNode(_context) {
  13270. this.included = true;
  13271. if (!this.deoptimized)
  13272. this.applyDeoptimizations();
  13273. }
  13274. initialise() {
  13275. super.initialise();
  13276. if (this.annotations &&
  13277. this.scope.context.options.treeshake.annotations) {
  13278. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13279. }
  13280. }
  13281. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13282. this.callee.render(code, options, {
  13283. isCalleeOfRenderedParent: true,
  13284. renderedSurroundingElement
  13285. });
  13286. renderCallArguments(code, options, this);
  13287. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  13288. this.hasCheckedForWarnings = true;
  13289. const variable = this.scope.findVariable(this.callee.name);
  13290. if (variable.isNamespace) {
  13291. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(this.callee.name), this.start);
  13292. }
  13293. if (this.callee.name === 'eval') {
  13294. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEval(this.scope.context.module.id), this.start);
  13295. }
  13296. }
  13297. }
  13298. applyDeoptimizations() {
  13299. this.deoptimized = true;
  13300. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13301. this.scope.context.requestTreeshakingPass();
  13302. }
  13303. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  13304. if (this.returnExpression === null) {
  13305. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13306. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  13307. }
  13308. return this.returnExpression;
  13309. }
  13310. }
  13311. class CatchClause extends NodeBase {
  13312. createScope(parentScope) {
  13313. this.scope = new ParameterScope(parentScope, true);
  13314. }
  13315. parseNode(esTreeNode) {
  13316. const { body, param, type } = esTreeNode;
  13317. this.type = type;
  13318. if (param) {
  13319. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  13320. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  13321. }
  13322. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  13323. return super.parseNode(esTreeNode);
  13324. }
  13325. }
  13326. CatchClause.prototype.preventChildBlockScope = true;
  13327. CatchClause.prototype.includeNode = onlyIncludeSelf;
  13328. class ChainExpression extends NodeBase {
  13329. // deoptimizations are not relevant as we are not caching values
  13330. deoptimizeCache() { }
  13331. getLiteralValueAtPath(path, recursionTracker, origin) {
  13332. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  13333. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  13334. }
  13335. hasEffects(context) {
  13336. return this.expression.hasEffectsAsChainElement(context) === true;
  13337. }
  13338. includePath(path, context) {
  13339. this.included = true;
  13340. this.expression.includePath(path, context);
  13341. }
  13342. removeAnnotations(code) {
  13343. this.expression.removeAnnotations(code);
  13344. }
  13345. }
  13346. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13347. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13348. class ClassBodyScope extends ChildScope {
  13349. constructor(parent, classNode) {
  13350. const { context } = parent;
  13351. super(parent, context);
  13352. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  13353. this.instanceScope = new ChildScope(this, context);
  13354. this.instanceScope.variables.set('this', new ThisVariable(context));
  13355. }
  13356. findLexicalBoundary() {
  13357. return this;
  13358. }
  13359. }
  13360. class ClassBody extends NodeBase {
  13361. createScope(parentScope) {
  13362. this.scope = new ClassBodyScope(parentScope, this.parent);
  13363. }
  13364. include(context, includeChildrenRecursively) {
  13365. this.included = true;
  13366. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  13367. for (const definition of this.body) {
  13368. definition.include(context, includeChildrenRecursively);
  13369. }
  13370. }
  13371. parseNode(esTreeNode) {
  13372. const body = (this.body = new Array(esTreeNode.body.length));
  13373. let index = 0;
  13374. for (const definition of esTreeNode.body) {
  13375. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  13376. }
  13377. return super.parseNode(esTreeNode);
  13378. }
  13379. }
  13380. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13381. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  13382. class ClassExpression extends ClassNode {
  13383. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13384. super.render(code, options);
  13385. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13386. code.appendRight(this.start, '(');
  13387. code.prependLeft(this.end, ')');
  13388. }
  13389. }
  13390. }
  13391. function tryCastLiteralValueToBoolean(literalValue) {
  13392. if (typeof literalValue === 'symbol') {
  13393. if (literalValue === UnknownFalsyValue) {
  13394. return false;
  13395. }
  13396. if (literalValue === UnknownTruthyValue) {
  13397. return true;
  13398. }
  13399. return UnknownValue;
  13400. }
  13401. return !!literalValue;
  13402. }
  13403. class MultiExpression extends ExpressionEntity {
  13404. constructor(expressions) {
  13405. super();
  13406. this.expressions = expressions;
  13407. }
  13408. deoptimizePath(path) {
  13409. for (const expression of this.expressions) {
  13410. expression.deoptimizePath(path);
  13411. }
  13412. }
  13413. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13414. return [
  13415. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  13416. false
  13417. ];
  13418. }
  13419. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13420. for (const expression of this.expressions) {
  13421. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  13422. return true;
  13423. }
  13424. return false;
  13425. }
  13426. }
  13427. class ConditionalExpression extends NodeBase {
  13428. constructor() {
  13429. super(...arguments);
  13430. this.expressionsToBeDeoptimized = [];
  13431. this.usedBranch = null;
  13432. }
  13433. get isBranchResolutionAnalysed() {
  13434. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13435. }
  13436. set isBranchResolutionAnalysed(value) {
  13437. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13438. }
  13439. get hasDeoptimizedCache() {
  13440. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13441. }
  13442. set hasDeoptimizedCache(value) {
  13443. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13444. }
  13445. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13446. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13447. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13448. }
  13449. deoptimizeCache() {
  13450. if (this.hasDeoptimizedCache)
  13451. return;
  13452. this.hasDeoptimizedCache = true;
  13453. if (this.usedBranch !== null) {
  13454. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  13455. this.usedBranch = null;
  13456. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13457. if (this.included) {
  13458. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13459. }
  13460. const { expressionsToBeDeoptimized } = this;
  13461. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  13462. for (const expression of expressionsToBeDeoptimized) {
  13463. expression.deoptimizeCache();
  13464. }
  13465. }
  13466. }
  13467. deoptimizePath(path) {
  13468. const usedBranch = this.getUsedBranch();
  13469. if (usedBranch) {
  13470. usedBranch.deoptimizePath(path);
  13471. }
  13472. else {
  13473. this.consequent.deoptimizePath(path);
  13474. this.alternate.deoptimizePath(path);
  13475. }
  13476. }
  13477. getLiteralValueAtPath(path, recursionTracker, origin) {
  13478. const usedBranch = this.getUsedBranch();
  13479. if (!usedBranch) {
  13480. if (this.hasDeoptimizedCache) {
  13481. return UnknownValue;
  13482. }
  13483. const consequentValue = this.consequent.getLiteralValueAtPath(path, recursionTracker, origin);
  13484. const castedConsequentValue = tryCastLiteralValueToBoolean(consequentValue);
  13485. if (castedConsequentValue === UnknownValue)
  13486. return UnknownValue;
  13487. const alternateValue = this.alternate.getLiteralValueAtPath(path, recursionTracker, origin);
  13488. const castedAlternateValue = tryCastLiteralValueToBoolean(alternateValue);
  13489. if (castedConsequentValue !== castedAlternateValue)
  13490. return UnknownValue;
  13491. this.expressionsToBeDeoptimized.push(origin);
  13492. if (consequentValue !== alternateValue)
  13493. return castedConsequentValue ? UnknownTruthyValue : UnknownFalsyValue;
  13494. return consequentValue;
  13495. }
  13496. this.expressionsToBeDeoptimized.push(origin);
  13497. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13498. }
  13499. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13500. const usedBranch = this.getUsedBranch();
  13501. if (!usedBranch)
  13502. return [
  13503. new MultiExpression([
  13504. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13505. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13506. ]),
  13507. false
  13508. ];
  13509. this.expressionsToBeDeoptimized.push(origin);
  13510. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13511. }
  13512. hasEffects(context) {
  13513. if (this.test.hasEffects(context))
  13514. return true;
  13515. const usedBranch = this.getUsedBranch();
  13516. if (!usedBranch) {
  13517. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  13518. }
  13519. return usedBranch.hasEffects(context);
  13520. }
  13521. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13522. const usedBranch = this.getUsedBranch();
  13523. if (!usedBranch) {
  13524. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13525. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  13526. }
  13527. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13528. }
  13529. include(context, includeChildrenRecursively) {
  13530. this.included = true;
  13531. const usedBranch = this.getUsedBranch();
  13532. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  13533. this.test.include(context, includeChildrenRecursively);
  13534. this.consequent.include(context, includeChildrenRecursively);
  13535. this.alternate.include(context, includeChildrenRecursively);
  13536. }
  13537. else {
  13538. usedBranch.include(context, includeChildrenRecursively);
  13539. }
  13540. }
  13541. includePath(path, context) {
  13542. this.included = true;
  13543. const usedBranch = this.getUsedBranch();
  13544. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  13545. this.consequent.includePath(path, context);
  13546. this.alternate.includePath(path, context);
  13547. }
  13548. else {
  13549. usedBranch.includePath(path, context);
  13550. }
  13551. }
  13552. includeCallArguments(interaction, context) {
  13553. const usedBranch = this.getUsedBranch();
  13554. if (usedBranch) {
  13555. usedBranch.includeCallArguments(interaction, context);
  13556. }
  13557. else {
  13558. this.consequent.includeCallArguments(interaction, context);
  13559. this.alternate.includeCallArguments(interaction, context);
  13560. }
  13561. }
  13562. removeAnnotations(code) {
  13563. this.test.removeAnnotations(code);
  13564. }
  13565. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  13566. if (this.test.included) {
  13567. this.test.render(code, options, { renderedSurroundingElement });
  13568. this.consequent.render(code, options);
  13569. this.alternate.render(code, options);
  13570. }
  13571. else {
  13572. const usedBranch = this.getUsedBranch();
  13573. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  13574. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  13575. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  13576. : colonPos) + 1);
  13577. if (preventASI) {
  13578. removeLineBreaks(code, inclusionStart, usedBranch.start);
  13579. }
  13580. code.remove(this.start, inclusionStart);
  13581. if (this.consequent.included) {
  13582. code.remove(colonPos, this.end);
  13583. }
  13584. this.test.removeAnnotations(code);
  13585. usedBranch.render(code, options, {
  13586. isCalleeOfRenderedParent,
  13587. preventASI: true,
  13588. renderedParentType: renderedParentType || this.parent.type,
  13589. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13590. });
  13591. }
  13592. }
  13593. getUsedBranch() {
  13594. if (this.isBranchResolutionAnalysed) {
  13595. return this.usedBranch;
  13596. }
  13597. this.isBranchResolutionAnalysed = true;
  13598. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  13599. return typeof testValue === 'symbol'
  13600. ? null
  13601. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  13602. }
  13603. }
  13604. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13605. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13606. class ContinueStatement extends NodeBase {
  13607. hasEffects(context) {
  13608. if (this.label) {
  13609. if (!context.ignore.labels.has(this.label.name))
  13610. return true;
  13611. context.includedLabels.add(this.label.name);
  13612. }
  13613. else {
  13614. if (!context.ignore.continues)
  13615. return true;
  13616. context.hasContinue = true;
  13617. }
  13618. context.brokenFlow = true;
  13619. return false;
  13620. }
  13621. include(context, includeChildrenRecursively) {
  13622. this.included = true;
  13623. if (this.label) {
  13624. this.label.include(context, includeChildrenRecursively);
  13625. context.includedLabels.add(this.label.name);
  13626. }
  13627. else {
  13628. context.hasContinue = true;
  13629. }
  13630. context.brokenFlow = true;
  13631. }
  13632. }
  13633. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13634. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13635. class DebuggerStatement extends NodeBase {
  13636. hasEffects() {
  13637. return true;
  13638. }
  13639. }
  13640. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  13641. class Decorator extends NodeBase {
  13642. hasEffects(context) {
  13643. return (this.expression.hasEffects(context) ||
  13644. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  13645. }
  13646. }
  13647. Decorator.prototype.includeNode = onlyIncludeSelf;
  13648. function hasLoopBodyEffects(context, body) {
  13649. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  13650. const { breaks, continues } = ignore;
  13651. ignore.breaks = true;
  13652. ignore.continues = true;
  13653. context.hasBreak = false;
  13654. context.hasContinue = false;
  13655. if (body.hasEffects(context))
  13656. return true;
  13657. ignore.breaks = breaks;
  13658. ignore.continues = continues;
  13659. context.hasBreak = hasBreak;
  13660. context.hasContinue = hasContinue;
  13661. context.brokenFlow = brokenFlow;
  13662. return false;
  13663. }
  13664. function includeLoopBody(context, body, includeChildrenRecursively) {
  13665. const { brokenFlow, hasBreak, hasContinue } = context;
  13666. context.hasBreak = false;
  13667. context.hasContinue = false;
  13668. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  13669. context.hasBreak = hasBreak;
  13670. context.hasContinue = hasContinue;
  13671. context.brokenFlow = brokenFlow;
  13672. }
  13673. class DoWhileStatement extends NodeBase {
  13674. hasEffects(context) {
  13675. if (this.test.hasEffects(context))
  13676. return true;
  13677. return hasLoopBodyEffects(context, this.body);
  13678. }
  13679. include(context, includeChildrenRecursively) {
  13680. this.included = true;
  13681. this.test.include(context, includeChildrenRecursively);
  13682. includeLoopBody(context, this.body, includeChildrenRecursively);
  13683. }
  13684. }
  13685. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13686. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13687. class EmptyStatement extends NodeBase {
  13688. hasEffects() {
  13689. return false;
  13690. }
  13691. }
  13692. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  13693. class ExportAllDeclaration extends NodeBase {
  13694. hasEffects() {
  13695. return false;
  13696. }
  13697. initialise() {
  13698. super.initialise();
  13699. this.scope.context.addExport(this);
  13700. }
  13701. render(code, _options, nodeRenderOptions) {
  13702. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13703. }
  13704. }
  13705. ExportAllDeclaration.prototype.needsBoundaries = true;
  13706. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13707. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13708. class ExportNamedDeclaration extends NodeBase {
  13709. bind() {
  13710. // Do not bind specifiers
  13711. this.declaration?.bind();
  13712. }
  13713. hasEffects(context) {
  13714. return !!this.declaration?.hasEffects(context);
  13715. }
  13716. initialise() {
  13717. super.initialise();
  13718. this.scope.context.addExport(this);
  13719. }
  13720. removeAnnotations(code) {
  13721. this.declaration?.removeAnnotations(code);
  13722. }
  13723. render(code, options, nodeRenderOptions) {
  13724. const { start, end } = nodeRenderOptions;
  13725. if (this.declaration === null) {
  13726. code.remove(start, end);
  13727. }
  13728. else {
  13729. let endBoundary = this.declaration.start;
  13730. // the start of the decorator may be before the start of the class declaration
  13731. if (this.declaration instanceof ClassDeclaration) {
  13732. const decorators = this.declaration.decorators;
  13733. for (const decorator of decorators) {
  13734. endBoundary = Math.min(endBoundary, decorator.start);
  13735. }
  13736. if (endBoundary <= this.start) {
  13737. endBoundary = this.declaration.start;
  13738. }
  13739. }
  13740. code.remove(this.start, endBoundary);
  13741. this.declaration.render(code, options, { end, start });
  13742. }
  13743. }
  13744. }
  13745. ExportNamedDeclaration.prototype.needsBoundaries = true;
  13746. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13747. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13748. class ExportSpecifier extends NodeBase {
  13749. }
  13750. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13751. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13752. class ForInStatement extends NodeBase {
  13753. createScope(parentScope) {
  13754. this.scope = new BlockScope(parentScope);
  13755. }
  13756. hasEffects(context) {
  13757. const { body, deoptimized, left, right } = this;
  13758. if (!deoptimized)
  13759. this.applyDeoptimizations();
  13760. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  13761. return true;
  13762. return hasLoopBodyEffects(context, body);
  13763. }
  13764. include(context, includeChildrenRecursively) {
  13765. const { body, deoptimized, left, right } = this;
  13766. if (!deoptimized)
  13767. this.applyDeoptimizations();
  13768. if (!this.included)
  13769. this.includeNode(context);
  13770. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13771. right.include(context, includeChildrenRecursively);
  13772. includeLoopBody(context, body, includeChildrenRecursively);
  13773. }
  13774. includeNode(context) {
  13775. this.included = true;
  13776. if (!this.deoptimized)
  13777. this.applyDeoptimizations();
  13778. this.right.includePath(UNKNOWN_PATH, context);
  13779. }
  13780. initialise() {
  13781. super.initialise();
  13782. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13783. }
  13784. render(code, options) {
  13785. this.left.render(code, options, NO_SEMICOLON);
  13786. this.right.render(code, options, NO_SEMICOLON);
  13787. // handle no space between "in" and the right side
  13788. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  13789. code.prependLeft(this.right.start, ' ');
  13790. }
  13791. this.body.render(code, options);
  13792. }
  13793. applyDeoptimizations() {
  13794. this.deoptimized = true;
  13795. this.left.deoptimizePath(EMPTY_PATH);
  13796. this.scope.context.requestTreeshakingPass();
  13797. }
  13798. }
  13799. class ForOfStatement extends NodeBase {
  13800. get await() {
  13801. return isFlagSet(this.flags, 131072 /* Flag.await */);
  13802. }
  13803. set await(value) {
  13804. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  13805. }
  13806. createScope(parentScope) {
  13807. this.scope = new BlockScope(parentScope);
  13808. }
  13809. hasEffects() {
  13810. if (!this.deoptimized)
  13811. this.applyDeoptimizations();
  13812. // Placeholder until proper Symbol.Iterator support
  13813. return true;
  13814. }
  13815. include(context, includeChildrenRecursively) {
  13816. const { body, deoptimized, left, right } = this;
  13817. if (!deoptimized)
  13818. this.applyDeoptimizations();
  13819. if (!this.included)
  13820. this.includeNode(context);
  13821. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13822. right.include(context, includeChildrenRecursively);
  13823. includeLoopBody(context, body, includeChildrenRecursively);
  13824. }
  13825. includeNode(context) {
  13826. this.included = true;
  13827. if (!this.deoptimized)
  13828. this.applyDeoptimizations();
  13829. this.right.includePath(UNKNOWN_PATH, context);
  13830. }
  13831. initialise() {
  13832. super.initialise();
  13833. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13834. }
  13835. render(code, options) {
  13836. this.left.render(code, options, NO_SEMICOLON);
  13837. this.right.render(code, options, NO_SEMICOLON);
  13838. // handle no space between "of" and the right side
  13839. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  13840. code.prependLeft(this.right.start, ' ');
  13841. }
  13842. this.body.render(code, options);
  13843. }
  13844. applyDeoptimizations() {
  13845. this.deoptimized = true;
  13846. this.left.deoptimizePath(EMPTY_PATH);
  13847. this.right.deoptimizePath(UNKNOWN_PATH);
  13848. this.scope.context.requestTreeshakingPass();
  13849. }
  13850. }
  13851. class ForStatement extends NodeBase {
  13852. createScope(parentScope) {
  13853. this.scope = new BlockScope(parentScope);
  13854. }
  13855. hasEffects(context) {
  13856. if (this.init?.hasEffects(context) ||
  13857. this.test?.hasEffects(context) ||
  13858. this.update?.hasEffects(context)) {
  13859. return true;
  13860. }
  13861. return hasLoopBodyEffects(context, this.body);
  13862. }
  13863. include(context, includeChildrenRecursively) {
  13864. this.included = true;
  13865. this.init?.include(context, includeChildrenRecursively, {
  13866. asSingleStatement: true
  13867. });
  13868. this.test?.include(context, includeChildrenRecursively);
  13869. this.update?.include(context, includeChildrenRecursively);
  13870. includeLoopBody(context, this.body, includeChildrenRecursively);
  13871. }
  13872. render(code, options) {
  13873. this.init?.render(code, options, NO_SEMICOLON);
  13874. this.test?.render(code, options, NO_SEMICOLON);
  13875. this.update?.render(code, options, NO_SEMICOLON);
  13876. this.body.render(code, options);
  13877. }
  13878. }
  13879. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13880. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13881. class FunctionExpression extends FunctionNode {
  13882. createScope(parentScope) {
  13883. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  13884. }
  13885. parseNode(esTreeNode) {
  13886. if (esTreeNode.id !== null) {
  13887. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  13888. }
  13889. return super.parseNode(esTreeNode);
  13890. }
  13891. onlyFunctionCallUsed() {
  13892. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  13893. this.parent.callee === this &&
  13894. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  13895. return isIIFE || super.onlyFunctionCallUsed();
  13896. }
  13897. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13898. super.render(code, options);
  13899. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13900. code.appendRight(this.start, '(');
  13901. code.prependLeft(this.end, ')');
  13902. }
  13903. }
  13904. }
  13905. class TrackingScope extends BlockScope {
  13906. constructor() {
  13907. super(...arguments);
  13908. this.hoistedDeclarations = [];
  13909. }
  13910. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13911. this.hoistedDeclarations.push(identifier);
  13912. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13913. }
  13914. }
  13915. const unset = Symbol('unset');
  13916. class IfStatement extends NodeBase {
  13917. constructor() {
  13918. super(...arguments);
  13919. this.testValue = unset;
  13920. }
  13921. deoptimizeCache() {
  13922. this.testValue = UnknownValue;
  13923. }
  13924. hasEffects(context) {
  13925. if (this.test.hasEffects(context)) {
  13926. return true;
  13927. }
  13928. const testValue = this.getTestValue();
  13929. if (typeof testValue === 'symbol') {
  13930. const { brokenFlow } = context;
  13931. if (this.consequent.hasEffects(context))
  13932. return true;
  13933. const consequentBrokenFlow = context.brokenFlow;
  13934. context.brokenFlow = brokenFlow;
  13935. if (this.alternate === null)
  13936. return false;
  13937. if (this.alternate.hasEffects(context))
  13938. return true;
  13939. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13940. return false;
  13941. }
  13942. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  13943. }
  13944. include(context, includeChildrenRecursively) {
  13945. this.included = true;
  13946. if (includeChildrenRecursively) {
  13947. this.includeRecursively(includeChildrenRecursively, context);
  13948. }
  13949. else {
  13950. const testValue = this.getTestValue();
  13951. if (typeof testValue === 'symbol') {
  13952. this.includeUnknownTest(context);
  13953. }
  13954. else {
  13955. this.includeKnownTest(context, testValue);
  13956. }
  13957. }
  13958. }
  13959. parseNode(esTreeNode) {
  13960. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  13961. if (esTreeNode.alternate) {
  13962. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  13963. }
  13964. return super.parseNode(esTreeNode);
  13965. }
  13966. render(code, options) {
  13967. const { snippets: { getPropertyAccess } } = options;
  13968. // Note that unknown test values are always included
  13969. const testValue = this.getTestValue();
  13970. const hoistedDeclarations = [];
  13971. const includesIfElse = this.test.included;
  13972. const noTreeshake = !this.scope.context.options.treeshake;
  13973. if (includesIfElse) {
  13974. this.test.render(code, options);
  13975. }
  13976. else {
  13977. code.remove(this.start, this.consequent.start);
  13978. }
  13979. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  13980. this.consequent.render(code, options);
  13981. }
  13982. else {
  13983. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  13984. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  13985. }
  13986. if (this.alternate) {
  13987. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  13988. if (includesIfElse) {
  13989. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  13990. code.prependLeft(this.alternate.start, ' ');
  13991. }
  13992. }
  13993. else {
  13994. code.remove(this.consequent.end, this.alternate.start);
  13995. }
  13996. this.alternate.render(code, options);
  13997. }
  13998. else {
  13999. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  14000. code.overwrite(this.alternate.start, this.end, ';');
  14001. }
  14002. else {
  14003. code.remove(this.consequent.end, this.end);
  14004. }
  14005. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  14006. }
  14007. }
  14008. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  14009. }
  14010. getTestValue() {
  14011. if (this.testValue === unset) {
  14012. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  14013. }
  14014. return this.testValue;
  14015. }
  14016. includeKnownTest(context, testValue) {
  14017. if (this.test.shouldBeIncluded(context)) {
  14018. this.test.include(context, false);
  14019. }
  14020. if (testValue && this.consequent.shouldBeIncluded(context)) {
  14021. this.consequent.include(context, false, { asSingleStatement: true });
  14022. }
  14023. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  14024. this.alternate.include(context, false, { asSingleStatement: true });
  14025. }
  14026. }
  14027. includeRecursively(includeChildrenRecursively, context) {
  14028. this.test.include(context, includeChildrenRecursively);
  14029. this.consequent.include(context, includeChildrenRecursively);
  14030. this.alternate?.include(context, includeChildrenRecursively);
  14031. }
  14032. includeUnknownTest(context) {
  14033. this.test.include(context, false);
  14034. const { brokenFlow } = context;
  14035. let consequentBrokenFlow = false;
  14036. if (this.consequent.shouldBeIncluded(context)) {
  14037. this.consequent.include(context, false, { asSingleStatement: true });
  14038. consequentBrokenFlow = context.brokenFlow;
  14039. context.brokenFlow = brokenFlow;
  14040. }
  14041. if (this.alternate?.shouldBeIncluded(context)) {
  14042. this.alternate.include(context, false, { asSingleStatement: true });
  14043. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  14044. }
  14045. }
  14046. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  14047. const hoistedVariables = [
  14048. ...new Set(hoistedDeclarations.map(identifier => {
  14049. const variable = identifier.variable;
  14050. return variable.included ? variable.getName(getPropertyAccess) : '';
  14051. }))
  14052. ]
  14053. .filter(Boolean)
  14054. .join(', ');
  14055. if (hoistedVariables) {
  14056. const parentType = this.parent.type;
  14057. const needsBraces = parentType !== parseAst_js.Program && parentType !== parseAst_js.BlockStatement;
  14058. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  14059. if (needsBraces) {
  14060. code.appendLeft(this.end, ` }`);
  14061. }
  14062. }
  14063. }
  14064. shouldKeepAlternateBranch() {
  14065. let currentParent = this.parent;
  14066. do {
  14067. if (currentParent instanceof IfStatement && currentParent.alternate) {
  14068. return true;
  14069. }
  14070. if (currentParent instanceof BlockStatement) {
  14071. return false;
  14072. }
  14073. currentParent = currentParent.parent;
  14074. } while (currentParent);
  14075. return false;
  14076. }
  14077. }
  14078. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14079. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14080. class ImportAttribute extends NodeBase {
  14081. }
  14082. class ImportDeclaration extends NodeBase {
  14083. // Do not bind specifiers or attributes
  14084. bind() { }
  14085. hasEffects() {
  14086. return false;
  14087. }
  14088. initialise() {
  14089. super.initialise();
  14090. this.scope.context.addImport(this);
  14091. }
  14092. render(code, _options, nodeRenderOptions) {
  14093. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  14094. }
  14095. }
  14096. ImportDeclaration.prototype.needsBoundaries = true;
  14097. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14098. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  14099. class ImportDefaultSpecifier extends NodeBase {
  14100. }
  14101. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14102. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14103. class ObjectPromiseHandler {
  14104. constructor(resolvedVariable) {
  14105. this.interaction = {
  14106. args: [null, resolvedVariable],
  14107. type: INTERACTION_CALLED,
  14108. withNew: false
  14109. };
  14110. }
  14111. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14112. deoptimizeInteraction(interaction);
  14113. if (interaction.type === INTERACTION_CALLED &&
  14114. path.length === 0 &&
  14115. (isFunctionExpressionNode(interaction.args[1]) ||
  14116. isArrowFunctionExpressionNode(interaction.args[1]))) {
  14117. interaction.args[1].deoptimizeArgumentsOnInteractionAtPath(this.interaction, [], recursionTracker);
  14118. }
  14119. }
  14120. includeCallArguments(interaction, context) {
  14121. // This includes the function call itself
  14122. includeInteractionWithoutThis(interaction, context);
  14123. if (interaction.type === INTERACTION_CALLED &&
  14124. (isFunctionExpressionNode(interaction.args[1]) ||
  14125. isArrowFunctionExpressionNode(interaction.args[1]))) {
  14126. interaction.args[1].includeCallArguments(this.interaction, context);
  14127. }
  14128. }
  14129. }
  14130. class EmptyPromiseHandler {
  14131. deoptimizeArgumentsOnInteractionAtPath(interaction) {
  14132. deoptimizeInteraction(interaction);
  14133. }
  14134. includeCallArguments(interaction, context) {
  14135. includeInteractionWithoutThis(interaction, context);
  14136. }
  14137. }
  14138. function getChunkInfoWithPath(chunk) {
  14139. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  14140. }
  14141. class ImportExpression extends NodeBase {
  14142. constructor() {
  14143. super(...arguments);
  14144. this.inlineNamespace = null;
  14145. this.resolution = null;
  14146. this.attributes = null;
  14147. this.mechanism = null;
  14148. this.namespaceExportName = undefined;
  14149. this.localResolution = null;
  14150. this.resolutionString = null;
  14151. }
  14152. get shouldIncludeDynamicAttributes() {
  14153. return isFlagSet(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */);
  14154. }
  14155. set shouldIncludeDynamicAttributes(value) {
  14156. this.flags = setFlag(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */, value);
  14157. }
  14158. bind() {
  14159. const { options, parent, resolution, source } = this;
  14160. source.bind();
  14161. options?.bind();
  14162. // Check if we resolved to a Module without using instanceof
  14163. if (typeof resolution !== 'object' || !resolution || !('namespace' in resolution)) {
  14164. return;
  14165. }
  14166. // In these cases, we can track exactly what is included or deoptimized:
  14167. // * import('foo'); // as statement
  14168. // * await import('foo') // use as awaited expression in any way
  14169. // * import('foo').then(n => {...}) // only if .then is called directly on the import()
  14170. if (isExpressionStatementNode(parent) || isAwaitExpressionNode(parent)) {
  14171. this.localResolution = { resolution, tracked: true };
  14172. return;
  14173. }
  14174. if (!isMemberExpressionNode(parent)) {
  14175. this.localResolution = { resolution, tracked: false };
  14176. return;
  14177. }
  14178. let currentParent = parent;
  14179. // eslint-disable-next-line @typescript-eslint/no-this-alias
  14180. let callExpression = this;
  14181. while (true) {
  14182. if (currentParent.computed ||
  14183. currentParent.object !== callExpression ||
  14184. !isIdentifierNode(currentParent.property) ||
  14185. !isCallExpressionNode(currentParent.parent)) {
  14186. break;
  14187. }
  14188. const propertyName = currentParent.property.name;
  14189. callExpression = currentParent.parent;
  14190. if (propertyName === 'then') {
  14191. const firstArgument = callExpression.arguments[0];
  14192. if (firstArgument === undefined ||
  14193. isFunctionExpressionNode(firstArgument) ||
  14194. isArrowFunctionExpressionNode(firstArgument)) {
  14195. currentParent.promiseHandler = new ObjectPromiseHandler(getDynamicNamespaceVariable(resolution.namespace));
  14196. this.localResolution = { resolution, tracked: true };
  14197. return;
  14198. }
  14199. }
  14200. else if (propertyName === 'catch' || propertyName === 'finally') {
  14201. if (isMemberExpressionNode(callExpression.parent)) {
  14202. currentParent.promiseHandler = new EmptyPromiseHandler();
  14203. currentParent = callExpression.parent;
  14204. continue;
  14205. }
  14206. if (isExpressionStatementNode(callExpression.parent)) {
  14207. currentParent.promiseHandler = new EmptyPromiseHandler();
  14208. this.localResolution = { resolution, tracked: true };
  14209. return;
  14210. }
  14211. }
  14212. break;
  14213. }
  14214. this.localResolution = { resolution, tracked: false };
  14215. }
  14216. deoptimizePath(path) {
  14217. this.localResolution?.resolution?.namespace.deoptimizePath(path);
  14218. }
  14219. hasEffects() {
  14220. return true;
  14221. }
  14222. include(context, includeChildrenRecursively) {
  14223. if (!this.included)
  14224. this.includeNode(context);
  14225. this.source.include(context, includeChildrenRecursively);
  14226. if (this.shouldIncludeDynamicAttributes) {
  14227. this.options?.include(context, includeChildrenRecursively);
  14228. }
  14229. if (includeChildrenRecursively) {
  14230. this.localResolution?.resolution.includeAllExports();
  14231. }
  14232. }
  14233. includeNode(context) {
  14234. this.included = true;
  14235. const { localResolution, scope, shouldIncludeDynamicAttributes } = this;
  14236. if (shouldIncludeDynamicAttributes) {
  14237. this.options?.includePath(UNKNOWN_PATH, context);
  14238. }
  14239. scope.context.includeDynamicImport(this);
  14240. scope.addAccessedDynamicImport(this);
  14241. if (localResolution) {
  14242. if (localResolution.tracked) {
  14243. localResolution.resolution.includeModuleInExecution();
  14244. }
  14245. else {
  14246. localResolution.resolution.includeAllExports();
  14247. }
  14248. }
  14249. }
  14250. includePath(path, context) {
  14251. if (!this.included)
  14252. this.includeNode(context);
  14253. this.localResolution?.resolution?.namespace.includeMemberPath(path, context);
  14254. }
  14255. initialise() {
  14256. super.initialise();
  14257. this.scope.context.addDynamicImport(this);
  14258. }
  14259. parseNode(esTreeNode) {
  14260. this.sourceAstNode = esTreeNode.source;
  14261. return super.parseNode(esTreeNode);
  14262. }
  14263. render(code, options) {
  14264. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  14265. if (this.inlineNamespace) {
  14266. const [left, right] = getDirectReturnFunction([], {
  14267. functionReturn: true,
  14268. lineBreakIndent: null,
  14269. name: null
  14270. });
  14271. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  14272. return;
  14273. }
  14274. if (this.mechanism) {
  14275. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  14276. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  14277. }
  14278. if (this.resolutionString) {
  14279. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  14280. if (this.namespaceExportName) {
  14281. const [left, right] = getDirectReturnFunction(['n'], {
  14282. functionReturn: true,
  14283. lineBreakIndent: null,
  14284. name: null
  14285. });
  14286. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  14287. }
  14288. }
  14289. else {
  14290. this.source.render(code, options);
  14291. }
  14292. if (this.attributes !== true) {
  14293. if (this.options) {
  14294. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  14295. }
  14296. if (this.attributes) {
  14297. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  14298. lineBreakIndent: null
  14299. })}`);
  14300. }
  14301. }
  14302. }
  14303. setExternalResolution(exportMode, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  14304. const { format } = options;
  14305. this.inlineNamespace = null;
  14306. this.resolutionString = resolutionString;
  14307. this.namespaceExportName = namespaceExportName;
  14308. this.attributes = attributes;
  14309. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  14310. let helper;
  14311. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  14312. if (helper) {
  14313. accessedGlobals.push(helper);
  14314. }
  14315. if (accessedGlobals.length > 0) {
  14316. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  14317. }
  14318. }
  14319. setInternalResolution(inlineNamespace) {
  14320. this.inlineNamespace = inlineNamespace;
  14321. }
  14322. getDynamicImportMechanismAndHelper(exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  14323. const { resolution, scope } = this;
  14324. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  14325. {
  14326. chunk: getChunkInfoWithPath(ownChunk),
  14327. customResolution: typeof resolution === 'string' ? resolution : null,
  14328. format,
  14329. getTargetChunkImports() {
  14330. if (targetChunk === null)
  14331. return null;
  14332. const chunkInfos = [];
  14333. const importerPath = ownChunk.getFileName();
  14334. for (const dep of targetChunk.dependencies) {
  14335. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  14336. if (dep instanceof ExternalChunk) {
  14337. chunkInfos.push({
  14338. fileName: dep.getFileName(),
  14339. resolvedImportPath,
  14340. type: 'external'
  14341. });
  14342. }
  14343. else {
  14344. chunkInfos.push({
  14345. chunk: dep.getPreRenderedChunkInfo(),
  14346. fileName: dep.getFileName(),
  14347. resolvedImportPath,
  14348. type: 'internal'
  14349. });
  14350. }
  14351. }
  14352. return chunkInfos;
  14353. },
  14354. moduleId: scope.context.module.id,
  14355. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  14356. targetModuleAttributes: resolution && typeof resolution !== 'string' ? resolution.info.attributes : {},
  14357. targetModuleId: resolution && typeof resolution !== 'string' ? resolution.id : null
  14358. }
  14359. ]);
  14360. if (mechanism) {
  14361. return { helper: null, mechanism };
  14362. }
  14363. const hasDynamicTarget = !resolution || typeof resolution === 'string';
  14364. switch (format) {
  14365. case 'cjs': {
  14366. if (dynamicImportInCjs &&
  14367. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  14368. return { helper: null, mechanism: null };
  14369. }
  14370. const helper = getInteropHelper(resolution, exportMode, interop);
  14371. let left = `require(`;
  14372. let right = `)`;
  14373. if (helper) {
  14374. left = `/*#__PURE__*/${helper}(${left}`;
  14375. right += ')';
  14376. }
  14377. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  14378. functionReturn: true,
  14379. lineBreakIndent: null,
  14380. name: null
  14381. });
  14382. left = `Promise.resolve().then(${functionLeft}${left}`;
  14383. right += `${functionRight})`;
  14384. if (!arrowFunctions && hasDynamicTarget) {
  14385. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  14386. needsArrowReturnParens: false,
  14387. needsWrappedFunction: true
  14388. });
  14389. right = ')';
  14390. }
  14391. return {
  14392. helper,
  14393. mechanism: { left, right }
  14394. };
  14395. }
  14396. case 'amd': {
  14397. const resolve = compact ? 'c' : 'resolve';
  14398. const reject = compact ? 'e' : 'reject';
  14399. const helper = getInteropHelper(resolution, exportMode, interop);
  14400. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  14401. functionReturn: false,
  14402. lineBreakIndent: null,
  14403. name: null
  14404. });
  14405. const resolveNamespace = helper
  14406. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  14407. : resolve;
  14408. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  14409. functionReturn: false,
  14410. lineBreakIndent: null,
  14411. name: null
  14412. });
  14413. let left = `new Promise(${handlerLeft}require([`;
  14414. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  14415. if (!arrowFunctions && hasDynamicTarget) {
  14416. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  14417. needsArrowReturnParens: false,
  14418. needsWrappedFunction: true
  14419. });
  14420. right = ')';
  14421. }
  14422. return {
  14423. helper,
  14424. mechanism: { left, right }
  14425. };
  14426. }
  14427. case 'system': {
  14428. return {
  14429. helper: null,
  14430. mechanism: {
  14431. left: 'module.import(',
  14432. right: ')'
  14433. }
  14434. };
  14435. }
  14436. }
  14437. return { helper: null, mechanism: null };
  14438. }
  14439. }
  14440. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14441. function getInteropHelper(resolution, exportMode, interop) {
  14442. return exportMode === 'external'
  14443. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  14444. : exportMode === 'default'
  14445. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  14446. : null;
  14447. }
  14448. const accessedImportGlobals = {
  14449. amd: ['require'],
  14450. cjs: ['require'],
  14451. system: ['module']
  14452. };
  14453. class ImportNamespaceSpecifier extends NodeBase {
  14454. }
  14455. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14456. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14457. class ImportSpecifier extends NodeBase {
  14458. }
  14459. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14460. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14461. class JSXIdentifier extends IdentifierBase {
  14462. constructor() {
  14463. super(...arguments);
  14464. this.isNativeElement = false;
  14465. }
  14466. bind() {
  14467. const type = this.getType();
  14468. if (type === 0 /* IdentifierType.Reference */) {
  14469. this.variable = this.scope.findVariable(this.name);
  14470. this.variable.addReference(this);
  14471. }
  14472. else if (type === 1 /* IdentifierType.NativeElementName */) {
  14473. this.isNativeElement = true;
  14474. }
  14475. }
  14476. include(context) {
  14477. if (!this.included)
  14478. this.includeNode(context);
  14479. }
  14480. includeNode(context) {
  14481. this.included = true;
  14482. if (!this.deoptimized)
  14483. this.applyDeoptimizations();
  14484. if (this.variable !== null) {
  14485. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14486. }
  14487. }
  14488. includePath(path, context) {
  14489. if (!this.included) {
  14490. this.included = true;
  14491. if (this.variable !== null) {
  14492. this.scope.context.includeVariableInModule(this.variable, path, context);
  14493. }
  14494. }
  14495. else if (path.length > 0) {
  14496. this.variable?.includePath(path, context);
  14497. }
  14498. }
  14499. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  14500. if (this.variable) {
  14501. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  14502. if (name !== this.name) {
  14503. code.overwrite(this.start, this.end, name, {
  14504. contentOnly: true,
  14505. storeName: true
  14506. });
  14507. }
  14508. }
  14509. else if (this.isNativeElement &&
  14510. this.scope.context.options.jsx.mode !== 'preserve') {
  14511. code.update(this.start, this.end, JSON.stringify(this.name));
  14512. }
  14513. }
  14514. getType() {
  14515. switch (this.parent.type) {
  14516. case 'JSXOpeningElement':
  14517. case 'JSXClosingElement': {
  14518. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  14519. ? 0 /* IdentifierType.Reference */
  14520. : 1 /* IdentifierType.NativeElementName */;
  14521. }
  14522. case 'JSXMemberExpression': {
  14523. return this.parent.object === this
  14524. ? 0 /* IdentifierType.Reference */
  14525. : 2 /* IdentifierType.Other */;
  14526. }
  14527. case 'JSXAttribute':
  14528. case 'JSXNamespacedName': {
  14529. return 2 /* IdentifierType.Other */;
  14530. }
  14531. default: {
  14532. /* istanbul ignore next */
  14533. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  14534. }
  14535. }
  14536. }
  14537. }
  14538. class JSXAttribute extends NodeBase {
  14539. render(code, options, { jsxMode } = parseAst_js.BLANK) {
  14540. super.render(code, options);
  14541. if (['classic', 'automatic'].includes(jsxMode)) {
  14542. const { name, value } = this;
  14543. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  14544. if (!(jsxMode === 'automatic' && key === 'key')) {
  14545. const safeKey = stringifyObjectKeyIfNeeded(key);
  14546. if (key !== safeKey) {
  14547. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  14548. }
  14549. if (value) {
  14550. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  14551. // foo="aa \n aa"
  14552. if (value instanceof Literal &&
  14553. typeof value.value === 'string' &&
  14554. value.value.includes('\n')) {
  14555. code.overwrite(value.start, value.end, JSON.stringify(value.value), {
  14556. contentOnly: true
  14557. });
  14558. }
  14559. }
  14560. else {
  14561. code.appendLeft(name.end, ': true');
  14562. }
  14563. }
  14564. }
  14565. }
  14566. }
  14567. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  14568. class JSXClosingBase extends NodeBase {
  14569. render(code, options) {
  14570. const { mode } = this.scope.context.options.jsx;
  14571. if (mode !== 'preserve') {
  14572. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  14573. }
  14574. else {
  14575. super.render(code, options);
  14576. }
  14577. }
  14578. }
  14579. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  14580. class JSXClosingElement extends JSXClosingBase {
  14581. }
  14582. class JSXClosingFragment extends JSXClosingBase {
  14583. }
  14584. class JSXSpreadAttribute extends NodeBase {
  14585. render(code, options) {
  14586. this.argument.render(code, options);
  14587. const { mode } = this.scope.context.options.jsx;
  14588. if (mode !== 'preserve') {
  14589. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  14590. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  14591. }
  14592. }
  14593. }
  14594. class JSXEmptyExpression extends NodeBase {
  14595. }
  14596. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  14597. class JSXExpressionContainer extends NodeBase {
  14598. includeNode(context) {
  14599. this.included = true;
  14600. if (!this.deoptimized)
  14601. this.applyDeoptimizations();
  14602. this.expression.includePath(UNKNOWN_PATH, context);
  14603. }
  14604. render(code, options) {
  14605. const { mode } = this.scope.context.options.jsx;
  14606. if (mode !== 'preserve') {
  14607. code.remove(this.start, this.expression.start);
  14608. code.remove(this.expression.end, this.end);
  14609. }
  14610. this.expression.render(code, options);
  14611. }
  14612. }
  14613. const RE_WHITESPACE_TRIM = /^[ \t]*\r?\n[ \t\r\n]*|[ \t]*\r?\n[ \t\r\n]*$/g;
  14614. const RE_WHITESPACE_MERGE = /[ \t]*\r?\n[ \t\r\n]*/g;
  14615. class JSXText extends NodeBase {
  14616. shouldRender() {
  14617. return !!this.getRenderedText();
  14618. }
  14619. render(code) {
  14620. const { mode } = this.scope.context.options.jsx;
  14621. if (mode !== 'preserve') {
  14622. code.overwrite(this.start, this.end, JSON.stringify(this.getRenderedText()), {
  14623. contentOnly: true
  14624. });
  14625. }
  14626. }
  14627. getRenderedText() {
  14628. if (this.renderedText === undefined)
  14629. this.renderedText = this.value
  14630. .replace(RE_WHITESPACE_TRIM, '')
  14631. .replace(RE_WHITESPACE_MERGE, ' ');
  14632. return this.renderedText;
  14633. }
  14634. }
  14635. JSXText.prototype.includeNode = onlyIncludeSelf;
  14636. function getRenderedJsxChildren(children) {
  14637. let renderedChildren = 0;
  14638. for (const child of children) {
  14639. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression) &&
  14640. (!(child instanceof JSXText) || child.shouldRender())) {
  14641. renderedChildren++;
  14642. }
  14643. }
  14644. return renderedChildren;
  14645. }
  14646. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  14647. const [baseName, nestedName] = factory.split('.');
  14648. let factoryVariable;
  14649. if (importSource) {
  14650. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  14651. if (preserve) {
  14652. // This pretends we are accessing an included global variable of the same name
  14653. const globalVariable = node.scope.findGlobal(baseName);
  14654. globalVariable.includePath(UNKNOWN_PATH, context);
  14655. // This excludes this variable from renaming
  14656. factoryVariable.globalName = baseName;
  14657. }
  14658. }
  14659. else {
  14660. factoryVariable = node.scope.findGlobal(baseName);
  14661. }
  14662. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  14663. if (factoryVariable instanceof LocalVariable) {
  14664. factoryVariable.consolidateInitializers();
  14665. factoryVariable.addUsedPlace(node);
  14666. node.scope.context.requestTreeshakingPass();
  14667. }
  14668. return factoryVariable;
  14669. }
  14670. class JSXElementBase extends NodeBase {
  14671. constructor() {
  14672. super(...arguments);
  14673. this.factoryVariable = null;
  14674. this.factory = null;
  14675. }
  14676. initialise() {
  14677. super.initialise();
  14678. const { importSource } = (this.jsxMode = this.getRenderingMode());
  14679. if (importSource) {
  14680. this.scope.context.addImportSource(importSource);
  14681. }
  14682. }
  14683. include(context, includeChildrenRecursively) {
  14684. if (!this.included)
  14685. this.includeNode(context);
  14686. for (const child of this.children) {
  14687. child.include(context, includeChildrenRecursively);
  14688. }
  14689. }
  14690. includeNode(context) {
  14691. this.included = true;
  14692. const { factory, importSource, mode } = this.jsxMode;
  14693. if (factory) {
  14694. this.factory = factory;
  14695. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  14696. }
  14697. }
  14698. getRenderingMode() {
  14699. const jsx = this.scope.context.options.jsx;
  14700. const { mode, factory, importSource } = jsx;
  14701. if (mode === 'automatic') {
  14702. return {
  14703. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  14704. importSource: jsx.jsxImportSource,
  14705. mode
  14706. };
  14707. }
  14708. return { factory, importSource, mode };
  14709. }
  14710. renderChildren(code, options, openingEnd) {
  14711. const { children } = this;
  14712. let hasMultipleChildren = false;
  14713. let childrenEnd = openingEnd;
  14714. let firstChild = null;
  14715. for (const child of children) {
  14716. if ((child instanceof JSXExpressionContainer &&
  14717. child.expression instanceof JSXEmptyExpression) ||
  14718. (child instanceof JSXText && !child.shouldRender())) {
  14719. code.remove(childrenEnd, child.end);
  14720. }
  14721. else {
  14722. code.appendLeft(childrenEnd, ', ');
  14723. child.render(code, options);
  14724. if (firstChild) {
  14725. hasMultipleChildren = true;
  14726. }
  14727. else {
  14728. firstChild = child;
  14729. }
  14730. }
  14731. childrenEnd = child.end;
  14732. }
  14733. return { childrenEnd, firstChild, hasMultipleChildren };
  14734. }
  14735. }
  14736. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  14737. class JSXElement extends JSXElementBase {
  14738. include(context, includeChildrenRecursively) {
  14739. super.include(context, includeChildrenRecursively);
  14740. this.openingElement.include(context, includeChildrenRecursively);
  14741. this.closingElement?.include(context, includeChildrenRecursively);
  14742. }
  14743. render(code, options) {
  14744. switch (this.jsxMode.mode) {
  14745. case 'classic': {
  14746. this.renderClassicMode(code, options);
  14747. break;
  14748. }
  14749. case 'automatic': {
  14750. this.renderAutomaticMode(code, options);
  14751. break;
  14752. }
  14753. default: {
  14754. super.render(code, options);
  14755. }
  14756. }
  14757. }
  14758. getRenderingMode() {
  14759. const jsx = this.scope.context.options.jsx;
  14760. const { mode, factory, importSource } = jsx;
  14761. if (mode === 'automatic') {
  14762. // In the case there is a key after a spread attribute, we fall back to
  14763. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  14764. // for reasoning.
  14765. let hasSpread = false;
  14766. for (const attribute of this.openingElement.attributes) {
  14767. if (attribute instanceof JSXSpreadAttribute) {
  14768. hasSpread = true;
  14769. }
  14770. else if (hasSpread && attribute.name.name === 'key') {
  14771. return { factory, importSource, mode: 'classic' };
  14772. }
  14773. }
  14774. }
  14775. return super.getRenderingMode();
  14776. }
  14777. renderClassicMode(code, options) {
  14778. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14779. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  14780. const [, ...nestedName] = factory.split('.');
  14781. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  14782. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  14783. this.renderChildren(code, options, openingEnd);
  14784. if (selfClosing) {
  14785. code.appendLeft(end, ')');
  14786. }
  14787. else {
  14788. closingElement.render(code, options);
  14789. }
  14790. }
  14791. renderAutomaticMode(code, options) {
  14792. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14793. const { closingElement, end, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  14794. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  14795. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingEnd);
  14796. if (firstChild) {
  14797. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  14798. if (!inObject) {
  14799. code.prependRight(firstChild.start, '{ ');
  14800. inObject = true;
  14801. }
  14802. previousEnd = closingElement.start;
  14803. if (hasMultipleChildren) {
  14804. code.appendLeft(previousEnd, ']');
  14805. }
  14806. }
  14807. // This ensures that attributesEnd never corresponds to this.end. This is
  14808. // important because we must never use code.move with this.end as target.
  14809. // Otherwise, this would interfere with parent elements that try to append
  14810. // code to this.end, which would appear BEFORE the moved code.
  14811. const attributesEnd = firstChild ? childrenEnd : previousEnd;
  14812. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', attributesEnd);
  14813. if (keyAttribute) {
  14814. const { value } = keyAttribute;
  14815. // This will appear to the left of the moved code...
  14816. code.appendLeft(attributesEnd, ', ');
  14817. if (value) {
  14818. code.move(value.start, value.end, attributesEnd);
  14819. }
  14820. else {
  14821. code.appendLeft(attributesEnd, 'true');
  14822. }
  14823. }
  14824. if (selfClosing) {
  14825. // Moving the key attribute will also move the parenthesis to the right position
  14826. code.appendLeft(keyAttribute?.value?.end || end, ')');
  14827. }
  14828. else {
  14829. closingElement.render(code, options);
  14830. }
  14831. }
  14832. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  14833. const { jsxMode: { mode }, openingElement } = this;
  14834. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  14835. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  14836. openingElement.render(code, options, { jsxMode: mode });
  14837. let keyAttribute = null;
  14838. let hasSpread = false;
  14839. let inObject = false;
  14840. let previousEnd = nameEnd;
  14841. let hasAttributes = false;
  14842. let firstAttribute = null;
  14843. for (const attribute of attributes) {
  14844. if (attribute instanceof JSXAttribute) {
  14845. if (extractKeyAttribute && attribute.name.name === 'key') {
  14846. keyAttribute = attribute;
  14847. code.remove(previousEnd, attribute.value?.start || attribute.end);
  14848. continue;
  14849. }
  14850. code.appendLeft(previousEnd, ',');
  14851. if (!inObject) {
  14852. code.prependRight(attribute.start, '{ ');
  14853. inObject = true;
  14854. }
  14855. hasAttributes = true;
  14856. }
  14857. else {
  14858. if (inObject) {
  14859. if (hasAttributes) {
  14860. code.appendLeft(previousEnd, ' ');
  14861. }
  14862. code.appendLeft(previousEnd, '},');
  14863. inObject = false;
  14864. }
  14865. else {
  14866. code.appendLeft(previousEnd, ',');
  14867. }
  14868. hasSpread = true;
  14869. }
  14870. previousEnd = attribute.end;
  14871. firstAttribute ??= attribute;
  14872. }
  14873. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  14874. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  14875. }
  14876. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  14877. if (inObject) {
  14878. code.appendLeft(attributesEnd, ' }');
  14879. }
  14880. if (hasSpread) {
  14881. if (hasAttributes) {
  14882. const { start } = firstAttribute;
  14883. if (firstAttribute instanceof JSXSpreadAttribute) {
  14884. code.prependRight(start, '{}, ');
  14885. }
  14886. code.prependRight(start, 'Object.assign(');
  14887. code.appendLeft(attributesEnd, ')');
  14888. }
  14889. }
  14890. else if (!hasAttributes) {
  14891. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  14892. }
  14893. }
  14894. }
  14895. class JSXFragment extends JSXElementBase {
  14896. include(context, includeChildrenRecursively) {
  14897. super.include(context, includeChildrenRecursively);
  14898. this.openingFragment.include(context, includeChildrenRecursively);
  14899. this.closingFragment.include(context, includeChildrenRecursively);
  14900. }
  14901. render(code, options) {
  14902. switch (this.jsxMode.mode) {
  14903. case 'classic': {
  14904. this.renderClassicMode(code, options);
  14905. break;
  14906. }
  14907. case 'automatic': {
  14908. this.renderAutomaticMode(code, options);
  14909. break;
  14910. }
  14911. default: {
  14912. super.render(code, options);
  14913. }
  14914. }
  14915. }
  14916. renderClassicMode(code, options) {
  14917. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14918. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  14919. const [, ...nestedName] = factory.split('.');
  14920. openingFragment.render(code, options);
  14921. code.prependRight(start, `/*#__PURE__*/${[
  14922. factoryVariable.getName(getPropertyAccess, useOriginalName),
  14923. ...nestedName
  14924. ].join('.')}(`);
  14925. code.appendLeft(openingFragment.end, ', null');
  14926. this.renderChildren(code, options, openingFragment.end);
  14927. closingFragment.render(code, options);
  14928. }
  14929. renderAutomaticMode(code, options) {
  14930. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14931. const { closingFragment, factoryVariable, openingFragment, start } = this;
  14932. openingFragment.render(code, options);
  14933. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  14934. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  14935. if (firstChild) {
  14936. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  14937. if (hasMultipleChildren) {
  14938. code.appendLeft(closingFragment.start, ']');
  14939. }
  14940. code.appendLeft(childrenEnd, ' }');
  14941. }
  14942. else {
  14943. code.appendLeft(openingFragment.end, ', {}');
  14944. }
  14945. closingFragment.render(code, options);
  14946. }
  14947. }
  14948. class JSXMemberExpression extends NodeBase {
  14949. includeNode(context) {
  14950. this.included = true;
  14951. if (!this.deoptimized)
  14952. this.applyDeoptimizations();
  14953. this.object.includePath([this.property.name], context);
  14954. }
  14955. includePath(path, context) {
  14956. if (!this.included)
  14957. this.includeNode(context);
  14958. this.object.includePath([this.property.name, ...path], context);
  14959. }
  14960. }
  14961. class JSXNamespacedName extends NodeBase {
  14962. }
  14963. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  14964. class JSXOpeningElement extends NodeBase {
  14965. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  14966. this.name.render(code, options);
  14967. for (const attribute of this.attributes) {
  14968. attribute.render(code, options, { jsxMode });
  14969. }
  14970. }
  14971. }
  14972. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  14973. class JSXOpeningFragment extends NodeBase {
  14974. constructor() {
  14975. super(...arguments);
  14976. this.fragment = null;
  14977. this.fragmentVariable = null;
  14978. }
  14979. includeNode(context) {
  14980. this.included = true;
  14981. if (!this.deoptimized)
  14982. this.applyDeoptimizations();
  14983. const jsx = this.scope.context.options.jsx;
  14984. if (jsx.mode === 'automatic') {
  14985. this.fragment = 'Fragment';
  14986. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  14987. }
  14988. else {
  14989. const { fragment, importSource, mode } = jsx;
  14990. if (fragment != null) {
  14991. this.fragment = fragment;
  14992. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  14993. }
  14994. }
  14995. }
  14996. render(code, options) {
  14997. const { mode } = this.scope.context.options.jsx;
  14998. if (mode !== 'preserve') {
  14999. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  15000. const [, ...nestedFragment] = this.fragment.split('.');
  15001. const fragment = [
  15002. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  15003. ...nestedFragment
  15004. ].join('.');
  15005. code.update(this.start, this.end, fragment);
  15006. }
  15007. }
  15008. }
  15009. class JSXSpreadChild extends NodeBase {
  15010. render(code, options) {
  15011. super.render(code, options);
  15012. const { mode } = this.scope.context.options.jsx;
  15013. if (mode !== 'preserve') {
  15014. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  15015. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  15016. }
  15017. }
  15018. }
  15019. class LabeledStatement extends NodeBase {
  15020. hasEffects(context) {
  15021. const { brokenFlow, includedLabels } = context;
  15022. context.ignore.labels.add(this.label.name);
  15023. context.includedLabels = new Set();
  15024. let bodyHasEffects = false;
  15025. if (this.body.hasEffects(context)) {
  15026. bodyHasEffects = true;
  15027. }
  15028. else {
  15029. context.ignore.labels.delete(this.label.name);
  15030. if (context.includedLabels.has(this.label.name)) {
  15031. context.includedLabels.delete(this.label.name);
  15032. context.brokenFlow = brokenFlow;
  15033. }
  15034. }
  15035. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  15036. return bodyHasEffects;
  15037. }
  15038. include(context, includeChildrenRecursively) {
  15039. if (!this.included)
  15040. this.includeNode(context);
  15041. const { brokenFlow, includedLabels } = context;
  15042. context.includedLabels = new Set();
  15043. this.body.include(context, includeChildrenRecursively);
  15044. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  15045. this.label.include(context, includeChildrenRecursively);
  15046. context.includedLabels.delete(this.label.name);
  15047. context.brokenFlow = brokenFlow;
  15048. }
  15049. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  15050. }
  15051. includeNode(context) {
  15052. this.included = true;
  15053. this.body.includePath(UNKNOWN_PATH, context);
  15054. }
  15055. render(code, options) {
  15056. if (this.label.included) {
  15057. this.label.render(code, options);
  15058. }
  15059. else {
  15060. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  15061. }
  15062. this.body.render(code, options);
  15063. }
  15064. }
  15065. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15066. class LogicalExpression extends NodeBase {
  15067. constructor() {
  15068. super(...arguments);
  15069. // We collect deoptimization information if usedBranch !== null
  15070. this.expressionsToBeDeoptimized = [];
  15071. this.usedBranch = null;
  15072. }
  15073. //private isBranchResolutionAnalysed = false;
  15074. get isBranchResolutionAnalysed() {
  15075. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  15076. }
  15077. set isBranchResolutionAnalysed(value) {
  15078. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  15079. }
  15080. get hasDeoptimizedCache() {
  15081. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  15082. }
  15083. set hasDeoptimizedCache(value) {
  15084. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  15085. }
  15086. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15087. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15088. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15089. }
  15090. deoptimizeCache() {
  15091. if (this.hasDeoptimizedCache)
  15092. return;
  15093. this.hasDeoptimizedCache = true;
  15094. if (this.usedBranch) {
  15095. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  15096. this.usedBranch = null;
  15097. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  15098. if (this.included) {
  15099. // As we are not tracking inclusions, we just include everything
  15100. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  15101. }
  15102. }
  15103. const { scope: { context }, expressionsToBeDeoptimized } = this;
  15104. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  15105. for (const expression of expressionsToBeDeoptimized) {
  15106. expression.deoptimizeCache();
  15107. }
  15108. // Request another pass because we need to ensure "include" runs again if
  15109. // it is rendered
  15110. context.requestTreeshakingPass();
  15111. }
  15112. deoptimizePath(path) {
  15113. const usedBranch = this.getUsedBranch();
  15114. if (usedBranch) {
  15115. usedBranch.deoptimizePath(path);
  15116. }
  15117. else {
  15118. this.left.deoptimizePath(path);
  15119. this.right.deoptimizePath(path);
  15120. }
  15121. }
  15122. getLiteralValueAtPath(path, recursionTracker, origin) {
  15123. if (origin === this)
  15124. return UnknownValue;
  15125. const usedBranch = this.getUsedBranch();
  15126. if (usedBranch) {
  15127. this.expressionsToBeDeoptimized.push(origin);
  15128. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  15129. }
  15130. else if (!this.hasDeoptimizedCache && !path.length) {
  15131. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  15132. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  15133. if (typeof booleanOrUnknown !== 'symbol') {
  15134. if (!booleanOrUnknown && this.operator === '&&') {
  15135. this.expressionsToBeDeoptimized.push(origin);
  15136. return UnknownFalsyValue;
  15137. }
  15138. if (booleanOrUnknown && this.operator === '||') {
  15139. this.expressionsToBeDeoptimized.push(origin);
  15140. return UnknownTruthyValue;
  15141. }
  15142. }
  15143. }
  15144. return UnknownValue;
  15145. }
  15146. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15147. const usedBranch = this.getUsedBranch();
  15148. if (usedBranch) {
  15149. this.expressionsToBeDeoptimized.push(origin);
  15150. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  15151. }
  15152. return [
  15153. new MultiExpression([
  15154. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  15155. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  15156. ]),
  15157. false
  15158. ];
  15159. }
  15160. hasEffects(context) {
  15161. if (this.left.hasEffects(context)) {
  15162. return true;
  15163. }
  15164. if (this.getUsedBranch() !== this.left) {
  15165. return this.right.hasEffects(context);
  15166. }
  15167. return false;
  15168. }
  15169. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15170. const usedBranch = this.getUsedBranch();
  15171. if (usedBranch) {
  15172. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  15173. }
  15174. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  15175. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  15176. }
  15177. include(context, includeChildrenRecursively) {
  15178. this.included = true;
  15179. const usedBranch = this.getUsedBranch();
  15180. if (includeChildrenRecursively ||
  15181. !usedBranch ||
  15182. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  15183. this.left.include(context, includeChildrenRecursively);
  15184. this.right.include(context, includeChildrenRecursively);
  15185. }
  15186. else {
  15187. usedBranch.include(context, includeChildrenRecursively);
  15188. }
  15189. }
  15190. includePath(path, context) {
  15191. this.included = true;
  15192. const usedBranch = this.getUsedBranch();
  15193. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  15194. this.left.includePath(path, context);
  15195. this.right.includePath(path, context);
  15196. }
  15197. else {
  15198. usedBranch.includePath(path, context);
  15199. }
  15200. }
  15201. removeAnnotations(code) {
  15202. this.left.removeAnnotations(code);
  15203. }
  15204. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  15205. if (!this.left.included || !this.right.included) {
  15206. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  15207. if (this.right.included) {
  15208. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  15209. code.remove(this.start, removePos);
  15210. if (preventASI) {
  15211. removeLineBreaks(code, removePos, this.right.start);
  15212. }
  15213. this.left.removeAnnotations(code);
  15214. }
  15215. else {
  15216. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  15217. }
  15218. this.getUsedBranch().render(code, options, {
  15219. isCalleeOfRenderedParent,
  15220. preventASI,
  15221. renderedParentType: renderedParentType || this.parent.type,
  15222. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  15223. });
  15224. }
  15225. else {
  15226. this.left.render(code, options, {
  15227. preventASI,
  15228. renderedSurroundingElement
  15229. });
  15230. this.right.render(code, options);
  15231. }
  15232. }
  15233. getUsedBranch() {
  15234. if (!this.isBranchResolutionAnalysed) {
  15235. this.isBranchResolutionAnalysed = true;
  15236. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  15237. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  15238. if (typeof booleanOrUnknown === 'symbol' ||
  15239. (this.operator === '??' && typeof leftValue === 'symbol')) {
  15240. return null;
  15241. }
  15242. else {
  15243. this.usedBranch =
  15244. (this.operator === '||' && booleanOrUnknown) ||
  15245. (this.operator === '&&' && !booleanOrUnknown) ||
  15246. (this.operator === '??' && leftValue != null)
  15247. ? this.left
  15248. : this.right;
  15249. }
  15250. }
  15251. return this.usedBranch;
  15252. }
  15253. }
  15254. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15255. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15256. class NewExpression extends NodeBase {
  15257. hasEffects(context) {
  15258. if (!this.deoptimized)
  15259. this.applyDeoptimizations();
  15260. for (const argument of this.arguments) {
  15261. if (argument.hasEffects(context))
  15262. return true;
  15263. }
  15264. if (this.annotationPure) {
  15265. return false;
  15266. }
  15267. return (this.callee.hasEffects(context) ||
  15268. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  15269. }
  15270. hasEffectsOnInteractionAtPath(path, { type }) {
  15271. return path.length > 0 || type !== INTERACTION_ACCESSED;
  15272. }
  15273. include(context, includeChildrenRecursively) {
  15274. if (!this.included)
  15275. this.includeNode(context);
  15276. if (includeChildrenRecursively) {
  15277. super.include(context, true);
  15278. }
  15279. else {
  15280. this.callee.include(context, false);
  15281. this.callee.includeCallArguments(this.interaction, context);
  15282. }
  15283. }
  15284. includeNode(context) {
  15285. this.included = true;
  15286. if (!this.deoptimized)
  15287. this.applyDeoptimizations();
  15288. this.callee.includePath(UNKNOWN_PATH, context);
  15289. }
  15290. initialise() {
  15291. super.initialise();
  15292. this.interaction = {
  15293. args: [null, ...this.arguments],
  15294. type: INTERACTION_CALLED,
  15295. withNew: true
  15296. };
  15297. if (this.annotations &&
  15298. this.scope.context.options.treeshake.annotations) {
  15299. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  15300. }
  15301. }
  15302. render(code, options) {
  15303. this.callee.render(code, options);
  15304. renderCallArguments(code, options, this);
  15305. }
  15306. applyDeoptimizations() {
  15307. this.deoptimized = true;
  15308. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15309. this.scope.context.requestTreeshakingPass();
  15310. }
  15311. }
  15312. class ObjectExpression extends NodeBase {
  15313. constructor() {
  15314. super(...arguments);
  15315. this.objectEntity = null;
  15316. this.protoProp = null;
  15317. }
  15318. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15319. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15320. }
  15321. deoptimizeCache() {
  15322. this.getObjectEntity().deoptimizeAllProperties();
  15323. }
  15324. deoptimizePath(path) {
  15325. this.getObjectEntity().deoptimizePath(path);
  15326. }
  15327. getLiteralValueAtPath(path, recursionTracker, origin) {
  15328. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  15329. }
  15330. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15331. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  15332. }
  15333. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15334. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  15335. }
  15336. include(context, includeChildrenRecursively) {
  15337. if (!this.included)
  15338. this.includeNode(context);
  15339. this.getObjectEntity().include(context, includeChildrenRecursively);
  15340. this.protoProp?.include(context, includeChildrenRecursively);
  15341. }
  15342. includeNode(context) {
  15343. this.included = true;
  15344. this.protoProp?.includePath(UNKNOWN_PATH, context);
  15345. }
  15346. includePath(path, context) {
  15347. if (!this.included)
  15348. this.includeNode(context);
  15349. this.getObjectEntity().includePath(path, context);
  15350. }
  15351. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  15352. if (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  15353. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression) {
  15354. code.appendRight(this.start, '(');
  15355. code.prependLeft(this.end, ')');
  15356. }
  15357. if (this.properties.length > 0) {
  15358. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  15359. let lastSeparatorPos = null;
  15360. for (const { node, separator, start, end } of separatedNodes) {
  15361. if (!node.included) {
  15362. treeshakeNode(node, code, start, end);
  15363. continue;
  15364. }
  15365. lastSeparatorPos = separator;
  15366. node.render(code, options);
  15367. }
  15368. if (lastSeparatorPos) {
  15369. code.remove(lastSeparatorPos, this.end - 1);
  15370. }
  15371. }
  15372. }
  15373. getObjectEntity() {
  15374. if (this.objectEntity !== null) {
  15375. return this.objectEntity;
  15376. }
  15377. let prototype = OBJECT_PROTOTYPE;
  15378. const properties = [];
  15379. for (const property of this.properties) {
  15380. if (property instanceof SpreadElement) {
  15381. properties.push({ key: UnknownKey, kind: 'init', property });
  15382. continue;
  15383. }
  15384. let key;
  15385. if (property.computed) {
  15386. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  15387. if (typeof keyValue === 'symbol') {
  15388. properties.push({
  15389. key: isAnyWellKnown(keyValue) ? keyValue : UnknownKey,
  15390. kind: property.kind,
  15391. property
  15392. });
  15393. continue;
  15394. }
  15395. else {
  15396. key = String(keyValue);
  15397. }
  15398. }
  15399. else {
  15400. key =
  15401. property.key instanceof Identifier
  15402. ? property.key.name
  15403. : String(property.key.value);
  15404. if (key === '__proto__' && property.kind === 'init') {
  15405. this.protoProp = property;
  15406. prototype =
  15407. property.value instanceof Literal && property.value.value === null
  15408. ? null
  15409. : property.value;
  15410. continue;
  15411. }
  15412. }
  15413. properties.push({ key, kind: property.kind, property });
  15414. }
  15415. return (this.objectEntity = new ObjectEntity(properties, prototype));
  15416. }
  15417. }
  15418. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15419. class PanicError extends NodeBase {
  15420. initialise() {
  15421. const { id } = this.scope.context.module;
  15422. // This simulates the current nested error structure. We could also just
  15423. // replace it with a flat error.
  15424. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message));
  15425. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  15426. return parseAst_js.error(moduleParseError);
  15427. }
  15428. }
  15429. class ParseError extends NodeBase {
  15430. initialise() {
  15431. const pos = this.start;
  15432. const { id } = this.scope.context.module;
  15433. // This simulates the current nested error structure. We could also just
  15434. // replace it with a flat error.
  15435. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message, pos));
  15436. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  15437. this.scope.context.error(moduleParseError, pos);
  15438. }
  15439. }
  15440. class PrivateIdentifier extends NodeBase {
  15441. }
  15442. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  15443. class Program extends NodeBase {
  15444. constructor() {
  15445. super(...arguments);
  15446. this.hasCachedEffect = null;
  15447. this.hasLoggedEffect = false;
  15448. }
  15449. hasCachedEffects() {
  15450. if (!this.included) {
  15451. return false;
  15452. }
  15453. return this.hasCachedEffect === null
  15454. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  15455. : this.hasCachedEffect;
  15456. }
  15457. hasEffects(context) {
  15458. for (const node of this.body) {
  15459. if (node.hasEffects(context)) {
  15460. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  15461. this.hasLoggedEffect = true;
  15462. const { code, log, module } = this.scope.context;
  15463. log(parseAst_js.LOGLEVEL_INFO, parseAst_js.logFirstSideEffect(code, module.id, parseAst_js.locate(code, node.start, { offsetLine: 1 })), node.start);
  15464. }
  15465. return (this.hasCachedEffect = true);
  15466. }
  15467. }
  15468. return false;
  15469. }
  15470. include(context, includeChildrenRecursively) {
  15471. this.included = true;
  15472. for (const node of this.body) {
  15473. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  15474. node.include(context, includeChildrenRecursively);
  15475. }
  15476. }
  15477. }
  15478. initialise() {
  15479. super.initialise();
  15480. if (this.invalidAnnotations)
  15481. for (const { start, end, type } of this.invalidAnnotations) {
  15482. this.scope.context.magicString.remove(start, end);
  15483. if (type === 'pure' || type === 'noSideEffects') {
  15484. 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);
  15485. }
  15486. }
  15487. }
  15488. render(code, options) {
  15489. let start = this.start;
  15490. if (code.original.startsWith('#!')) {
  15491. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  15492. code.remove(0, start);
  15493. }
  15494. if (this.body.length > 0) {
  15495. // Keep all consecutive lines that start with a comment
  15496. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  15497. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  15498. if (firstLineBreak[0] === -1) {
  15499. break;
  15500. }
  15501. start += firstLineBreak[1];
  15502. }
  15503. renderStatementList(this.body, code, start, this.end, options);
  15504. }
  15505. else {
  15506. super.render(code, options);
  15507. }
  15508. }
  15509. }
  15510. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15511. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  15512. class Property extends MethodBase {
  15513. //declare method: boolean;
  15514. get method() {
  15515. return isFlagSet(this.flags, 262144 /* Flag.method */);
  15516. }
  15517. set method(value) {
  15518. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  15519. }
  15520. //declare shorthand: boolean;
  15521. get shorthand() {
  15522. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  15523. }
  15524. set shorthand(value) {
  15525. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  15526. }
  15527. declare(kind, destructuredInitPath, init) {
  15528. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  15529. }
  15530. deoptimizeAssignment(destructuredInitPath, init) {
  15531. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  15532. }
  15533. hasEffects(context) {
  15534. return this.key.hasEffects(context) || this.value.hasEffects(context);
  15535. }
  15536. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  15537. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  15538. }
  15539. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  15540. const path = this.getPathInProperty(destructuredInitPath);
  15541. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  15542. this.included;
  15543. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  15544. this.key.include(context, false);
  15545. if (!this.value.included) {
  15546. this.value.includeNode(context);
  15547. // Unfortunately, we need to include the value again now, so that any
  15548. // declared variables are properly included.
  15549. this.value.includeDestructuredIfNecessary(context, path, init);
  15550. }
  15551. }
  15552. if (!this.included && included) {
  15553. this.includeNode(context);
  15554. }
  15555. return this.included;
  15556. }
  15557. include(context, includeChildrenRecursively) {
  15558. this.included = true;
  15559. this.key.include(context, includeChildrenRecursively);
  15560. this.value.include(context, includeChildrenRecursively);
  15561. }
  15562. includePath(path, context) {
  15563. this.included = true;
  15564. this.value.includePath(path, context);
  15565. }
  15566. markDeclarationReached() {
  15567. this.value.markDeclarationReached();
  15568. }
  15569. render(code, options) {
  15570. if (!this.shorthand) {
  15571. this.key.render(code, options);
  15572. }
  15573. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  15574. }
  15575. getPathInProperty(destructuredInitPath) {
  15576. return destructuredInitPath.at(-1) === UnknownKey
  15577. ? destructuredInitPath
  15578. : // For now, we only consider static paths as we do not know how to
  15579. // deoptimize the path in the dynamic case.
  15580. this.computed
  15581. ? [...destructuredInitPath, UnknownKey]
  15582. : this.key instanceof Identifier
  15583. ? [...destructuredInitPath, this.key.name]
  15584. : [...destructuredInitPath, String(this.key.value)];
  15585. }
  15586. }
  15587. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15588. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  15589. class PropertyDefinition extends NodeBase {
  15590. get computed() {
  15591. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  15592. }
  15593. set computed(value) {
  15594. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  15595. }
  15596. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15597. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15598. }
  15599. deoptimizePath(path) {
  15600. this.value?.deoptimizePath(path);
  15601. }
  15602. getLiteralValueAtPath(path, recursionTracker, origin) {
  15603. return this.value
  15604. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  15605. : UnknownValue;
  15606. }
  15607. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15608. return this.value
  15609. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  15610. : UNKNOWN_RETURN_EXPRESSION;
  15611. }
  15612. hasEffects(context) {
  15613. return (this.key.hasEffects(context) ||
  15614. (this.static && !!this.value?.hasEffects(context)) ||
  15615. checkEffectForNodes(this.decorators, context));
  15616. }
  15617. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15618. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  15619. }
  15620. includeNode(context) {
  15621. this.included = true;
  15622. this.value?.includePath(UNKNOWN_PATH, context);
  15623. for (const decorator of this.decorators) {
  15624. decorator.includePath(UNKNOWN_PATH, context);
  15625. }
  15626. }
  15627. }
  15628. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  15629. class ReturnStatement extends NodeBase {
  15630. hasEffects(context) {
  15631. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  15632. return true;
  15633. context.brokenFlow = true;
  15634. return false;
  15635. }
  15636. include(context, includeChildrenRecursively) {
  15637. if (!this.included)
  15638. this.includeNode(context);
  15639. this.argument?.include(context, includeChildrenRecursively);
  15640. context.brokenFlow = true;
  15641. }
  15642. includeNode(context) {
  15643. this.included = true;
  15644. this.argument?.includePath(UNKNOWN_PATH, context);
  15645. }
  15646. initialise() {
  15647. super.initialise();
  15648. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  15649. }
  15650. render(code, options) {
  15651. if (this.argument) {
  15652. this.argument.render(code, options, { preventASI: true });
  15653. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  15654. code.prependLeft(this.start + 6, ' ');
  15655. }
  15656. }
  15657. }
  15658. }
  15659. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15660. class SequenceExpression extends NodeBase {
  15661. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15662. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15663. }
  15664. deoptimizePath(path) {
  15665. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  15666. }
  15667. getLiteralValueAtPath(path, recursionTracker, origin) {
  15668. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  15669. }
  15670. hasEffects(context) {
  15671. for (const expression of this.expressions) {
  15672. if (expression.hasEffects(context))
  15673. return true;
  15674. }
  15675. return false;
  15676. }
  15677. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15678. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  15679. }
  15680. include(context, includeChildrenRecursively) {
  15681. this.included = true;
  15682. const lastExpression = this.expressions[this.expressions.length - 1];
  15683. for (const expression of this.expressions) {
  15684. if (includeChildrenRecursively ||
  15685. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  15686. expression.shouldBeIncluded(context)) {
  15687. expression.include(context, includeChildrenRecursively);
  15688. }
  15689. }
  15690. }
  15691. includePath(path, context) {
  15692. this.included = true;
  15693. this.expressions[this.expressions.length - 1].includePath(path, context);
  15694. }
  15695. removeAnnotations(code) {
  15696. this.expressions[0].removeAnnotations(code);
  15697. }
  15698. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = parseAst_js.BLANK) {
  15699. let includedNodes = 0;
  15700. let lastSeparatorPos = null;
  15701. const lastNode = this.expressions[this.expressions.length - 1];
  15702. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  15703. if (!node.included) {
  15704. treeshakeNode(node, code, start, end);
  15705. continue;
  15706. }
  15707. includedNodes++;
  15708. lastSeparatorPos = separator;
  15709. if (includedNodes === 1 && preventASI) {
  15710. removeLineBreaks(code, start, node.start);
  15711. }
  15712. if (includedNodes === 1) {
  15713. const parentType = renderedParentType || this.parent.type;
  15714. node.render(code, options, {
  15715. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  15716. renderedParentType: parentType,
  15717. renderedSurroundingElement: parentType
  15718. });
  15719. }
  15720. else {
  15721. node.render(code, options);
  15722. }
  15723. }
  15724. if (lastSeparatorPos) {
  15725. code.remove(lastSeparatorPos, this.end);
  15726. }
  15727. }
  15728. }
  15729. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15730. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15731. class Super extends NodeBase {
  15732. bind() {
  15733. this.variable = this.scope.findVariable('this');
  15734. }
  15735. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15736. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15737. }
  15738. deoptimizePath(path) {
  15739. this.variable.deoptimizePath(path);
  15740. }
  15741. include(context) {
  15742. if (!this.included)
  15743. this.includeNode(context);
  15744. }
  15745. includeNode(context) {
  15746. this.included = true;
  15747. if (!this.deoptimized)
  15748. this.applyDeoptimizations();
  15749. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15750. }
  15751. }
  15752. class SwitchCase extends NodeBase {
  15753. hasEffects(context) {
  15754. if (this.test?.hasEffects(context))
  15755. return true;
  15756. for (const node of this.consequent) {
  15757. if (context.brokenFlow)
  15758. break;
  15759. if (node.hasEffects(context))
  15760. return true;
  15761. }
  15762. return false;
  15763. }
  15764. include(context, includeChildrenRecursively) {
  15765. this.included = true;
  15766. this.test?.include(context, includeChildrenRecursively);
  15767. for (const node of this.consequent) {
  15768. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  15769. node.include(context, includeChildrenRecursively);
  15770. }
  15771. }
  15772. render(code, options, nodeRenderOptions) {
  15773. if (this.test) {
  15774. this.test.render(code, options);
  15775. if (this.test.start === this.start + 4) {
  15776. code.prependLeft(this.test.start, ' ');
  15777. }
  15778. }
  15779. if (this.consequent.length > 0) {
  15780. const testEnd = this.test
  15781. ? this.test.end
  15782. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  15783. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  15784. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  15785. }
  15786. }
  15787. }
  15788. SwitchCase.prototype.needsBoundaries = true;
  15789. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15790. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  15791. class SwitchStatement extends NodeBase {
  15792. createScope(parentScope) {
  15793. this.parentScope = parentScope;
  15794. this.scope = new BlockScope(parentScope);
  15795. }
  15796. hasEffects(context) {
  15797. if (this.discriminant.hasEffects(context))
  15798. return true;
  15799. const { brokenFlow, hasBreak, ignore } = context;
  15800. const { breaks } = ignore;
  15801. ignore.breaks = true;
  15802. context.hasBreak = false;
  15803. let onlyHasBrokenFlow = true;
  15804. for (const switchCase of this.cases) {
  15805. if (switchCase.hasEffects(context))
  15806. return true;
  15807. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15808. context.hasBreak = false;
  15809. context.brokenFlow = brokenFlow;
  15810. }
  15811. if (this.defaultCase !== null) {
  15812. context.brokenFlow = onlyHasBrokenFlow;
  15813. }
  15814. ignore.breaks = breaks;
  15815. context.hasBreak = hasBreak;
  15816. return false;
  15817. }
  15818. include(context, includeChildrenRecursively) {
  15819. this.included = true;
  15820. this.discriminant.include(context, includeChildrenRecursively);
  15821. const { brokenFlow, hasBreak } = context;
  15822. context.hasBreak = false;
  15823. let onlyHasBrokenFlow = true;
  15824. let isCaseIncluded = includeChildrenRecursively ||
  15825. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  15826. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  15827. const switchCase = this.cases[caseIndex];
  15828. if (switchCase.included) {
  15829. isCaseIncluded = true;
  15830. }
  15831. if (!isCaseIncluded) {
  15832. const hasEffectsContext = createHasEffectsContext();
  15833. hasEffectsContext.ignore.breaks = true;
  15834. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  15835. }
  15836. if (isCaseIncluded) {
  15837. switchCase.include(context, includeChildrenRecursively);
  15838. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15839. context.hasBreak = false;
  15840. context.brokenFlow = brokenFlow;
  15841. }
  15842. else {
  15843. onlyHasBrokenFlow = brokenFlow;
  15844. }
  15845. }
  15846. if (isCaseIncluded && this.defaultCase !== null) {
  15847. context.brokenFlow = onlyHasBrokenFlow;
  15848. }
  15849. context.hasBreak = hasBreak;
  15850. }
  15851. initialise() {
  15852. super.initialise();
  15853. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  15854. if (this.cases[caseIndex].test === null) {
  15855. this.defaultCase = caseIndex;
  15856. return;
  15857. }
  15858. }
  15859. this.defaultCase = null;
  15860. }
  15861. parseNode(esTreeNode) {
  15862. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  15863. return super.parseNode(esTreeNode);
  15864. }
  15865. render(code, options) {
  15866. this.discriminant.render(code, options);
  15867. if (this.cases.length > 0) {
  15868. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  15869. }
  15870. }
  15871. }
  15872. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15873. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15874. class TaggedTemplateExpression extends CallExpressionBase {
  15875. get hasCheckedForWarnings() {
  15876. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  15877. }
  15878. set hasCheckedForWarnings(value) {
  15879. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  15880. }
  15881. hasEffects(context) {
  15882. if (!this.deoptimized)
  15883. this.applyDeoptimizations();
  15884. for (const argument of this.quasi.expressions) {
  15885. if (argument.hasEffects(context))
  15886. return true;
  15887. }
  15888. return (this.tag.hasEffects(context) ||
  15889. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  15890. }
  15891. include(context, includeChildrenRecursively) {
  15892. if (!this.included)
  15893. this.includeNode(context);
  15894. if (includeChildrenRecursively) {
  15895. super.include(context, true);
  15896. }
  15897. else {
  15898. this.quasi.include(context, false);
  15899. this.tag.include(context, false);
  15900. this.tag.includeCallArguments(this.interaction, context);
  15901. }
  15902. }
  15903. initialise() {
  15904. super.initialise();
  15905. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  15906. this.interaction = {
  15907. args: [
  15908. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  15909. ...this.args
  15910. ],
  15911. type: INTERACTION_CALLED,
  15912. withNew: false
  15913. };
  15914. }
  15915. render(code, options) {
  15916. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  15917. this.quasi.render(code, options);
  15918. if (!this.hasCheckedForWarnings && this.tag.type === parseAst_js.Identifier) {
  15919. this.hasCheckedForWarnings = true;
  15920. const name = this.tag.name;
  15921. const variable = this.scope.findVariable(name);
  15922. if (variable.isNamespace) {
  15923. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
  15924. }
  15925. }
  15926. }
  15927. applyDeoptimizations() {
  15928. this.deoptimized = true;
  15929. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15930. this.scope.context.requestTreeshakingPass();
  15931. }
  15932. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  15933. if (this.returnExpression === null) {
  15934. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  15935. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  15936. }
  15937. return this.returnExpression;
  15938. }
  15939. }
  15940. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  15941. class TemplateElement extends NodeBase {
  15942. get tail() {
  15943. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  15944. }
  15945. set tail(value) {
  15946. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  15947. }
  15948. // Do not try to bind value
  15949. bind() { }
  15950. hasEffects() {
  15951. return false;
  15952. }
  15953. parseNode(esTreeNode) {
  15954. this.value = esTreeNode.value;
  15955. return super.parseNode(esTreeNode);
  15956. }
  15957. render() { }
  15958. }
  15959. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  15960. class TemplateLiteral extends NodeBase {
  15961. deoptimizeArgumentsOnInteractionAtPath() { }
  15962. getLiteralValueAtPath(path) {
  15963. if (path.length > 0 || this.quasis.length !== 1) {
  15964. return UnknownValue;
  15965. }
  15966. return this.quasis[0].value.cooked;
  15967. }
  15968. getReturnExpressionWhenCalledAtPath(path) {
  15969. if (path.length !== 1) {
  15970. return UNKNOWN_RETURN_EXPRESSION;
  15971. }
  15972. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  15973. }
  15974. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15975. if (interaction.type === INTERACTION_ACCESSED) {
  15976. return path.length > 1;
  15977. }
  15978. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  15979. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  15980. }
  15981. return true;
  15982. }
  15983. includeNode(context) {
  15984. this.included = true;
  15985. if (!this.deoptimized)
  15986. this.applyDeoptimizations();
  15987. for (const node of this.expressions) {
  15988. node.includePath(UNKNOWN_PATH, context);
  15989. }
  15990. }
  15991. render(code, options) {
  15992. code.indentExclusionRanges.push([this.start, this.end]);
  15993. super.render(code, options);
  15994. }
  15995. }
  15996. class ModuleScope extends ChildScope {
  15997. constructor(parent, context, importDescriptions) {
  15998. super(parent, context);
  15999. this.importDescriptions = importDescriptions;
  16000. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  16001. }
  16002. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  16003. if (this.importDescriptions.has(identifier.name)) {
  16004. context.error(parseAst_js.logRedeclarationError(identifier.name), identifier.start);
  16005. }
  16006. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  16007. }
  16008. addExportDefaultDeclaration(exportDefaultDeclaration, context) {
  16009. const variable = new ExportDefaultVariable(exportDefaultDeclaration, context);
  16010. this.variables.set('default', variable);
  16011. return variable;
  16012. }
  16013. addNamespaceMemberAccess() { }
  16014. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  16015. // all module level variables are already deconflicted when deconflicting the chunk
  16016. for (const scope of this.children)
  16017. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  16018. }
  16019. findLexicalBoundary() {
  16020. return this;
  16021. }
  16022. findVariable(name) {
  16023. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  16024. if (knownVariable) {
  16025. return knownVariable;
  16026. }
  16027. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  16028. if (variable instanceof GlobalVariable) {
  16029. this.accessedOutsideVariables.set(name, variable);
  16030. }
  16031. return variable;
  16032. }
  16033. }
  16034. class ThisExpression extends NodeBase {
  16035. bind() {
  16036. this.variable = this.scope.findVariable('this');
  16037. }
  16038. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  16039. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  16040. }
  16041. deoptimizePath(path) {
  16042. this.variable.deoptimizePath(path);
  16043. }
  16044. hasEffectsOnInteractionAtPath(path, interaction, context) {
  16045. if (path.length === 0) {
  16046. return interaction.type !== INTERACTION_ACCESSED;
  16047. }
  16048. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  16049. }
  16050. include(context) {
  16051. if (!this.included)
  16052. this.includeNode(context);
  16053. }
  16054. includeNode(context) {
  16055. this.included = true;
  16056. if (!this.deoptimized)
  16057. this.applyDeoptimizations();
  16058. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  16059. }
  16060. includePath(path, context) {
  16061. if (!this.included) {
  16062. this.included = true;
  16063. this.scope.context.includeVariableInModule(this.variable, path, context);
  16064. }
  16065. else if (path.length > 0) {
  16066. this.variable.includePath(path, context);
  16067. }
  16068. const functionScope = findFunctionScope(this.scope, this.variable);
  16069. if (functionScope &&
  16070. functionScope.functionNode.parent instanceof Property &&
  16071. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  16072. functionScope.functionNode.parent.parent.includePath(path, context);
  16073. }
  16074. }
  16075. initialise() {
  16076. super.initialise();
  16077. this.alias =
  16078. this.scope.findLexicalBoundary() instanceof ModuleScope
  16079. ? this.scope.context.moduleContext
  16080. : null;
  16081. if (this.alias === 'undefined') {
  16082. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logThisIsUndefined(), this.start);
  16083. }
  16084. }
  16085. render(code) {
  16086. if (this.alias !== null) {
  16087. code.overwrite(this.start, this.end, this.alias, {
  16088. contentOnly: false,
  16089. storeName: true
  16090. });
  16091. }
  16092. }
  16093. }
  16094. function findFunctionScope(scope, thisVariable) {
  16095. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  16096. if (!(scope instanceof ChildScope)) {
  16097. return null;
  16098. }
  16099. scope = scope.parent;
  16100. }
  16101. return scope;
  16102. }
  16103. class ThrowStatement extends NodeBase {
  16104. hasEffects() {
  16105. return true;
  16106. }
  16107. include(context, includeChildrenRecursively) {
  16108. if (!this.included)
  16109. this.includeNode(context);
  16110. this.argument.include(context, includeChildrenRecursively);
  16111. context.brokenFlow = true;
  16112. }
  16113. includeNode(context) {
  16114. if (!this.included) {
  16115. this.included = true;
  16116. this.argument.includePath(UNKNOWN_PATH, context);
  16117. }
  16118. }
  16119. render(code, options) {
  16120. this.argument.render(code, options, { preventASI: true });
  16121. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  16122. code.prependLeft(this.start + 5, ' ');
  16123. }
  16124. }
  16125. }
  16126. class TryStatement extends NodeBase {
  16127. constructor() {
  16128. super(...arguments);
  16129. this.directlyIncluded = false;
  16130. this.includedLabelsAfterBlock = null;
  16131. }
  16132. hasEffects(context) {
  16133. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  16134. ? this.block.body.length > 0
  16135. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  16136. }
  16137. include(context, includeChildrenRecursively) {
  16138. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  16139. const { brokenFlow, includedLabels } = context;
  16140. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  16141. this.included = true;
  16142. this.directlyIncluded = true;
  16143. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  16144. if (includedLabels.size > 0) {
  16145. this.includedLabelsAfterBlock = [...includedLabels];
  16146. }
  16147. context.brokenFlow = brokenFlow;
  16148. }
  16149. else if (this.includedLabelsAfterBlock) {
  16150. for (const label of this.includedLabelsAfterBlock) {
  16151. includedLabels.add(label);
  16152. }
  16153. }
  16154. if (this.handler !== null) {
  16155. this.handler.include(context, includeChildrenRecursively);
  16156. context.brokenFlow = brokenFlow;
  16157. }
  16158. this.finalizer?.include(context, includeChildrenRecursively);
  16159. }
  16160. }
  16161. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16162. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  16163. const unaryOperators = {
  16164. '!': value => !value,
  16165. '+': value => +value,
  16166. '-': value => -value,
  16167. delete: () => UnknownValue,
  16168. typeof: value => typeof value,
  16169. void: () => undefined,
  16170. '~': value => ~value
  16171. };
  16172. const UNASSIGNED = Symbol('Unassigned');
  16173. class UnaryExpression extends NodeBase {
  16174. constructor() {
  16175. super(...arguments);
  16176. this.renderedLiteralValue = UNASSIGNED;
  16177. }
  16178. get prefix() {
  16179. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  16180. }
  16181. set prefix(value) {
  16182. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  16183. }
  16184. deoptimizeCache() {
  16185. this.renderedLiteralValue = UnknownValue;
  16186. }
  16187. getLiteralValueAtPath(path, recursionTracker, origin) {
  16188. if (path.length > 0)
  16189. return UnknownValue;
  16190. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  16191. if (typeof argumentValue === 'symbol') {
  16192. if (this.operator === 'void')
  16193. return undefined;
  16194. if (this.operator === '!') {
  16195. if (argumentValue === UnknownFalsyValue)
  16196. return true;
  16197. if (argumentValue === UnknownTruthyValue)
  16198. return false;
  16199. }
  16200. return UnknownValue;
  16201. }
  16202. return unaryOperators[this.operator](argumentValue);
  16203. }
  16204. hasEffects(context) {
  16205. if (!this.deoptimized)
  16206. this.applyDeoptimizations();
  16207. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  16208. return false;
  16209. return (this.argument.hasEffects(context) ||
  16210. (this.operator === 'delete' &&
  16211. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  16212. }
  16213. hasEffectsOnInteractionAtPath(path, { type }) {
  16214. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  16215. }
  16216. applyDeoptimizations() {
  16217. this.deoptimized = true;
  16218. if (this.operator === 'delete') {
  16219. this.argument.deoptimizePath(EMPTY_PATH);
  16220. this.scope.context.requestTreeshakingPass();
  16221. }
  16222. }
  16223. getRenderedLiteralValue(includeChildrenRecursively) {
  16224. if (this.renderedLiteralValue !== UNASSIGNED)
  16225. return this.renderedLiteralValue;
  16226. return (this.renderedLiteralValue = includeChildrenRecursively
  16227. ? UnknownValue
  16228. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  16229. }
  16230. include(context, includeChildrenRecursively, _options) {
  16231. if (!this.deoptimized)
  16232. this.applyDeoptimizations();
  16233. this.included = true;
  16234. // Check if the argument is an identifier that should be preserved as a reference for readability
  16235. const shouldPreserveArgument = this.argument instanceof Identifier && this.argument.variable?.included;
  16236. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  16237. this.argument.shouldBeIncluded(context) ||
  16238. shouldPreserveArgument) {
  16239. this.argument.include(context, includeChildrenRecursively);
  16240. this.renderedLiteralValue = UnknownValue;
  16241. }
  16242. }
  16243. render(code, options) {
  16244. if (typeof this.renderedLiteralValue === 'symbol') {
  16245. super.render(code, options);
  16246. }
  16247. else {
  16248. let value = this.renderedLiteralValue;
  16249. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  16250. value = ` ${value}`;
  16251. }
  16252. code.overwrite(this.start, this.end, value);
  16253. }
  16254. }
  16255. }
  16256. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  16257. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  16258. class UpdateExpression extends NodeBase {
  16259. hasEffects(context) {
  16260. if (!this.deoptimized)
  16261. this.applyDeoptimizations();
  16262. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  16263. }
  16264. hasEffectsOnInteractionAtPath(path, { type }) {
  16265. return path.length > 1 || type !== INTERACTION_ACCESSED;
  16266. }
  16267. include(context, includeChildrenRecursively) {
  16268. if (!this.included)
  16269. this.includeNode(context);
  16270. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  16271. }
  16272. initialise() {
  16273. super.initialise();
  16274. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  16275. }
  16276. render(code, options) {
  16277. const { exportNamesByVariable, format, snippets: { _ } } = options;
  16278. this.argument.render(code, options);
  16279. if (format === 'system') {
  16280. const variable = this.argument.variable;
  16281. const exportNames = exportNamesByVariable.get(variable);
  16282. if (exportNames) {
  16283. if (this.prefix) {
  16284. if (exportNames.length === 1) {
  16285. renderSystemExportExpression(variable, this.start, this.end, code, options);
  16286. }
  16287. else {
  16288. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options);
  16289. }
  16290. }
  16291. else {
  16292. const operator = this.operator[0];
  16293. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options, `${_}${operator}${_}1`);
  16294. }
  16295. }
  16296. }
  16297. }
  16298. applyDeoptimizations() {
  16299. this.deoptimized = true;
  16300. this.argument.deoptimizePath(EMPTY_PATH);
  16301. if (this.argument instanceof Identifier) {
  16302. const variable = this.scope.findVariable(this.argument.name);
  16303. variable.markReassigned();
  16304. }
  16305. this.scope.context.requestTreeshakingPass();
  16306. }
  16307. }
  16308. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  16309. function isReassignedExportsMember(variable, exportNamesByVariable) {
  16310. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  16311. }
  16312. class VariableDeclaration extends NodeBase {
  16313. deoptimizePath() {
  16314. for (const declarator of this.declarations) {
  16315. declarator.deoptimizePath(EMPTY_PATH);
  16316. }
  16317. }
  16318. hasEffectsOnInteractionAtPath() {
  16319. return false;
  16320. }
  16321. include(context, includeChildrenRecursively, { asSingleStatement } = parseAst_js.BLANK) {
  16322. this.included = true;
  16323. for (const declarator of this.declarations) {
  16324. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  16325. declarator.include(context, includeChildrenRecursively);
  16326. }
  16327. const { id, init } = declarator;
  16328. if (asSingleStatement) {
  16329. id.include(context, includeChildrenRecursively);
  16330. }
  16331. if (init &&
  16332. id.included &&
  16333. !init.included &&
  16334. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  16335. init.include(context, includeChildrenRecursively);
  16336. }
  16337. }
  16338. }
  16339. initialise() {
  16340. super.initialise();
  16341. for (const declarator of this.declarations) {
  16342. declarator.declareDeclarator(this.kind);
  16343. }
  16344. }
  16345. removeAnnotations(code) {
  16346. this.declarations[0].removeAnnotations(code);
  16347. }
  16348. render(code, options, nodeRenderOptions = parseAst_js.BLANK) {
  16349. if (this.areAllDeclarationsIncludedAndNotExported(options.exportNamesByVariable)) {
  16350. for (const declarator of this.declarations) {
  16351. declarator.render(code, options);
  16352. }
  16353. if (!nodeRenderOptions.isNoStatement &&
  16354. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  16355. code.appendLeft(this.end, ';');
  16356. }
  16357. }
  16358. else {
  16359. this.renderReplacedDeclarations(code, options);
  16360. }
  16361. }
  16362. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  16363. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  16364. code.remove(this.end - 1, this.end);
  16365. }
  16366. separatorString += ';';
  16367. if (lastSeparatorPos === null) {
  16368. code.appendLeft(renderedContentEnd, separatorString);
  16369. }
  16370. else {
  16371. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  16372. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  16373. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  16374. actualContentEnd--;
  16375. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  16376. actualContentEnd--;
  16377. }
  16378. }
  16379. if (actualContentEnd === lastSeparatorPos + 1) {
  16380. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  16381. }
  16382. else {
  16383. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  16384. code.remove(actualContentEnd, renderedContentEnd);
  16385. }
  16386. }
  16387. if (systemPatternExports.length > 0) {
  16388. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  16389. }
  16390. }
  16391. renderReplacedDeclarations(code, options) {
  16392. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  16393. let actualContentEnd, renderedContentEnd;
  16394. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  16395. let lastSeparatorPos = renderedContentEnd - 1;
  16396. code.remove(this.start, lastSeparatorPos);
  16397. let isInDeclaration = false;
  16398. let hasRenderedContent = false;
  16399. let separatorString = '', leadingString, nextSeparatorString;
  16400. const aggregatedSystemExports = [];
  16401. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  16402. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  16403. if (!node.included) {
  16404. treeshakeNode(node, code, start, end);
  16405. continue;
  16406. }
  16407. node.render(code, options);
  16408. leadingString = '';
  16409. nextSeparatorString = '';
  16410. if (!node.id.included ||
  16411. (node.id instanceof Identifier &&
  16412. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  16413. if (hasRenderedContent) {
  16414. separatorString += ';';
  16415. }
  16416. isInDeclaration = false;
  16417. }
  16418. else {
  16419. if (singleSystemExport && singleSystemExport === node.id.variable) {
  16420. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  16421. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  16422. }
  16423. if (isInDeclaration) {
  16424. separatorString += ',';
  16425. }
  16426. else {
  16427. if (hasRenderedContent) {
  16428. separatorString += ';';
  16429. }
  16430. leadingString += `${this.kind} `;
  16431. isInDeclaration = true;
  16432. }
  16433. }
  16434. if (renderedContentEnd === lastSeparatorPos + 1) {
  16435. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  16436. }
  16437. else {
  16438. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  16439. code.appendLeft(renderedContentEnd, leadingString);
  16440. }
  16441. actualContentEnd = contentEnd;
  16442. renderedContentEnd = end;
  16443. hasRenderedContent = true;
  16444. lastSeparatorPos = separator;
  16445. separatorString = nextSeparatorString;
  16446. }
  16447. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  16448. }
  16449. areAllDeclarationsIncludedAndNotExported(exportNamesByVariable) {
  16450. if (this.kind === 'await using' || this.kind === 'using') {
  16451. return true;
  16452. }
  16453. for (const declarator of this.declarations) {
  16454. if (!declarator.id.included)
  16455. return false;
  16456. if (declarator.id.type === parseAst_js.Identifier) {
  16457. if (exportNamesByVariable.has(declarator.id.variable))
  16458. return false;
  16459. }
  16460. else {
  16461. const exportedVariables = [];
  16462. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  16463. if (exportedVariables.length > 0)
  16464. return false;
  16465. }
  16466. }
  16467. return true;
  16468. }
  16469. }
  16470. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  16471. let singleSystemExport = null;
  16472. if (options.format === 'system') {
  16473. for (const { node } of separatedNodes) {
  16474. if (node.id instanceof Identifier &&
  16475. node.init &&
  16476. aggregatedSystemExports.length === 0 &&
  16477. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  16478. singleSystemExport = node.id.variable;
  16479. aggregatedSystemExports.push(singleSystemExport);
  16480. }
  16481. else {
  16482. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  16483. }
  16484. }
  16485. if (aggregatedSystemExports.length > 1) {
  16486. singleSystemExport = null;
  16487. }
  16488. else if (singleSystemExport) {
  16489. aggregatedSystemExports.length = 0;
  16490. }
  16491. }
  16492. return singleSystemExport;
  16493. }
  16494. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16495. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  16496. class VariableDeclarator extends NodeBase {
  16497. declareDeclarator(kind) {
  16498. this.isUsingDeclaration = kind === 'using';
  16499. this.isAsyncUsingDeclaration = kind === 'await using';
  16500. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  16501. }
  16502. deoptimizePath(path) {
  16503. this.id.deoptimizePath(path);
  16504. }
  16505. hasEffects(context) {
  16506. const initEffect = this.init?.hasEffects(context);
  16507. this.id.markDeclarationReached();
  16508. return (initEffect ||
  16509. this.isUsingDeclaration ||
  16510. this.isAsyncUsingDeclaration ||
  16511. this.id.hasEffects(context) ||
  16512. (this.scope.context.options.treeshake
  16513. .propertyReadSideEffects &&
  16514. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  16515. }
  16516. include(context, includeChildrenRecursively) {
  16517. const { id, init } = this;
  16518. if (!this.included)
  16519. this.includeNode(context);
  16520. init?.include(context, includeChildrenRecursively);
  16521. id.markDeclarationReached();
  16522. if (includeChildrenRecursively) {
  16523. id.include(context, includeChildrenRecursively);
  16524. }
  16525. else {
  16526. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  16527. }
  16528. }
  16529. removeAnnotations(code) {
  16530. this.init?.removeAnnotations(code);
  16531. }
  16532. render(code, options) {
  16533. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  16534. const { end, id, init, start } = this;
  16535. const renderId = id.included || this.isUsingDeclaration || this.isAsyncUsingDeclaration;
  16536. if (renderId) {
  16537. id.render(code, options);
  16538. }
  16539. else {
  16540. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  16541. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  16542. }
  16543. if (init) {
  16544. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  16545. const renderedVariable = id.variable.getName(getPropertyAccess);
  16546. if (renderedVariable !== id.name) {
  16547. code.appendLeft(init.start + 5, ` ${id.name}`);
  16548. }
  16549. }
  16550. init.render(code, options, renderId ? parseAst_js.BLANK : { renderedSurroundingElement: parseAst_js.ExpressionStatement });
  16551. }
  16552. else if (id instanceof Identifier &&
  16553. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  16554. code.appendLeft(end, `${_}=${_}void 0`);
  16555. }
  16556. }
  16557. includeNode(context) {
  16558. this.included = true;
  16559. const { id, init } = this;
  16560. if (init) {
  16561. if (this.isUsingDeclaration) {
  16562. init.includePath(SYMBOL_DISPOSE_PATH, context);
  16563. }
  16564. else if (this.isAsyncUsingDeclaration) {
  16565. init.includePath(SYMBOL_ASYNC_DISPOSE_PATH, context);
  16566. }
  16567. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  16568. const { name, variable } = id;
  16569. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  16570. if (accessedVariable !== variable) {
  16571. accessedVariable.forbidName(name);
  16572. }
  16573. }
  16574. }
  16575. }
  16576. }
  16577. }
  16578. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  16579. const SYMBOL_DISPOSE_PATH = [SymbolDispose];
  16580. const SYMBOL_ASYNC_DISPOSE_PATH = [SymbolAsyncDispose];
  16581. class WhileStatement extends NodeBase {
  16582. hasEffects(context) {
  16583. if (this.test.hasEffects(context))
  16584. return true;
  16585. return hasLoopBodyEffects(context, this.body);
  16586. }
  16587. include(context, includeChildrenRecursively) {
  16588. this.included = true;
  16589. this.test.include(context, includeChildrenRecursively);
  16590. includeLoopBody(context, this.body, includeChildrenRecursively);
  16591. }
  16592. }
  16593. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16594. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  16595. class YieldExpression extends NodeBase {
  16596. applyDeoptimizations() {
  16597. this.deoptimized = true;
  16598. this.argument?.deoptimizePath(UNKNOWN_PATH);
  16599. }
  16600. hasEffects(context) {
  16601. if (!this.deoptimized)
  16602. this.applyDeoptimizations();
  16603. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  16604. }
  16605. includeNode(context) {
  16606. this.included = true;
  16607. if (!this.deoptimized)
  16608. this.applyDeoptimizations();
  16609. this.argument?.includePath(UNKNOWN_PATH, context);
  16610. }
  16611. render(code, options) {
  16612. if (this.argument) {
  16613. this.argument.render(code, options, { preventASI: true });
  16614. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  16615. code.prependLeft(this.start + 5, ' ');
  16616. }
  16617. }
  16618. }
  16619. }
  16620. // This file is generated by scripts/generate-buffer-parsers.js.
  16621. // Do not edit this file directly.
  16622. function convertProgram(buffer, parent, parentScope) {
  16623. return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
  16624. }
  16625. const nodeTypeStrings = [
  16626. 'PanicError',
  16627. 'ParseError',
  16628. 'ArrayExpression',
  16629. 'ArrayPattern',
  16630. 'ArrowFunctionExpression',
  16631. 'AssignmentExpression',
  16632. 'AssignmentPattern',
  16633. 'AwaitExpression',
  16634. 'BinaryExpression',
  16635. 'BlockStatement',
  16636. 'BreakStatement',
  16637. 'CallExpression',
  16638. 'CatchClause',
  16639. 'ChainExpression',
  16640. 'ClassBody',
  16641. 'ClassDeclaration',
  16642. 'ClassExpression',
  16643. 'ConditionalExpression',
  16644. 'ContinueStatement',
  16645. 'DebuggerStatement',
  16646. 'Decorator',
  16647. 'ExpressionStatement',
  16648. 'DoWhileStatement',
  16649. 'EmptyStatement',
  16650. 'ExportAllDeclaration',
  16651. 'ExportDefaultDeclaration',
  16652. 'ExportNamedDeclaration',
  16653. 'ExportSpecifier',
  16654. 'ExpressionStatement',
  16655. 'ForInStatement',
  16656. 'ForOfStatement',
  16657. 'ForStatement',
  16658. 'FunctionDeclaration',
  16659. 'FunctionExpression',
  16660. 'Identifier',
  16661. 'IfStatement',
  16662. 'ImportAttribute',
  16663. 'ImportDeclaration',
  16664. 'ImportDefaultSpecifier',
  16665. 'ImportExpression',
  16666. 'ImportNamespaceSpecifier',
  16667. 'ImportSpecifier',
  16668. 'JSXAttribute',
  16669. 'JSXClosingElement',
  16670. 'JSXClosingFragment',
  16671. 'JSXElement',
  16672. 'JSXEmptyExpression',
  16673. 'JSXExpressionContainer',
  16674. 'JSXFragment',
  16675. 'JSXIdentifier',
  16676. 'JSXMemberExpression',
  16677. 'JSXNamespacedName',
  16678. 'JSXOpeningElement',
  16679. 'JSXOpeningFragment',
  16680. 'JSXSpreadAttribute',
  16681. 'JSXSpreadChild',
  16682. 'JSXText',
  16683. 'LabeledStatement',
  16684. 'Literal',
  16685. 'Literal',
  16686. 'Literal',
  16687. 'Literal',
  16688. 'Literal',
  16689. 'Literal',
  16690. 'LogicalExpression',
  16691. 'MemberExpression',
  16692. 'MetaProperty',
  16693. 'MethodDefinition',
  16694. 'NewExpression',
  16695. 'ObjectExpression',
  16696. 'ObjectPattern',
  16697. 'PrivateIdentifier',
  16698. 'Program',
  16699. 'Property',
  16700. 'PropertyDefinition',
  16701. 'RestElement',
  16702. 'ReturnStatement',
  16703. 'SequenceExpression',
  16704. 'SpreadElement',
  16705. 'StaticBlock',
  16706. 'Super',
  16707. 'SwitchCase',
  16708. 'SwitchStatement',
  16709. 'TaggedTemplateExpression',
  16710. 'TemplateElement',
  16711. 'TemplateLiteral',
  16712. 'ThisExpression',
  16713. 'ThrowStatement',
  16714. 'TryStatement',
  16715. 'UnaryExpression',
  16716. 'UpdateExpression',
  16717. 'VariableDeclaration',
  16718. 'VariableDeclarator',
  16719. 'WhileStatement',
  16720. 'YieldExpression'
  16721. ];
  16722. const nodeConstructors$1 = [
  16723. PanicError,
  16724. ParseError,
  16725. ArrayExpression,
  16726. ArrayPattern,
  16727. ArrowFunctionExpression,
  16728. AssignmentExpression,
  16729. AssignmentPattern,
  16730. AwaitExpression,
  16731. BinaryExpression,
  16732. BlockStatement,
  16733. BreakStatement,
  16734. CallExpression,
  16735. CatchClause,
  16736. ChainExpression,
  16737. ClassBody,
  16738. ClassDeclaration,
  16739. ClassExpression,
  16740. ConditionalExpression,
  16741. ContinueStatement,
  16742. DebuggerStatement,
  16743. Decorator,
  16744. ExpressionStatement,
  16745. DoWhileStatement,
  16746. EmptyStatement,
  16747. ExportAllDeclaration,
  16748. ExportDefaultDeclaration,
  16749. ExportNamedDeclaration,
  16750. ExportSpecifier,
  16751. ExpressionStatement,
  16752. ForInStatement,
  16753. ForOfStatement,
  16754. ForStatement,
  16755. FunctionDeclaration,
  16756. FunctionExpression,
  16757. Identifier,
  16758. IfStatement,
  16759. ImportAttribute,
  16760. ImportDeclaration,
  16761. ImportDefaultSpecifier,
  16762. ImportExpression,
  16763. ImportNamespaceSpecifier,
  16764. ImportSpecifier,
  16765. JSXAttribute,
  16766. JSXClosingElement,
  16767. JSXClosingFragment,
  16768. JSXElement,
  16769. JSXEmptyExpression,
  16770. JSXExpressionContainer,
  16771. JSXFragment,
  16772. JSXIdentifier,
  16773. JSXMemberExpression,
  16774. JSXNamespacedName,
  16775. JSXOpeningElement,
  16776. JSXOpeningFragment,
  16777. JSXSpreadAttribute,
  16778. JSXSpreadChild,
  16779. JSXText,
  16780. LabeledStatement,
  16781. Literal,
  16782. Literal,
  16783. Literal,
  16784. Literal,
  16785. Literal,
  16786. Literal,
  16787. LogicalExpression,
  16788. MemberExpression,
  16789. MetaProperty,
  16790. MethodDefinition,
  16791. NewExpression,
  16792. ObjectExpression,
  16793. ObjectPattern,
  16794. PrivateIdentifier,
  16795. Program,
  16796. Property,
  16797. PropertyDefinition,
  16798. RestElement,
  16799. ReturnStatement,
  16800. SequenceExpression,
  16801. SpreadElement,
  16802. StaticBlock,
  16803. Super,
  16804. SwitchCase,
  16805. SwitchStatement,
  16806. TaggedTemplateExpression,
  16807. TemplateElement,
  16808. TemplateLiteral,
  16809. ThisExpression,
  16810. ThrowStatement,
  16811. TryStatement,
  16812. UnaryExpression,
  16813. UpdateExpression,
  16814. VariableDeclaration,
  16815. VariableDeclarator,
  16816. WhileStatement,
  16817. YieldExpression
  16818. ];
  16819. const bufferParsers = [
  16820. function panicError(node, position, buffer) {
  16821. node.message = buffer.convertString(buffer[position]);
  16822. },
  16823. function parseError(node, position, buffer) {
  16824. node.message = buffer.convertString(buffer[position]);
  16825. },
  16826. function arrayExpression(node, position, buffer) {
  16827. const { scope } = node;
  16828. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16829. },
  16830. function arrayPattern(node, position, buffer) {
  16831. const { scope } = node;
  16832. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16833. },
  16834. function arrowFunctionExpression(node, position, buffer) {
  16835. const { scope } = node;
  16836. const flags = buffer[position];
  16837. node.async = (flags & 1) === 1;
  16838. node.expression = (flags & 2) === 2;
  16839. node.generator = (flags & 4) === 4;
  16840. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16841. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16842. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  16843. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16844. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  16845. },
  16846. function assignmentExpression(node, position, buffer) {
  16847. const { scope } = node;
  16848. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16849. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16850. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16851. },
  16852. function assignmentPattern(node, position, buffer) {
  16853. const { scope } = node;
  16854. node.left = convertNode(node, scope, buffer[position], buffer);
  16855. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16856. },
  16857. function awaitExpression(node, position, buffer) {
  16858. const { scope } = node;
  16859. node.argument = convertNode(node, scope, buffer[position], buffer);
  16860. },
  16861. function binaryExpression(node, position, buffer) {
  16862. const { scope } = node;
  16863. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16864. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16865. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16866. },
  16867. function blockStatement(node, position, buffer) {
  16868. const { scope } = node;
  16869. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16870. },
  16871. function breakStatement(node, position, buffer) {
  16872. const { scope } = node;
  16873. const labelPosition = buffer[position];
  16874. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16875. },
  16876. function callExpression(node, position, buffer) {
  16877. const { scope } = node;
  16878. const flags = buffer[position];
  16879. node.optional = (flags & 1) === 1;
  16880. node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16881. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  16882. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  16883. },
  16884. function catchClause(node, position, buffer) {
  16885. const { scope } = node;
  16886. const parameterPosition = buffer[position];
  16887. const parameter = (node.param =
  16888. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  16889. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  16890. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  16891. },
  16892. function chainExpression(node, position, buffer) {
  16893. const { scope } = node;
  16894. node.expression = convertNode(node, scope, buffer[position], buffer);
  16895. },
  16896. function classBody(node, position, buffer) {
  16897. const { scope } = node;
  16898. const bodyPosition = buffer[position];
  16899. if (bodyPosition) {
  16900. const length = buffer[bodyPosition];
  16901. const body = (node.body = new Array(length));
  16902. for (let index = 0; index < length; index++) {
  16903. const nodePosition = buffer[bodyPosition + 1 + index];
  16904. body[index] = convertNode(node, buffer[nodePosition] !== 79 &&
  16905. (buffer[nodePosition + 3] & /* the static flag is always first */ 1) === 0
  16906. ? scope.instanceScope
  16907. : scope, nodePosition, buffer);
  16908. }
  16909. }
  16910. else {
  16911. node.body = [];
  16912. }
  16913. },
  16914. function classDeclaration(node, position, buffer) {
  16915. const { scope } = node;
  16916. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16917. const idPosition = buffer[position + 1];
  16918. node.id =
  16919. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16920. const superClassPosition = buffer[position + 2];
  16921. node.superClass =
  16922. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16923. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16924. },
  16925. function classExpression(node, position, buffer) {
  16926. const { scope } = node;
  16927. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16928. const idPosition = buffer[position + 1];
  16929. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  16930. const superClassPosition = buffer[position + 2];
  16931. node.superClass =
  16932. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16933. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16934. },
  16935. function conditionalExpression(node, position, buffer) {
  16936. const { scope } = node;
  16937. node.test = convertNode(node, scope, buffer[position], buffer);
  16938. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  16939. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  16940. },
  16941. function continueStatement(node, position, buffer) {
  16942. const { scope } = node;
  16943. const labelPosition = buffer[position];
  16944. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16945. },
  16946. function debuggerStatement() { },
  16947. function decorator(node, position, buffer) {
  16948. const { scope } = node;
  16949. node.expression = convertNode(node, scope, buffer[position], buffer);
  16950. },
  16951. function directive(node, position, buffer) {
  16952. const { scope } = node;
  16953. node.directive = buffer.convertString(buffer[position]);
  16954. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  16955. },
  16956. function doWhileStatement(node, position, buffer) {
  16957. const { scope } = node;
  16958. node.body = convertNode(node, scope, buffer[position], buffer);
  16959. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  16960. },
  16961. function emptyStatement() { },
  16962. function exportAllDeclaration(node, position, buffer) {
  16963. const { scope } = node;
  16964. const exportedPosition = buffer[position];
  16965. node.exported =
  16966. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  16967. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16968. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16969. },
  16970. function exportDefaultDeclaration(node, position, buffer) {
  16971. const { scope } = node;
  16972. node.declaration = convertNode(node, scope, buffer[position], buffer);
  16973. },
  16974. function exportNamedDeclaration(node, position, buffer) {
  16975. const { scope } = node;
  16976. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16977. const sourcePosition = buffer[position + 1];
  16978. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  16979. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16980. const declarationPosition = buffer[position + 3];
  16981. node.declaration =
  16982. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  16983. },
  16984. function exportSpecifier(node, position, buffer) {
  16985. const { scope } = node;
  16986. node.local = convertNode(node, scope, buffer[position], buffer);
  16987. const exportedPosition = buffer[position + 1];
  16988. node.exported =
  16989. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  16990. },
  16991. function expressionStatement(node, position, buffer) {
  16992. const { scope } = node;
  16993. node.expression = convertNode(node, scope, buffer[position], buffer);
  16994. },
  16995. function forInStatement(node, position, buffer) {
  16996. const { scope } = node;
  16997. node.left = convertNode(node, scope, buffer[position], buffer);
  16998. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16999. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  17000. },
  17001. function forOfStatement(node, position, buffer) {
  17002. const { scope } = node;
  17003. const flags = buffer[position];
  17004. node.await = (flags & 1) === 1;
  17005. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  17006. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  17007. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  17008. },
  17009. function forStatement(node, position, buffer) {
  17010. const { scope } = node;
  17011. const initPosition = buffer[position];
  17012. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  17013. const testPosition = buffer[position + 1];
  17014. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  17015. const updatePosition = buffer[position + 2];
  17016. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  17017. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  17018. },
  17019. function functionDeclaration(node, position, buffer) {
  17020. const { scope } = node;
  17021. const flags = buffer[position];
  17022. node.async = (flags & 1) === 1;
  17023. node.generator = (flags & 2) === 2;
  17024. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  17025. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  17026. const idPosition = buffer[position + 2];
  17027. node.id =
  17028. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  17029. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  17030. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  17031. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  17032. },
  17033. function functionExpression(node, position, buffer) {
  17034. const { scope } = node;
  17035. const flags = buffer[position];
  17036. node.async = (flags & 1) === 1;
  17037. node.generator = (flags & 2) === 2;
  17038. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  17039. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  17040. const idPosition = buffer[position + 2];
  17041. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  17042. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  17043. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  17044. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  17045. },
  17046. function identifier(node, position, buffer) {
  17047. node.name = buffer.convertString(buffer[position]);
  17048. },
  17049. function ifStatement(node, position, buffer) {
  17050. const { scope } = node;
  17051. node.test = convertNode(node, scope, buffer[position], buffer);
  17052. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  17053. const alternatePosition = buffer[position + 2];
  17054. node.alternate =
  17055. alternatePosition === 0
  17056. ? null
  17057. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  17058. },
  17059. function importAttribute(node, position, buffer) {
  17060. const { scope } = node;
  17061. node.key = convertNode(node, scope, buffer[position], buffer);
  17062. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  17063. },
  17064. function importDeclaration(node, position, buffer) {
  17065. const { scope } = node;
  17066. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  17067. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  17068. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  17069. const phaseIndex = buffer[position + 3];
  17070. node.phase = phaseIndex === 0 ? undefined : parseAst_js.FIXED_STRINGS[phaseIndex];
  17071. },
  17072. function importDefaultSpecifier(node, position, buffer) {
  17073. const { scope } = node;
  17074. node.local = convertNode(node, scope, buffer[position], buffer);
  17075. },
  17076. function importExpression(node, position, buffer) {
  17077. const { scope } = node;
  17078. node.source = convertNode(node, scope, buffer[position], buffer);
  17079. node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
  17080. const optionsPosition = buffer[position + 1];
  17081. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  17082. const phaseIndex = buffer[position + 2];
  17083. node.phase = phaseIndex === 0 ? undefined : parseAst_js.FIXED_STRINGS[phaseIndex];
  17084. },
  17085. function importNamespaceSpecifier(node, position, buffer) {
  17086. const { scope } = node;
  17087. node.local = convertNode(node, scope, buffer[position], buffer);
  17088. },
  17089. function importSpecifier(node, position, buffer) {
  17090. const { scope } = node;
  17091. const importedPosition = buffer[position];
  17092. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  17093. node.imported =
  17094. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  17095. },
  17096. function jsxAttribute(node, position, buffer) {
  17097. const { scope } = node;
  17098. node.name = convertNode(node, scope, buffer[position], buffer);
  17099. const valuePosition = buffer[position + 1];
  17100. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  17101. },
  17102. function jsxClosingElement(node, position, buffer) {
  17103. const { scope } = node;
  17104. node.name = convertNode(node, scope, buffer[position], buffer);
  17105. },
  17106. function jsxClosingFragment() { },
  17107. function jsxElement(node, position, buffer) {
  17108. const { scope } = node;
  17109. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  17110. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  17111. const closingElementPosition = buffer[position + 2];
  17112. node.closingElement =
  17113. closingElementPosition === 0
  17114. ? null
  17115. : convertNode(node, scope, closingElementPosition, buffer);
  17116. },
  17117. function jsxEmptyExpression() { },
  17118. function jsxExpressionContainer(node, position, buffer) {
  17119. const { scope } = node;
  17120. node.expression = convertNode(node, scope, buffer[position], buffer);
  17121. },
  17122. function jsxFragment(node, position, buffer) {
  17123. const { scope } = node;
  17124. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  17125. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  17126. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  17127. },
  17128. function jsxIdentifier(node, position, buffer) {
  17129. node.name = buffer.convertString(buffer[position]);
  17130. },
  17131. function jsxMemberExpression(node, position, buffer) {
  17132. const { scope } = node;
  17133. node.object = convertNode(node, scope, buffer[position], buffer);
  17134. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  17135. },
  17136. function jsxNamespacedName(node, position, buffer) {
  17137. const { scope } = node;
  17138. node.namespace = convertNode(node, scope, buffer[position], buffer);
  17139. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  17140. },
  17141. function jsxOpeningElement(node, position, buffer) {
  17142. const { scope } = node;
  17143. const flags = buffer[position];
  17144. node.selfClosing = (flags & 1) === 1;
  17145. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  17146. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  17147. },
  17148. function jsxOpeningFragment(node) {
  17149. node.attributes = [];
  17150. node.selfClosing = false;
  17151. },
  17152. function jsxSpreadAttribute(node, position, buffer) {
  17153. const { scope } = node;
  17154. node.argument = convertNode(node, scope, buffer[position], buffer);
  17155. },
  17156. function jsxSpreadChild(node, position, buffer) {
  17157. const { scope } = node;
  17158. node.expression = convertNode(node, scope, buffer[position], buffer);
  17159. },
  17160. function jsxText(node, position, buffer) {
  17161. node.value = buffer.convertString(buffer[position]);
  17162. node.raw = buffer.convertString(buffer[position + 1]);
  17163. },
  17164. function labeledStatement(node, position, buffer) {
  17165. const { scope } = node;
  17166. node.label = convertNode(node, scope, buffer[position], buffer);
  17167. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  17168. },
  17169. function literalBigInt(node, position, buffer) {
  17170. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  17171. node.raw = buffer.convertString(buffer[position + 1]);
  17172. node.value = BigInt(bigint);
  17173. },
  17174. function literalBoolean(node, position, buffer) {
  17175. const flags = buffer[position];
  17176. const value = (node.value = (flags & 1) === 1);
  17177. node.raw = value ? 'true' : 'false';
  17178. },
  17179. function literalNull(node) {
  17180. node.value = null;
  17181. },
  17182. function literalNumber(node, position, buffer) {
  17183. const rawPosition = buffer[position];
  17184. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  17185. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  17186. },
  17187. function literalRegExp(node, position, buffer) {
  17188. const flags = buffer.convertString(buffer[position]);
  17189. const pattern = buffer.convertString(buffer[position + 1]);
  17190. node.raw = `/${pattern}/${flags}`;
  17191. node.regex = { flags, pattern };
  17192. node.value = new RegExp(pattern, flags);
  17193. },
  17194. function literalString(node, position, buffer) {
  17195. node.value = buffer.convertString(buffer[position]);
  17196. const rawPosition = buffer[position + 1];
  17197. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  17198. },
  17199. function logicalExpression(node, position, buffer) {
  17200. const { scope } = node;
  17201. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  17202. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  17203. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  17204. },
  17205. function memberExpression(node, position, buffer) {
  17206. const { scope } = node;
  17207. const flags = buffer[position];
  17208. node.computed = (flags & 1) === 1;
  17209. node.optional = (flags & 2) === 2;
  17210. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  17211. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  17212. },
  17213. function metaProperty(node, position, buffer) {
  17214. const { scope } = node;
  17215. node.meta = convertNode(node, scope, buffer[position], buffer);
  17216. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  17217. },
  17218. function methodDefinition(node, position, buffer) {
  17219. const { scope } = node;
  17220. const flags = buffer[position];
  17221. node.static = (flags & 1) === 1;
  17222. node.computed = (flags & 2) === 2;
  17223. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  17224. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  17225. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  17226. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 4]];
  17227. },
  17228. function newExpression(node, position, buffer) {
  17229. const { scope } = node;
  17230. node.annotations = parseAst_js.convertAnnotations(buffer[position], buffer);
  17231. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  17232. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  17233. },
  17234. function objectExpression(node, position, buffer) {
  17235. const { scope } = node;
  17236. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  17237. },
  17238. function objectPattern(node, position, buffer) {
  17239. const { scope } = node;
  17240. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  17241. },
  17242. function privateIdentifier(node, position, buffer) {
  17243. node.name = buffer.convertString(buffer[position]);
  17244. },
  17245. function program(node, position, buffer) {
  17246. const { scope } = node;
  17247. node.body = convertNodeList(node, scope, buffer[position], buffer);
  17248. node.invalidAnnotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  17249. },
  17250. function property(node, position, buffer) {
  17251. const { scope } = node;
  17252. const flags = buffer[position];
  17253. node.method = (flags & 1) === 1;
  17254. node.shorthand = (flags & 2) === 2;
  17255. node.computed = (flags & 4) === 4;
  17256. const keyPosition = buffer[position + 1];
  17257. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  17258. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 3]];
  17259. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  17260. },
  17261. function propertyDefinition(node, position, buffer) {
  17262. const { scope } = node;
  17263. const flags = buffer[position];
  17264. node.static = (flags & 1) === 1;
  17265. node.computed = (flags & 2) === 2;
  17266. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  17267. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  17268. const valuePosition = buffer[position + 3];
  17269. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  17270. },
  17271. function restElement(node, position, buffer) {
  17272. const { scope } = node;
  17273. node.argument = convertNode(node, scope, buffer[position], buffer);
  17274. },
  17275. function returnStatement(node, position, buffer) {
  17276. const { scope } = node;
  17277. const argumentPosition = buffer[position];
  17278. node.argument =
  17279. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  17280. },
  17281. function sequenceExpression(node, position, buffer) {
  17282. const { scope } = node;
  17283. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  17284. },
  17285. function spreadElement(node, position, buffer) {
  17286. const { scope } = node;
  17287. node.argument = convertNode(node, scope, buffer[position], buffer);
  17288. },
  17289. function staticBlock(node, position, buffer) {
  17290. const { scope } = node;
  17291. node.body = convertNodeList(node, scope, buffer[position], buffer);
  17292. },
  17293. function superElement() { },
  17294. function switchCase(node, position, buffer) {
  17295. const { scope } = node;
  17296. const testPosition = buffer[position];
  17297. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  17298. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  17299. },
  17300. function switchStatement(node, position, buffer) {
  17301. const { scope } = node;
  17302. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  17303. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  17304. },
  17305. function taggedTemplateExpression(node, position, buffer) {
  17306. const { scope } = node;
  17307. node.tag = convertNode(node, scope, buffer[position], buffer);
  17308. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  17309. },
  17310. function templateElement(node, position, buffer) {
  17311. const flags = buffer[position];
  17312. node.tail = (flags & 1) === 1;
  17313. const cookedPosition = buffer[position + 1];
  17314. const cooked = cookedPosition === 0 ? null : buffer.convertString(cookedPosition);
  17315. const raw = buffer.convertString(buffer[position + 2]);
  17316. node.value = { cooked, raw };
  17317. },
  17318. function templateLiteral(node, position, buffer) {
  17319. const { scope } = node;
  17320. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  17321. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  17322. },
  17323. function thisExpression() { },
  17324. function throwStatement(node, position, buffer) {
  17325. const { scope } = node;
  17326. node.argument = convertNode(node, scope, buffer[position], buffer);
  17327. },
  17328. function tryStatement(node, position, buffer) {
  17329. const { scope } = node;
  17330. node.block = convertNode(node, scope, buffer[position], buffer);
  17331. const handlerPosition = buffer[position + 1];
  17332. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  17333. const finalizerPosition = buffer[position + 2];
  17334. node.finalizer =
  17335. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  17336. },
  17337. function unaryExpression(node, position, buffer) {
  17338. const { scope } = node;
  17339. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  17340. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  17341. },
  17342. function updateExpression(node, position, buffer) {
  17343. const { scope } = node;
  17344. const flags = buffer[position];
  17345. node.prefix = (flags & 1) === 1;
  17346. node.operator = parseAst_js.FIXED_STRINGS[buffer[position + 1]];
  17347. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  17348. },
  17349. function variableDeclaration(node, position, buffer) {
  17350. const { scope } = node;
  17351. node.kind = parseAst_js.FIXED_STRINGS[buffer[position]];
  17352. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  17353. },
  17354. function variableDeclarator(node, position, buffer) {
  17355. const { scope } = node;
  17356. node.id = convertNode(node, scope, buffer[position], buffer);
  17357. const initPosition = buffer[position + 1];
  17358. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  17359. },
  17360. function whileStatement(node, position, buffer) {
  17361. const { scope } = node;
  17362. node.test = convertNode(node, scope, buffer[position], buffer);
  17363. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  17364. },
  17365. function yieldExpression(node, position, buffer) {
  17366. const { scope } = node;
  17367. const flags = buffer[position];
  17368. node.delegate = (flags & 1) === 1;
  17369. const argumentPosition = buffer[position + 1];
  17370. node.argument =
  17371. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  17372. }
  17373. ];
  17374. function convertNode(parent, parentScope, position, buffer) {
  17375. const nodeType = buffer[position];
  17376. const NodeConstructor = nodeConstructors$1[nodeType];
  17377. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  17378. if (!NodeConstructor) {
  17379. console.trace();
  17380. throw new Error(`Unknown node type: ${nodeType}`);
  17381. }
  17382. const node = new NodeConstructor(parent, parentScope);
  17383. node.type = nodeTypeStrings[nodeType];
  17384. node.start = buffer[position + 1];
  17385. node.end = buffer[position + 2];
  17386. bufferParsers[nodeType](node, position + 3, buffer);
  17387. node.initialise();
  17388. return node;
  17389. }
  17390. function convertNodeList(parent, parentScope, position, buffer) {
  17391. if (position === 0)
  17392. return parseAst_js.EMPTY_ARRAY;
  17393. const length = buffer[position++];
  17394. const list = new Array(length);
  17395. for (let index = 0; index < length; index++) {
  17396. const nodePosition = buffer[position++];
  17397. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  17398. }
  17399. return list;
  17400. }
  17401. class UnknownNode extends NodeBase {
  17402. hasEffects() {
  17403. return true;
  17404. }
  17405. include(context) {
  17406. super.include(context, true);
  17407. }
  17408. }
  17409. // This file is generated by scripts/generate-node-index.js.
  17410. // Do not edit this file directly.
  17411. const nodeConstructors = {
  17412. ArrayExpression,
  17413. ArrayPattern,
  17414. ArrowFunctionExpression,
  17415. AssignmentExpression,
  17416. AssignmentPattern,
  17417. AwaitExpression,
  17418. BinaryExpression,
  17419. BlockStatement,
  17420. BreakStatement,
  17421. CallExpression,
  17422. CatchClause,
  17423. ChainExpression,
  17424. ClassBody,
  17425. ClassDeclaration,
  17426. ClassExpression,
  17427. ConditionalExpression,
  17428. ContinueStatement,
  17429. DebuggerStatement,
  17430. Decorator,
  17431. DoWhileStatement,
  17432. EmptyStatement,
  17433. ExportAllDeclaration,
  17434. ExportDefaultDeclaration,
  17435. ExportNamedDeclaration,
  17436. ExportSpecifier,
  17437. ExpressionStatement,
  17438. ForInStatement,
  17439. ForOfStatement,
  17440. ForStatement,
  17441. FunctionDeclaration,
  17442. FunctionExpression,
  17443. Identifier,
  17444. IfStatement,
  17445. ImportAttribute,
  17446. ImportDeclaration,
  17447. ImportDefaultSpecifier,
  17448. ImportExpression,
  17449. ImportNamespaceSpecifier,
  17450. ImportSpecifier,
  17451. JSXAttribute,
  17452. JSXClosingElement,
  17453. JSXClosingFragment,
  17454. JSXElement,
  17455. JSXEmptyExpression,
  17456. JSXExpressionContainer,
  17457. JSXFragment,
  17458. JSXIdentifier,
  17459. JSXMemberExpression,
  17460. JSXNamespacedName,
  17461. JSXOpeningElement,
  17462. JSXOpeningFragment,
  17463. JSXSpreadAttribute,
  17464. JSXSpreadChild,
  17465. JSXText,
  17466. LabeledStatement,
  17467. Literal,
  17468. LogicalExpression,
  17469. MemberExpression,
  17470. MetaProperty,
  17471. MethodDefinition,
  17472. NewExpression,
  17473. ObjectExpression,
  17474. ObjectPattern,
  17475. PanicError,
  17476. ParseError,
  17477. PrivateIdentifier,
  17478. Program,
  17479. Property,
  17480. PropertyDefinition,
  17481. RestElement,
  17482. ReturnStatement,
  17483. SequenceExpression,
  17484. SpreadElement,
  17485. StaticBlock,
  17486. Super,
  17487. SwitchCase,
  17488. SwitchStatement,
  17489. TaggedTemplateExpression,
  17490. TemplateElement,
  17491. TemplateLiteral,
  17492. ThisExpression,
  17493. ThrowStatement,
  17494. TryStatement,
  17495. UnaryExpression,
  17496. UnknownNode,
  17497. UpdateExpression,
  17498. VariableDeclaration,
  17499. VariableDeclarator,
  17500. WhileStatement,
  17501. YieldExpression
  17502. };
  17503. class ExportShimVariable extends Variable {
  17504. constructor(module) {
  17505. super(MISSING_EXPORT_SHIM_VARIABLE);
  17506. this.module = module;
  17507. }
  17508. includePath(path, context) {
  17509. super.includePath(path, context);
  17510. this.module.needsExportShim = true;
  17511. }
  17512. }
  17513. const sourceMapCache = new WeakMap();
  17514. /**
  17515. * This clears the decoded array and falls back to the encoded string form.
  17516. * Sourcemap mappings arrays can be very large and holding on to them for longer
  17517. * than is necessary leads to poor heap utilization.
  17518. */
  17519. function resetCacheToEncoded(cache) {
  17520. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  17521. cache.encodedMappings = encode(cache.decodedMappings);
  17522. }
  17523. cache.decodedMappings = undefined;
  17524. }
  17525. function resetSourcemapCache(map, sourcemapChain) {
  17526. if (map) {
  17527. const cache = sourceMapCache.get(map);
  17528. if (cache) {
  17529. resetCacheToEncoded(cache);
  17530. }
  17531. }
  17532. if (!sourcemapChain) {
  17533. return;
  17534. }
  17535. for (const map of sourcemapChain) {
  17536. if (map.missing)
  17537. continue;
  17538. resetSourcemapCache(map);
  17539. }
  17540. }
  17541. function decodedSourcemap(map) {
  17542. if (!map)
  17543. return null;
  17544. if (typeof map === 'string') {
  17545. map = JSON.parse(map);
  17546. }
  17547. if (!map.mappings) {
  17548. return {
  17549. mappings: [],
  17550. names: [],
  17551. sources: [],
  17552. version: 3
  17553. };
  17554. }
  17555. const originalMappings = map.mappings;
  17556. const isAlreadyDecoded = Array.isArray(originalMappings);
  17557. const cache = {
  17558. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  17559. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  17560. };
  17561. const decodedMap = {
  17562. ...map,
  17563. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  17564. // where the mappings field is never actually accessed. This appears to greatly reduce
  17565. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  17566. get mappings() {
  17567. if (cache.decodedMappings) {
  17568. return cache.decodedMappings;
  17569. }
  17570. // If decodedMappings doesn't exist then encodedMappings should.
  17571. // The only scenario where cache.encodedMappings should be undefined is if the map
  17572. // this was constructed from was already decoded, or if mappings was set to a new
  17573. // decoded string. In either case, this line shouldn't get hit.
  17574. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  17575. cache.encodedMappings = undefined;
  17576. return cache.decodedMappings;
  17577. }
  17578. };
  17579. sourceMapCache.set(decodedMap, cache);
  17580. return decodedMap;
  17581. }
  17582. function getId(m) {
  17583. return m.id;
  17584. }
  17585. function getOriginalLocation(sourcemapChain, location) {
  17586. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  17587. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  17588. const sourcemap = filteredSourcemapChain.pop();
  17589. const line = sourcemap.mappings[location.line - 1];
  17590. if (line) {
  17591. const filteredLine = line.filter((segment) => segment.length > 1);
  17592. const lastSegment = filteredLine[filteredLine.length - 1];
  17593. let previousSegment = filteredLine[0];
  17594. for (let segment of filteredLine) {
  17595. if (segment[0] >= location.column || segment === lastSegment) {
  17596. const notMatched = segment[0] !== location.column;
  17597. segment = notMatched ? previousSegment : segment;
  17598. location = {
  17599. column: segment[3],
  17600. line: segment[2] + 1
  17601. };
  17602. continue traceSourcemap;
  17603. }
  17604. previousSegment = segment;
  17605. }
  17606. }
  17607. throw new Error("Can't resolve original location of error.");
  17608. }
  17609. return location;
  17610. }
  17611. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  17612. function getAttributesFromImportExpression(node) {
  17613. const { scope: { context }, options, start } = node;
  17614. if (!(options instanceof ObjectExpression)) {
  17615. if (options) {
  17616. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), start);
  17617. }
  17618. return parseAst_js.EMPTY_OBJECT;
  17619. }
  17620. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  17621. if (!assertProperty) {
  17622. return parseAst_js.EMPTY_OBJECT;
  17623. }
  17624. if (!(assertProperty instanceof ObjectExpression)) {
  17625. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportOptionsAreInvalid(context.module.id), start);
  17626. return parseAst_js.EMPTY_OBJECT;
  17627. }
  17628. const assertFields = assertProperty.properties
  17629. .map(property => {
  17630. const key = getPropertyKey(property);
  17631. if (typeof key === 'string' &&
  17632. typeof property.value.value === 'string') {
  17633. return [key, property.value.value];
  17634. }
  17635. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), property.start);
  17636. return null;
  17637. })
  17638. .filter((property) => !!property);
  17639. if (assertFields.length > 0) {
  17640. return Object.fromEntries(assertFields);
  17641. }
  17642. return parseAst_js.EMPTY_OBJECT;
  17643. }
  17644. const getPropertyKey = (property) => {
  17645. const key = property.key;
  17646. return (key &&
  17647. !property.computed &&
  17648. (key.name || key.value));
  17649. };
  17650. function getAttributesFromImportExportDeclaration(attributes) {
  17651. return attributes?.length
  17652. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  17653. : parseAst_js.EMPTY_OBJECT;
  17654. }
  17655. function doAttributesDiffer(assertionA, assertionB) {
  17656. const keysA = Object.keys(assertionA);
  17657. return (keysA.length !== Object.keys(assertionB).length ||
  17658. keysA.some(key => assertionA[key] !== assertionB[key]));
  17659. }
  17660. let timers = new Map();
  17661. function getPersistedLabel(label, level) {
  17662. switch (level) {
  17663. case 1: {
  17664. return `# ${label}`;
  17665. }
  17666. case 2: {
  17667. return `## ${label}`;
  17668. }
  17669. case 3: {
  17670. return label;
  17671. }
  17672. default: {
  17673. return `- ${label}`;
  17674. }
  17675. }
  17676. }
  17677. function timeStartImpl(label, level = 3) {
  17678. label = getPersistedLabel(label, level);
  17679. const startMemory = process$1.memoryUsage().heapUsed;
  17680. const startTime = node_perf_hooks.performance.now();
  17681. const timer = timers.get(label);
  17682. if (timer === undefined) {
  17683. timers.set(label, {
  17684. memory: 0,
  17685. startMemory,
  17686. startTime,
  17687. time: 0,
  17688. totalMemory: 0
  17689. });
  17690. }
  17691. else {
  17692. timer.startMemory = startMemory;
  17693. timer.startTime = startTime;
  17694. }
  17695. }
  17696. function timeEndImpl(label, level = 3) {
  17697. label = getPersistedLabel(label, level);
  17698. const timer = timers.get(label);
  17699. if (timer !== undefined) {
  17700. const currentMemory = process$1.memoryUsage().heapUsed;
  17701. timer.memory += currentMemory - timer.startMemory;
  17702. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  17703. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  17704. }
  17705. }
  17706. function getTimings() {
  17707. const newTimings = {};
  17708. for (const [label, { memory, time, totalMemory }] of timers) {
  17709. newTimings[label] = [time, memory, totalMemory];
  17710. }
  17711. return newTimings;
  17712. }
  17713. let timeStart = doNothing;
  17714. let timeEnd = doNothing;
  17715. const TIMED_PLUGIN_HOOKS = [
  17716. 'augmentChunkHash',
  17717. 'buildEnd',
  17718. 'buildStart',
  17719. 'generateBundle',
  17720. 'load',
  17721. 'moduleParsed',
  17722. 'options',
  17723. 'outputOptions',
  17724. 'renderChunk',
  17725. 'renderDynamicImport',
  17726. 'renderStart',
  17727. 'resolveDynamicImport',
  17728. 'resolveFileUrl',
  17729. 'resolveId',
  17730. 'resolveImportMeta',
  17731. 'shouldTransformCachedModule',
  17732. 'transform',
  17733. 'writeBundle'
  17734. ];
  17735. function getPluginWithTimers(plugin, index) {
  17736. if (plugin._hasTimer)
  17737. return plugin;
  17738. plugin._hasTimer = true;
  17739. for (const hook of TIMED_PLUGIN_HOOKS) {
  17740. if (hook in plugin) {
  17741. let timerLabel = `plugin ${index}`;
  17742. if (plugin.name) {
  17743. timerLabel += ` (${plugin.name})`;
  17744. }
  17745. timerLabel += ` - ${hook}`;
  17746. const handler = function (...parameters) {
  17747. timeStart(timerLabel, 4);
  17748. const result = hookFunction.apply(this, parameters);
  17749. timeEnd(timerLabel, 4);
  17750. return result;
  17751. };
  17752. let hookFunction;
  17753. if (typeof plugin[hook].handler === 'function') {
  17754. hookFunction = plugin[hook].handler;
  17755. plugin[hook].handler = handler;
  17756. }
  17757. else {
  17758. hookFunction = plugin[hook];
  17759. plugin[hook] = handler;
  17760. }
  17761. }
  17762. }
  17763. return plugin;
  17764. }
  17765. function initialiseTimers(inputOptions) {
  17766. if (inputOptions.perf) {
  17767. timers = new Map();
  17768. timeStart = timeStartImpl;
  17769. timeEnd = timeEndImpl;
  17770. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  17771. }
  17772. else {
  17773. timeStart = doNothing;
  17774. timeEnd = doNothing;
  17775. }
  17776. }
  17777. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  17778. identifier: null,
  17779. localName: MISSING_EXPORT_SHIM_VARIABLE
  17780. };
  17781. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map(), importChain, sideEffectModules, exportOrReexportModules) {
  17782. const searchedModules = searchedNamesAndModules.get(name);
  17783. if (searchedModules) {
  17784. if (searchedModules.has(target)) {
  17785. return isExportAllSearch ? [null] : parseAst_js.error(parseAst_js.logCircularReexport(name, target.id));
  17786. }
  17787. searchedModules.add(target);
  17788. }
  17789. else {
  17790. searchedNamesAndModules.set(name, new Set([target]));
  17791. }
  17792. return target.getVariableForExportName(name, {
  17793. exportOrReexportModules,
  17794. importChain,
  17795. importerForSideEffects,
  17796. isExportAllSearch,
  17797. searchedNamesAndModules,
  17798. sideEffectModules
  17799. });
  17800. }
  17801. function getAndExtendSideEffectModules(variable, module) {
  17802. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  17803. let currentVariable = variable;
  17804. const referencedVariables = new Set([currentVariable]);
  17805. while (true) {
  17806. const importingModule = currentVariable.module;
  17807. currentVariable =
  17808. currentVariable instanceof ExportDefaultVariable
  17809. ? currentVariable.getDirectOriginalVariable()
  17810. : currentVariable instanceof SyntheticNamedExportVariable
  17811. ? currentVariable.syntheticNamespace
  17812. : null;
  17813. if (!currentVariable || referencedVariables.has(currentVariable)) {
  17814. break;
  17815. }
  17816. referencedVariables.add(currentVariable);
  17817. sideEffectModules.add(importingModule);
  17818. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  17819. if (originalSideEffects) {
  17820. for (const module of originalSideEffects) {
  17821. sideEffectModules.add(module);
  17822. }
  17823. }
  17824. }
  17825. return sideEffectModules;
  17826. }
  17827. class Module {
  17828. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  17829. this.graph = graph;
  17830. this.id = id;
  17831. this.options = options;
  17832. this.alternativeReexportModules = new Map();
  17833. this.chunkFileNames = new Set();
  17834. this.chunkNames = [];
  17835. this.cycles = new Set();
  17836. this.dependencies = new Set();
  17837. this.dynamicDependencies = new Set();
  17838. this.dynamicImporters = [];
  17839. this.dynamicImports = [];
  17840. this.execIndex = Infinity;
  17841. this.hasTreeShakingPassStarted = false;
  17842. this.implicitlyLoadedAfter = new Set();
  17843. this.implicitlyLoadedBefore = new Set();
  17844. this.importDescriptions = new Map();
  17845. this.importMetas = [];
  17846. this.importedFromNotTreeshaken = false;
  17847. this.importers = [];
  17848. this.includedDynamicImporters = [];
  17849. this.includedTopLevelAwaitingDynamicImporters = new Set();
  17850. this.includedImports = new Set();
  17851. this.isExecuted = false;
  17852. this.isUserDefinedEntryPoint = false;
  17853. this.needsExportShim = false;
  17854. this.sideEffectDependenciesByVariable = new Map();
  17855. this.sourcePhaseSources = new Set();
  17856. this.sourcesWithAttributes = new Map();
  17857. this.allExportsIncluded = false;
  17858. this.ast = null;
  17859. this.exportAllModules = [];
  17860. this.exportAllSources = new Set();
  17861. this.exportDescriptions = new Map();
  17862. this.exportedVariablesByName = null;
  17863. this.exportNamesByVariable = null;
  17864. this.exportShimVariable = new ExportShimVariable(this);
  17865. this.namespaceReexportsByName = new Map();
  17866. this.reexportDescriptions = new Map();
  17867. this.relevantDependencies = null;
  17868. this.syntheticExports = new Map();
  17869. this.syntheticNamespace = null;
  17870. this.transformDependencies = [];
  17871. this.excludeFromSourcemap = /\0/.test(id);
  17872. this.context = options.moduleContext(id);
  17873. this.preserveSignature = this.options.preserveEntrySignatures;
  17874. // eslint-disable-next-line @typescript-eslint/no-this-alias
  17875. const module = this;
  17876. const { dynamicImports, dynamicImporters, exportAllSources, exportDescriptions, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  17877. this.info = {
  17878. ast: null,
  17879. attributes,
  17880. code: null,
  17881. get dynamicallyImportedIdResolutions() {
  17882. return dynamicImports
  17883. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  17884. .filter(Boolean);
  17885. },
  17886. get dynamicallyImportedIds() {
  17887. // We cannot use this.dynamicDependencies because this is needed before
  17888. // dynamicDependencies are populated
  17889. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  17890. },
  17891. get dynamicImporters() {
  17892. return dynamicImporters.sort();
  17893. },
  17894. get exportedBindings() {
  17895. const exportBindings = { '.': [...exportDescriptions.keys()] };
  17896. for (const [name, { source }] of reexportDescriptions) {
  17897. (exportBindings[source] ??= []).push(name);
  17898. }
  17899. for (const source of exportAllSources) {
  17900. (exportBindings[source] ??= []).push('*');
  17901. }
  17902. return exportBindings;
  17903. },
  17904. get exports() {
  17905. return [
  17906. ...exportDescriptions.keys(),
  17907. ...reexportDescriptions.keys(),
  17908. ...[...exportAllSources].map(() => '*')
  17909. ];
  17910. },
  17911. get hasDefaultExport() {
  17912. // This information is only valid after parsing
  17913. if (!module.ast) {
  17914. return null;
  17915. }
  17916. return module.exportDescriptions.has('default') || reexportDescriptions.has('default');
  17917. },
  17918. id,
  17919. get implicitlyLoadedAfterOneOf() {
  17920. return Array.from(implicitlyLoadedAfter, getId).sort();
  17921. },
  17922. get implicitlyLoadedBefore() {
  17923. return Array.from(implicitlyLoadedBefore, getId).sort();
  17924. },
  17925. get importedIdResolutions() {
  17926. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  17927. },
  17928. get importedIds() {
  17929. // We cannot use this.dependencies because this is needed before
  17930. // dependencies are populated
  17931. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  17932. },
  17933. get importers() {
  17934. return importers.sort();
  17935. },
  17936. isEntry,
  17937. isExternal: false,
  17938. get isIncluded() {
  17939. if (graph.phase !== BuildPhase.GENERATE) {
  17940. return null;
  17941. }
  17942. return module.isIncluded();
  17943. },
  17944. meta: { ...meta },
  17945. moduleSideEffects,
  17946. safeVariableNames: null,
  17947. syntheticNamedExports
  17948. };
  17949. }
  17950. basename() {
  17951. const base = path.basename(this.id);
  17952. const extension = path.extname(this.id);
  17953. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  17954. }
  17955. bindReferences() {
  17956. this.ast.bind();
  17957. }
  17958. cacheInfoGetters() {
  17959. cacheObjectGetters(this.info, [
  17960. 'dynamicallyImportedIdResolutions',
  17961. 'dynamicallyImportedIds',
  17962. 'dynamicImporters',
  17963. 'exportedBindings',
  17964. 'exports',
  17965. 'hasDefaultExport',
  17966. 'implicitlyLoadedAfterOneOf',
  17967. 'implicitlyLoadedBefore',
  17968. 'importedIdResolutions',
  17969. 'importedIds',
  17970. 'importers'
  17971. ]);
  17972. }
  17973. error(properties, pos) {
  17974. if (pos !== undefined) {
  17975. this.addLocationToLogProps(properties, pos);
  17976. }
  17977. return parseAst_js.error(properties);
  17978. }
  17979. // sum up the length of all ast nodes that are included
  17980. estimateSize() {
  17981. let size = 0;
  17982. for (const node of this.ast.body) {
  17983. if (node.included) {
  17984. size += node.end - node.start;
  17985. }
  17986. }
  17987. return size;
  17988. }
  17989. getDependenciesToBeIncluded() {
  17990. if (this.relevantDependencies)
  17991. return this.relevantDependencies;
  17992. this.relevantDependencies = new Set();
  17993. const necessaryDependencies = new Set();
  17994. const alwaysCheckedDependencies = new Set();
  17995. const dependencyVariables = new Set(this.includedImports);
  17996. if (this.info.isEntry ||
  17997. this.includedDynamicImporters.length > 0 ||
  17998. this.namespace.included ||
  17999. this.implicitlyLoadedAfter.size > 0) {
  18000. for (const variable of this.getExportedVariablesByName().values()) {
  18001. if (variable.included) {
  18002. dependencyVariables.add(variable);
  18003. }
  18004. }
  18005. }
  18006. for (let variable of dependencyVariables) {
  18007. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  18008. if (sideEffectDependencies) {
  18009. for (const module of sideEffectDependencies) {
  18010. alwaysCheckedDependencies.add(module);
  18011. }
  18012. }
  18013. if (variable instanceof SyntheticNamedExportVariable) {
  18014. variable = variable.getBaseVariable();
  18015. }
  18016. else if (variable instanceof ExportDefaultVariable) {
  18017. variable = variable.getOriginalVariable();
  18018. }
  18019. necessaryDependencies.add(variable.module);
  18020. }
  18021. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  18022. for (const dependency of this.dependencies) {
  18023. this.relevantDependencies.add(dependency);
  18024. }
  18025. }
  18026. else {
  18027. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  18028. }
  18029. for (const dependency of necessaryDependencies) {
  18030. this.relevantDependencies.add(dependency);
  18031. }
  18032. return this.relevantDependencies;
  18033. }
  18034. getExportedVariablesByName() {
  18035. if (this.exportedVariablesByName) {
  18036. return this.exportedVariablesByName;
  18037. }
  18038. const exportedVariablesByName = (this.exportedVariablesByName = new Map());
  18039. for (const name of this.exportDescriptions.keys()) {
  18040. // We do not count the synthetic namespace as a regular export to hide it
  18041. // from entry signatures and namespace objects
  18042. if (name !== this.info.syntheticNamedExports) {
  18043. const [exportedVariable] = this.getVariableForExportName(name);
  18044. if (exportedVariable) {
  18045. exportedVariablesByName.set(name, exportedVariable);
  18046. }
  18047. else {
  18048. return parseAst_js.error(parseAst_js.logMissingEntryExport(name, this.id));
  18049. }
  18050. }
  18051. }
  18052. for (const name of this.reexportDescriptions.keys()) {
  18053. const [exportedVariable] = this.getVariableForExportName(name);
  18054. if (exportedVariable) {
  18055. exportedVariablesByName.set(name, exportedVariable);
  18056. }
  18057. }
  18058. for (const module of this.exportAllModules) {
  18059. if (module instanceof ExternalModule) {
  18060. exportedVariablesByName.set(`*${module.id}`, module.getVariableForExportName('*', {
  18061. importChain: [this.id]
  18062. })[0]);
  18063. continue;
  18064. }
  18065. for (const name of module.getExportedVariablesByName().keys()) {
  18066. if (name !== 'default' && !exportedVariablesByName.has(name)) {
  18067. const [exportedVariable] = this.getVariableForExportName(name);
  18068. if (exportedVariable) {
  18069. exportedVariablesByName.set(name, exportedVariable);
  18070. }
  18071. }
  18072. }
  18073. }
  18074. return (this.exportedVariablesByName = new Map([...exportedVariablesByName].sort(sortExportedVariables)));
  18075. }
  18076. getExportNamesByVariable() {
  18077. if (this.exportNamesByVariable) {
  18078. return this.exportNamesByVariable;
  18079. }
  18080. const exportNamesByVariable = new Map();
  18081. for (const [exportName, variable] of this.getExportedVariablesByName().entries()) {
  18082. const tracedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
  18083. if (!variable || !(variable.included || variable instanceof ExternalVariable)) {
  18084. continue;
  18085. }
  18086. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  18087. if (existingExportNames) {
  18088. existingExportNames.push(exportName);
  18089. }
  18090. else {
  18091. exportNamesByVariable.set(tracedVariable, [exportName]);
  18092. }
  18093. }
  18094. return (this.exportNamesByVariable = exportNamesByVariable);
  18095. }
  18096. getRenderedExports() {
  18097. // only direct exports are counted here, not reexports at all
  18098. const renderedExports = [];
  18099. const removedExports = [];
  18100. for (const exportName of this.exportDescriptions.keys()) {
  18101. (this.getExportedVariablesByName().get(exportName)?.included
  18102. ? renderedExports
  18103. : removedExports).push(exportName);
  18104. }
  18105. return { removedExports, renderedExports };
  18106. }
  18107. getSyntheticNamespace() {
  18108. if (this.syntheticNamespace === null) {
  18109. this.syntheticNamespace = undefined;
  18110. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  18111. ? this.info.syntheticNamedExports
  18112. : 'default', { onlyExplicit: true });
  18113. }
  18114. if (!this.syntheticNamespace) {
  18115. return parseAst_js.error(parseAst_js.logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  18116. }
  18117. return this.syntheticNamespace;
  18118. }
  18119. getVariableForExportName(name, { importerForSideEffects, importChain = [], isExportAllSearch, onlyExplicit, searchedNamesAndModules, sideEffectModules, exportOrReexportModules } = parseAst_js.EMPTY_OBJECT) {
  18120. if (name[0] === '*') {
  18121. if (name.length === 1) {
  18122. // export * from './other'
  18123. return [this.namespace];
  18124. }
  18125. // export * from 'external'
  18126. const module = this.graph.modulesById.get(name.slice(1));
  18127. return module.getVariableForExportName('*', {
  18128. importChain: [...importChain, this.id]
  18129. });
  18130. }
  18131. // export { foo } from './other'
  18132. const reexportDeclaration = this.reexportDescriptions.get(name);
  18133. if (reexportDeclaration) {
  18134. const [variable, options] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules, [...importChain, this.id], sideEffectModules, exportOrReexportModules);
  18135. if (!variable) {
  18136. return this.error(parseAst_js.logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id, !!options?.missingButExportExists), reexportDeclaration.start);
  18137. }
  18138. if (importerForSideEffects) {
  18139. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  18140. if (this.info.moduleSideEffects) {
  18141. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  18142. }
  18143. }
  18144. if (this.info.moduleSideEffects) {
  18145. sideEffectModules?.add(this);
  18146. }
  18147. exportOrReexportModules?.add(this);
  18148. return [variable];
  18149. }
  18150. const exportDeclaration = this.exportDescriptions.get(name);
  18151. if (exportDeclaration) {
  18152. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  18153. return [this.exportShimVariable];
  18154. }
  18155. const name = exportDeclaration.localName;
  18156. const variable = this.traceVariable(name, {
  18157. exportOrReexportModules,
  18158. importerForSideEffects,
  18159. searchedNamesAndModules,
  18160. sideEffectModules
  18161. });
  18162. if (!variable) {
  18163. return [null, { missingButExportExists: true }];
  18164. }
  18165. if (importerForSideEffects) {
  18166. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  18167. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  18168. }
  18169. sideEffectModules?.add(this);
  18170. exportOrReexportModules?.add(this);
  18171. return [variable];
  18172. }
  18173. if (onlyExplicit) {
  18174. return [null];
  18175. }
  18176. if (name !== 'default') {
  18177. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  18178. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, [...importChain, this.id]);
  18179. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  18180. if (foundNamespaceReexport[0]) {
  18181. const [namespaceReexportVariable, namespaceReexportOptions] = foundNamespaceReexport;
  18182. if (importerForSideEffects) {
  18183. const { exportOrReexportModules, sideEffectModules } = namespaceReexportOptions;
  18184. for (const module of exportOrReexportModules) {
  18185. if (importerForSideEffects.alternativeReexportModules.has(namespaceReexportVariable)) {
  18186. continue;
  18187. }
  18188. setAlternativeExporterIfCyclic(namespaceReexportVariable, importerForSideEffects, module);
  18189. }
  18190. for (const module of sideEffectModules) {
  18191. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, namespaceReexportVariable, (getNewSet)).add(module);
  18192. }
  18193. }
  18194. return foundNamespaceReexport;
  18195. }
  18196. }
  18197. if (this.info.syntheticNamedExports) {
  18198. return [
  18199. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  18200. ];
  18201. }
  18202. // we don't want to create shims when we are just
  18203. // probing export * modules for exports
  18204. if (!isExportAllSearch && this.options.shimMissingExports) {
  18205. this.shimMissingExport(name);
  18206. return [this.exportShimVariable];
  18207. }
  18208. return [null];
  18209. }
  18210. hasEffects() {
  18211. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  18212. }
  18213. include() {
  18214. const context = createInclusionContext();
  18215. if (this.ast.shouldBeIncluded(context))
  18216. this.ast.include(context, false);
  18217. }
  18218. includeAllExports() {
  18219. if (this.allExportsIncluded)
  18220. return;
  18221. this.allExportsIncluded = true;
  18222. this.includeModuleInExecution();
  18223. const inclusionContext = createInclusionContext();
  18224. for (const variable of this.getExportedVariablesByName().values()) {
  18225. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  18226. variable.deoptimizePath(UNKNOWN_PATH);
  18227. if (variable instanceof ExternalVariable) {
  18228. variable.module.reexported = true;
  18229. }
  18230. }
  18231. }
  18232. includeAllInBundle() {
  18233. this.ast.include(createInclusionContext(), true);
  18234. this.includeAllExports();
  18235. }
  18236. includeModuleInExecution() {
  18237. if (!this.isExecuted) {
  18238. markModuleAndImpureDependenciesAsExecuted(this);
  18239. this.graph.needsTreeshakingPass = true;
  18240. }
  18241. }
  18242. isIncluded() {
  18243. // Modules where this.ast is missing have been loaded via this.load and are
  18244. // not yet fully processed, hence they cannot be included.
  18245. return (this.ast &&
  18246. (this.ast.included ||
  18247. this.namespace.included ||
  18248. this.importedFromNotTreeshaken ||
  18249. this.exportShimVariable.included));
  18250. }
  18251. linkImports() {
  18252. this.addModulesToImportDescriptions(this.importDescriptions);
  18253. this.addModulesToImportDescriptions(this.reexportDescriptions);
  18254. const externalExportAllModules = [];
  18255. for (const source of this.exportAllSources) {
  18256. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  18257. if (module instanceof ExternalModule) {
  18258. externalExportAllModules.push(module);
  18259. continue;
  18260. }
  18261. this.exportAllModules.push(module);
  18262. }
  18263. this.exportAllModules.push(...externalExportAllModules);
  18264. }
  18265. log(level, properties, pos) {
  18266. this.addLocationToLogProps(properties, pos);
  18267. this.options.onLog(level, properties);
  18268. }
  18269. render(options) {
  18270. const source = this.magicString.clone();
  18271. this.ast.render(source, options);
  18272. source.trim();
  18273. const { usesTopLevelAwait } = this.astContext;
  18274. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  18275. return parseAst_js.error(parseAst_js.logInvalidFormatForTopLevelAwait(this.id, options.format));
  18276. }
  18277. return { source, usesTopLevelAwait };
  18278. }
  18279. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, safeVariableNames, ...moduleOptions }) {
  18280. timeStart('generate ast', 3);
  18281. if (code.startsWith('#!')) {
  18282. const shebangEndPosition = code.indexOf('\n');
  18283. this.shebang = code.slice(2, shebangEndPosition);
  18284. }
  18285. this.info.code = code;
  18286. this.info.safeVariableNames = safeVariableNames;
  18287. this.originalCode = originalCode;
  18288. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  18289. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  18290. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  18291. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  18292. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  18293. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  18294. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  18295. if (transformFiles) {
  18296. this.transformFiles = transformFiles;
  18297. }
  18298. this.transformDependencies = transformDependencies;
  18299. this.customTransformCache = customTransformCache;
  18300. this.updateOptions(moduleOptions);
  18301. this.resolvedIds = resolvedIds ?? Object.create(null);
  18302. // By default, `id` is the file name. Custom resolvers and loaders
  18303. // can change that, but it makes sense to use it for the source file name
  18304. const fileName = this.id;
  18305. this.magicString = new MagicString(code, {
  18306. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  18307. indentExclusionRanges: []
  18308. });
  18309. this.astContext = {
  18310. addDynamicImport: this.addDynamicImport.bind(this),
  18311. addExport: this.addExport.bind(this),
  18312. addImport: this.addImport.bind(this),
  18313. addImportMeta: this.addImportMeta.bind(this),
  18314. addImportSource: this.addImportSource.bind(this),
  18315. code, // Only needed for debugging
  18316. deoptimizationTracker: this.graph.deoptimizationTracker,
  18317. error: this.error.bind(this),
  18318. fileName, // Needed for warnings
  18319. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  18320. getModuleExecIndex: () => this.execIndex,
  18321. getModuleName: this.basename.bind(this),
  18322. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  18323. importDescriptions: this.importDescriptions,
  18324. includeDynamicImport: this.includeDynamicImport.bind(this),
  18325. includeVariableInModule: this.includeVariableInModule.bind(this),
  18326. log: this.log.bind(this),
  18327. magicString: this.magicString,
  18328. manualPureFunctions: this.graph.pureFunctions,
  18329. module: this,
  18330. moduleContext: this.context,
  18331. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  18332. options: this.options,
  18333. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  18334. traceExport: (name) => this.getVariableForExportName(name),
  18335. traceVariable: this.traceVariable.bind(this),
  18336. usesTopLevelAwait: false
  18337. };
  18338. this.scope = new ModuleScope(this.graph.scope, this.astContext, this.importDescriptions);
  18339. this.namespace = new NamespaceVariable(this.astContext);
  18340. const programParent = { context: this.astContext, type: 'Module' };
  18341. if (ast) {
  18342. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  18343. this.info.ast = ast;
  18344. }
  18345. else {
  18346. // Measuring asynchronous code does not provide reasonable results
  18347. timeEnd('generate ast', 3);
  18348. const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
  18349. timeStart('generate ast', 3);
  18350. this.ast = convertProgram(astBuffer, programParent, this.scope);
  18351. // Make lazy and apply LRU cache to not hog the memory
  18352. Object.defineProperty(this.info, 'ast', {
  18353. get: () => {
  18354. if (this.graph.astLru.has(fileName)) {
  18355. return this.graph.astLru.get(fileName);
  18356. }
  18357. else {
  18358. const parsedAst = this.tryParse();
  18359. // If the cache is not disabled, we need to keep the AST in memory
  18360. // until the end when the cache is generated
  18361. if (this.options.cache !== false) {
  18362. Object.defineProperty(this.info, 'ast', {
  18363. value: parsedAst
  18364. });
  18365. return parsedAst;
  18366. }
  18367. // Otherwise, we keep it in a small LRU cache to not hog too much
  18368. // memory but allow the same AST to be requested several times.
  18369. this.graph.astLru.set(fileName, parsedAst);
  18370. return parsedAst;
  18371. }
  18372. }
  18373. });
  18374. }
  18375. timeEnd('generate ast', 3);
  18376. }
  18377. toJSON() {
  18378. return {
  18379. ast: this.info.ast,
  18380. attributes: this.info.attributes,
  18381. code: this.info.code,
  18382. customTransformCache: this.customTransformCache,
  18383. dependencies: Array.from(this.dependencies, getId),
  18384. id: this.id,
  18385. meta: this.info.meta,
  18386. moduleSideEffects: this.info.moduleSideEffects,
  18387. originalCode: this.originalCode,
  18388. originalSourcemap: this.originalSourcemap,
  18389. resolvedIds: this.resolvedIds,
  18390. safeVariableNames: this.info.safeVariableNames,
  18391. sourcemapChain: this.sourcemapChain,
  18392. syntheticNamedExports: this.info.syntheticNamedExports,
  18393. transformDependencies: this.transformDependencies,
  18394. transformFiles: this.transformFiles
  18395. };
  18396. }
  18397. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules, sideEffectModules, exportOrReexportModules } = parseAst_js.EMPTY_OBJECT) {
  18398. const localVariable = this.scope.variables.get(name);
  18399. if (localVariable) {
  18400. return localVariable;
  18401. }
  18402. const importDescription = this.importDescriptions.get(name);
  18403. if (importDescription) {
  18404. const otherModule = importDescription.module;
  18405. if (otherModule instanceof Module && importDescription.name === '*') {
  18406. return otherModule.namespace;
  18407. }
  18408. const [declaration, options] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules, [this.id], sideEffectModules, exportOrReexportModules);
  18409. if (!declaration) {
  18410. return this.error(parseAst_js.logMissingExport(importDescription.name, this.id, otherModule.id, !!options?.missingButExportExists), importDescription.start);
  18411. }
  18412. return declaration;
  18413. }
  18414. return null;
  18415. }
  18416. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  18417. if (moduleSideEffects != null) {
  18418. this.info.moduleSideEffects = moduleSideEffects;
  18419. }
  18420. if (syntheticNamedExports != null) {
  18421. this.info.syntheticNamedExports = syntheticNamedExports;
  18422. }
  18423. if (meta != null) {
  18424. Object.assign(this.info.meta, meta);
  18425. }
  18426. }
  18427. addDynamicImport(node) {
  18428. let argument = node.sourceAstNode;
  18429. if (argument.type === parseAst_js.TemplateLiteral) {
  18430. if (argument.quasis.length === 1 &&
  18431. typeof argument.quasis[0].value.cooked === 'string') {
  18432. argument = argument.quasis[0].value.cooked;
  18433. }
  18434. }
  18435. else if (argument.type === parseAst_js.Literal &&
  18436. typeof argument.value === 'string') {
  18437. argument = argument.value;
  18438. }
  18439. this.dynamicImports.push({ argument, id: null, node });
  18440. }
  18441. assertUniqueExportName(name, nodeStart) {
  18442. if (this.exportDescriptions.has(name) || this.reexportDescriptions.has(name)) {
  18443. this.error(parseAst_js.logDuplicateExportError(name), nodeStart);
  18444. }
  18445. }
  18446. addExport(node) {
  18447. if (node instanceof ExportDefaultDeclaration) {
  18448. // export default foo;
  18449. this.assertUniqueExportName('default', node.start);
  18450. this.exportDescriptions.set('default', {
  18451. identifier: node.variable.getAssignedVariableName(),
  18452. localName: 'default'
  18453. });
  18454. }
  18455. else if (node instanceof ExportAllDeclaration) {
  18456. const source = node.source.value;
  18457. this.addSource(source, node);
  18458. if (node.exported) {
  18459. // export * as name from './other'
  18460. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  18461. this.assertUniqueExportName(name, node.exported.start);
  18462. this.reexportDescriptions.set(name, {
  18463. localName: '*',
  18464. module: null, // filled in later,
  18465. source,
  18466. start: node.start
  18467. });
  18468. }
  18469. else {
  18470. // export * from './other'
  18471. this.exportAllSources.add(source);
  18472. }
  18473. }
  18474. else if (node.source instanceof Literal) {
  18475. // export { name } from './other'
  18476. const source = node.source.value;
  18477. this.addSource(source, node);
  18478. for (const { exported, local, start } of node.specifiers) {
  18479. const name = exported instanceof Literal ? exported.value : exported.name;
  18480. this.assertUniqueExportName(name, start);
  18481. this.reexportDescriptions.set(name, {
  18482. localName: local instanceof Literal ? local.value : local.name,
  18483. module: null, // filled in later,
  18484. source,
  18485. start
  18486. });
  18487. }
  18488. }
  18489. else if (node.declaration) {
  18490. const declaration = node.declaration;
  18491. if (declaration instanceof VariableDeclaration) {
  18492. // export var { foo, bar } = ...
  18493. // export var foo = 1, bar = 2;
  18494. for (const declarator of declaration.declarations) {
  18495. for (const localName of extractAssignedNames(declarator.id)) {
  18496. this.assertUniqueExportName(localName, declarator.id.start);
  18497. this.exportDescriptions.set(localName, { identifier: null, localName });
  18498. }
  18499. }
  18500. }
  18501. else {
  18502. // export function foo () {}
  18503. const localName = declaration.id.name;
  18504. this.assertUniqueExportName(localName, declaration.id.start);
  18505. this.exportDescriptions.set(localName, { identifier: null, localName });
  18506. }
  18507. }
  18508. else {
  18509. // export { foo, bar, baz }
  18510. for (const { local, exported } of node.specifiers) {
  18511. // except for reexports, local must be an Identifier
  18512. const localName = local.name;
  18513. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  18514. this.assertUniqueExportName(exportedName, exported.start);
  18515. this.exportDescriptions.set(exportedName, { identifier: null, localName });
  18516. }
  18517. }
  18518. }
  18519. addImport(node) {
  18520. const source = node.source.value;
  18521. this.addSource(source, node);
  18522. for (const specifier of node.specifiers) {
  18523. const localName = specifier.local.name;
  18524. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  18525. this.error(parseAst_js.logRedeclarationError(localName), specifier.local.start);
  18526. }
  18527. const name = node.phase === 'source'
  18528. ? SOURCE_PHASE_IMPORT
  18529. : specifier instanceof ImportDefaultSpecifier
  18530. ? 'default'
  18531. : specifier instanceof ImportNamespaceSpecifier
  18532. ? '*'
  18533. : specifier.imported instanceof Identifier
  18534. ? specifier.imported.name
  18535. : specifier.imported.value;
  18536. this.importDescriptions.set(localName, {
  18537. module: null, // filled in later
  18538. name,
  18539. phase: node.phase === 'source' ? 'source' : 'instance',
  18540. source,
  18541. start: specifier.start
  18542. });
  18543. }
  18544. }
  18545. addImportSource(importSource) {
  18546. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  18547. this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
  18548. }
  18549. }
  18550. addImportMeta(node) {
  18551. this.importMetas.push(node);
  18552. }
  18553. addLocationToLogProps(properties, pos) {
  18554. properties.id = this.id;
  18555. properties.pos = pos;
  18556. let code = this.info.code;
  18557. const location = parseAst_js.locate(code, pos, { offsetLine: 1 });
  18558. if (location) {
  18559. let { column, line } = location;
  18560. try {
  18561. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  18562. code = this.originalCode;
  18563. }
  18564. catch (error_) {
  18565. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidSourcemapForError(error_, this.id, column, line, pos));
  18566. }
  18567. parseAst_js.augmentCodeLocation(properties, { column, line }, code, this.id);
  18568. }
  18569. }
  18570. addModulesToImportDescriptions(importDescription) {
  18571. for (const specifier of importDescription.values()) {
  18572. const { id } = this.resolvedIds[specifier.source];
  18573. specifier.module = this.graph.modulesById.get(id);
  18574. }
  18575. }
  18576. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  18577. const handledDependencies = new Set();
  18578. const addSideEffectDependencies = (possibleDependencies) => {
  18579. for (const dependency of possibleDependencies) {
  18580. if (handledDependencies.has(dependency)) {
  18581. continue;
  18582. }
  18583. handledDependencies.add(dependency);
  18584. if (necessaryDependencies.has(dependency)) {
  18585. relevantDependencies.add(dependency);
  18586. continue;
  18587. }
  18588. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  18589. continue;
  18590. }
  18591. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  18592. relevantDependencies.add(dependency);
  18593. continue;
  18594. }
  18595. addSideEffectDependencies(dependency.dependencies);
  18596. }
  18597. };
  18598. addSideEffectDependencies(this.dependencies);
  18599. addSideEffectDependencies(alwaysCheckedDependencies);
  18600. }
  18601. addSource(source, declaration) {
  18602. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  18603. const existingAttributes = this.sourcesWithAttributes.get(source);
  18604. if (existingAttributes) {
  18605. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  18606. this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  18607. }
  18608. }
  18609. else {
  18610. this.sourcesWithAttributes.set(source, parsedAttributes);
  18611. }
  18612. if (declaration.phase === 'source') {
  18613. this.sourcePhaseSources.add(source);
  18614. }
  18615. }
  18616. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  18617. const { id } = this.resolvedIds[importSource];
  18618. const module = this.graph.modulesById.get(id);
  18619. const [variable] = module.getVariableForExportName(baseName, { importChain: [this.id] });
  18620. if (!variable) {
  18621. return this.error(parseAst_js.logMissingJsxExport(baseName, id, this.id), nodeStart);
  18622. }
  18623. return variable;
  18624. }
  18625. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, importChain) {
  18626. let foundSyntheticDeclaration = null;
  18627. const foundInternalDeclarations = new Map();
  18628. const foundExternalDeclarations = new Set();
  18629. const sideEffectModules = new Set();
  18630. const exportOrReexportModules = new Set();
  18631. for (const module of this.exportAllModules) {
  18632. // Synthetic namespaces should not hide "regular" exports of the same name
  18633. if (module.info.syntheticNamedExports === name) {
  18634. continue;
  18635. }
  18636. const [variable, options] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  18637. // We are creating a copy to handle the case where the same binding is
  18638. // imported through different namespace reexports gracefully
  18639. copyNameToModulesMap(searchedNamesAndModules), importChain, sideEffectModules, exportOrReexportModules);
  18640. if (module instanceof ExternalModule || options?.indirectExternal) {
  18641. foundExternalDeclarations.add(variable);
  18642. }
  18643. else if (variable instanceof SyntheticNamedExportVariable) {
  18644. if (!foundSyntheticDeclaration) {
  18645. foundSyntheticDeclaration = variable;
  18646. }
  18647. }
  18648. else if (variable) {
  18649. foundInternalDeclarations.set(variable, module);
  18650. }
  18651. }
  18652. if (foundInternalDeclarations.size > 0) {
  18653. const foundDeclarationList = [...foundInternalDeclarations];
  18654. const usedDeclaration = foundDeclarationList[0][0];
  18655. if (foundDeclarationList.length === 1) {
  18656. return [usedDeclaration, { exportOrReexportModules, sideEffectModules }];
  18657. }
  18658. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  18659. // TODO we are pretending it was not found while it should behave like "undefined"
  18660. return [null];
  18661. }
  18662. if (foundExternalDeclarations.size > 0) {
  18663. const foundDeclarationList = [...foundExternalDeclarations];
  18664. const usedDeclaration = foundDeclarationList[0];
  18665. if (foundDeclarationList.length > 1) {
  18666. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  18667. }
  18668. return [
  18669. usedDeclaration,
  18670. { exportOrReexportModules, indirectExternal: true, sideEffectModules }
  18671. ];
  18672. }
  18673. if (foundSyntheticDeclaration) {
  18674. return [foundSyntheticDeclaration, { exportOrReexportModules, sideEffectModules }];
  18675. }
  18676. return [null];
  18677. }
  18678. includeAndGetAdditionalMergedNamespaces() {
  18679. const externalNamespaces = new Set();
  18680. const syntheticNamespaces = new Set();
  18681. for (const module of [this, ...this.exportAllModules]) {
  18682. if (module instanceof ExternalModule) {
  18683. const [externalVariable] = module.getVariableForExportName('*', {
  18684. importChain: [this.id]
  18685. });
  18686. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  18687. this.includedImports.add(externalVariable);
  18688. externalNamespaces.add(externalVariable);
  18689. }
  18690. else if (module.info.syntheticNamedExports) {
  18691. const syntheticNamespace = module.getSyntheticNamespace();
  18692. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  18693. this.includedImports.add(syntheticNamespace);
  18694. syntheticNamespaces.add(syntheticNamespace);
  18695. }
  18696. }
  18697. return [...syntheticNamespaces, ...externalNamespaces];
  18698. }
  18699. includeDynamicImport(node) {
  18700. const { resolution } = node;
  18701. if (resolution instanceof Module) {
  18702. if (!resolution.includedDynamicImporters.includes(this)) {
  18703. resolution.includedDynamicImporters.push(this);
  18704. // If a module has a top-level await, removing this entry can create
  18705. // deadlocks.
  18706. if (this.astContext.usesTopLevelAwait) {
  18707. resolution.includedTopLevelAwaitingDynamicImporters.add(this);
  18708. }
  18709. }
  18710. }
  18711. }
  18712. includeVariable(variable, path, context) {
  18713. const { included, module: variableModule } = variable;
  18714. variable.includePath(path, context);
  18715. if (included) {
  18716. if (variableModule instanceof Module && variableModule !== this) {
  18717. getAndExtendSideEffectModules(variable, this);
  18718. }
  18719. return;
  18720. }
  18721. this.graph.needsTreeshakingPass = true;
  18722. if (!(variableModule instanceof Module)) {
  18723. return;
  18724. }
  18725. variableModule.includeModuleInExecution();
  18726. if (variableModule !== this) {
  18727. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  18728. for (const module of sideEffectModules) {
  18729. module.includeModuleInExecution();
  18730. }
  18731. }
  18732. }
  18733. includeVariableInModule(variable, path, context) {
  18734. this.includeVariable(variable, path, context);
  18735. const variableModule = variable.module;
  18736. if (variableModule && variableModule !== this) {
  18737. this.includedImports.add(variable);
  18738. }
  18739. }
  18740. shimMissingExport(name) {
  18741. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
  18742. this.exportDescriptions.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  18743. }
  18744. tryParse() {
  18745. try {
  18746. return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
  18747. }
  18748. catch (error_) {
  18749. return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
  18750. }
  18751. }
  18752. }
  18753. // if there is a cyclic import in the reexport chain, we should not
  18754. // import from the original module but from the cyclic module to not
  18755. // mess up execution order.
  18756. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  18757. if (variable.module instanceof Module && variable.module !== reexporter) {
  18758. const exporterCycles = variable.module.cycles;
  18759. if (exporterCycles.size > 0) {
  18760. const importerCycles = reexporter.cycles;
  18761. for (const cycleSymbol of importerCycles) {
  18762. if (exporterCycles.has(cycleSymbol)) {
  18763. importer.alternativeReexportModules.set(variable, reexporter);
  18764. break;
  18765. }
  18766. }
  18767. }
  18768. }
  18769. }
  18770. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  18771. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  18772. const sortExportedVariables = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
  18773. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  18774. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  18775. async function createAddons(options, outputPluginDriver, chunk) {
  18776. try {
  18777. let [banner, footer, intro, outro] = await Promise.all([
  18778. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  18779. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  18780. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  18781. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  18782. ]);
  18783. if (intro)
  18784. intro += '\n\n';
  18785. if (outro)
  18786. outro = `\n\n${outro}`;
  18787. if (banner)
  18788. banner += '\n';
  18789. if (footer)
  18790. footer = '\n' + footer;
  18791. return { banner, footer, intro, outro };
  18792. }
  18793. catch (error_) {
  18794. return parseAst_js.error(parseAst_js.logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  18795. }
  18796. }
  18797. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  18798. amd: deconflictImportsOther,
  18799. cjs: deconflictImportsOther,
  18800. es: deconflictImportsEsmOrSystem,
  18801. iife: deconflictImportsOther,
  18802. system: deconflictImportsEsmOrSystem,
  18803. umd: deconflictImportsOther
  18804. };
  18805. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  18806. const reversedModules = [...modules].reverse();
  18807. for (const module of reversedModules) {
  18808. module.scope.addUsedOutsideNames(usedNames, accessedGlobalsByScope);
  18809. }
  18810. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  18811. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  18812. for (const module of reversedModules) {
  18813. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  18814. }
  18815. }
  18816. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  18817. // This is needed for namespace reexports
  18818. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  18819. if (preserveModules || dependency instanceof ExternalChunk) {
  18820. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  18821. }
  18822. }
  18823. for (const variable of imports) {
  18824. const module = variable.module;
  18825. const name = variable.name;
  18826. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  18827. variable.setRenderNames(null, (module instanceof ExternalModule
  18828. ? externalChunkByModule.get(module)
  18829. : chunkByModule.get(module)).variableName);
  18830. }
  18831. else if (module instanceof ExternalModule && variable.isSourcePhase) {
  18832. variable.setRenderNames(null, getSafeName(module.suggestedVariableName + '__source', usedNames, variable.forbiddenNames));
  18833. }
  18834. else if (module instanceof ExternalModule && name === 'default') {
  18835. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  18836. ? module.suggestedVariableName + '__default'
  18837. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  18838. }
  18839. else {
  18840. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  18841. }
  18842. }
  18843. for (const variable of syntheticExports) {
  18844. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18845. }
  18846. }
  18847. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  18848. for (const chunk of dependencies) {
  18849. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  18850. }
  18851. for (const chunk of deconflictedNamespace) {
  18852. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  18853. }
  18854. for (const externalModule of deconflictedDefault) {
  18855. externalModule.defaultVariableName =
  18856. deconflictedNamespace.has(externalModule) &&
  18857. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  18858. ? externalModule.namespaceVariableName
  18859. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  18860. }
  18861. for (const variable of imports) {
  18862. const module = variable.module;
  18863. if (module instanceof ExternalModule) {
  18864. const chunk = externalChunkByModule.get(module);
  18865. const name = variable.name;
  18866. if (name === 'default') {
  18867. const moduleInterop = interop(module.id);
  18868. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  18869. ? chunk.defaultVariableName
  18870. : chunk.variableName;
  18871. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  18872. variable.setRenderNames(variableName, 'default');
  18873. }
  18874. else {
  18875. variable.setRenderNames(null, variableName);
  18876. }
  18877. }
  18878. else if (name === '*') {
  18879. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  18880. ? chunk.namespaceVariableName
  18881. : chunk.variableName);
  18882. }
  18883. else {
  18884. // if the second parameter is `null`, it uses its "name" for the property name
  18885. variable.setRenderNames(chunk.variableName, null);
  18886. }
  18887. }
  18888. else {
  18889. const chunk = chunkByModule.get(module);
  18890. if (preserveModules && variable.isNamespace) {
  18891. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  18892. }
  18893. else if (chunk.exportMode === 'default') {
  18894. variable.setRenderNames(null, chunk.variableName);
  18895. }
  18896. else {
  18897. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  18898. }
  18899. }
  18900. }
  18901. }
  18902. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  18903. for (const module of modules) {
  18904. module.info.safeVariableNames ||= {};
  18905. for (const variable of module.scope.variables.values()) {
  18906. if (variable.included &&
  18907. // this will only happen for exports in some formats
  18908. !(variable.renderBaseName ||
  18909. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  18910. // We need to make sure that variables that corresponding to object
  18911. // prototype methods are not accidentally matched.
  18912. const cachedSafeVariableName = Object.getOwnPropertyDescriptor(module.info.safeVariableNames, variable.name)?.value;
  18913. if (cachedSafeVariableName && !usedNames.has(cachedSafeVariableName)) {
  18914. usedNames.add(cachedSafeVariableName);
  18915. variable.setRenderNames(null, cachedSafeVariableName);
  18916. continue;
  18917. }
  18918. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18919. module.info.safeVariableNames[variable.name] = variable.renderName;
  18920. }
  18921. }
  18922. if (includedNamespaces.has(module)) {
  18923. const namespace = module.namespace;
  18924. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  18925. }
  18926. }
  18927. }
  18928. function assignExportsToMangledNames(exports$1, exportsByName, exportNamesByVariable) {
  18929. let nameIndex = 0;
  18930. for (const variable of exports$1) {
  18931. let [exportName] = variable.name;
  18932. if (exportsByName.has(exportName)) {
  18933. do {
  18934. exportName = toBase64(++nameIndex);
  18935. // skip past leading number identifiers
  18936. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  18937. nameIndex += 9 * 64 ** (exportName.length - 1);
  18938. exportName = toBase64(nameIndex);
  18939. }
  18940. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  18941. }
  18942. exportsByName.set(exportName, variable);
  18943. exportNamesByVariable.set(variable, [exportName]);
  18944. }
  18945. }
  18946. function assignExportsToNames(exports$1, exportsByName, exportNamesByVariable) {
  18947. for (const variable of exports$1) {
  18948. let nameIndex = 0;
  18949. let exportName = variable.name;
  18950. while (exportsByName.has(exportName)) {
  18951. exportName = variable.name + '$' + ++nameIndex;
  18952. }
  18953. exportsByName.set(exportName, variable);
  18954. exportNamesByVariable.set(variable, [exportName]);
  18955. }
  18956. }
  18957. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  18958. const exportKeys = chunk.getExportNames();
  18959. if (exportMode === 'default') {
  18960. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  18961. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  18962. }
  18963. }
  18964. else if (exportMode === 'none' && exportKeys.length > 0) {
  18965. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  18966. }
  18967. if (exportMode === 'auto') {
  18968. if (exportKeys.length === 0) {
  18969. exportMode = 'none';
  18970. }
  18971. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  18972. exportMode = 'default';
  18973. }
  18974. else {
  18975. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  18976. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMixedExport(facadeModuleId, name));
  18977. }
  18978. exportMode = 'named';
  18979. }
  18980. }
  18981. return exportMode;
  18982. }
  18983. function guessIndentString(code) {
  18984. const lines = code.split('\n');
  18985. const tabbed = lines.filter(line => /^\t+/.test(line));
  18986. const spaced = lines.filter(line => /^ {2,}/.test(line));
  18987. if (tabbed.length === 0 && spaced.length === 0) {
  18988. return null;
  18989. }
  18990. // More lines tabbed than spaced? Assume tabs, and
  18991. // default to tabs in the case of a tie (or nothing
  18992. // to go on)
  18993. if (tabbed.length >= spaced.length) {
  18994. return '\t';
  18995. }
  18996. // Otherwise, we need to guess the multiple
  18997. const min = spaced.reduce((previous, current) => {
  18998. const numberSpaces = /^ +/.exec(current)[0].length;
  18999. return Math.min(numberSpaces, previous);
  19000. }, Infinity);
  19001. return ' '.repeat(min);
  19002. }
  19003. function getIndentString(modules, options) {
  19004. if (options.indent !== true)
  19005. return options.indent;
  19006. for (const module of modules) {
  19007. const indent = guessIndentString(module.originalCode);
  19008. if (indent !== null)
  19009. return indent;
  19010. }
  19011. return '\t';
  19012. }
  19013. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  19014. const staticDependencyBlocks = [];
  19015. const handledDependencies = new Set();
  19016. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  19017. const module = orderedModules[modulePos];
  19018. if (!handledDependencies.has(module)) {
  19019. const staticDependencies = [];
  19020. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  19021. staticDependencyBlocks.unshift(staticDependencies);
  19022. }
  19023. }
  19024. const dependencies = new Set();
  19025. for (const block of staticDependencyBlocks) {
  19026. for (const dependency of block) {
  19027. dependencies.add(dependency);
  19028. }
  19029. }
  19030. return dependencies;
  19031. }
  19032. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  19033. const dependencies = module.getDependenciesToBeIncluded();
  19034. for (const dependency of dependencies) {
  19035. if (dependency instanceof ExternalModule) {
  19036. staticDependencies.push(externalChunkByModule.get(dependency));
  19037. continue;
  19038. }
  19039. const dependencyChunk = chunkByModule.get(dependency);
  19040. if (dependencyChunk !== chunk) {
  19041. staticDependencies.push(dependencyChunk);
  19042. continue;
  19043. }
  19044. if (!handledModules.has(dependency)) {
  19045. handledModules.add(dependency);
  19046. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  19047. }
  19048. }
  19049. }
  19050. const RESERVED_USED_NAMES = [
  19051. 'Object',
  19052. 'Promise',
  19053. 'module',
  19054. 'exports',
  19055. 'require',
  19056. '__filename',
  19057. '__dirname',
  19058. ...HELPER_NAMES
  19059. ];
  19060. const NON_ASSET_EXTENSIONS = new Set([
  19061. '.js',
  19062. '.jsx',
  19063. '.ts',
  19064. '.tsx',
  19065. '.mjs',
  19066. '.mts',
  19067. '.cjs',
  19068. '.cts'
  19069. ]);
  19070. function getGlobalName(chunk, globals, hasExports, log) {
  19071. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  19072. if (globalName) {
  19073. return globalName;
  19074. }
  19075. if (hasExports) {
  19076. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingGlobalName(chunk.id, chunk.variableName));
  19077. return chunk.variableName;
  19078. }
  19079. }
  19080. class Chunk {
  19081. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  19082. this.orderedModules = orderedModules;
  19083. this.inputOptions = inputOptions;
  19084. this.outputOptions = outputOptions;
  19085. this.unsetOptions = unsetOptions;
  19086. this.pluginDriver = pluginDriver;
  19087. this.modulesById = modulesById;
  19088. this.chunkByModule = chunkByModule;
  19089. this.externalChunkByModule = externalChunkByModule;
  19090. this.facadeChunkByModule = facadeChunkByModule;
  19091. this.includedNamespaces = includedNamespaces;
  19092. this.manualChunkAlias = manualChunkAlias;
  19093. this.getPlaceholder = getPlaceholder;
  19094. this.bundle = bundle;
  19095. this.inputBase = inputBase;
  19096. this.snippets = snippets;
  19097. this.dependencies = new Set();
  19098. this.entryModules = [];
  19099. this.exportMode = 'named';
  19100. this.facadeModule = null;
  19101. this.namespaceVariableName = '';
  19102. this.variableName = '';
  19103. this.isManualChunk = false;
  19104. this.accessedGlobalsByScope = new Map();
  19105. this.dynamicEntryModules = [];
  19106. this.dynamicName = null;
  19107. this.exportNamesByVariable = new Map();
  19108. this.exports = new Set();
  19109. this.exportsByName = new Map();
  19110. this.fileName = null;
  19111. this.implicitEntryModules = [];
  19112. this.implicitlyLoadedBefore = new Set();
  19113. this.imports = new Set();
  19114. this.includedDynamicImports = null;
  19115. this.includedReexportsByModule = new Map();
  19116. // This may be updated in the constructor
  19117. this.isEmpty = true;
  19118. this.name = null;
  19119. this.needsExportsShim = false;
  19120. this.preRenderedChunkInfo = null;
  19121. this.preliminaryFileName = null;
  19122. this.preliminarySourcemapFileName = null;
  19123. this.renderedChunkInfo = null;
  19124. this.renderedDependencies = null;
  19125. this.renderedModules = Object.create(null);
  19126. this.sortedExportNames = null;
  19127. this.strictFacade = false;
  19128. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  19129. this.allowExtensionModules = new Set();
  19130. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  19131. const chunkModules = new Set(orderedModules);
  19132. for (const module of orderedModules) {
  19133. chunkByModule.set(module, this);
  19134. if (module.namespace.included && !outputOptions.preserveModules) {
  19135. includedNamespaces.add(module);
  19136. }
  19137. if (this.isEmpty && module.isIncluded()) {
  19138. this.isEmpty = false;
  19139. }
  19140. if (module.info.isEntry || outputOptions.preserveModules) {
  19141. this.entryModules.push(module);
  19142. }
  19143. for (const importer of module.includedDynamicImporters) {
  19144. if (!chunkModules.has(importer)) {
  19145. this.dynamicEntryModules.push(module);
  19146. // Modules with synthetic exports need an artificial namespace for dynamic imports
  19147. if (module.info.syntheticNamedExports) {
  19148. includedNamespaces.add(module);
  19149. this.exports.add(module.namespace);
  19150. }
  19151. // This only needs to run once
  19152. break;
  19153. }
  19154. }
  19155. if (module.implicitlyLoadedAfter.size > 0) {
  19156. this.implicitEntryModules.push(module);
  19157. }
  19158. }
  19159. this.suggestedVariableName = makeLegal(this.generateVariableName());
  19160. this.isManualChunk = manualChunkAlias !== null;
  19161. }
  19162. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  19163. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  19164. chunk.assignFacadeName(facadeName, facadedModule);
  19165. if (!facadeChunkByModule.has(facadedModule)) {
  19166. facadeChunkByModule.set(facadedModule, chunk);
  19167. }
  19168. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  19169. chunk.dependencies.add(dependency instanceof Module
  19170. ? chunkByModule.get(dependency)
  19171. : externalChunkByModule.get(dependency));
  19172. }
  19173. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  19174. facadedModule.info.moduleSideEffects &&
  19175. facadedModule.hasEffects()) {
  19176. chunk.dependencies.add(chunkByModule.get(facadedModule));
  19177. }
  19178. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  19179. chunk.facadeModule = facadedModule;
  19180. chunk.strictFacade = true;
  19181. return chunk;
  19182. }
  19183. canModuleBeFacade(module, exposedVariables) {
  19184. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  19185. // All exports of this chunk need to be exposed by the candidate module
  19186. for (const exposedVariable of this.exports) {
  19187. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  19188. return false;
  19189. }
  19190. }
  19191. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  19192. for (const exposedVariable of exposedVariables) {
  19193. if (!(exposedVariable.module === module ||
  19194. moduleExportNamesByVariable.has(exposedVariable) ||
  19195. (exposedVariable instanceof SyntheticNamedExportVariable &&
  19196. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  19197. return false;
  19198. }
  19199. }
  19200. return true;
  19201. }
  19202. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  19203. const renderedChunkInfo = this.getRenderedChunkInfo();
  19204. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  19205. const preliminaryFileName = renderedChunkInfo.fileName;
  19206. const fileName = (this.fileName = finalize(preliminaryFileName));
  19207. return {
  19208. ...renderedChunkInfo,
  19209. code,
  19210. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  19211. fileName,
  19212. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  19213. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  19214. finalize(fileName),
  19215. bindings
  19216. ])),
  19217. imports: renderedChunkInfo.imports.map(finalize),
  19218. map,
  19219. preliminaryFileName,
  19220. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  19221. sourcemapFileName
  19222. };
  19223. }
  19224. generateExports() {
  19225. this.sortedExportNames = null;
  19226. const remainingExports = new Set(this.exports);
  19227. if (this.facadeModule !== null &&
  19228. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  19229. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  19230. for (const [variable, exportNames] of exportNamesByVariable) {
  19231. this.exportNamesByVariable.set(variable, [...exportNames]);
  19232. for (const exportName of exportNames) {
  19233. this.exportsByName.set(exportName, variable);
  19234. }
  19235. remainingExports.delete(variable);
  19236. }
  19237. }
  19238. for (const module of this.allowExtensionModules) {
  19239. const exportNamesByVariable = module.getExportNamesByVariable();
  19240. for (const [variable, exportNames] of exportNamesByVariable) {
  19241. this.exportNamesByVariable.set(variable, [...exportNames]);
  19242. for (const exportName of exportNames) {
  19243. this.exportsByName.set(exportName, variable);
  19244. }
  19245. remainingExports.delete(variable);
  19246. }
  19247. }
  19248. if (this.outputOptions.minifyInternalExports) {
  19249. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  19250. }
  19251. else {
  19252. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  19253. }
  19254. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  19255. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  19256. }
  19257. generateFacades() {
  19258. const facades = [];
  19259. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  19260. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  19261. for (const module of entryModules) {
  19262. if (module.preserveSignature === 'allow-extension') {
  19263. const canPreserveExports = this.canPreserveModuleExports(module);
  19264. if (canPreserveExports &&
  19265. !module.chunkFileNames.size &&
  19266. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  19267. this.allowExtensionModules.add(module);
  19268. if (!this.facadeModule) {
  19269. this.facadeModule = module;
  19270. this.strictFacade = false;
  19271. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  19272. }
  19273. this.facadeChunkByModule.set(module, this);
  19274. continue;
  19275. }
  19276. }
  19277. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  19278. // mapping must run after Set 'name' dedupe
  19279. name => ({
  19280. name
  19281. }));
  19282. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  19283. requiredFacades.push({});
  19284. }
  19285. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  19286. if (requiredFacades.length === 0) {
  19287. requiredFacades.push({});
  19288. }
  19289. if (!this.facadeModule) {
  19290. const needsStrictFacade = !this.outputOptions.preserveModules &&
  19291. (module.preserveSignature === 'strict' ||
  19292. (module.preserveSignature === 'exports-only' &&
  19293. module.getExportNamesByVariable().size > 0));
  19294. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  19295. this.facadeModule = module;
  19296. this.facadeChunkByModule.set(module, this);
  19297. if (module.preserveSignature) {
  19298. this.strictFacade = needsStrictFacade;
  19299. }
  19300. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  19301. }
  19302. }
  19303. for (const facadeName of requiredFacades) {
  19304. 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));
  19305. }
  19306. }
  19307. for (const module of this.dynamicEntryModules) {
  19308. if (module.info.syntheticNamedExports)
  19309. continue;
  19310. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  19311. this.facadeModule = module;
  19312. this.facadeChunkByModule.set(module, this);
  19313. this.strictFacade = true;
  19314. this.dynamicName = getChunkNameFromModule(module);
  19315. }
  19316. else if (this.facadeModule === module &&
  19317. !this.strictFacade &&
  19318. this.canModuleBeFacade(module, exposedVariables)) {
  19319. this.strictFacade = true;
  19320. }
  19321. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  19322. this.includedNamespaces.add(module);
  19323. this.exports.add(module.namespace);
  19324. }
  19325. }
  19326. if (!this.outputOptions.preserveModules) {
  19327. this.addNecessaryImportsForFacades();
  19328. }
  19329. return facades;
  19330. }
  19331. canPreserveModuleExports(module) {
  19332. const exportNamesByVariable = module.getExportNamesByVariable();
  19333. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  19334. for (const [variable, exportNames] of exportNamesByVariable) {
  19335. for (const exportName of exportNames) {
  19336. const existingVariable = this.exportsByName.get(exportName);
  19337. // It's ok if the same export name in two modules references the exact same variable
  19338. if (existingVariable && existingVariable !== variable) {
  19339. return false;
  19340. }
  19341. }
  19342. }
  19343. // No actual conflicts found, add export names for future conflict checks
  19344. for (const [variable, exportNames] of exportNamesByVariable) {
  19345. for (const exportName of exportNames) {
  19346. this.exportsByName.set(exportName, variable);
  19347. }
  19348. }
  19349. return true;
  19350. }
  19351. getChunkName() {
  19352. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  19353. }
  19354. getExportNames() {
  19355. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  19356. }
  19357. getFileName() {
  19358. return this.fileName || this.getPreliminaryFileName().fileName;
  19359. }
  19360. getImportPath(importer) {
  19361. return escapeId(parseAst_js.getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  19362. }
  19363. getPreliminaryFileName() {
  19364. if (this.preliminaryFileName) {
  19365. return this.preliminaryFileName;
  19366. }
  19367. let fileName;
  19368. let hashPlaceholder = null;
  19369. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  19370. if (file) {
  19371. fileName = path.basename(file);
  19372. }
  19373. else if (this.fileName === null) {
  19374. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  19375. ? [entryFileNames, 'output.entryFileNames']
  19376. : [chunkFileNames, 'output.chunkFileNames'];
  19377. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  19378. format: () => format,
  19379. hash: size => hashPlaceholder ||
  19380. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  19381. name: () => this.getChunkName()
  19382. });
  19383. if (!hashPlaceholder) {
  19384. fileName = makeUnique(fileName, this.bundle);
  19385. }
  19386. }
  19387. else {
  19388. fileName = this.fileName;
  19389. }
  19390. if (!hashPlaceholder) {
  19391. this.bundle[fileName] = FILE_PLACEHOLDER;
  19392. }
  19393. // Caching is essential to not conflict with the file name reservation above
  19394. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  19395. }
  19396. getPreliminarySourcemapFileName() {
  19397. if (this.preliminarySourcemapFileName) {
  19398. return this.preliminarySourcemapFileName;
  19399. }
  19400. const { sourcemapFileNames, format } = this.outputOptions;
  19401. if (!sourcemapFileNames) {
  19402. return null;
  19403. }
  19404. let hashPlaceholder = null;
  19405. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  19406. let sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  19407. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  19408. format: () => format,
  19409. hash: size => hashPlaceholder ||
  19410. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  19411. name: () => this.getChunkName()
  19412. });
  19413. if (!hashPlaceholder) {
  19414. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  19415. }
  19416. return (this.preliminarySourcemapFileName = {
  19417. fileName: sourcemapFileName,
  19418. hashPlaceholder
  19419. });
  19420. }
  19421. getRenderedChunkInfo() {
  19422. if (this.renderedChunkInfo) {
  19423. return this.renderedChunkInfo;
  19424. }
  19425. return (this.renderedChunkInfo = {
  19426. ...this.getPreRenderedChunkInfo(),
  19427. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  19428. fileName: this.getFileName(),
  19429. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  19430. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  19431. imports: Array.from(this.dependencies, resolveFileName),
  19432. modules: this.renderedModules,
  19433. referencedFiles: this.getReferencedFiles()
  19434. });
  19435. }
  19436. getVariableExportName(variable) {
  19437. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  19438. return '*';
  19439. }
  19440. return this.exportNamesByVariable.get(variable)[0];
  19441. }
  19442. link() {
  19443. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  19444. for (const module of this.orderedModules) {
  19445. this.addImplicitlyLoadedBeforeFromModule(module);
  19446. this.setUpChunkImportsAndExportsForModule(module);
  19447. }
  19448. }
  19449. inlineTransitiveImports() {
  19450. const { facadeModule, dependencies, outputOptions } = this;
  19451. const { hoistTransitiveImports, preserveModules } = outputOptions;
  19452. // for static and dynamic entry points, add transitive dependencies to this
  19453. // chunk's dependencies to avoid loading latency
  19454. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  19455. for (const dep of dependencies) {
  19456. if (dep instanceof Chunk)
  19457. this.inlineChunkDependencies(dep);
  19458. }
  19459. }
  19460. }
  19461. async render() {
  19462. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  19463. const { format, preserveModules } = outputOptions;
  19464. const preliminaryFileName = this.getPreliminaryFileName();
  19465. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  19466. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  19467. const renderedDependencies = [...this.getRenderedDependencies().values()];
  19468. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  19469. let hasExports = renderedExports.length > 0;
  19470. let hasDefaultExport = false;
  19471. for (const renderedDependency of renderedDependencies) {
  19472. const { reexports } = renderedDependency;
  19473. if (reexports?.length) {
  19474. hasExports = true;
  19475. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  19476. hasDefaultExport = true;
  19477. }
  19478. if (format === 'es') {
  19479. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  19480. }
  19481. }
  19482. }
  19483. if (!hasDefaultExport) {
  19484. for (const { exported } of renderedExports) {
  19485. if (exported === 'default') {
  19486. hasDefaultExport = true;
  19487. break;
  19488. }
  19489. }
  19490. }
  19491. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  19492. finalisers[format](renderedSource, {
  19493. accessedGlobals,
  19494. dependencies: renderedDependencies,
  19495. exports: renderedExports,
  19496. hasDefaultExport,
  19497. hasExports,
  19498. id: preliminaryFileName.fileName,
  19499. indent,
  19500. intro,
  19501. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  19502. isModuleFacade: facadeModule !== null,
  19503. log: onLog,
  19504. namedExportsMode: exportMode !== 'default',
  19505. outro,
  19506. snippets,
  19507. usesTopLevelAwait
  19508. }, outputOptions);
  19509. if (banner)
  19510. magicString.prepend(banner);
  19511. if (format === 'es' || format === 'cjs') {
  19512. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  19513. if (shebang) {
  19514. magicString.prepend(`#!${shebang}\n`);
  19515. }
  19516. }
  19517. if (footer)
  19518. magicString.append(footer);
  19519. return {
  19520. chunk: this,
  19521. magicString,
  19522. preliminaryFileName,
  19523. preliminarySourcemapFileName,
  19524. usedModules
  19525. };
  19526. }
  19527. addImplicitlyLoadedBeforeFromModule(baseModule) {
  19528. const { chunkByModule, implicitlyLoadedBefore } = this;
  19529. for (const module of baseModule.implicitlyLoadedBefore) {
  19530. const chunk = chunkByModule.get(module);
  19531. if (chunk && chunk !== this) {
  19532. implicitlyLoadedBefore.add(chunk);
  19533. }
  19534. }
  19535. }
  19536. addNecessaryImportsForFacades() {
  19537. for (const [module, variables] of this.includedReexportsByModule) {
  19538. if (this.includedNamespaces.has(module)) {
  19539. for (const variable of variables) {
  19540. this.imports.add(variable);
  19541. }
  19542. }
  19543. }
  19544. }
  19545. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  19546. if (fileName) {
  19547. this.fileName = fileName;
  19548. }
  19549. else {
  19550. this.name = this.outputOptions.sanitizeFileName(name ||
  19551. (preservePath
  19552. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  19553. : getChunkNameFromModule(facadedModule)));
  19554. }
  19555. }
  19556. checkCircularDependencyImport(variable, importingModule) {
  19557. const variableModule = variable.module;
  19558. if (variableModule instanceof Module) {
  19559. const exportChunk = this.chunkByModule.get(variableModule);
  19560. let alternativeReexportModule;
  19561. do {
  19562. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  19563. if (alternativeReexportModule) {
  19564. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  19565. if (exportingChunk !== exportChunk) {
  19566. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCyclicCrossChunkReexport(
  19567. // Namespaces do not have an export name
  19568. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  19569. }
  19570. importingModule = alternativeReexportModule;
  19571. }
  19572. } while (alternativeReexportModule);
  19573. }
  19574. }
  19575. ensureReexportsAreAvailableForModule(module) {
  19576. const includedReexports = [];
  19577. const map = module.getExportNamesByVariable();
  19578. for (const exportedVariable of map.keys()) {
  19579. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  19580. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  19581. this.checkCircularDependencyImport(importedVariable, module);
  19582. // When preserving modules, we do not create namespace objects but directly
  19583. // use the actual namespaces, which would be broken by this logic.
  19584. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19585. const exportingModule = importedVariable.module;
  19586. if (exportingModule instanceof Module) {
  19587. const chunk = this.chunkByModule.get(exportingModule);
  19588. if (chunk && chunk !== this) {
  19589. chunk.exports.add(importedVariable);
  19590. includedReexports.push(importedVariable);
  19591. if (isSynthetic) {
  19592. this.imports.add(importedVariable);
  19593. }
  19594. }
  19595. }
  19596. }
  19597. }
  19598. if (includedReexports.length > 0) {
  19599. this.includedReexportsByModule.set(module, includedReexports);
  19600. }
  19601. }
  19602. generateVariableName() {
  19603. if (this.manualChunkAlias) {
  19604. return this.manualChunkAlias;
  19605. }
  19606. const moduleForNaming = this.entryModules[0] ||
  19607. this.implicitEntryModules[0] ||
  19608. this.dynamicEntryModules[0] ||
  19609. this.orderedModules[this.orderedModules.length - 1];
  19610. if (moduleForNaming) {
  19611. return getChunkNameFromModule(moduleForNaming);
  19612. }
  19613. return 'chunk';
  19614. }
  19615. getChunkExportDeclarations(format) {
  19616. const exports$1 = [];
  19617. for (const exportName of this.getExportNames()) {
  19618. if (exportName[0] === '*')
  19619. continue;
  19620. const variable = this.exportsByName.get(exportName);
  19621. if (!(variable instanceof SyntheticNamedExportVariable)) {
  19622. const module = variable.module;
  19623. if (module) {
  19624. const chunk = this.chunkByModule.get(module);
  19625. if (chunk !== this) {
  19626. if (!chunk || format !== 'es') {
  19627. continue;
  19628. }
  19629. const chunkDep = this.renderedDependencies.get(chunk);
  19630. if (!chunkDep) {
  19631. continue;
  19632. }
  19633. const { imports, reexports } = chunkDep;
  19634. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  19635. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  19636. if (!isImported) {
  19637. continue;
  19638. }
  19639. }
  19640. }
  19641. }
  19642. let expression = null;
  19643. let hoisted = false;
  19644. let local = variable.getName(this.snippets.getPropertyAccess);
  19645. if (variable instanceof LocalVariable) {
  19646. for (const declaration of variable.declarations) {
  19647. if (declaration.parent instanceof FunctionDeclaration ||
  19648. (declaration instanceof ExportDefaultDeclaration &&
  19649. declaration.declaration instanceof FunctionDeclaration)) {
  19650. hoisted = true;
  19651. break;
  19652. }
  19653. }
  19654. }
  19655. else if (variable instanceof SyntheticNamedExportVariable) {
  19656. expression = local;
  19657. if (format === 'es') {
  19658. local = variable.renderName;
  19659. }
  19660. }
  19661. exports$1.push({
  19662. exported: exportName,
  19663. expression,
  19664. hoisted,
  19665. local
  19666. });
  19667. }
  19668. return exports$1;
  19669. }
  19670. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  19671. const dependencies = new Set();
  19672. const deconflictedDefault = new Set();
  19673. const deconflictedNamespace = new Set();
  19674. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  19675. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  19676. const module = variable.module;
  19677. if (module instanceof ExternalModule) {
  19678. const chunk = this.externalChunkByModule.get(module);
  19679. dependencies.add(chunk);
  19680. if (addNonNamespacesAndInteropHelpers) {
  19681. if (variable.name === 'default') {
  19682. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  19683. deconflictedDefault.add(chunk);
  19684. }
  19685. }
  19686. else if (variable.isNamespace &&
  19687. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  19688. (this.imports.has(variable) ||
  19689. !this.exportNamesByVariable.get(variable)?.every(name => name[0] === '*'))) {
  19690. // We only need to deconflict it if the namespace is actually
  19691. // created as a variable, i.e. because it is used internally or
  19692. // because it is reexported as an object
  19693. deconflictedNamespace.add(chunk);
  19694. }
  19695. }
  19696. }
  19697. else {
  19698. const chunk = this.chunkByModule.get(module);
  19699. if (chunk !== this) {
  19700. dependencies.add(chunk);
  19701. if (addNonNamespacesAndInteropHelpers &&
  19702. chunk.exportMode === 'default' &&
  19703. variable.isNamespace) {
  19704. deconflictedNamespace.add(chunk);
  19705. }
  19706. }
  19707. }
  19708. }
  19709. }
  19710. if (addDependenciesWithoutBindings) {
  19711. for (const dependency of this.dependencies) {
  19712. dependencies.add(dependency);
  19713. }
  19714. }
  19715. return { deconflictedDefault, deconflictedNamespace, dependencies };
  19716. }
  19717. getDynamicDependencies() {
  19718. return this.getIncludedDynamicImports()
  19719. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  19720. resolvedDynamicImport.chunk ||
  19721. resolvedDynamicImport.externalChunk ||
  19722. resolvedDynamicImport.resolution)
  19723. .filter((resolution) => resolution !== this &&
  19724. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  19725. }
  19726. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  19727. const { externalImportAttributes } = this.outputOptions;
  19728. const keepExternalImportAttributes = ['es', 'cjs'].includes(this.outputOptions.format) && externalImportAttributes;
  19729. if (resolution instanceof ExternalModule) {
  19730. const chunk = this.externalChunkByModule.get(resolution);
  19731. const dynamicAttributes = chunk.getImportAttributes(this.snippets);
  19732. return [
  19733. `'${chunk.getImportPath(fileName)}'`,
  19734. dynamicAttributes || (keepExternalImportAttributes ? true : null)
  19735. ];
  19736. }
  19737. let attributes = null;
  19738. if (keepExternalImportAttributes) {
  19739. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  19740. attributes =
  19741. attributesFromImportAttributes === parseAst_js.EMPTY_OBJECT
  19742. ? true
  19743. : formatAttributes(attributesFromImportAttributes, this.snippets);
  19744. }
  19745. return [resolution || '', attributes];
  19746. }
  19747. getFallbackChunkName() {
  19748. if (this.manualChunkAlias) {
  19749. return this.manualChunkAlias;
  19750. }
  19751. if (this.dynamicName) {
  19752. return this.dynamicName;
  19753. }
  19754. if (this.fileName) {
  19755. return parseAst_js.getAliasName(this.fileName);
  19756. }
  19757. return parseAst_js.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  19758. }
  19759. getImportSpecifiers() {
  19760. const { interop } = this.outputOptions;
  19761. const importsByDependency = new Map();
  19762. for (const variable of this.imports) {
  19763. const module = variable.module;
  19764. let dependency;
  19765. let imported;
  19766. const isSourcePhase = module instanceof ExternalModule && variable.isSourcePhase;
  19767. if (module instanceof ExternalModule) {
  19768. dependency = this.externalChunkByModule.get(module);
  19769. imported = variable.name;
  19770. if (!isSourcePhase &&
  19771. imported !== 'default' &&
  19772. imported !== '*' &&
  19773. interop(module.id) === 'defaultOnly') {
  19774. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, false));
  19775. }
  19776. }
  19777. else {
  19778. dependency = this.chunkByModule.get(module);
  19779. imported = dependency.getVariableExportName(variable);
  19780. }
  19781. getOrCreate(importsByDependency, dependency, getNewArray).push({
  19782. imported,
  19783. local: variable.getName(this.snippets.getPropertyAccess),
  19784. phase: isSourcePhase ? 'source' : 'instance'
  19785. });
  19786. }
  19787. return importsByDependency;
  19788. }
  19789. getIncludedDynamicImports() {
  19790. if (this.includedDynamicImports) {
  19791. return this.includedDynamicImports;
  19792. }
  19793. const includedDynamicImports = [];
  19794. for (const module of this.orderedModules) {
  19795. for (const { node } of module.dynamicImports) {
  19796. if (!node.included) {
  19797. continue;
  19798. }
  19799. const { resolution } = node;
  19800. includedDynamicImports.push(resolution instanceof Module
  19801. ? {
  19802. chunk: this.chunkByModule.get(resolution),
  19803. externalChunk: null,
  19804. facadeChunk: this.facadeChunkByModule.get(resolution),
  19805. node,
  19806. resolution
  19807. }
  19808. : resolution instanceof ExternalModule
  19809. ? {
  19810. chunk: null,
  19811. externalChunk: this.externalChunkByModule.get(resolution),
  19812. facadeChunk: null,
  19813. node,
  19814. resolution
  19815. }
  19816. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  19817. }
  19818. }
  19819. return (this.includedDynamicImports = includedDynamicImports);
  19820. }
  19821. getPreRenderedChunkInfo() {
  19822. if (this.preRenderedChunkInfo) {
  19823. return this.preRenderedChunkInfo;
  19824. }
  19825. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  19826. return (this.preRenderedChunkInfo = {
  19827. exports: this.getExportNames(),
  19828. facadeModuleId: facadeModule && facadeModule.id,
  19829. isDynamicEntry: dynamicEntryModules.length > 0,
  19830. isEntry: !!facadeModule?.info.isEntry,
  19831. isImplicitEntry: implicitEntryModules.length > 0,
  19832. moduleIds: orderedModules.map(({ id }) => id),
  19833. name: this.getChunkName(),
  19834. type: 'chunk'
  19835. });
  19836. }
  19837. getPreserveModulesChunkNameFromModule(module) {
  19838. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  19839. if (predefinedChunkName)
  19840. return predefinedChunkName;
  19841. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  19842. const sanitizedId = sanitizeFileName(parseAst_js.normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  19843. const extensionName = path.extname(sanitizedId);
  19844. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  19845. ? sanitizedId.slice(0, -extensionName.length)
  19846. : sanitizedId;
  19847. if (parseAst_js.isAbsolute(idWithoutExtension)) {
  19848. if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
  19849. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  19850. }
  19851. else {
  19852. // handle edge case in Windows
  19853. if (this.inputBase === '/' && idWithoutExtension[0] !== '/') {
  19854. return parseAst_js.relative(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  19855. }
  19856. return parseAst_js.relative(this.inputBase, idWithoutExtension);
  19857. }
  19858. }
  19859. else {
  19860. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
  19861. }
  19862. }
  19863. getReexportSpecifiers() {
  19864. const { externalLiveBindings, interop } = this.outputOptions;
  19865. const reexportSpecifiers = new Map();
  19866. for (let exportName of this.getExportNames()) {
  19867. let dependency;
  19868. let imported;
  19869. let needsLiveBinding;
  19870. if (exportName[0] === '*') {
  19871. const id = exportName.slice(1);
  19872. if (interop(id) === 'defaultOnly') {
  19873. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnexpectedNamespaceReexport(id));
  19874. }
  19875. needsLiveBinding = externalLiveBindings;
  19876. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  19877. imported = exportName = '*';
  19878. }
  19879. else {
  19880. const variable = this.exportsByName.get(exportName);
  19881. if (variable instanceof SyntheticNamedExportVariable)
  19882. continue;
  19883. const module = variable.module;
  19884. if (module instanceof Module) {
  19885. dependency = this.chunkByModule.get(module);
  19886. if (dependency === this)
  19887. continue;
  19888. imported = dependency.getVariableExportName(variable);
  19889. needsLiveBinding = variable.isReassigned;
  19890. }
  19891. else {
  19892. dependency = this.externalChunkByModule.get(module);
  19893. imported = variable.name;
  19894. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  19895. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, true));
  19896. }
  19897. needsLiveBinding =
  19898. externalLiveBindings &&
  19899. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  19900. }
  19901. }
  19902. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  19903. imported,
  19904. needsLiveBinding,
  19905. reexported: exportName
  19906. });
  19907. }
  19908. return reexportSpecifiers;
  19909. }
  19910. getReferencedFiles() {
  19911. const referencedFiles = new Set();
  19912. for (const module of this.orderedModules) {
  19913. for (const meta of module.importMetas) {
  19914. const fileName = meta.getReferencedFileName(this.pluginDriver);
  19915. if (fileName) {
  19916. referencedFiles.add(fileName);
  19917. }
  19918. }
  19919. }
  19920. return [...referencedFiles];
  19921. }
  19922. getRenderedDependencies() {
  19923. if (this.renderedDependencies) {
  19924. return this.renderedDependencies;
  19925. }
  19926. const importSpecifiers = this.getImportSpecifiers();
  19927. const reexportSpecifiers = this.getReexportSpecifiers();
  19928. const renderedDependencies = new Map();
  19929. const fileName = this.getFileName();
  19930. for (const dependency of this.dependencies) {
  19931. const imports = importSpecifiers.get(dependency) || null;
  19932. const reexports = reexportSpecifiers.get(dependency) || null;
  19933. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  19934. const importPath = dependency.getImportPath(fileName);
  19935. // Separate source-phase imports from regular imports
  19936. const sourcePhaseImport = imports?.find(index => index.phase === 'source');
  19937. const instanceImports = imports?.filter(index => index.phase !== 'source') ?? null;
  19938. renderedDependencies.set(dependency, {
  19939. attributes: dependency instanceof ExternalChunk
  19940. ? dependency.getImportAttributes(this.snippets)
  19941. : null,
  19942. defaultVariableName: dependency.defaultVariableName,
  19943. globalName: dependency instanceof ExternalChunk &&
  19944. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  19945. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  19946. importPath,
  19947. imports: instanceImports && instanceImports.length > 0 ? instanceImports : null,
  19948. isChunk: dependency instanceof Chunk,
  19949. name: dependency.variableName,
  19950. namedExportsMode,
  19951. namespaceVariableName: dependency.namespaceVariableName,
  19952. reexports,
  19953. sourcePhaseImport: sourcePhaseImport?.local
  19954. });
  19955. }
  19956. return (this.renderedDependencies = renderedDependencies);
  19957. }
  19958. inlineChunkDependencies(chunk) {
  19959. for (const dep of chunk.dependencies) {
  19960. if (this.dependencies.has(dep))
  19961. continue;
  19962. this.dependencies.add(dep);
  19963. if (dep instanceof Chunk) {
  19964. this.inlineChunkDependencies(dep);
  19965. }
  19966. }
  19967. }
  19968. // This method changes properties on the AST before rendering and must not be async
  19969. renderModules(fileName) {
  19970. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  19971. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  19972. const { _, cnst, n } = snippets;
  19973. this.setDynamicImportResolutions(fileName);
  19974. this.setImportMetaResolutions(fileName);
  19975. this.setIdentifierRenderResolutions();
  19976. const magicString = new Bundle$1({ separator: `${n}${n}` });
  19977. const indent = getIndentString(orderedModules, outputOptions);
  19978. const usedModules = [];
  19979. let hoistedSource = '';
  19980. const accessedGlobals = new Set();
  19981. const renderedModuleSources = new Map();
  19982. const renderOptions = {
  19983. accessedDocumentCurrentScript: false,
  19984. exportNamesByVariable,
  19985. format,
  19986. freeze,
  19987. importAttributesKey,
  19988. indent,
  19989. pluginDriver,
  19990. snippets,
  19991. symbols,
  19992. useOriginalName: null
  19993. };
  19994. let usesTopLevelAwait = false;
  19995. for (const module of orderedModules) {
  19996. let renderedLength = 0;
  19997. let source;
  19998. if (module.isIncluded() || includedNamespaces.has(module)) {
  19999. const rendered = module.render(renderOptions);
  20000. if (!renderOptions.accessedDocumentCurrentScript &&
  20001. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  20002. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  20003. }
  20004. renderOptions.accessedDocumentCurrentScript = false;
  20005. ({ source } = rendered);
  20006. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  20007. renderedLength = source.length();
  20008. if (renderedLength) {
  20009. if (compact && source.lastLine().includes('//'))
  20010. source.append('\n');
  20011. renderedModuleSources.set(module, source);
  20012. magicString.addSource(source);
  20013. usedModules.push(module);
  20014. }
  20015. const namespace = module.namespace;
  20016. if (includedNamespaces.has(module)) {
  20017. const rendered = namespace.renderBlock(renderOptions);
  20018. if (namespace.renderFirst())
  20019. hoistedSource += n + rendered;
  20020. else
  20021. magicString.addSource(new MagicString(rendered));
  20022. }
  20023. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  20024. if (accessedGlobalVariables) {
  20025. for (const name of accessedGlobalVariables) {
  20026. accessedGlobals.add(name);
  20027. }
  20028. }
  20029. }
  20030. const { renderedExports, removedExports } = module.getRenderedExports();
  20031. renderedModules[module.id] = {
  20032. get code() {
  20033. return source?.toString() ?? null;
  20034. },
  20035. originalLength: module.originalCode.length,
  20036. removedExports,
  20037. renderedExports,
  20038. renderedLength
  20039. };
  20040. }
  20041. if (hoistedSource)
  20042. magicString.prepend(hoistedSource + n + n);
  20043. if (this.needsExportsShim) {
  20044. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  20045. }
  20046. const renderedSource = compact ? magicString : magicString.trim();
  20047. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  20048. onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyChunk(this.getChunkName()));
  20049. }
  20050. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  20051. }
  20052. setDynamicImportResolutions(fileName) {
  20053. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  20054. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  20055. if (resolvedDynamicImport.chunk) {
  20056. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  20057. if (chunk === this) {
  20058. node.setInternalResolution(resolution.namespace);
  20059. }
  20060. else {
  20061. node.setExternalResolution((facadeChunk || chunk).exportMode, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  20062. }
  20063. }
  20064. else {
  20065. const { node, resolution } = resolvedDynamicImport;
  20066. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  20067. node.setExternalResolution('external', outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  20068. }
  20069. }
  20070. }
  20071. setIdentifierRenderResolutions() {
  20072. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  20073. const syntheticExports = new Set();
  20074. for (const exportName of this.getExportNames()) {
  20075. const exportVariable = this.exportsByName.get(exportName);
  20076. if (format !== 'es' &&
  20077. format !== 'system' &&
  20078. exportVariable.isReassigned &&
  20079. !exportVariable.isId) {
  20080. exportVariable.setRenderNames('exports', exportName);
  20081. }
  20082. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  20083. syntheticExports.add(exportVariable);
  20084. }
  20085. else {
  20086. exportVariable.setRenderNames(null, null);
  20087. }
  20088. }
  20089. for (const module of this.orderedModules) {
  20090. if (module.needsExportShim) {
  20091. this.needsExportsShim = true;
  20092. break;
  20093. }
  20094. }
  20095. const usedNames = new Set(RESERVED_USED_NAMES);
  20096. if (this.needsExportsShim) {
  20097. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  20098. }
  20099. if (symbols) {
  20100. usedNames.add('Symbol');
  20101. }
  20102. 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);
  20103. }
  20104. setImportMetaResolutions(fileName) {
  20105. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  20106. for (const module of orderedModules) {
  20107. for (const importMeta of module.importMetas) {
  20108. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  20109. }
  20110. if (includedNamespaces.has(module)) {
  20111. module.namespace.prepare(accessedGlobalsByScope);
  20112. }
  20113. }
  20114. }
  20115. setUpChunkImportsAndExportsForModule(module) {
  20116. const moduleImports = new Set(module.includedImports);
  20117. // when we are not preserving modules, we need to make all namespace variables available for
  20118. // rendering the namespace object
  20119. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  20120. for (const variable of module.getExportedVariablesByName().values()) {
  20121. if (variable.included) {
  20122. moduleImports.add(variable);
  20123. }
  20124. }
  20125. }
  20126. for (let variable of moduleImports) {
  20127. if (variable instanceof ExportDefaultVariable) {
  20128. variable = variable.getOriginalVariable();
  20129. }
  20130. if (variable instanceof SyntheticNamedExportVariable) {
  20131. variable = variable.getBaseVariable();
  20132. }
  20133. const chunk = this.chunkByModule.get(variable.module);
  20134. if (chunk !== this) {
  20135. this.imports.add(variable);
  20136. if (variable.module instanceof Module) {
  20137. this.checkCircularDependencyImport(variable, module);
  20138. // When preserving modules, we do not create namespace objects but directly
  20139. // use the actual namespaces, which would be broken by this logic.
  20140. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  20141. chunk.exports.add(variable);
  20142. }
  20143. }
  20144. }
  20145. }
  20146. if (this.includedNamespaces.has(module) ||
  20147. (module.info.isEntry && module.preserveSignature !== false) ||
  20148. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  20149. this.ensureReexportsAreAvailableForModule(module);
  20150. }
  20151. for (const { node: { included, resolution } } of module.dynamicImports) {
  20152. if (included &&
  20153. resolution instanceof Module &&
  20154. this.chunkByModule.get(resolution) === this &&
  20155. !this.includedNamespaces.has(resolution)) {
  20156. this.includedNamespaces.add(resolution);
  20157. this.ensureReexportsAreAvailableForModule(resolution);
  20158. }
  20159. }
  20160. }
  20161. }
  20162. function getChunkNameFromModule(module) {
  20163. return getPredefinedChunkNameFromModule(module) ?? parseAst_js.getAliasName(module.id);
  20164. }
  20165. function getPredefinedChunkNameFromModule(module) {
  20166. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  20167. }
  20168. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  20169. const importedBindingsPerDependency = {};
  20170. for (const [dependency, declaration] of renderedDependencies) {
  20171. const specifiers = new Set();
  20172. if (declaration.imports) {
  20173. for (const { imported } of declaration.imports) {
  20174. specifiers.add(imported);
  20175. }
  20176. }
  20177. if (declaration.reexports) {
  20178. for (const { imported } of declaration.reexports) {
  20179. specifiers.add(imported);
  20180. }
  20181. }
  20182. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  20183. }
  20184. return importedBindingsPerDependency;
  20185. }
  20186. const QUERY_HASH_REGEX = /[#?]/;
  20187. const resolveFileName = (dependency) => dependency.getFileName();
  20188. /**
  20189. * Concatenate a number of iterables to a new iterable without fully evaluating
  20190. * their iterators. Useful when e.g. working with large sets or lists and when
  20191. * there is a chance that the iterators will not be fully exhausted.
  20192. */
  20193. function* concatLazy(iterables) {
  20194. for (const iterable of iterables) {
  20195. yield* iterable;
  20196. }
  20197. }
  20198. /**
  20199. * At its core, the algorithm first starts from each static or dynamic entry
  20200. * point and then assigns that entry point to all modules than can be reached
  20201. * via static imports. We call this the *dependent entry points* of that
  20202. * module.
  20203. *
  20204. * Then we group all modules with the same dependent entry points into chunks
  20205. * as those modules will always be loaded together.
  20206. *
  20207. * One non-trivial optimization we can apply is that dynamic entries are
  20208. * different from static entries in so far as when a dynamic import occurs,
  20209. * some modules are already in memory. If some of these modules are also
  20210. * dependencies of the dynamic entry, then it does not make sense to create a
  20211. * separate chunk for them. Instead, the dynamic import target can load them
  20212. * from the importing chunk.
  20213. *
  20214. * With regard to chunking, if B is implicitly loaded after A, then this can be
  20215. * handled the same way as if there was a dynamic import A => B.
  20216. *
  20217. * Example:
  20218. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  20219. * Then the initial algorithm would assign A into the A chunk, C into the C
  20220. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  20221. * points A and C.
  20222. * However we know that C can only be loaded from A, so A and its dependency B
  20223. * must already be in memory when C is loaded. So it is enough to create only
  20224. * two chunks A containing [AB] and C containing [C].
  20225. *
  20226. * So we do not assign the dynamic entry C as dependent entry point to modules
  20227. * that are already loaded.
  20228. *
  20229. * In a more complex example, let us assume that we have entry points X and Y.
  20230. * Further, let us assume
  20231. * X -> A, X -> B, X -> C,
  20232. * Y -> A, Y -> B,
  20233. * A => D,
  20234. * D -> B, D -> C
  20235. * So without dynamic import optimization, the dependent entry points are
  20236. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  20237. * chunks.
  20238. *
  20239. * Now D is loaded only after A is loaded. But A is loaded if either X is
  20240. * loaded or Y is loaded. So the modules that are already in memory when D is
  20241. * loaded are the intersection of all modules that X depends on with all
  20242. * modules that Y depends on, which in this case are the modules A and B.
  20243. * We could also say they are all modules that have both X and Y as dependent
  20244. * entry points.
  20245. *
  20246. * So we can remove D as dependent entry point from A and B, which means they
  20247. * both now have only XY as dependent entry points and can be merged into the
  20248. * same chunk.
  20249. *
  20250. * Now let us extend this to the most general case where we have several
  20251. * dynamic importers for one dynamic entry point.
  20252. *
  20253. * In the most general form, it works like this:
  20254. * For each dynamic entry point, we have a number of dynamic importers, which
  20255. * are the modules importing it. Using the previous ideas, we can determine
  20256. * the modules already in memory for each dynamic importer by looking for all
  20257. * modules that have all the dependent entry points of the dynamic importer as
  20258. * dependent entry points.
  20259. * So the modules that are guaranteed to be in memory when the dynamic entry
  20260. * point is loaded are the intersection of the modules already in memory for
  20261. * each dynamic importer.
  20262. *
  20263. * Assuming that A => D and B => D and A has dependent entry points XY and B
  20264. * has dependent entry points YZ, then the modules guaranteed to be in memory
  20265. * are all modules that have at least XYZ as dependent entry points.
  20266. * We call XYZ the *dynamically dependent entry points* of D.
  20267. *
  20268. * Now there is one last case to consider: If one of the dynamically dependent
  20269. * entries is itself a dynamic entry, then any module is in memory that either
  20270. * is a dependency of that dynamic entry or again has the dynamic dependent
  20271. * entries of that dynamic entry as dependent entry points.
  20272. *
  20273. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  20274. * complexity with regard to dynamic entries that blew up for very large
  20275. * projects.
  20276. *
  20277. * If we have an efficient way to do Set operations, an alternative approach
  20278. * would be to instead collect already loaded modules per dynamic entry. And as
  20279. * all chunks from the initial grouping would behave the same, we can instead
  20280. * collect already loaded chunks for a performance improvement.
  20281. *
  20282. * To do that efficiently, need
  20283. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  20284. * imports that can be triggered by a dynamic entry
  20285. * - a Map of static dependencies per entry
  20286. * - a Map of already loaded chunks per entry that we initially populate with
  20287. * empty Sets for static entries and Sets containing all entries for dynamic
  20288. * entries
  20289. *
  20290. * For efficient operations, we assign each entry a numerical index and
  20291. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  20292. * bit index. Then the last two maps can be represented as arrays of BigInt
  20293. * values.
  20294. *
  20295. * Then we iterate through each dynamic entry. We set the already loaded modules
  20296. * to the intersection of the previously already loaded modules with the union
  20297. * of the already loaded modules of that chunk with its static dependencies.
  20298. *
  20299. * If the already loaded modules changed, then we use the Map of dynamic imports
  20300. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  20301. * them back into the iteration. As an additional optimization, we note for
  20302. * each dynamic entry which dynamic dependent entries have changed and only
  20303. * intersect those entries again on subsequent interations.
  20304. *
  20305. * Then we remove the dynamic entries from the list of dependent entries for
  20306. * those chunks that are already loaded for that dynamic entry and create
  20307. * another round of chunks.
  20308. */
  20309. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  20310. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks);
  20311. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  20312. // Each chunk is identified by its position in this array
  20313. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, modulesInManualChunks, chunkDefinitions));
  20314. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  20315. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  20316. // If we no longer want this, we should make a copy here.
  20317. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  20318. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  20319. // This mutates the dependentEntries in chunkAtoms
  20320. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  20321. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  20322. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  20323. alias: null,
  20324. modules
  20325. })));
  20326. return chunkDefinitions;
  20327. }
  20328. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  20329. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  20330. const manualChunkModulesByAlias = Object.create(null);
  20331. const sortedEntriesWithAlias = [...manualChunkAliasByEntry].sort(([entryA], [entryB]) => entryA.execIndex - entryB.execIndex);
  20332. for (const [entry, alias] of sortedEntriesWithAlias) {
  20333. if (isManualChunksFunctionForm && onlyExplicitManualChunks) {
  20334. (manualChunkModulesByAlias[alias] ||= []).push(entry);
  20335. }
  20336. else {
  20337. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  20338. }
  20339. }
  20340. const manualChunks = Object.entries(manualChunkModulesByAlias);
  20341. const chunkDefinitions = new Array(manualChunks.length);
  20342. let index = 0;
  20343. for (const [alias, modules] of manualChunks) {
  20344. chunkDefinitions[index++] = { alias, modules };
  20345. }
  20346. return { chunkDefinitions, modulesInManualChunks };
  20347. }
  20348. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  20349. const modulesToHandle = new Set([entry]);
  20350. for (const module of modulesToHandle) {
  20351. modulesInManualChunks.add(module);
  20352. manualChunkModules.push(module);
  20353. for (const dependency of module.dependencies) {
  20354. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  20355. modulesToHandle.add(dependency);
  20356. }
  20357. }
  20358. }
  20359. }
  20360. function analyzeModuleGraph(entries) {
  20361. const dynamicEntryModules = new Set();
  20362. const awaitedDynamicEntryModules = new Set();
  20363. const dependentEntriesByModule = new Map();
  20364. const allEntriesSet = new Set(entries);
  20365. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  20366. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  20367. let entryIndex = 0;
  20368. for (const currentEntry of allEntriesSet) {
  20369. const dynamicImportsForCurrentEntry = new Set();
  20370. const awaitedDynamicImportsForCurrentEntry = new Set();
  20371. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  20372. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  20373. const staticDependencies = new Set([currentEntry]);
  20374. for (const module of staticDependencies) {
  20375. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  20376. for (const dependency of module.getDependenciesToBeIncluded()) {
  20377. if (!(dependency instanceof ExternalModule)) {
  20378. staticDependencies.add(dependency);
  20379. }
  20380. }
  20381. for (const { node: { resolution } } of module.dynamicImports) {
  20382. if (resolution instanceof Module &&
  20383. resolution.includedDynamicImporters.length > 0 &&
  20384. !allEntriesSet.has(resolution)) {
  20385. dynamicEntryModules.add(resolution);
  20386. allEntriesSet.add(resolution);
  20387. dynamicImportsForCurrentEntry.add(resolution);
  20388. for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
  20389. if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
  20390. awaitedDynamicEntryModules.add(resolution);
  20391. awaitedDynamicImportsForCurrentEntry.add(resolution);
  20392. break;
  20393. }
  20394. }
  20395. }
  20396. }
  20397. for (const dependency of module.implicitlyLoadedBefore) {
  20398. if (!allEntriesSet.has(dependency)) {
  20399. dynamicEntryModules.add(dependency);
  20400. allEntriesSet.add(dependency);
  20401. }
  20402. }
  20403. }
  20404. entryIndex++;
  20405. }
  20406. const allEntries = [...allEntriesSet];
  20407. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  20408. return {
  20409. allEntries,
  20410. awaitedDynamicImportsByEntry,
  20411. dependentEntriesByModule,
  20412. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
  20413. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  20414. dynamicImportsByEntry
  20415. };
  20416. }
  20417. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  20418. const entryIndexByModule = new Map();
  20419. const dynamicEntries = new Set();
  20420. const awaitedDynamicEntries = new Set();
  20421. for (const [entryIndex, entry] of allEntries.entries()) {
  20422. entryIndexByModule.set(entry, entryIndex);
  20423. if (dynamicEntryModules.has(entry)) {
  20424. dynamicEntries.add(entryIndex);
  20425. }
  20426. if (awaitedDynamicEntryModules.has(entry)) {
  20427. awaitedDynamicEntries.add(entryIndex);
  20428. }
  20429. }
  20430. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  20431. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  20432. return {
  20433. awaitedDynamicEntries,
  20434. awaitedDynamicImportsByEntry,
  20435. dynamicEntries,
  20436. dynamicImportsByEntry
  20437. };
  20438. }
  20439. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  20440. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  20441. let index = 0;
  20442. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  20443. const dynamicImports = new Set();
  20444. for (const dynamicEntry of dynamicImportModules) {
  20445. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  20446. }
  20447. dynamicImportsByEntry[index++] = dynamicImports;
  20448. }
  20449. return dynamicImportsByEntry;
  20450. }
  20451. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  20452. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  20453. for (const dynamicEntryIndex of dynamicEntries) {
  20454. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  20455. const dynamicEntry = allEntries[dynamicEntryIndex];
  20456. for (const importer of concatLazy([
  20457. getDynamicImporters(dynamicEntry),
  20458. dynamicEntry.implicitlyLoadedAfter
  20459. ])) {
  20460. const importerEntries = dependentEntriesByModule.get(importer);
  20461. if (!importerEntries) {
  20462. continue;
  20463. }
  20464. for (const entry of importerEntries) {
  20465. dynamicallyDependentEntries.add(entry);
  20466. }
  20467. }
  20468. }
  20469. return dynamicallyDependentEntriesByDynamicEntry;
  20470. }
  20471. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  20472. const chunkModules = Object.create(null);
  20473. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  20474. let chunkSignature = 0n;
  20475. for (const entryIndex of dependentEntries) {
  20476. chunkSignature |= 1n << BigInt(entryIndex);
  20477. }
  20478. (chunkModules[String(chunkSignature)] ||= {
  20479. dependentEntries: new Set(dependentEntries),
  20480. modules: []
  20481. }).modules.push(...modules);
  20482. }
  20483. return Object.values(chunkModules);
  20484. }
  20485. function* getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, modulesInManualChunks, chunkDefinitions) {
  20486. for (const [module, dependentEntries] of dependentEntriesByModule) {
  20487. if (!modulesInManualChunks.has(module)) {
  20488. if (module.cycles.size > 0 && module.includedTopLevelAwaitingDynamicImporters.size > 0) {
  20489. chunkDefinitions.push({
  20490. alias: null,
  20491. modules: [module]
  20492. });
  20493. continue;
  20494. }
  20495. yield { dependentEntries, modules: [module] };
  20496. }
  20497. }
  20498. }
  20499. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  20500. // The indices correspond to the indices in allEntries. The atoms correspond
  20501. // to bits in the bigint values where chunk 0 is the lowest bit.
  20502. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  20503. // This toggles the bits for each atom that is a dependency of an entry
  20504. let atomMask = 1n;
  20505. for (const { dependentEntries } of chunkAtoms) {
  20506. for (const entryIndex of dependentEntries) {
  20507. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  20508. }
  20509. atomMask <<= 1n;
  20510. }
  20511. return staticDependencyAtomsByEntry;
  20512. }
  20513. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  20514. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  20515. // Dynamic entries have all atoms as already loaded initially because we then
  20516. // intersect with the static dependency atoms of all dynamic importers.
  20517. // Static entries cannot have already loaded atoms.
  20518. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  20519. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  20520. // We delete here so that they can be added again if necessary to be handled
  20521. // again by the loop
  20522. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  20523. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  20524. let updatedLoadedAtoms = knownLoadedAtoms;
  20525. for (const entryIndex of dynamicallyDependentEntries) {
  20526. updatedLoadedAtoms &=
  20527. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  20528. }
  20529. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  20530. // updated again
  20531. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  20532. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  20533. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  20534. // If this adds an entry that was deleted before, it will be handled
  20535. // again. This is the reason why we delete every entry from this map
  20536. // that we processed.
  20537. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  20538. }
  20539. }
  20540. }
  20541. return alreadyLoadedAtomsByEntry;
  20542. }
  20543. /**
  20544. * This removes all unnecessary dynamic entries from the dependentEntries in its
  20545. * first argument if a chunk is already loaded without that entry.
  20546. */
  20547. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  20548. // Remove entries from dependent entries if a chunk is already loaded without
  20549. // that entry. Do not remove already loaded atoms where some dynamic imports
  20550. // are awaited to avoid cycles in the output.
  20551. let chunkMask = 1n;
  20552. for (const { dependentEntries } of chunkAtoms) {
  20553. for (const entryIndex of dependentEntries) {
  20554. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  20555. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  20556. dependentEntries.delete(entryIndex);
  20557. }
  20558. }
  20559. chunkMask <<= 1n;
  20560. }
  20561. }
  20562. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  20563. const chunksBySignature = Object.create(null);
  20564. const chunkByModule = new Map();
  20565. const sizeByAtom = new Array(chunkAtoms.length);
  20566. let sideEffectAtoms = 0n;
  20567. let atomMask = 1n;
  20568. let index = 0;
  20569. for (const { dependentEntries, modules } of chunkAtoms) {
  20570. let chunkSignature = 0n;
  20571. let correlatedAtoms = -1n;
  20572. for (const entryIndex of dependentEntries) {
  20573. chunkSignature |= 1n << BigInt(entryIndex);
  20574. // Correlated atoms are the atoms that are guaranteed to be loaded as
  20575. // well when a given atom is loaded. It is the intersection of the already
  20576. // loaded modules of each chunk merged with its static dependencies.
  20577. correlatedAtoms &=
  20578. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  20579. }
  20580. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  20581. containedAtoms: 0n,
  20582. correlatedAtoms,
  20583. dependencies: new Set(),
  20584. dependentChunks: new Set(),
  20585. dependentEntries: new Set(dependentEntries),
  20586. modules: [],
  20587. pure: true,
  20588. size: 0
  20589. });
  20590. let atomSize = 0;
  20591. let pure = true;
  20592. for (const module of modules) {
  20593. chunkByModule.set(module, chunk);
  20594. // Unfortunately, we cannot take tree-shaking into account here because
  20595. // rendering did not happen yet, but we can detect empty modules
  20596. if (module.isIncluded()) {
  20597. pure &&= !module.hasEffects();
  20598. // we use a trivial size for the default minChunkSize to improve
  20599. // performance
  20600. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  20601. }
  20602. }
  20603. if (!pure) {
  20604. sideEffectAtoms |= atomMask;
  20605. }
  20606. sizeByAtom[index++] = atomSize;
  20607. chunk.containedAtoms |= atomMask;
  20608. chunk.modules.push(...modules);
  20609. chunk.pure &&= pure;
  20610. chunk.size += atomSize;
  20611. atomMask <<= 1n;
  20612. }
  20613. const chunks = Object.values(chunksBySignature);
  20614. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  20615. return { chunks, sideEffectAtoms, sizeByAtom };
  20616. }
  20617. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  20618. const signatureByExternalModule = new Map();
  20619. let externalSideEffectAtoms = 0n;
  20620. for (const chunk of chunks) {
  20621. const { dependencies, modules } = chunk;
  20622. for (const module of modules) {
  20623. for (const dependency of module.getDependenciesToBeIncluded()) {
  20624. if (dependency instanceof ExternalModule) {
  20625. if (dependency.info.moduleSideEffects) {
  20626. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  20627. const signature = nextAvailableAtomMask;
  20628. nextAvailableAtomMask <<= 1n;
  20629. externalSideEffectAtoms |= signature;
  20630. return signature;
  20631. });
  20632. chunk.containedAtoms |= signature;
  20633. chunk.correlatedAtoms |= signature;
  20634. }
  20635. }
  20636. else {
  20637. const dependencyChunk = chunkByModule.get(dependency);
  20638. if (dependencyChunk && dependencyChunk !== chunk) {
  20639. dependencies.add(dependencyChunk);
  20640. dependencyChunk.dependentChunks.add(chunk);
  20641. }
  20642. }
  20643. }
  20644. }
  20645. }
  20646. return externalSideEffectAtoms;
  20647. }
  20648. /**
  20649. * This function tries to get rid of small chunks by merging them with other
  20650. * chunks.
  20651. *
  20652. * We can only merge chunks safely if after the merge, loading any entry point
  20653. * in any allowed order will not trigger side effects that should not have been
  20654. * triggered. While side effects are usually things like global function calls,
  20655. * global variable mutations or potentially thrown errors, details do not
  20656. * matter here, and we just discern chunks without side effects (pure chunks)
  20657. * from other chunks.
  20658. *
  20659. * As a first step, we assign each pre-generated chunk with side effects a
  20660. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  20661. *
  20662. * Now to determine the side effects of loading a chunk, one also has to take
  20663. * the side effects of its dependencies into account. So if A depends on B
  20664. * (A -> B) and both have side effects, loading A triggers effects AB.
  20665. *
  20666. * Now from the previous step we know that each chunk is uniquely determine by
  20667. * the entry points that depend on it and cause it to load, which we will call
  20668. * its dependent entry points.
  20669. *
  20670. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  20671. * Starting from that idea, we can determine a set of chunks—and thus a set
  20672. * of side effects—that must have been triggered if a certain chunk has been
  20673. * loaded. Basically, it is the intersection of all chunks loaded by the
  20674. * dependent entry points of a given chunk. We call the corresponding side
  20675. * effects the correlated side effects of that chunk.
  20676. *
  20677. * Example:
  20678. * X -> ABC, Y -> ADE, A-> F, B -> D
  20679. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  20680. * The intersection is ADF. So we know that when A is loaded, D and F must also
  20681. * be in memory even though neither D nor A is a dependency of the other.
  20682. * If all have side effects, we call ADF the correlated side effects of A. The
  20683. * correlated side effects need to remain constant when merging chunks.
  20684. *
  20685. * In contrast, we have the dependency side effects of A, which represents
  20686. * the side effects we trigger if we directly load A. In this example, the
  20687. * dependency side effects are AF.
  20688. * For entry chunks, dependency and correlated side effects are the same.
  20689. *
  20690. * With these concepts, merging chunks is allowed if the correlated side
  20691. * effects of each entry do not change. Thus, we are allowed to merge two
  20692. * chunks if
  20693. *
  20694. * a) the dependency side effects of each chunk are a subset of the correlated
  20695. * side effects of the other chunk, so no additional side effects are
  20696. * triggered for any entry, or
  20697. * b) The dependent entry points of chunk A are a subset of the dependent entry
  20698. * points of chunk B while the dependency side effects of A are a subset of
  20699. * the correlated side effects of B. Because in that scenario, whenever A is
  20700. * loaded, B is loaded as well. But there are cases when B is loaded where A
  20701. * is not loaded. So if we merge the chunks, all dependency side effects of
  20702. * A will be added to the correlated side effects of B, and as the latter is
  20703. * not allowed to change, the former need to be a subset of the latter.
  20704. *
  20705. * Another consideration when merging small chunks into other chunks is to
  20706. * avoid
  20707. * that too much additional code is loaded. This is achieved when the dependent
  20708. * entries of the small chunk are a subset of the dependent entries of the
  20709. * other
  20710. * chunk. Because then when the small chunk is loaded, the other chunk was
  20711. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  20712. * additional size of the small chunk is loaded unnecessarily.
  20713. *
  20714. * So the algorithm performs merges in two passes:
  20715. *
  20716. * 1. First we try to merge small chunks A only into other chunks B if the
  20717. * dependent entries of A are a subset of the dependent entries of B and the
  20718. * dependency side effects of A are a subset of the correlated side effects
  20719. * of B.
  20720. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  20721. * following the rule (a), starting with the smallest chunks to look for
  20722. * possible merge targets.
  20723. */
  20724. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  20725. timeStart('optimize chunks', 3);
  20726. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  20727. if (!chunkPartition) {
  20728. timeEnd('optimize chunks', 3);
  20729. return chunks; // the actual modules
  20730. }
  20731. if (minChunkSize > 1) {
  20732. log('info', parseAst_js.logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  20733. }
  20734. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  20735. if (minChunkSize > 1) {
  20736. log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  20737. }
  20738. timeEnd('optimize chunks', 3);
  20739. return [...chunkPartition.small, ...chunkPartition.big];
  20740. }
  20741. function getPartitionedChunks(chunks, minChunkSize) {
  20742. const smallChunks = [];
  20743. const bigChunks = [];
  20744. for (const chunk of chunks) {
  20745. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  20746. }
  20747. if (smallChunks.length === 0) {
  20748. return null;
  20749. }
  20750. smallChunks.sort(compareChunkSize);
  20751. bigChunks.sort(compareChunkSize);
  20752. return {
  20753. big: new Set(bigChunks),
  20754. small: new Set(smallChunks)
  20755. };
  20756. }
  20757. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  20758. return sizeA - sizeB;
  20759. }
  20760. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  20761. const { small } = chunkPartition;
  20762. for (const mergedChunk of small) {
  20763. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  20764. // In the default case, we do not accept size increases
  20765. minChunkSize <= 1 ? 1 : Infinity);
  20766. if (bestTargetChunk) {
  20767. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  20768. small.delete(mergedChunk);
  20769. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  20770. bestTargetChunk.modules.push(...modules);
  20771. bestTargetChunk.size += size;
  20772. bestTargetChunk.pure &&= pure;
  20773. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  20774. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  20775. bestTargetChunk.containedAtoms |= containedAtoms;
  20776. for (const entry of mergedChunk.dependentEntries) {
  20777. dependentEntries.add(entry);
  20778. }
  20779. for (const dependency of mergedChunk.dependencies) {
  20780. dependencies.add(dependency);
  20781. dependency.dependentChunks.delete(mergedChunk);
  20782. dependency.dependentChunks.add(bestTargetChunk);
  20783. }
  20784. for (const dependentChunk of mergedChunk.dependentChunks) {
  20785. dependentChunks.add(dependentChunk);
  20786. dependentChunk.dependencies.delete(mergedChunk);
  20787. dependentChunk.dependencies.add(bestTargetChunk);
  20788. }
  20789. dependencies.delete(bestTargetChunk);
  20790. dependentChunks.delete(bestTargetChunk);
  20791. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  20792. }
  20793. }
  20794. }
  20795. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  20796. let bestTargetChunk = null;
  20797. // In the default case, we do not accept size increases
  20798. for (const targetChunk of concatLazy([small, big])) {
  20799. if (mergedChunk === targetChunk)
  20800. continue;
  20801. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  20802. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  20803. bestTargetChunk = targetChunk;
  20804. if (additionalSizeAfterMerge === 0)
  20805. break;
  20806. smallestAdditionalSize = additionalSizeAfterMerge;
  20807. }
  20808. }
  20809. return bestTargetChunk;
  20810. }
  20811. /**
  20812. * Determine the additional unused code size that would be added by merging the
  20813. * two chunks. This is not an exact measurement but rather an upper bound. If
  20814. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  20815. * is returned.
  20816. * Merging will not produce cycles if none of the direct non-merged
  20817. * dependencies of a chunk have the other chunk as a transitive dependency.
  20818. */
  20819. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  20820. // The maximum additional unused code size allowed to be added by the merge,
  20821. // taking dependencies into account, needs to be below this number
  20822. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20823. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  20824. return firstSize < currentAdditionalSize
  20825. ? firstSize +
  20826. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  20827. : Infinity;
  20828. }
  20829. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20830. const { correlatedAtoms } = dependencyChunk;
  20831. let dependencyAtoms = dependentChunk.containedAtoms;
  20832. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  20833. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  20834. return Infinity;
  20835. }
  20836. const chunksToCheck = new Set(dependentChunk.dependencies);
  20837. for (const { dependencies, containedAtoms } of chunksToCheck) {
  20838. dependencyAtoms |= containedAtoms;
  20839. const containedSideEffects = containedAtoms & sideEffectAtoms;
  20840. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  20841. return Infinity;
  20842. }
  20843. for (const dependency of dependencies) {
  20844. if (dependency === dependencyChunk) {
  20845. return Infinity;
  20846. }
  20847. chunksToCheck.add(dependency);
  20848. }
  20849. }
  20850. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  20851. }
  20852. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  20853. let size = 0;
  20854. let atomIndex = 0;
  20855. let atomSignature = 1n;
  20856. const { length } = sizeByAtom;
  20857. for (; atomIndex < length; atomIndex++) {
  20858. if ((atoms & atomSignature) === atomSignature) {
  20859. size += sizeByAtom[atomIndex];
  20860. }
  20861. atomSignature <<= 1n;
  20862. if (size >= currentAdditionalSize) {
  20863. return Infinity;
  20864. }
  20865. }
  20866. return size;
  20867. }
  20868. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  20869. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  20870. }
  20871. // ported from https://github.com/substack/node-commondir
  20872. function commondir(files) {
  20873. if (files.length === 0)
  20874. return '/';
  20875. if (files.length === 1)
  20876. return path.dirname(files[0]);
  20877. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  20878. const pathSegments = file.split(/\/+|\\+/);
  20879. let index;
  20880. for (index = 0; commonSegments[index] === pathSegments[index] &&
  20881. index < Math.min(commonSegments.length, pathSegments.length); index++)
  20882. ;
  20883. return commonSegments.slice(0, index);
  20884. }, files[0].split(/\/+|\\+/));
  20885. // Windows correctly handles paths with forward-slashes
  20886. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  20887. }
  20888. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  20889. function sortByExecutionOrder(units) {
  20890. units.sort(compareExecIndex);
  20891. }
  20892. // This process is currently faulty in so far as it only takes the first entry
  20893. // module into account and assumes that dynamic imports are imported in a
  20894. // certain order.
  20895. // A better algorithm would follow every possible execution path and mark which
  20896. // modules are executed before or after which other modules. THen the chunking
  20897. // would need to take care that in each chunk, all modules are always executed
  20898. // in the same sequence.
  20899. function analyseModuleExecution(entryModules) {
  20900. let nextExecIndex = 0;
  20901. const cyclePaths = [];
  20902. const analysedModules = new Set();
  20903. const dynamicImports = new Set();
  20904. const parents = new Map();
  20905. const orderedModules = [];
  20906. const handleSyncLoadedModule = (module, parent) => {
  20907. if (parents.has(module)) {
  20908. if (!analysedModules.has(module)) {
  20909. cyclePaths.push(getCyclePath(module, parent, parents));
  20910. }
  20911. return;
  20912. }
  20913. parents.set(module, parent);
  20914. analyseModule(module);
  20915. };
  20916. const analyseModule = (module) => {
  20917. if (module instanceof Module) {
  20918. for (const dependency of module.dependencies) {
  20919. handleSyncLoadedModule(dependency, module);
  20920. }
  20921. for (const dependency of module.implicitlyLoadedBefore) {
  20922. dynamicImports.add(dependency);
  20923. }
  20924. for (const { node: { resolution, scope } } of module.dynamicImports) {
  20925. if (resolution instanceof Module) {
  20926. if (scope.context.usesTopLevelAwait) {
  20927. handleSyncLoadedModule(resolution, module);
  20928. }
  20929. else {
  20930. dynamicImports.add(resolution);
  20931. }
  20932. }
  20933. }
  20934. orderedModules.push(module);
  20935. }
  20936. module.execIndex = nextExecIndex++;
  20937. analysedModules.add(module);
  20938. };
  20939. for (const currentEntry of entryModules) {
  20940. if (!parents.has(currentEntry)) {
  20941. parents.set(currentEntry, null);
  20942. analyseModule(currentEntry);
  20943. }
  20944. }
  20945. for (const currentEntry of dynamicImports) {
  20946. if (!parents.has(currentEntry)) {
  20947. parents.set(currentEntry, null);
  20948. analyseModule(currentEntry);
  20949. }
  20950. }
  20951. return { cyclePaths, orderedModules };
  20952. }
  20953. function getCyclePath(module, parent, parents) {
  20954. const cycleSymbol = Symbol(module.id);
  20955. const path = [module.id];
  20956. let nextModule = parent;
  20957. module.cycles.add(cycleSymbol);
  20958. while (nextModule !== module) {
  20959. nextModule.cycles.add(cycleSymbol);
  20960. path.push(nextModule.id);
  20961. nextModule = parents.get(nextModule);
  20962. }
  20963. path.push(path[0]);
  20964. path.reverse();
  20965. return path;
  20966. }
  20967. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  20968. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  20969. const cnst = constBindings ? 'const' : 'var';
  20970. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  20971. const getFunctionIntro = arrowFunctions
  20972. ? (parameters, { isAsync, name }) => {
  20973. const singleParameter = parameters.length === 1;
  20974. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  20975. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  20976. }
  20977. : getNonArrowFunctionIntro;
  20978. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  20979. `${getFunctionIntro(parameters, {
  20980. isAsync: false,
  20981. name
  20982. })}${arrowFunctions
  20983. ? lineBreakIndent
  20984. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  20985. : ''
  20986. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  20987. arrowFunctions
  20988. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  20989. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  20990. ];
  20991. const isValidPropertyName = reservedNamesAsProps
  20992. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  20993. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  20994. return {
  20995. _,
  20996. cnst,
  20997. getDirectReturnFunction,
  20998. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  20999. const [left, right] = getDirectReturnFunction(parameters, {
  21000. functionReturn: true,
  21001. lineBreakIndent: null,
  21002. name: null
  21003. });
  21004. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  21005. },
  21006. getFunctionIntro,
  21007. getNonArrowFunctionIntro,
  21008. getObject(fields, { lineBreakIndent }) {
  21009. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  21010. return `{${fields
  21011. .map(([key, value]) => {
  21012. if (key === null)
  21013. return `${prefix}${value}`;
  21014. const keyInObject = stringifyObjectKeyIfNeeded(key);
  21015. return key === value && objectShorthand && key === keyInObject
  21016. ? prefix + key
  21017. : `${prefix}${keyInObject}:${_}${value}`;
  21018. })
  21019. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  21020. },
  21021. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  21022. n,
  21023. s
  21024. };
  21025. }
  21026. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  21027. class Source {
  21028. constructor(filename, content) {
  21029. this.isOriginal = true;
  21030. this.filename = filename;
  21031. this.content = content;
  21032. }
  21033. traceSegment(line, column, name) {
  21034. return { column, line, name, source: this };
  21035. }
  21036. }
  21037. class Link {
  21038. constructor(map, sources) {
  21039. this.sources = sources;
  21040. this.names = map.names;
  21041. this.mappings = map.mappings;
  21042. }
  21043. traceMappings() {
  21044. const sources = [];
  21045. const sourceIndexMap = new Map();
  21046. const sourcesContent = [];
  21047. const names = [];
  21048. const nameIndexMap = new Map();
  21049. const mappings = [];
  21050. for (const line of this.mappings) {
  21051. const tracedLine = [];
  21052. for (const segment of line) {
  21053. if (segment.length === 1)
  21054. continue;
  21055. const source = this.sources[segment[1]];
  21056. if (!source)
  21057. continue;
  21058. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  21059. if (traced) {
  21060. const { column, line, name, source: { content, filename } } = traced;
  21061. let sourceIndex = sourceIndexMap.get(filename);
  21062. if (sourceIndex === undefined) {
  21063. sourceIndex = sources.length;
  21064. sources.push(filename);
  21065. sourceIndexMap.set(filename, sourceIndex);
  21066. sourcesContent[sourceIndex] = content;
  21067. }
  21068. else if (sourcesContent[sourceIndex] == null) {
  21069. sourcesContent[sourceIndex] = content;
  21070. }
  21071. else if (content != null && sourcesContent[sourceIndex] !== content) {
  21072. return parseAst_js.error(parseAst_js.logConflictingSourcemapSources(filename));
  21073. }
  21074. const tracedSegment = [segment[0], sourceIndex, line, column];
  21075. if (name) {
  21076. let nameIndex = nameIndexMap.get(name);
  21077. if (nameIndex === undefined) {
  21078. nameIndex = names.length;
  21079. names.push(name);
  21080. nameIndexMap.set(name, nameIndex);
  21081. }
  21082. tracedSegment[4] = nameIndex;
  21083. }
  21084. tracedLine.push(tracedSegment);
  21085. }
  21086. }
  21087. mappings.push(tracedLine);
  21088. }
  21089. return { mappings, names, sources, sourcesContent };
  21090. }
  21091. traceSegment(line, column, name) {
  21092. const segments = this.mappings[line];
  21093. if (!segments)
  21094. return null;
  21095. // binary search through segments for the given column
  21096. let searchStart = 0;
  21097. const lastSegmentIndex = segments.length - 1;
  21098. let searchEnd = lastSegmentIndex;
  21099. while (searchStart <= searchEnd) {
  21100. const m = (searchStart + searchEnd) >> 1;
  21101. let segment = segments[m];
  21102. // If a sourcemap does not have sufficient resolution to contain a
  21103. // necessary mapping, e.g. because it only contains line information or
  21104. // the column is not precise (e.g. the sourcemap is generated by esbuild, segment[0] may be shorter than the location of the first letter),
  21105. // we approximate by finding the closest segment whose segment[0] is less than the given column
  21106. if (segment[0] !== column && searchStart === searchEnd) {
  21107. const approximatedSegmentIndex = segments[searchStart][0] > column ? Math.max(0, searchStart - 1) : searchStart;
  21108. segment = segments[approximatedSegmentIndex];
  21109. }
  21110. if (segment[0] === column || searchStart === searchEnd) {
  21111. if (segment.length == 1)
  21112. return null;
  21113. const source = this.sources[segment[1]];
  21114. if (!source)
  21115. return null;
  21116. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  21117. }
  21118. if (segment[0] > column) {
  21119. searchEnd = m - 1;
  21120. }
  21121. else {
  21122. searchStart = m + 1;
  21123. }
  21124. }
  21125. return null;
  21126. }
  21127. }
  21128. function getLinkMap(log) {
  21129. return function linkMap(source, map) {
  21130. if (!map.missing) {
  21131. return new Link(map, [source]);
  21132. }
  21133. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logSourcemapBroken(map.plugin));
  21134. return new Link({
  21135. mappings: [],
  21136. names: []
  21137. }, [source]);
  21138. };
  21139. }
  21140. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  21141. let source;
  21142. if (originalSourcemap) {
  21143. const sources = originalSourcemap.sources;
  21144. const sourcesContent = originalSourcemap.sourcesContent || [];
  21145. const directory = path.dirname(id) || '.';
  21146. const sourceRoot = originalSourcemap.sourceRoot || '.';
  21147. const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  21148. source = new Link(originalSourcemap, baseSources);
  21149. }
  21150. else {
  21151. source = new Source(id, originalCode);
  21152. }
  21153. return sourcemapChain.reduce(linkMap, source);
  21154. }
  21155. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  21156. const linkMap = getLinkMap(log);
  21157. const moduleSources = modules
  21158. .filter(module => !module.excludeFromSourcemap)
  21159. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  21160. const link = new Link(map, moduleSources);
  21161. const source = bundleSourcemapChain.reduce(linkMap, link);
  21162. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  21163. if (file) {
  21164. const directory = path.dirname(file);
  21165. sources = sources.map((source) => path.relative(directory, source));
  21166. file = path.basename(file);
  21167. }
  21168. for (const module of modules) {
  21169. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  21170. }
  21171. return new SourceMap({
  21172. file,
  21173. mappings,
  21174. names,
  21175. sources,
  21176. sourcesContent: excludeContent ? undefined : sourcesContent
  21177. });
  21178. }
  21179. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  21180. if (sourcemapChain.length === 0) {
  21181. return originalSourcemap;
  21182. }
  21183. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  21184. const map = source.traceMappings();
  21185. return decodedSourcemap({ version: 3, ...map });
  21186. }
  21187. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  21188. // this for an actual sourceMappingURL
  21189. let SOURCEMAPPING_URL = 'sourceMa';
  21190. SOURCEMAPPING_URL += 'ppingURL';
  21191. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  21192. timeStart('render chunks', 2);
  21193. reserveEntryChunksInBundle(chunks);
  21194. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  21195. timeEnd('render chunks', 2);
  21196. timeStart('transform chunks', 2);
  21197. const getHash = hasherByType[outputOptions.hashCharacters];
  21198. const chunkGraph = getChunkGraph(chunks);
  21199. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  21200. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  21201. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  21202. timeEnd('transform chunks', 2);
  21203. }
  21204. function reserveEntryChunksInBundle(chunks) {
  21205. for (const chunk of chunks) {
  21206. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  21207. // reserves name in bundle as side effect if it does not contain a hash
  21208. chunk.getPreliminaryFileName();
  21209. }
  21210. }
  21211. }
  21212. function getChunkGraph(chunks) {
  21213. return Object.fromEntries(chunks.map(chunk => {
  21214. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  21215. return [renderedChunkInfo.fileName, renderedChunkInfo];
  21216. }));
  21217. }
  21218. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  21219. let map = null;
  21220. const sourcemapChain = [];
  21221. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  21222. if (result == null)
  21223. return code;
  21224. if (typeof result === 'string')
  21225. result = {
  21226. code: result,
  21227. map: undefined
  21228. };
  21229. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  21230. if (result.map !== null) {
  21231. const map = decodedSourcemap(result.map);
  21232. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  21233. }
  21234. return result.code;
  21235. });
  21236. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  21237. if (!compact && code[code.length - 1] !== '\n')
  21238. code += '\n';
  21239. if (sourcemap) {
  21240. timeStart('sourcemaps', 3);
  21241. let resultingFile;
  21242. if (file)
  21243. resultingFile = path.resolve(sourcemapFile || file);
  21244. else if (dir)
  21245. resultingFile = path.resolve(dir, fileName);
  21246. else
  21247. resultingFile = path.resolve(fileName);
  21248. const decodedMap = magicString.generateDecodedMap({});
  21249. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  21250. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  21251. let sourcePath = map.sources[sourcesIndex];
  21252. const sourcemapPath = `${resultingFile}.map`;
  21253. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  21254. if (typeof ignoreList !== 'boolean') {
  21255. parseAst_js.error(parseAst_js.logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  21256. }
  21257. if (ignoreList) {
  21258. if (map.x_google_ignoreList === undefined) {
  21259. map.x_google_ignoreList = [];
  21260. }
  21261. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  21262. map.x_google_ignoreList.push(sourcesIndex);
  21263. }
  21264. }
  21265. if (sourcemapPathTransform) {
  21266. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  21267. if (typeof sourcePath !== 'string') {
  21268. parseAst_js.error(parseAst_js.logFailedValidation(`sourcemapPathTransform function must return a string.`));
  21269. }
  21270. }
  21271. map.sources[sourcesIndex] = parseAst_js.normalize(sourcePath);
  21272. }
  21273. timeEnd('sourcemaps', 3);
  21274. }
  21275. return {
  21276. code,
  21277. map
  21278. };
  21279. }
  21280. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  21281. const nonHashedChunksWithPlaceholders = [];
  21282. const renderedChunksByPlaceholder = new Map();
  21283. const hashDependenciesByPlaceholder = new Map();
  21284. const initialHashesByPlaceholder = new Map();
  21285. const placeholders = new Set();
  21286. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  21287. if (hashPlaceholder)
  21288. placeholders.add(hashPlaceholder);
  21289. }
  21290. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  21291. const transformedChunk = {
  21292. chunk,
  21293. fileName,
  21294. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  21295. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  21296. };
  21297. const { code, map } = transformedChunk;
  21298. if (hashPlaceholder) {
  21299. // To create a reproducible content-only hash, all placeholders are
  21300. // replaced with the same value before hashing
  21301. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  21302. let contentToHash = transformedCode;
  21303. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  21304. if (pluginHash) {
  21305. augmentation += pluginHash;
  21306. }
  21307. return augmentation;
  21308. });
  21309. if (hashAugmentation) {
  21310. contentToHash += hashAugmentation;
  21311. }
  21312. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  21313. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  21314. containedPlaceholders,
  21315. contentHash: getHash(contentToHash)
  21316. });
  21317. }
  21318. else {
  21319. nonHashedChunksWithPlaceholders.push(transformedChunk);
  21320. }
  21321. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  21322. if (map && sourcemapHashPlaceholder) {
  21323. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  21324. }
  21325. }));
  21326. return {
  21327. hashDependenciesByPlaceholder,
  21328. initialHashesByPlaceholder,
  21329. nonHashedChunksWithPlaceholders,
  21330. placeholders,
  21331. renderedChunksByPlaceholder
  21332. };
  21333. }
  21334. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  21335. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  21336. for (const placeholder of placeholders) {
  21337. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  21338. let contentToHash = '';
  21339. const hashDependencyPlaceholders = new Set([placeholder]);
  21340. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  21341. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  21342. contentToHash += contentHash;
  21343. for (const containedPlaceholder of containedPlaceholders) {
  21344. // When looping over a map, setting an entry only causes a new iteration if the key is new
  21345. hashDependencyPlaceholders.add(containedPlaceholder);
  21346. }
  21347. }
  21348. let finalFileName;
  21349. let finalHash;
  21350. do {
  21351. // In case of a hash collision, create a hash of the hash
  21352. if (finalHash) {
  21353. contentToHash = finalHash;
  21354. }
  21355. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  21356. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  21357. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  21358. bundle[finalFileName] = FILE_PLACEHOLDER;
  21359. hashesByPlaceholder.set(placeholder, finalHash);
  21360. }
  21361. return hashesByPlaceholder;
  21362. }
  21363. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  21364. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  21365. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  21366. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  21367. let finalSourcemapFileName = null;
  21368. if (map) {
  21369. if (options.sourcemapDebugIds) {
  21370. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  21371. }
  21372. finalSourcemapFileName = sourcemapFileName
  21373. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  21374. : `${finalFileName}.map`;
  21375. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  21376. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  21377. }
  21378. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  21379. }
  21380. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  21381. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  21382. let finalSourcemapFileName = null;
  21383. if (map) {
  21384. if (options.sourcemapDebugIds) {
  21385. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  21386. }
  21387. finalSourcemapFileName = sourcemapFileName
  21388. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  21389. : `${fileName}.map`;
  21390. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  21391. }
  21392. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  21393. }
  21394. }
  21395. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  21396. let url;
  21397. if (sourcemap === 'inline') {
  21398. url = map.toUrl();
  21399. }
  21400. else {
  21401. const sourcemapFileName = path.basename(fileName);
  21402. url = sourcemapBaseUrl
  21403. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  21404. : sourcemapFileName;
  21405. pluginDriver.emitFile({
  21406. fileName,
  21407. originalFileName: null,
  21408. source: map.toString(),
  21409. type: 'asset'
  21410. });
  21411. }
  21412. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  21413. }
  21414. function calculateDebugIdAndGetComment(code, map) {
  21415. const hash = hasherByType.hex(code);
  21416. const debugId = [
  21417. hash.slice(0, 8),
  21418. hash.slice(8, 12),
  21419. '4' + hash.slice(12, 15),
  21420. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  21421. hash.slice(20, 32)
  21422. ].join('-');
  21423. map.debugId = debugId;
  21424. return '//# debugId=' + debugId + '\n';
  21425. }
  21426. class Bundle {
  21427. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  21428. this.outputOptions = outputOptions;
  21429. this.unsetOptions = unsetOptions;
  21430. this.inputOptions = inputOptions;
  21431. this.pluginDriver = pluginDriver;
  21432. this.graph = graph;
  21433. this.facadeChunkByModule = new Map();
  21434. this.includedNamespaces = new Set();
  21435. }
  21436. async generate(isWrite) {
  21437. timeStart('GENERATE', 1);
  21438. const outputBundleBase = Object.create(null);
  21439. const outputBundle = getOutputBundle(outputBundleBase);
  21440. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  21441. try {
  21442. timeStart('initialize render', 2);
  21443. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  21444. timeEnd('initialize render', 2);
  21445. timeStart('generate chunks', 2);
  21446. const getHashPlaceholder = getHashPlaceholderGenerator();
  21447. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  21448. if (chunks.length > 1) {
  21449. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  21450. }
  21451. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  21452. for (const chunk of chunks) {
  21453. chunk.generateExports();
  21454. chunk.inlineTransitiveImports();
  21455. }
  21456. timeEnd('generate chunks', 2);
  21457. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  21458. }
  21459. catch (error_) {
  21460. await this.pluginDriver.hookParallel('renderError', [error_]);
  21461. throw error_;
  21462. }
  21463. removeUnreferencedAssets(outputBundle);
  21464. timeStart('generate bundle', 2);
  21465. await this.pluginDriver.hookSeq('generateBundle', [
  21466. this.outputOptions,
  21467. outputBundle,
  21468. isWrite
  21469. ]);
  21470. this.finaliseAssets(outputBundle);
  21471. validateOutputBundleFileNames(outputBundle);
  21472. timeEnd('generate bundle', 2);
  21473. timeEnd('GENERATE', 1);
  21474. return outputBundleBase;
  21475. }
  21476. async addManualChunks(manualChunks) {
  21477. const manualChunkAliasByEntry = new Map();
  21478. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  21479. alias,
  21480. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  21481. })));
  21482. for (const { alias, entries } of chunkEntries) {
  21483. for (const entry of entries) {
  21484. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  21485. }
  21486. }
  21487. return manualChunkAliasByEntry;
  21488. }
  21489. assignManualChunks(getManualChunk) {
  21490. const manualChunkAliasByEntry = new Map();
  21491. const manualChunksApi = {
  21492. getModuleIds: () => this.graph.modulesById.keys(),
  21493. getModuleInfo: this.graph.getModuleInfo
  21494. };
  21495. for (const module of this.graph.modulesById.values()) {
  21496. if (module instanceof Module) {
  21497. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  21498. if (typeof manualChunkAlias === 'string') {
  21499. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  21500. }
  21501. }
  21502. }
  21503. return manualChunkAliasByEntry;
  21504. }
  21505. finaliseAssets(bundle) {
  21506. if (this.outputOptions.validate) {
  21507. for (const file of Object.values(bundle)) {
  21508. if ('code' in file) {
  21509. try {
  21510. parseAst_js.parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  21511. }
  21512. catch (error_) {
  21513. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logChunkInvalid(file, error_));
  21514. }
  21515. }
  21516. }
  21517. }
  21518. this.pluginDriver.finaliseAssets();
  21519. }
  21520. async generateChunks(bundle, getHashPlaceholder) {
  21521. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules, onlyExplicitManualChunks } = this.outputOptions;
  21522. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  21523. ? await this.addManualChunks(manualChunks)
  21524. : this.assignManualChunks(manualChunks);
  21525. const snippets = getGenerateCodeSnippets(this.outputOptions);
  21526. const includedModules = getIncludedModules(this.graph.modulesById);
  21527. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  21528. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  21529. const executableModule = inlineDynamicImports
  21530. ? [{ alias: null, modules: includedModules }]
  21531. : preserveModules
  21532. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  21533. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, typeof manualChunks === 'function', onlyExplicitManualChunks);
  21534. const chunks = new Array(executableModule.length);
  21535. const chunkByModule = new Map();
  21536. let index = 0;
  21537. for (const { alias, modules } of executableModule) {
  21538. sortByExecutionOrder(modules);
  21539. 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);
  21540. chunks[index++] = chunk;
  21541. }
  21542. for (const chunk of chunks) {
  21543. chunk.link();
  21544. }
  21545. if (!inlineDynamicImports && !preserveModules) {
  21546. this.checkCircularChunks(chunks);
  21547. }
  21548. const facades = [];
  21549. for (const chunk of chunks) {
  21550. facades.push(...chunk.generateFacades());
  21551. }
  21552. return [...chunks, ...facades];
  21553. }
  21554. checkCircularChunks(chunks) {
  21555. const visited = new Set();
  21556. const parents = new Map();
  21557. const handleDependency = (chunk, parent) => {
  21558. if (parents.has(chunk)) {
  21559. if (!visited.has(chunk)) {
  21560. const path = [chunk.getChunkName()];
  21561. let isManualChunkConflict = chunk.isManualChunk;
  21562. let nextChunk = parent;
  21563. while (nextChunk !== chunk && nextChunk) {
  21564. path.push(nextChunk.getChunkName());
  21565. isManualChunkConflict &&= nextChunk.isManualChunk;
  21566. nextChunk = parents.get(nextChunk);
  21567. }
  21568. path.push(path[0]);
  21569. path.reverse();
  21570. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularChunk(path, isManualChunkConflict));
  21571. }
  21572. return;
  21573. }
  21574. parents.set(chunk, parent);
  21575. analyseChunk(chunk);
  21576. };
  21577. const analyseChunk = (chunk) => {
  21578. for (const dependency of chunk.dependencies) {
  21579. if (dependency instanceof Chunk) {
  21580. handleDependency(dependency, chunk);
  21581. }
  21582. }
  21583. visited.add(chunk);
  21584. };
  21585. for (const chunk of chunks) {
  21586. if (!parents.has(chunk)) {
  21587. analyseChunk(chunk);
  21588. }
  21589. }
  21590. }
  21591. }
  21592. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  21593. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  21594. 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));
  21595. if (typeof outputOptions.file === 'string')
  21596. 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'));
  21597. if (outputOptions.sourcemapFile)
  21598. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapFile', parseAst_js.URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  21599. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  21600. 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'));
  21601. }
  21602. function getIncludedModules(modulesById) {
  21603. const includedModules = [];
  21604. for (const module of modulesById.values()) {
  21605. if (module instanceof Module &&
  21606. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  21607. includedModules.push(module);
  21608. }
  21609. }
  21610. return includedModules;
  21611. }
  21612. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  21613. const absoluteEntryModulePaths = [];
  21614. for (const module of includedModules) {
  21615. if ((module.info.isEntry || preserveModules) && parseAst_js.isAbsolute(module.id)) {
  21616. absoluteEntryModulePaths.push(module.id);
  21617. }
  21618. }
  21619. return absoluteEntryModulePaths;
  21620. }
  21621. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  21622. const externalChunkByModule = new Map();
  21623. for (const module of modulesById.values()) {
  21624. if (module instanceof ExternalModule) {
  21625. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  21626. }
  21627. }
  21628. return externalChunkByModule;
  21629. }
  21630. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  21631. const existingAlias = manualChunkAliasByEntry.get(module);
  21632. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  21633. return parseAst_js.error(parseAst_js.logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  21634. }
  21635. manualChunkAliasByEntry.set(module, alias);
  21636. }
  21637. function isFileNameOutsideOutputDirectory(fileName) {
  21638. // Use join() to normalize ".." segments, then replace backslashes so the
  21639. // string checks below work identically on Windows and POSIX.
  21640. const normalized = path.join(fileName).replaceAll('\\', '/');
  21641. return (normalized === '..' ||
  21642. normalized.startsWith('../') ||
  21643. normalized === '.' ||
  21644. parseAst_js.isAbsolute(normalized));
  21645. }
  21646. function validateOutputBundleFileNames(bundle) {
  21647. for (const [bundleKey, entry] of Object.entries(bundle)) {
  21648. if (isFileNameOutsideOutputDirectory(bundleKey)) {
  21649. return parseAst_js.error(parseAst_js.logFileNameOutsideOutputDirectory(bundleKey));
  21650. }
  21651. if (entry.type !== 'placeholder') {
  21652. const { fileName } = entry;
  21653. if (fileName !== bundleKey && isFileNameOutsideOutputDirectory(fileName)) {
  21654. return parseAst_js.error(parseAst_js.logFileNameOutsideOutputDirectory(fileName));
  21655. }
  21656. }
  21657. }
  21658. }
  21659. function flru (max) {
  21660. var num, curr, prev;
  21661. var limit = max;
  21662. function keep(key, value) {
  21663. if (++num > limit) {
  21664. prev = curr;
  21665. reset(1);
  21666. ++num;
  21667. }
  21668. curr[key] = value;
  21669. }
  21670. function reset(isPartial) {
  21671. num = 0;
  21672. curr = Object.create(null);
  21673. isPartial || (prev=Object.create(null));
  21674. }
  21675. reset();
  21676. return {
  21677. clear: reset,
  21678. has: function (key) {
  21679. return curr[key] !== void 0 || prev[key] !== void 0;
  21680. },
  21681. get: function (key) {
  21682. var val = curr[key];
  21683. if (val !== void 0) return val;
  21684. if ((val=prev[key]) !== void 0) {
  21685. keep(key, val);
  21686. return val;
  21687. }
  21688. },
  21689. set: function (key, value) {
  21690. if (curr[key] !== void 0) {
  21691. curr[key] = value;
  21692. } else {
  21693. keep(key, value);
  21694. }
  21695. }
  21696. };
  21697. }
  21698. class GlobalScope extends Scope {
  21699. constructor() {
  21700. super();
  21701. this.parent = null;
  21702. this.variables.set('undefined', new UndefinedVariable());
  21703. }
  21704. findVariable(name) {
  21705. let variable = this.variables.get(name);
  21706. if (!variable) {
  21707. variable = new GlobalVariable(name);
  21708. this.variables.set(name, variable);
  21709. }
  21710. return variable;
  21711. }
  21712. }
  21713. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes) {
  21714. let skipped = null;
  21715. let replaceContext = null;
  21716. if (skip) {
  21717. skipped = new Set();
  21718. for (const skippedCall of skip) {
  21719. if (source === skippedCall.source && importer === skippedCall.importer) {
  21720. skipped.add(skippedCall.plugin);
  21721. }
  21722. }
  21723. replaceContext = (pluginContext, plugin) => ({
  21724. ...pluginContext,
  21725. resolve: (source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = parseAst_js.BLANK) => {
  21726. skipSelf ??= true;
  21727. if (skipSelf &&
  21728. skip.findIndex(skippedCall => {
  21729. return (skippedCall.plugin === plugin &&
  21730. skippedCall.source === source &&
  21731. skippedCall.importer === importer);
  21732. }) !== -1) {
  21733. // This means that the plugin recursively called itself
  21734. // Thus returning Promise.resolve(null) in purpose of fallback to default behavior of `resolveId` plugin hook.
  21735. return Promise.resolve(null);
  21736. }
  21737. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, importerAttributes, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  21738. }
  21739. });
  21740. }
  21741. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, importerAttributes, isEntry }], replaceContext, skipped);
  21742. }
  21743. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, fs) {
  21744. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes);
  21745. if (pluginResult != null) {
  21746. const [resolveIdResult, plugin] = pluginResult;
  21747. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  21748. return {
  21749. ...resolveIdResult,
  21750. resolvedBy: plugin.name
  21751. };
  21752. }
  21753. if (typeof resolveIdResult === 'string') {
  21754. return {
  21755. id: resolveIdResult,
  21756. resolvedBy: plugin.name
  21757. };
  21758. }
  21759. return resolveIdResult;
  21760. }
  21761. // external modules (non-entry modules that start with neither '.' or '/')
  21762. // are skipped at this stage.
  21763. if (importer !== undefined && !parseAst_js.isAbsolute(source) && source[0] !== '.')
  21764. return null;
  21765. // `resolve` processes paths from right to left, prepending them until an
  21766. // absolute path is created. Absolute importees therefore shortcircuit the
  21767. // resolve call and require no special handing on our part.
  21768. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  21769. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks, fs);
  21770. }
  21771. async function addJsExtensionIfNecessary(file, preserveSymlinks, fs) {
  21772. return ((await findFile(file, preserveSymlinks, fs)) ??
  21773. (await findFile(file + '.mjs', preserveSymlinks, fs)) ??
  21774. (await findFile(file + '.js', preserveSymlinks, fs)));
  21775. }
  21776. async function findFile(file, preserveSymlinks, fs) {
  21777. try {
  21778. const stats = await fs.lstat(file);
  21779. if (!preserveSymlinks && stats.isSymbolicLink())
  21780. return await findFile(await fs.realpath(file), preserveSymlinks, fs);
  21781. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  21782. // check case
  21783. const name = path.basename(file);
  21784. const files = await fs.readdir(path.dirname(file));
  21785. if (files.includes(name))
  21786. return file;
  21787. }
  21788. }
  21789. catch {
  21790. // suppress
  21791. }
  21792. }
  21793. function stripBom(content) {
  21794. if (content.charCodeAt(0) === 0xfe_ff) {
  21795. return stripBom(content.slice(1));
  21796. }
  21797. return content;
  21798. }
  21799. async function transform(source, module, pluginDriver, options) {
  21800. const id = module.id;
  21801. const sourcemapChain = [];
  21802. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  21803. const originalCode = source.code;
  21804. let ast = source.ast;
  21805. const transformDependencies = [];
  21806. const emittedFiles = [];
  21807. let customTransformCache = false;
  21808. const useCustomTransformCache = () => (customTransformCache = true);
  21809. let pluginName = '';
  21810. let currentSource = source.code;
  21811. function transformReducer(previousCode, result, plugin) {
  21812. let code;
  21813. let map;
  21814. if (typeof result === 'string') {
  21815. code = result;
  21816. }
  21817. else if (result && typeof result === 'object') {
  21818. module.updateOptions(result);
  21819. if (result.code == null) {
  21820. if (result.map || result.ast) {
  21821. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNoTransformMapOrAstWithoutCode(plugin.name));
  21822. }
  21823. return previousCode;
  21824. }
  21825. if (result.attributes) {
  21826. parseAst_js.warnDeprecation('Returning attributes from the "transform" hook is forbidden.', parseAst_js.URL_TRANSFORM, false, options);
  21827. }
  21828. ({ code, map, ast } = result);
  21829. }
  21830. else {
  21831. return previousCode;
  21832. }
  21833. // strict null check allows 'null' maps to not be pushed to the chain,
  21834. // while 'undefined' gets the missing map warning
  21835. if (map !== null) {
  21836. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  21837. missing: true,
  21838. plugin: plugin.name
  21839. });
  21840. }
  21841. currentSource = code;
  21842. return code;
  21843. }
  21844. const getLogHandler = (handler) => (log, pos) => {
  21845. log = normalizeLog(log);
  21846. if (pos)
  21847. parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
  21848. log.id = id;
  21849. log.hook = 'transform';
  21850. handler(log);
  21851. };
  21852. let code;
  21853. try {
  21854. code = await pluginDriver.hookReduceArg0('transform', [
  21855. currentSource,
  21856. id,
  21857. {
  21858. attributes: module.info.attributes
  21859. }
  21860. ], transformReducer, (pluginContext, plugin) => {
  21861. pluginName = plugin.name;
  21862. return {
  21863. ...pluginContext,
  21864. addWatchFile(id) {
  21865. transformDependencies.push(id);
  21866. pluginContext.addWatchFile(id);
  21867. },
  21868. cache: customTransformCache
  21869. ? pluginContext.cache
  21870. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  21871. debug: getLogHandler(pluginContext.debug),
  21872. emitFile(emittedFile) {
  21873. emittedFiles.push(emittedFile);
  21874. return pluginDriver.emitFile(emittedFile);
  21875. },
  21876. error(error_, pos) {
  21877. if (typeof error_ === 'string')
  21878. error_ = { message: error_ };
  21879. if (pos)
  21880. parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
  21881. error_.id = id;
  21882. error_.hook = 'transform';
  21883. return pluginContext.error(error_);
  21884. },
  21885. getCombinedSourcemap() {
  21886. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, options.onLog);
  21887. if (!combinedMap) {
  21888. const magicString = new MagicString(originalCode);
  21889. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  21890. }
  21891. if (originalSourcemap !== combinedMap) {
  21892. originalSourcemap = combinedMap;
  21893. sourcemapChain.length = 0;
  21894. }
  21895. return new SourceMap({
  21896. ...combinedMap,
  21897. file: null,
  21898. sourcesContent: combinedMap.sourcesContent
  21899. });
  21900. },
  21901. info: getLogHandler(pluginContext.info),
  21902. setAssetSource() {
  21903. return this.error(parseAst_js.logInvalidSetAssetSourceCall());
  21904. },
  21905. warn: getLogHandler(pluginContext.warn)
  21906. };
  21907. });
  21908. }
  21909. catch (error_) {
  21910. return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
  21911. }
  21912. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  21913. emittedFiles.length > 0)
  21914. module.transformFiles = emittedFiles;
  21915. return {
  21916. ast,
  21917. code,
  21918. customTransformCache,
  21919. originalCode,
  21920. originalSourcemap,
  21921. safeVariableNames: null,
  21922. sourcemapChain,
  21923. transformDependencies
  21924. };
  21925. }
  21926. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  21927. class ModuleLoader {
  21928. constructor(graph, modulesById, options, pluginDriver) {
  21929. this.graph = graph;
  21930. this.modulesById = modulesById;
  21931. this.options = options;
  21932. this.pluginDriver = pluginDriver;
  21933. this.implicitEntryModules = new Set();
  21934. this.indexedEntryModules = [];
  21935. this.latestLoadModulesPromise = Promise.resolve();
  21936. this.moduleLoadPromises = new Map();
  21937. this.modulesWithLoadedDependencies = new Set();
  21938. this.nextChunkNamePriority = 0;
  21939. this.nextEntryModuleIndex = 0;
  21940. this.resolveId = async (source, importer, customOptions, isEntry, attributes, importerAttributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  21941. ? false
  21942. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, importerAttributes, this.options.fs), importer, source), attributes);
  21943. this.hasModuleSideEffects = options.treeshake
  21944. ? options.treeshake.moduleSideEffects
  21945. : () => true;
  21946. }
  21947. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  21948. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks, undefined))));
  21949. await this.awaitLoadModulesPromise();
  21950. return result;
  21951. }
  21952. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  21953. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  21954. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  21955. const firstChunkNamePriority = this.nextChunkNamePriority;
  21956. this.nextChunkNamePriority += unresolvedEntryModules.length;
  21957. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null, undefined, undefined))).then(entryModules => {
  21958. for (const [index, entryModule] of entryModules.entries()) {
  21959. entryModule.isUserDefinedEntryPoint =
  21960. entryModule.isUserDefinedEntryPoint || isUserDefined;
  21961. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  21962. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  21963. if (existingIndexedModule) {
  21964. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  21965. }
  21966. else {
  21967. this.indexedEntryModules.push({
  21968. index: firstEntryModuleIndex + index,
  21969. module: entryModule
  21970. });
  21971. }
  21972. }
  21973. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  21974. return entryModules;
  21975. }));
  21976. await this.awaitLoadModulesPromise();
  21977. return {
  21978. entryModules: this.indexedEntryModules.map(({ module }) => module),
  21979. implicitEntryModules: [...this.implicitEntryModules],
  21980. newEntryModules
  21981. };
  21982. }
  21983. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  21984. const unresolvedModule = {
  21985. fileName: fileName || null,
  21986. id,
  21987. importer,
  21988. name: name || null
  21989. };
  21990. const module = implicitlyLoadedAfterOneOf
  21991. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  21992. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  21993. if (preserveSignature != null) {
  21994. module.preserveSignature = preserveSignature;
  21995. }
  21996. return module;
  21997. }
  21998. async preloadModule(resolvedId) {
  21999. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  22000. return module.info;
  22001. }
  22002. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  22003. const chunkNamePriority = this.nextChunkNamePriority++;
  22004. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null, undefined, undefined).then(async (entryModule) => {
  22005. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  22006. if (!entryModule.info.isEntry) {
  22007. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id, undefined, undefined)));
  22008. // We need to check again if this is still an entry module as these
  22009. // changes need to be performed atomically to avoid race conditions
  22010. // if the same module is re-emitted as an entry module.
  22011. // The inverse changes happen in "handleExistingModule"
  22012. if (!entryModule.info.isEntry) {
  22013. this.implicitEntryModules.add(entryModule);
  22014. for (const module of implicitlyLoadedAfterModules) {
  22015. entryModule.implicitlyLoadedAfter.add(module);
  22016. }
  22017. for (const dependant of entryModule.implicitlyLoadedAfter) {
  22018. dependant.implicitlyLoadedBefore.add(entryModule);
  22019. }
  22020. }
  22021. }
  22022. return entryModule;
  22023. }));
  22024. }
  22025. async addModuleSource(id, importer, module) {
  22026. let source;
  22027. try {
  22028. source = await this.graph.fileOperationQueue.run(async () => {
  22029. const content = await this.pluginDriver.hookFirst('load', [
  22030. id,
  22031. { attributes: module.info.attributes }
  22032. ]);
  22033. if (content !== null) {
  22034. if (typeof content === 'object' && content.attributes) {
  22035. parseAst_js.warnDeprecation('Returning attributes from the "load" hook is forbidden.', parseAst_js.URL_LOAD, false, this.options);
  22036. }
  22037. return content;
  22038. }
  22039. this.graph.watchFiles[id] = true;
  22040. return (await this.options.fs.readFile(id, { encoding: 'utf8' }));
  22041. });
  22042. }
  22043. catch (error_) {
  22044. let message = `Could not load ${id}`;
  22045. if (importer)
  22046. message += ` (imported by ${parseAst_js.relativeId(importer)})`;
  22047. message += `: ${error_.message}`;
  22048. error_.message = message;
  22049. throw error_;
  22050. }
  22051. const sourceDescription = typeof source === 'string'
  22052. ? { code: source }
  22053. : source != null && typeof source === 'object' && typeof source.code === 'string'
  22054. ? source
  22055. : parseAst_js.error(parseAst_js.logBadLoader(id));
  22056. sourceDescription.code = stripBom(sourceDescription.code);
  22057. const cachedModule = this.graph.cachedModules.get(id);
  22058. if (cachedModule &&
  22059. !cachedModule.customTransformCache &&
  22060. cachedModule.originalCode === sourceDescription.code &&
  22061. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  22062. {
  22063. ast: cachedModule.ast,
  22064. attributes: cachedModule.attributes,
  22065. code: cachedModule.code,
  22066. id: cachedModule.id,
  22067. meta: cachedModule.meta,
  22068. moduleSideEffects: cachedModule.moduleSideEffects,
  22069. resolvedSources: cachedModule.resolvedIds,
  22070. syntheticNamedExports: cachedModule.syntheticNamedExports
  22071. }
  22072. ]))) {
  22073. if (cachedModule.transformFiles) {
  22074. for (const emittedFile of cachedModule.transformFiles)
  22075. this.pluginDriver.emitFile(emittedFile);
  22076. }
  22077. await module.setSource(cachedModule);
  22078. }
  22079. else {
  22080. module.updateOptions(sourceDescription);
  22081. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options));
  22082. }
  22083. }
  22084. async awaitLoadModulesPromise() {
  22085. let startingPromise;
  22086. do {
  22087. startingPromise = this.latestLoadModulesPromise;
  22088. await startingPromise;
  22089. } while (startingPromise !== this.latestLoadModulesPromise);
  22090. }
  22091. extendLoadModulesPromise(loadNewModulesPromise) {
  22092. this.latestLoadModulesPromise = Promise.all([
  22093. loadNewModulesPromise,
  22094. this.latestLoadModulesPromise
  22095. ]);
  22096. this.latestLoadModulesPromise.catch(() => {
  22097. /* Avoid unhandled Promise rejections */
  22098. });
  22099. return loadNewModulesPromise;
  22100. }
  22101. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  22102. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([{ argument, node }, resolvedId]) => {
  22103. if (resolvedId === null)
  22104. return null;
  22105. if (typeof resolvedId === 'string') {
  22106. node.resolution = resolvedId;
  22107. return null;
  22108. }
  22109. if (node.phase === 'source' && !resolvedId.external) {
  22110. return parseAst_js.error(parseAst_js.logNonExternalSourcePhaseImport(typeof argument === 'string' ? argument : parseAst_js.relativeId(resolvedId.id), module.id));
  22111. }
  22112. return (node.resolution = await this.fetchResolvedDependency(parseAst_js.relativeId(resolvedId.id), module.id, resolvedId));
  22113. })));
  22114. for (const dependency of dependencies) {
  22115. if (dependency) {
  22116. module.dynamicDependencies.add(dependency);
  22117. dependency.dynamicImporters.push(module.id);
  22118. }
  22119. }
  22120. }
  22121. // If this is a preload, then this method always waits for the dependencies of
  22122. // the module to be resolved.
  22123. // Otherwise, if the module does not exist, it waits for the module and all
  22124. // its dependencies to be loaded.
  22125. // Otherwise, it returns immediately.
  22126. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  22127. const existingModule = this.modulesById.get(id);
  22128. if (existingModule instanceof Module) {
  22129. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  22130. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  22131. }
  22132. await this.handleExistingModule(existingModule, isEntry, isPreload);
  22133. return existingModule;
  22134. }
  22135. if (existingModule instanceof ExternalModule) {
  22136. return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
  22137. }
  22138. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  22139. this.modulesById.set(id, module);
  22140. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  22141. this.getResolveStaticDependencyPromises(module),
  22142. this.getResolveDynamicImportPromises(module),
  22143. loadAndResolveDependenciesPromise
  22144. ]);
  22145. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  22146. loadAndResolveDependenciesPromise.catch(() => {
  22147. /* avoid unhandled promise rejections */
  22148. });
  22149. this.moduleLoadPromises.set(module, loadPromise);
  22150. const resolveDependencyPromises = await loadPromise;
  22151. if (!isPreload) {
  22152. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  22153. }
  22154. else if (isPreload === RESOLVE_DEPENDENCIES) {
  22155. await loadAndResolveDependenciesPromise;
  22156. }
  22157. return module;
  22158. }
  22159. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  22160. if (this.modulesWithLoadedDependencies.has(module)) {
  22161. return;
  22162. }
  22163. this.modulesWithLoadedDependencies.add(module);
  22164. await Promise.all([
  22165. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  22166. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  22167. ]);
  22168. module.linkImports();
  22169. // To handle errors when resolving dependencies or in moduleParsed
  22170. await loadAndResolveDependenciesPromise;
  22171. }
  22172. fetchResolvedDependency(source, importer, resolvedId) {
  22173. if (resolvedId.external) {
  22174. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  22175. let externalModule = this.modulesById.get(id);
  22176. if (!externalModule) {
  22177. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
  22178. this.modulesById.set(id, externalModule);
  22179. }
  22180. else if (!(externalModule instanceof ExternalModule)) {
  22181. return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
  22182. }
  22183. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  22184. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  22185. }
  22186. return Promise.resolve(externalModule);
  22187. }
  22188. return this.fetchModule(resolvedId, importer, false, false);
  22189. }
  22190. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  22191. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => {
  22192. if (module.sourcePhaseSources.has(source) && !resolvedId.external) {
  22193. return parseAst_js.error(parseAst_js.logNonExternalSourcePhaseImport(source, module.id));
  22194. }
  22195. return this.fetchResolvedDependency(source, module.id, resolvedId);
  22196. })))) {
  22197. module.dependencies.add(dependency);
  22198. dependency.importers.push(module.id);
  22199. }
  22200. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  22201. for (const dependency of module.dependencies) {
  22202. if (dependency instanceof Module) {
  22203. dependency.importedFromNotTreeshaken = true;
  22204. }
  22205. }
  22206. }
  22207. }
  22208. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  22209. const { makeAbsoluteExternalsRelative } = this.options;
  22210. if (resolveIdResult) {
  22211. if (typeof resolveIdResult === 'object') {
  22212. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  22213. return {
  22214. ...resolveIdResult,
  22215. external: external &&
  22216. (external === 'relative' ||
  22217. !parseAst_js.isAbsolute(resolveIdResult.id) ||
  22218. (external === true &&
  22219. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  22220. 'absolute')
  22221. };
  22222. }
  22223. const external = this.options.external(resolveIdResult, importer, true);
  22224. return {
  22225. external: external &&
  22226. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  22227. 'absolute'),
  22228. id: external && makeAbsoluteExternalsRelative
  22229. ? normalizeRelativeExternalId(resolveIdResult, importer)
  22230. : resolveIdResult
  22231. };
  22232. }
  22233. const id = makeAbsoluteExternalsRelative
  22234. ? normalizeRelativeExternalId(source, importer)
  22235. : source;
  22236. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  22237. return null;
  22238. }
  22239. return {
  22240. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  22241. id
  22242. };
  22243. }
  22244. getResolveDynamicImportPromises(module) {
  22245. return module.dynamicImports.map(async (dynamicImport) => {
  22246. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  22247. if (!resolvedId || typeof resolvedId === 'string') {
  22248. dynamicImport.node.shouldIncludeDynamicAttributes = true;
  22249. }
  22250. else {
  22251. dynamicImport.node.shouldIncludeDynamicAttributes = !!resolvedId.external;
  22252. dynamicImport.id = resolvedId.id;
  22253. }
  22254. return [dynamicImport, resolvedId];
  22255. });
  22256. }
  22257. getResolveStaticDependencyPromises(module) {
  22258. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  22259. source,
  22260. (module.resolvedIds[source] =
  22261. module.resolvedIds[source] ||
  22262. this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes), source, module.id, attributes))
  22263. ]);
  22264. }
  22265. getResolvedIdWithDefaults(resolvedId, attributes) {
  22266. if (!resolvedId) {
  22267. return null;
  22268. }
  22269. const external = resolvedId.external || false;
  22270. return {
  22271. attributes: resolvedId.attributes || attributes,
  22272. external,
  22273. id: resolvedId.id,
  22274. meta: resolvedId.meta || {},
  22275. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  22276. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  22277. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  22278. };
  22279. }
  22280. async handleExistingModule(module, isEntry, isPreload) {
  22281. const loadPromise = this.moduleLoadPromises.get(module);
  22282. if (isPreload) {
  22283. return isPreload === RESOLVE_DEPENDENCIES
  22284. ? waitForDependencyResolution(loadPromise)
  22285. : loadPromise;
  22286. }
  22287. if (isEntry) {
  22288. // This reverts the changes in addEntryWithImplicitDependants and needs to
  22289. // be performed atomically
  22290. module.info.isEntry = true;
  22291. this.implicitEntryModules.delete(module);
  22292. for (const dependant of module.implicitlyLoadedAfter) {
  22293. dependant.implicitlyLoadedBefore.delete(module);
  22294. }
  22295. module.implicitlyLoadedAfter.clear();
  22296. }
  22297. return this.fetchModuleDependencies(module, ...(await loadPromise));
  22298. }
  22299. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  22300. if (resolvedId === null) {
  22301. if (parseAst_js.isRelative(source)) {
  22302. return parseAst_js.error(parseAst_js.logUnresolvedImport(source, importer));
  22303. }
  22304. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnresolvedImportTreatedAsExternal(source, importer));
  22305. return {
  22306. attributes,
  22307. external: true,
  22308. id: source,
  22309. meta: {},
  22310. moduleSideEffects: this.hasModuleSideEffects(source, true),
  22311. resolvedBy: 'rollup',
  22312. syntheticNamedExports: false
  22313. };
  22314. }
  22315. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  22316. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logExternalSyntheticExports(source, importer));
  22317. }
  22318. return resolvedId;
  22319. }
  22320. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false, importerAttributes) {
  22321. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT, importerAttributes, this.options.fs);
  22322. if (resolveIdResult == null) {
  22323. return parseAst_js.error(implicitlyLoadedBefore === null
  22324. ? parseAst_js.logUnresolvedEntry(unresolvedId)
  22325. : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  22326. }
  22327. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  22328. if (resolveIdResult === false || isExternalModules) {
  22329. return parseAst_js.error(implicitlyLoadedBefore === null
  22330. ? isExternalModules && isLoadForManualChunks
  22331. ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  22332. : parseAst_js.logEntryCannotBeExternal(unresolvedId)
  22333. : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  22334. }
  22335. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  22336. ? resolveIdResult
  22337. : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
  22338. }
  22339. async resolveDynamicImport(module, specifier, importer, attributes) {
  22340. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  22341. specifier,
  22342. importer,
  22343. { attributes, importerAttributes: module.info.attributes }
  22344. ]);
  22345. if (typeof specifier !== 'string') {
  22346. if (typeof resolution === 'string') {
  22347. return resolution;
  22348. }
  22349. if (!resolution) {
  22350. return null;
  22351. }
  22352. return this.getResolvedIdWithDefaults(resolution, attributes);
  22353. }
  22354. if (resolution == null) {
  22355. const existingResolution = module.resolvedIds[specifier];
  22356. if (existingResolution) {
  22357. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  22358. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  22359. }
  22360. return existingResolution;
  22361. }
  22362. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes, module.info.attributes), specifier, module.id, attributes));
  22363. }
  22364. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  22365. }
  22366. }
  22367. function normalizeRelativeExternalId(source, importer) {
  22368. return parseAst_js.isRelative(source)
  22369. ? importer
  22370. ? path.resolve(importer, '..', source)
  22371. : path.resolve(source)
  22372. : source;
  22373. }
  22374. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  22375. if (fileName !== null) {
  22376. module.chunkFileNames.add(fileName);
  22377. }
  22378. else if (name !== null) {
  22379. // Always keep chunkNames sorted by priority
  22380. let namePosition = 0;
  22381. while (module.chunkNames[namePosition]?.priority < priority)
  22382. namePosition++;
  22383. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  22384. }
  22385. }
  22386. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  22387. return (makeAbsoluteExternalsRelative === true ||
  22388. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && parseAst_js.isRelative(source)) ||
  22389. !parseAst_js.isAbsolute(id));
  22390. }
  22391. async function waitForDependencyResolution(loadPromise) {
  22392. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  22393. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  22394. }
  22395. class Queue {
  22396. constructor(maxParallel) {
  22397. this.maxParallel = maxParallel;
  22398. this.queue = [];
  22399. this.workerCount = 0;
  22400. }
  22401. run(task) {
  22402. return new Promise((resolve, reject) => {
  22403. this.queue.push({ reject, resolve, task });
  22404. this.work();
  22405. });
  22406. }
  22407. async work() {
  22408. if (this.workerCount >= this.maxParallel)
  22409. return;
  22410. this.workerCount++;
  22411. let entry;
  22412. while ((entry = this.queue.shift())) {
  22413. const { reject, resolve, task } = entry;
  22414. try {
  22415. const result = await task();
  22416. resolve(result);
  22417. }
  22418. catch (error) {
  22419. reject(error);
  22420. }
  22421. }
  22422. this.workerCount--;
  22423. }
  22424. }
  22425. function normalizeEntryModules(entryModules) {
  22426. if (Array.isArray(entryModules)) {
  22427. return entryModules.map(id => ({
  22428. fileName: null,
  22429. id,
  22430. implicitlyLoadedAfter: [],
  22431. importer: undefined,
  22432. name: null
  22433. }));
  22434. }
  22435. return Object.entries(entryModules).map(([name, id]) => ({
  22436. fileName: null,
  22437. id,
  22438. implicitlyLoadedAfter: [],
  22439. importer: undefined,
  22440. name
  22441. }));
  22442. }
  22443. class Graph {
  22444. constructor(options, watcher) {
  22445. this.options = options;
  22446. this.astLru = flru(5);
  22447. this.cachedModules = new Map();
  22448. this.deoptimizationTracker = new EntityPathTracker();
  22449. this.entryModules = [];
  22450. this.modulesById = new Map();
  22451. this.needsTreeshakingPass = false;
  22452. this.newlyIncludedVariableInits = new Set();
  22453. this.phase = BuildPhase.LOAD_AND_PARSE;
  22454. this.scope = new GlobalScope();
  22455. this.watchFiles = Object.create(null);
  22456. this.watchMode = false;
  22457. this.externalModules = [];
  22458. this.implicitEntryModules = [];
  22459. this.modules = [];
  22460. this.getModuleInfo = (moduleId) => {
  22461. const foundModule = this.modulesById.get(moduleId);
  22462. if (!foundModule)
  22463. return null;
  22464. return foundModule.info;
  22465. };
  22466. if (options.cache !== false) {
  22467. if (options.cache?.modules) {
  22468. for (const module of options.cache.modules)
  22469. this.cachedModules.set(module.id, module);
  22470. }
  22471. this.pluginCache = options.cache?.plugins || Object.create(null);
  22472. // increment access counter
  22473. for (const name in this.pluginCache) {
  22474. const cache = this.pluginCache[name];
  22475. for (const value of Object.values(cache))
  22476. value[0]++;
  22477. }
  22478. }
  22479. if (watcher) {
  22480. this.watchMode = true;
  22481. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  22482. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  22483. watcher.onCurrentRun('change', handleChange);
  22484. watcher.onCurrentRun('close', handleClose);
  22485. }
  22486. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  22487. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  22488. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  22489. this.pureFunctions = getPureFunctions(options);
  22490. }
  22491. async build() {
  22492. timeStart('generate module graph', 2);
  22493. await this.generateModuleGraph();
  22494. timeEnd('generate module graph', 2);
  22495. timeStart('sort and bind modules', 2);
  22496. this.phase = BuildPhase.ANALYSE;
  22497. this.sortAndBindModules();
  22498. timeEnd('sort and bind modules', 2);
  22499. timeStart('mark included statements', 2);
  22500. this.includeStatements();
  22501. timeEnd('mark included statements', 2);
  22502. this.phase = BuildPhase.GENERATE;
  22503. }
  22504. getCache() {
  22505. // handle plugin cache eviction
  22506. for (const name in this.pluginCache) {
  22507. const cache = this.pluginCache[name];
  22508. let allDeleted = true;
  22509. for (const [key, value] of Object.entries(cache)) {
  22510. if (value[0] >= this.options.experimentalCacheExpiry)
  22511. delete cache[key];
  22512. else
  22513. allDeleted = false;
  22514. }
  22515. if (allDeleted)
  22516. delete this.pluginCache[name];
  22517. }
  22518. return {
  22519. modules: this.modules.map(module => module.toJSON()),
  22520. plugins: this.pluginCache
  22521. };
  22522. }
  22523. async generateModuleGraph() {
  22524. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  22525. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  22526. if (this.entryModules.length === 0) {
  22527. throw new Error('You must supply options.input to rollup');
  22528. }
  22529. for (const module of this.modulesById.values()) {
  22530. module.cacheInfoGetters();
  22531. if (module instanceof Module) {
  22532. this.modules.push(module);
  22533. }
  22534. else {
  22535. this.externalModules.push(module);
  22536. }
  22537. }
  22538. }
  22539. includeStatements() {
  22540. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  22541. for (const module of entryModules) {
  22542. markModuleAndImpureDependenciesAsExecuted(module);
  22543. }
  22544. if (this.options.treeshake) {
  22545. let treeshakingPass = 1;
  22546. this.newlyIncludedVariableInits.clear();
  22547. do {
  22548. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  22549. this.needsTreeshakingPass = false;
  22550. for (const module of this.modules) {
  22551. if (module.isExecuted) {
  22552. module.hasTreeShakingPassStarted = true;
  22553. if (module.info.moduleSideEffects === 'no-treeshake') {
  22554. module.includeAllInBundle();
  22555. }
  22556. else {
  22557. module.include();
  22558. }
  22559. for (const entity of this.newlyIncludedVariableInits) {
  22560. this.newlyIncludedVariableInits.delete(entity);
  22561. entity.include(createInclusionContext(), false);
  22562. }
  22563. }
  22564. }
  22565. if (treeshakingPass === 1) {
  22566. // We only include exports after the first pass to avoid issues with
  22567. // the TDZ detection logic
  22568. for (const module of entryModules) {
  22569. if (module.preserveSignature !== false) {
  22570. module.includeAllExports();
  22571. this.needsTreeshakingPass = true;
  22572. }
  22573. }
  22574. }
  22575. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  22576. } while (this.needsTreeshakingPass);
  22577. }
  22578. else {
  22579. for (const module of this.modules)
  22580. module.includeAllInBundle();
  22581. }
  22582. for (const externalModule of this.externalModules)
  22583. externalModule.warnUnusedImports();
  22584. for (const module of this.implicitEntryModules) {
  22585. for (const dependant of module.implicitlyLoadedAfter) {
  22586. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  22587. parseAst_js.error(parseAst_js.logImplicitDependantIsNotIncluded(dependant));
  22588. }
  22589. }
  22590. }
  22591. }
  22592. sortAndBindModules() {
  22593. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  22594. for (const cyclePath of cyclePaths) {
  22595. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularDependency(cyclePath));
  22596. }
  22597. this.modules = orderedModules;
  22598. for (const module of this.modules) {
  22599. module.bindReferences();
  22600. }
  22601. this.warnForMissingExports();
  22602. }
  22603. warnForMissingExports() {
  22604. for (const module of this.modules) {
  22605. for (const importDescription of module.importDescriptions.values()) {
  22606. if (importDescription.name !== '*' && importDescription.phase !== 'source') {
  22607. const [variable, options] = importDescription.module.getVariableForExportName(importDescription.name, { importChain: [module.id] });
  22608. if (!variable) {
  22609. module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(importDescription.name, module.id, importDescription.module.id, !!options?.missingButExportExists), importDescription.start);
  22610. }
  22611. }
  22612. }
  22613. }
  22614. }
  22615. }
  22616. function formatAction([pluginName, hookName, parameters]) {
  22617. const action = `(${pluginName}) ${hookName}`;
  22618. const s = JSON.stringify;
  22619. switch (hookName) {
  22620. case 'resolveId': {
  22621. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  22622. }
  22623. case 'load': {
  22624. return `${action} ${s(parameters[0])}`;
  22625. }
  22626. case 'transform': {
  22627. return `${action} ${s(parameters[1])}`;
  22628. }
  22629. case 'shouldTransformCachedModule': {
  22630. return `${action} ${s(parameters[0].id)}`;
  22631. }
  22632. case 'moduleParsed': {
  22633. return `${action} ${s(parameters[0].id)}`;
  22634. }
  22635. }
  22636. return action;
  22637. }
  22638. let handleBeforeExit = null;
  22639. const rejectByPluginDriver = new Map();
  22640. async function catchUnfinishedHookActions(pluginDriver, callback) {
  22641. const emptyEventLoopPromise = new Promise((_, reject) => {
  22642. rejectByPluginDriver.set(pluginDriver, reject);
  22643. if (!handleBeforeExit) {
  22644. // We only ever create a single event listener to avoid max listener and
  22645. // other issues
  22646. handleBeforeExit = () => {
  22647. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  22648. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  22649. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  22650. [...unfulfilledActions].map(formatAction).join('\n')));
  22651. }
  22652. };
  22653. process$1.once('beforeExit', handleBeforeExit);
  22654. }
  22655. });
  22656. try {
  22657. return await Promise.race([callback(), emptyEventLoopPromise]);
  22658. }
  22659. finally {
  22660. rejectByPluginDriver.delete(pluginDriver);
  22661. if (rejectByPluginDriver.size === 0) {
  22662. process$1.off('beforeExit', handleBeforeExit);
  22663. handleBeforeExit = null;
  22664. }
  22665. }
  22666. }
  22667. async function initWasm() { }
  22668. const fs = /*#__PURE__*/_mergeNamespaces({
  22669. __proto__: null
  22670. }, [promises__namespace]);
  22671. async function normalizeInputOptions(config, watchMode) {
  22672. // These are options that may trigger special warnings or behaviour later
  22673. // if the user did not select an explicit value
  22674. const unsetOptions = new Set();
  22675. const context = config.context ?? 'undefined';
  22676. const plugins = await normalizePluginOption(config.plugins);
  22677. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  22678. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  22679. const strictDeprecations = config.strictDeprecations || false;
  22680. const maxParallelFileOps = getMaxParallelFileOps(config);
  22681. const options = {
  22682. cache: getCache(config),
  22683. context,
  22684. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  22685. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  22686. external: getIdMatcher(config.external),
  22687. fs: config.fs ?? fs,
  22688. input: getInput(config),
  22689. jsx: getJsx(config),
  22690. logLevel,
  22691. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  22692. maxParallelFileOps,
  22693. moduleContext: getModuleContext(config, context),
  22694. onLog,
  22695. perf: config.perf || false,
  22696. plugins,
  22697. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  22698. preserveSymlinks: config.preserveSymlinks || false,
  22699. shimMissingExports: config.shimMissingExports || false,
  22700. strictDeprecations,
  22701. treeshake: getTreeshake(config)
  22702. };
  22703. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  22704. return { options, unsetOptions };
  22705. }
  22706. const getCache = (config) => config.cache === true // `true` is the default
  22707. ? undefined
  22708. : config.cache?.cache || config.cache;
  22709. const getIdMatcher = (option) => {
  22710. if (option === true) {
  22711. return () => true;
  22712. }
  22713. if (typeof option === 'function') {
  22714. return (id, ...parameters) => (id[0] !== '\0' && option(id, ...parameters)) || false;
  22715. }
  22716. if (option) {
  22717. const ids = new Set();
  22718. const matchers = [];
  22719. for (const value of ensureArray$1(option)) {
  22720. if (value instanceof RegExp) {
  22721. matchers.push(value);
  22722. }
  22723. else {
  22724. ids.add(value);
  22725. }
  22726. }
  22727. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  22728. }
  22729. return () => false;
  22730. };
  22731. const getInput = (config) => {
  22732. const configInput = config.input;
  22733. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  22734. };
  22735. const getJsx = (config) => {
  22736. const configJsx = config.jsx;
  22737. if (!configJsx)
  22738. return false;
  22739. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ');
  22740. const { factory, importSource, mode } = configWithPreset;
  22741. switch (mode) {
  22742. case 'automatic': {
  22743. return {
  22744. factory: factory || 'React.createElement',
  22745. importSource: importSource || 'react',
  22746. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  22747. mode: 'automatic'
  22748. };
  22749. }
  22750. case 'preserve': {
  22751. if (importSource && !(factory || configWithPreset.fragment)) {
  22752. 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'));
  22753. }
  22754. return {
  22755. factory: factory || null,
  22756. fragment: configWithPreset.fragment || null,
  22757. importSource: importSource || null,
  22758. mode: 'preserve'
  22759. };
  22760. }
  22761. // case 'classic':
  22762. default: {
  22763. if (mode && mode !== 'classic') {
  22764. parseAst_js.error(parseAst_js.logInvalidOption('jsx.mode', parseAst_js.URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  22765. }
  22766. return {
  22767. factory: factory || 'React.createElement',
  22768. fragment: configWithPreset.fragment || 'React.Fragment',
  22769. importSource: importSource || null,
  22770. mode: 'classic'
  22771. };
  22772. }
  22773. }
  22774. };
  22775. const getMaxParallelFileOps = (config) => {
  22776. const maxParallelFileOps = config.maxParallelFileOps;
  22777. if (typeof maxParallelFileOps === 'number') {
  22778. if (maxParallelFileOps <= 0)
  22779. return Infinity;
  22780. return maxParallelFileOps;
  22781. }
  22782. return 1000;
  22783. };
  22784. const getModuleContext = (config, context) => {
  22785. const configModuleContext = config.moduleContext;
  22786. if (typeof configModuleContext === 'function') {
  22787. return id => configModuleContext(id) ?? context;
  22788. }
  22789. if (configModuleContext) {
  22790. const contextByModuleId = Object.create(null);
  22791. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  22792. contextByModuleId[path.resolve(key)] = moduleContext;
  22793. }
  22794. return id => contextByModuleId[id] ?? context;
  22795. }
  22796. return () => context;
  22797. };
  22798. const getTreeshake = (config) => {
  22799. const configTreeshake = config.treeshake;
  22800. if (configTreeshake === false) {
  22801. return false;
  22802. }
  22803. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ');
  22804. return {
  22805. annotations: configWithPreset.annotations !== false,
  22806. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  22807. manualPureFunctions: configWithPreset.manualPureFunctions ?? parseAst_js.EMPTY_ARRAY,
  22808. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  22809. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  22810. ? 'always'
  22811. : configWithPreset.propertyReadSideEffects !== false,
  22812. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  22813. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  22814. };
  22815. };
  22816. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  22817. if (typeof moduleSideEffectsOption === 'boolean') {
  22818. return () => moduleSideEffectsOption;
  22819. }
  22820. if (moduleSideEffectsOption === 'no-external') {
  22821. return (_id, external) => !external;
  22822. }
  22823. if (typeof moduleSideEffectsOption === 'function') {
  22824. return (id, external) => id[0] === '\0' ? true : moduleSideEffectsOption(id, external) !== false;
  22825. }
  22826. if (Array.isArray(moduleSideEffectsOption)) {
  22827. const ids = new Set(moduleSideEffectsOption);
  22828. return id => ids.has(id);
  22829. }
  22830. if (moduleSideEffectsOption) {
  22831. 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'));
  22832. }
  22833. return () => true;
  22834. };
  22835. // https://datatracker.ietf.org/doc/html/rfc2396
  22836. // eslint-disable-next-line no-control-regex
  22837. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  22838. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  22839. function sanitizeFileName(name) {
  22840. const match = DRIVE_LETTER_REGEX.exec(name);
  22841. const driveLetter = match ? match[0] : '';
  22842. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  22843. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  22844. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  22845. }
  22846. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  22847. // These are options that may trigger special warnings or behaviour later
  22848. // if the user did not select an explicit value
  22849. const unsetOptions = new Set(unsetInputOptions);
  22850. const compact = config.compact || false;
  22851. const format = getFormat(config);
  22852. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  22853. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  22854. const file = getFile(config, preserveModules, inputOptions);
  22855. const generatedCode = getGeneratedCode(config);
  22856. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  22857. const outputOptions = {
  22858. amd: getAmd(config),
  22859. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  22860. banner: getAddon(config, 'banner'),
  22861. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  22862. compact,
  22863. dir: getDir(config, file),
  22864. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  22865. entryFileNames: getEntryFileNames(config, unsetOptions),
  22866. esModule: config.esModule ?? 'if-default-prop',
  22867. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  22868. exports: getExports(config, unsetOptions),
  22869. extend: config.extend || false,
  22870. externalImportAssertions: externalImportAttributes,
  22871. externalImportAttributes,
  22872. externalLiveBindings: config.externalLiveBindings ?? true,
  22873. file,
  22874. footer: getAddon(config, 'footer'),
  22875. format,
  22876. freeze: config.freeze ?? true,
  22877. generatedCode,
  22878. globals: config.globals || {},
  22879. hashCharacters: config.hashCharacters ?? 'base64',
  22880. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  22881. importAttributesKey: config.importAttributesKey ?? 'assert',
  22882. indent: getIndent(config, compact),
  22883. inlineDynamicImports,
  22884. interop: getInterop(config),
  22885. intro: getAddon(config, 'intro'),
  22886. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  22887. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  22888. name: config.name,
  22889. noConflict: config.noConflict || false,
  22890. onlyExplicitManualChunks: config.onlyExplicitManualChunks || false,
  22891. outro: getAddon(config, 'outro'),
  22892. paths: config.paths || {},
  22893. plugins: await normalizePluginOption(config.plugins),
  22894. preserveModules,
  22895. preserveModulesRoot: getPreserveModulesRoot(config),
  22896. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  22897. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  22898. ? config.sanitizeFileName
  22899. : config.sanitizeFileName === false
  22900. ? id => id
  22901. : sanitizeFileName,
  22902. sourcemap: config.sourcemap || false,
  22903. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  22904. sourcemapDebugIds: config.sourcemapDebugIds || false,
  22905. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  22906. sourcemapFile: config.sourcemapFile,
  22907. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  22908. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  22909. ? config.sourcemapIgnoreList
  22910. : config.sourcemapIgnoreList === false
  22911. ? () => false
  22912. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  22913. sourcemapPathTransform: config.sourcemapPathTransform,
  22914. strict: config.strict ?? true,
  22915. systemNullSetters: config.systemNullSetters ?? true,
  22916. validate: config.validate || false,
  22917. virtualDirname: config.virtualDirname || '_virtual'
  22918. };
  22919. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  22920. return { options: outputOptions, unsetOptions };
  22921. }
  22922. const getFile = (config, preserveModules, inputOptions) => {
  22923. const { file } = config;
  22924. if (typeof file === 'string') {
  22925. if (preserveModules) {
  22926. 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'));
  22927. }
  22928. if (!Array.isArray(inputOptions.input))
  22929. 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'));
  22930. }
  22931. return file;
  22932. };
  22933. const getFormat = (config) => {
  22934. const configFormat = config.format;
  22935. switch (configFormat) {
  22936. case undefined:
  22937. case 'es':
  22938. case 'esm':
  22939. case 'module': {
  22940. return 'es';
  22941. }
  22942. case 'cjs':
  22943. case 'commonjs': {
  22944. return 'cjs';
  22945. }
  22946. case 'system':
  22947. case 'systemjs': {
  22948. return 'system';
  22949. }
  22950. case 'amd':
  22951. case 'iife':
  22952. case 'umd': {
  22953. return configFormat;
  22954. }
  22955. default: {
  22956. 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));
  22957. }
  22958. }
  22959. };
  22960. const getInlineDynamicImports = (config, inputOptions) => {
  22961. const inlineDynamicImports = config.inlineDynamicImports || false;
  22962. const { input } = inputOptions;
  22963. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22964. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22965. }
  22966. return inlineDynamicImports;
  22967. };
  22968. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22969. const preserveModules = config.preserveModules || false;
  22970. if (preserveModules) {
  22971. if (inlineDynamicImports) {
  22972. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  22973. }
  22974. if (inputOptions.preserveEntrySignatures === false) {
  22975. return parseAst_js.error(parseAst_js.logInvalidOption('preserveEntrySignatures', parseAst_js.URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  22976. }
  22977. }
  22978. return preserveModules;
  22979. };
  22980. const getPreserveModulesRoot = (config) => {
  22981. const { preserveModulesRoot } = config;
  22982. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22983. return undefined;
  22984. }
  22985. return path.resolve(preserveModulesRoot);
  22986. };
  22987. const getAmd = (config) => {
  22988. const mergedOption = {
  22989. autoId: false,
  22990. basePath: '',
  22991. define: 'define',
  22992. forceJsExtensionForImports: false,
  22993. ...config.amd
  22994. };
  22995. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22996. 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"'));
  22997. }
  22998. if (mergedOption.basePath && !mergedOption.autoId) {
  22999. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.basePath', parseAst_js.URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  23000. }
  23001. return mergedOption.autoId
  23002. ? {
  23003. autoId: true,
  23004. basePath: mergedOption.basePath,
  23005. define: mergedOption.define,
  23006. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  23007. }
  23008. : {
  23009. autoId: false,
  23010. define: mergedOption.define,
  23011. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  23012. id: mergedOption.id
  23013. };
  23014. };
  23015. const getAddon = (config, name) => {
  23016. const configAddon = config[name];
  23017. if (typeof configAddon === 'function') {
  23018. return configAddon;
  23019. }
  23020. return () => configAddon || '';
  23021. };
  23022. const getDir = (config, file) => {
  23023. const { dir } = config;
  23024. if (typeof dir === 'string' && typeof file === 'string') {
  23025. 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'));
  23026. }
  23027. return dir;
  23028. };
  23029. const getEntryFileNames = (config, unsetOptions) => {
  23030. const configEntryFileNames = config.entryFileNames;
  23031. if (configEntryFileNames == null) {
  23032. unsetOptions.add('entryFileNames');
  23033. }
  23034. return configEntryFileNames ?? '[name].js';
  23035. };
  23036. function getExports(config, unsetOptions) {
  23037. const configExports = config.exports;
  23038. if (configExports == null) {
  23039. unsetOptions.add('exports');
  23040. }
  23041. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  23042. return parseAst_js.error(parseAst_js.logInvalidExportOptionValue(configExports));
  23043. }
  23044. return configExports || 'auto';
  23045. }
  23046. const getExternalImportAttributes = (config, inputOptions) => {
  23047. if (config.externalImportAssertions != undefined) {
  23048. parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  23049. }
  23050. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  23051. };
  23052. const getGeneratedCode = (config) => {
  23053. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
  23054. return {
  23055. arrowFunctions: configWithPreset.arrowFunctions === true,
  23056. constBindings: configWithPreset.constBindings === true,
  23057. objectShorthand: configWithPreset.objectShorthand === true,
  23058. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  23059. symbols: configWithPreset.symbols === true
  23060. };
  23061. };
  23062. const getIndent = (config, compact) => {
  23063. if (compact) {
  23064. return '';
  23065. }
  23066. const configIndent = config.indent;
  23067. return configIndent === false ? '' : (configIndent ?? true);
  23068. };
  23069. const ALLOWED_INTEROP_TYPES = new Set([
  23070. 'compat',
  23071. 'auto',
  23072. 'esModule',
  23073. 'default',
  23074. 'defaultOnly'
  23075. ]);
  23076. const getInterop = (config) => {
  23077. const configInterop = config.interop;
  23078. if (typeof configInterop === 'function') {
  23079. const interopPerId = Object.create(null);
  23080. let defaultInterop = null;
  23081. return id => id === null
  23082. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  23083. : id in interopPerId
  23084. ? interopPerId[id]
  23085. : validateInterop((interopPerId[id] = configInterop(id)));
  23086. }
  23087. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  23088. };
  23089. const validateInterop = (interop) => {
  23090. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  23091. 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));
  23092. }
  23093. return interop;
  23094. };
  23095. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  23096. const configManualChunks = config.manualChunks;
  23097. if (configManualChunks) {
  23098. if (inlineDynamicImports) {
  23099. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  23100. }
  23101. if (preserveModules) {
  23102. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  23103. }
  23104. }
  23105. return configManualChunks || {};
  23106. };
  23107. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  23108. const getSourcemapFileNames = (config, unsetOptions) => {
  23109. const configSourcemapFileNames = config.sourcemapFileNames;
  23110. if (configSourcemapFileNames == null) {
  23111. unsetOptions.add('sourcemapFileNames');
  23112. }
  23113. return configSourcemapFileNames;
  23114. };
  23115. const getSourcemapBaseUrl = (config) => {
  23116. const { sourcemapBaseUrl } = config;
  23117. if (sourcemapBaseUrl) {
  23118. if (parseAst_js.isValidUrl(sourcemapBaseUrl)) {
  23119. return parseAst_js.addTrailingSlashIfMissed(sourcemapBaseUrl);
  23120. }
  23121. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapBaseUrl', parseAst_js.URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  23122. }
  23123. };
  23124. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  23125. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  23126. function rollup(rawInputOptions) {
  23127. return rollupInternal(rawInputOptions, null);
  23128. }
  23129. async function rollupInternal(rawInputOptions, watcher) {
  23130. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  23131. initialiseTimers(inputOptions);
  23132. await initWasm();
  23133. const graph = new Graph(inputOptions, watcher);
  23134. // remove the cache object from the memory after graph creation (cache is not used anymore)
  23135. const useCache = rawInputOptions.cache !== false;
  23136. if (rawInputOptions.cache) {
  23137. inputOptions.cache = undefined;
  23138. rawInputOptions.cache = undefined;
  23139. }
  23140. timeStart('BUILD', 1);
  23141. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  23142. try {
  23143. timeStart('initialize', 2);
  23144. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  23145. timeEnd('initialize', 2);
  23146. await graph.build();
  23147. }
  23148. catch (error_) {
  23149. const watchFiles = Object.keys(graph.watchFiles);
  23150. if (watchFiles.length > 0) {
  23151. error_.watchFiles = watchFiles;
  23152. }
  23153. try {
  23154. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  23155. }
  23156. catch (buildEndError) {
  23157. // Create a compound error object to include both errors, based on the original error
  23158. const compoundError = parseAst_js.getRollupError({
  23159. ...error_,
  23160. 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}`
  23161. });
  23162. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  23163. throw compoundError;
  23164. }
  23165. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  23166. throw error_;
  23167. }
  23168. try {
  23169. await graph.pluginDriver.hookParallel('buildEnd', []);
  23170. }
  23171. catch (buildEndError) {
  23172. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  23173. throw buildEndError;
  23174. }
  23175. });
  23176. timeEnd('BUILD', 1);
  23177. const result = {
  23178. get cache() {
  23179. return useCache ? graph.getCache() : undefined;
  23180. },
  23181. async close() {
  23182. if (result.closed)
  23183. return;
  23184. result.closed = true;
  23185. await graph.pluginDriver.hookParallel('closeBundle', []);
  23186. },
  23187. closed: false,
  23188. async [Symbol.asyncDispose]() {
  23189. await this.close();
  23190. },
  23191. async generate(rawOutputOptions) {
  23192. if (result.closed)
  23193. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  23194. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  23195. },
  23196. get watchFiles() {
  23197. return Object.keys(graph.watchFiles);
  23198. },
  23199. async write(rawOutputOptions) {
  23200. if (result.closed)
  23201. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  23202. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  23203. }
  23204. };
  23205. if (inputOptions.perf)
  23206. result.getTimings = getTimings;
  23207. return result;
  23208. }
  23209. async function getInputOptions(initialInputOptions, watchMode) {
  23210. if (!initialInputOptions) {
  23211. throw new Error('You must supply an options object to rollup');
  23212. }
  23213. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  23214. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  23215. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  23216. return { options, unsetOptions };
  23217. }
  23218. async function getProcessedInputOptions(inputOptions, watchMode) {
  23219. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  23220. const logLevel = inputOptions.logLevel || parseAst_js.LOGLEVEL_INFO;
  23221. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  23222. for (const plugin of plugins) {
  23223. const { name, options } = plugin;
  23224. const handler = 'handler' in options ? options.handler : options;
  23225. const processedOptions = await handler.call({
  23226. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  23227. error: (error_) => parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  23228. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  23229. meta: { rollupVersion: version, watchMode },
  23230. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  23231. }, inputOptions);
  23232. if (processedOptions) {
  23233. inputOptions = processedOptions;
  23234. }
  23235. }
  23236. return inputOptions;
  23237. }
  23238. function normalizePlugins(plugins, anonymousPrefix) {
  23239. for (const [index, plugin] of plugins.entries()) {
  23240. if (!plugin.name) {
  23241. plugin.name = `${anonymousPrefix}${index + 1}`;
  23242. }
  23243. }
  23244. }
  23245. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  23246. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  23247. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  23248. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  23249. const generated = await bundle.generate(isWrite);
  23250. if (isWrite) {
  23251. timeStart('WRITE', 1);
  23252. if (!outputOptions.dir && !outputOptions.file) {
  23253. return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
  23254. }
  23255. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
  23256. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  23257. timeEnd('WRITE', 1);
  23258. }
  23259. return createOutput(generated);
  23260. });
  23261. }
  23262. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  23263. if (!rawOutputOptions) {
  23264. throw new Error('You must supply an options object');
  23265. }
  23266. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  23267. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  23268. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  23269. return {
  23270. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  23271. outputPluginDriver
  23272. };
  23273. }
  23274. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  23275. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  23276. const emitError = () => pluginContext.error(parseAst_js.logCannotEmitFromOptionsHook());
  23277. return {
  23278. ...pluginContext,
  23279. emitFile: emitError,
  23280. setAssetSource: emitError
  23281. };
  23282. }), inputOptions, unsetInputOptions);
  23283. }
  23284. function createOutput(outputBundle) {
  23285. return {
  23286. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  23287. };
  23288. }
  23289. var SortingFileType;
  23290. (function (SortingFileType) {
  23291. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  23292. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  23293. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  23294. })(SortingFileType || (SortingFileType = {}));
  23295. function getSortingFileType(file) {
  23296. if (file.type === 'asset') {
  23297. return SortingFileType.ASSET;
  23298. }
  23299. if (file.isEntry) {
  23300. return SortingFileType.ENTRY_CHUNK;
  23301. }
  23302. return SortingFileType.SECONDARY_CHUNK;
  23303. }
  23304. async function writeOutputFile(outputFile, outputOptions, { fs: { mkdir, writeFile } }) {
  23305. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  23306. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  23307. await mkdir(path.dirname(fileName), { recursive: true });
  23308. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  23309. }
  23310. /**
  23311. * Auxiliary function for defining rollup configuration
  23312. * Mainly to facilitate IDE code prompts, after all, export default does not
  23313. * prompt, even if you add @type annotations, it is not accurate
  23314. * @param options
  23315. */
  23316. function defineConfig(options) {
  23317. return options;
  23318. }
  23319. exports.bold = bold;
  23320. exports.commandAliases = commandAliases;
  23321. exports.createFilter = createFilter;
  23322. exports.cyan = cyan;
  23323. exports.defineConfig = defineConfig;
  23324. exports.ensureArray = ensureArray$1;
  23325. exports.getAugmentedNamespace = getAugmentedNamespace;
  23326. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  23327. exports.getNewArray = getNewArray;
  23328. exports.getOrCreate = getOrCreate;
  23329. exports.gray = gray;
  23330. exports.green = green;
  23331. exports.handleError = handleError;
  23332. exports.isWatchEnabled = isWatchEnabled;
  23333. exports.mergeOptions = mergeOptions;
  23334. exports.normalizePluginOption = normalizePluginOption;
  23335. exports.pc = pc;
  23336. exports.rollup = rollup;
  23337. exports.rollupInternal = rollupInternal;
  23338. exports.stderr = stderr;
  23339. exports.underline = underline;
  23340. exports.version = version;
  23341. exports.yellow = yellow;
  23342. //# sourceMappingURL=rollup.js.map