rollup.js 903 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842
  1. /*
  2. @license
  3. Rollup.js v4.52.5
  4. Sat, 18 Oct 2025 06:53:02 GMT - commit 55a8fd5a70820f274921edf394efbbaa620f0962
  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.52.5";
  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, () => []).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 } = parseAst_js.BLANK) {
  907. skipSelf ??= true;
  908. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, 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. /**
  954. * Posix glob regex
  955. */
  956. const DOT_LITERAL = '\\.';
  957. const PLUS_LITERAL = '\\+';
  958. const QMARK_LITERAL = '\\?';
  959. const SLASH_LITERAL = '\\/';
  960. const ONE_CHAR = '(?=.)';
  961. const QMARK = '[^/]';
  962. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  963. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  964. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  965. const NO_DOT = `(?!${DOT_LITERAL})`;
  966. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  967. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  968. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  969. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  970. const STAR = `${QMARK}*?`;
  971. const SEP = '/';
  972. const POSIX_CHARS = {
  973. DOT_LITERAL,
  974. PLUS_LITERAL,
  975. QMARK_LITERAL,
  976. SLASH_LITERAL,
  977. ONE_CHAR,
  978. QMARK,
  979. END_ANCHOR,
  980. DOTS_SLASH,
  981. NO_DOT,
  982. NO_DOTS,
  983. NO_DOT_SLASH,
  984. NO_DOTS_SLASH,
  985. QMARK_NO_DOT,
  986. STAR,
  987. START_ANCHOR,
  988. SEP
  989. };
  990. /**
  991. * Windows glob regex
  992. */
  993. const WINDOWS_CHARS = {
  994. ...POSIX_CHARS,
  995. SLASH_LITERAL: `[${WIN_SLASH}]`,
  996. QMARK: WIN_NO_SLASH,
  997. STAR: `${WIN_NO_SLASH}*?`,
  998. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  999. NO_DOT: `(?!${DOT_LITERAL})`,
  1000. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1001. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  1002. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  1003. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  1004. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  1005. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  1006. SEP: '\\'
  1007. };
  1008. /**
  1009. * POSIX Bracket Regex
  1010. */
  1011. const POSIX_REGEX_SOURCE = {
  1012. alnum: 'a-zA-Z0-9',
  1013. alpha: 'a-zA-Z',
  1014. ascii: '\\x00-\\x7F',
  1015. blank: ' \\t',
  1016. cntrl: '\\x00-\\x1F\\x7F',
  1017. digit: '0-9',
  1018. graph: '\\x21-\\x7E',
  1019. lower: 'a-z',
  1020. print: '\\x20-\\x7E ',
  1021. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  1022. space: ' \\t\\r\\n\\v\\f',
  1023. upper: 'A-Z',
  1024. word: 'A-Za-z0-9_',
  1025. xdigit: 'A-Fa-f0-9'
  1026. };
  1027. constants = {
  1028. MAX_LENGTH: 1024 * 64,
  1029. POSIX_REGEX_SOURCE,
  1030. // regular expressions
  1031. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  1032. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  1033. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  1034. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  1035. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  1036. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  1037. // Replace globs with equivalent patterns to reduce parsing time.
  1038. REPLACEMENTS: {
  1039. __proto__: null,
  1040. '***': '*',
  1041. '**/**': '**',
  1042. '**/**/**': '**'
  1043. },
  1044. // Digits
  1045. CHAR_0: 48, /* 0 */
  1046. CHAR_9: 57, /* 9 */
  1047. // Alphabet chars.
  1048. CHAR_UPPERCASE_A: 65, /* A */
  1049. CHAR_LOWERCASE_A: 97, /* a */
  1050. CHAR_UPPERCASE_Z: 90, /* Z */
  1051. CHAR_LOWERCASE_Z: 122, /* z */
  1052. CHAR_LEFT_PARENTHESES: 40, /* ( */
  1053. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  1054. CHAR_ASTERISK: 42, /* * */
  1055. // Non-alphabetic chars.
  1056. CHAR_AMPERSAND: 38, /* & */
  1057. CHAR_AT: 64, /* @ */
  1058. CHAR_BACKWARD_SLASH: 92, /* \ */
  1059. CHAR_CARRIAGE_RETURN: 13, /* \r */
  1060. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  1061. CHAR_COLON: 58, /* : */
  1062. CHAR_COMMA: 44, /* , */
  1063. CHAR_DOT: 46, /* . */
  1064. CHAR_DOUBLE_QUOTE: 34, /* " */
  1065. CHAR_EQUAL: 61, /* = */
  1066. CHAR_EXCLAMATION_MARK: 33, /* ! */
  1067. CHAR_FORM_FEED: 12, /* \f */
  1068. CHAR_FORWARD_SLASH: 47, /* / */
  1069. CHAR_GRAVE_ACCENT: 96, /* ` */
  1070. CHAR_HASH: 35, /* # */
  1071. CHAR_HYPHEN_MINUS: 45, /* - */
  1072. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  1073. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  1074. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  1075. CHAR_LINE_FEED: 10, /* \n */
  1076. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  1077. CHAR_PERCENT: 37, /* % */
  1078. CHAR_PLUS: 43, /* + */
  1079. CHAR_QUESTION_MARK: 63, /* ? */
  1080. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  1081. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  1082. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  1083. CHAR_SEMICOLON: 59, /* ; */
  1084. CHAR_SINGLE_QUOTE: 39, /* ' */
  1085. CHAR_SPACE: 32, /* */
  1086. CHAR_TAB: 9, /* \t */
  1087. CHAR_UNDERSCORE: 95, /* _ */
  1088. CHAR_VERTICAL_LINE: 124, /* | */
  1089. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  1090. /**
  1091. * Create EXTGLOB_CHARS
  1092. */
  1093. extglobChars(chars) {
  1094. return {
  1095. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  1096. '?': { type: 'qmark', open: '(?:', close: ')?' },
  1097. '+': { type: 'plus', open: '(?:', close: ')+' },
  1098. '*': { type: 'star', open: '(?:', close: ')*' },
  1099. '@': { type: 'at', open: '(?:', close: ')' }
  1100. };
  1101. },
  1102. /**
  1103. * Create GLOB_CHARS
  1104. */
  1105. globChars(win32) {
  1106. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  1107. }
  1108. };
  1109. return constants;
  1110. }
  1111. /*global navigator*/
  1112. var hasRequiredUtils;
  1113. function requireUtils () {
  1114. if (hasRequiredUtils) return utils;
  1115. hasRequiredUtils = 1;
  1116. (function (exports) {
  1117. const {
  1118. REGEX_BACKSLASH,
  1119. REGEX_REMOVE_BACKSLASH,
  1120. REGEX_SPECIAL_CHARS,
  1121. REGEX_SPECIAL_CHARS_GLOBAL
  1122. } = /*@__PURE__*/ requireConstants();
  1123. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  1124. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  1125. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  1126. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  1127. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  1128. exports.isWindows = () => {
  1129. if (typeof navigator !== 'undefined' && navigator.platform) {
  1130. const platform = navigator.platform.toLowerCase();
  1131. return platform === 'win32' || platform === 'windows';
  1132. }
  1133. if (typeof process !== 'undefined' && process.platform) {
  1134. return process.platform === 'win32';
  1135. }
  1136. return false;
  1137. };
  1138. exports.removeBackslashes = str => {
  1139. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  1140. return match === '\\' ? '' : match;
  1141. });
  1142. };
  1143. exports.escapeLast = (input, char, lastIdx) => {
  1144. const idx = input.lastIndexOf(char, lastIdx);
  1145. if (idx === -1) return input;
  1146. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  1147. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  1148. };
  1149. exports.removePrefix = (input, state = {}) => {
  1150. let output = input;
  1151. if (output.startsWith('./')) {
  1152. output = output.slice(2);
  1153. state.prefix = './';
  1154. }
  1155. return output;
  1156. };
  1157. exports.wrapOutput = (input, state = {}, options = {}) => {
  1158. const prepend = options.contains ? '' : '^';
  1159. const append = options.contains ? '' : '$';
  1160. let output = `${prepend}(?:${input})${append}`;
  1161. if (state.negated === true) {
  1162. output = `(?:^(?!${output}).*$)`;
  1163. }
  1164. return output;
  1165. };
  1166. exports.basename = (path, { windows } = {}) => {
  1167. const segs = path.split(windows ? /[\\/]/ : '/');
  1168. const last = segs[segs.length - 1];
  1169. if (last === '') {
  1170. return segs[segs.length - 2];
  1171. }
  1172. return last;
  1173. };
  1174. } (utils));
  1175. return utils;
  1176. }
  1177. var scan_1;
  1178. var hasRequiredScan;
  1179. function requireScan () {
  1180. if (hasRequiredScan) return scan_1;
  1181. hasRequiredScan = 1;
  1182. const utils = /*@__PURE__*/ requireUtils();
  1183. const {
  1184. CHAR_ASTERISK, /* * */
  1185. CHAR_AT, /* @ */
  1186. CHAR_BACKWARD_SLASH, /* \ */
  1187. CHAR_COMMA, /* , */
  1188. CHAR_DOT, /* . */
  1189. CHAR_EXCLAMATION_MARK, /* ! */
  1190. CHAR_FORWARD_SLASH, /* / */
  1191. CHAR_LEFT_CURLY_BRACE, /* { */
  1192. CHAR_LEFT_PARENTHESES, /* ( */
  1193. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  1194. CHAR_PLUS, /* + */
  1195. CHAR_QUESTION_MARK, /* ? */
  1196. CHAR_RIGHT_CURLY_BRACE, /* } */
  1197. CHAR_RIGHT_PARENTHESES, /* ) */
  1198. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  1199. } = /*@__PURE__*/ requireConstants();
  1200. const isPathSeparator = code => {
  1201. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  1202. };
  1203. const depth = token => {
  1204. if (token.isPrefix !== true) {
  1205. token.depth = token.isGlobstar ? Infinity : 1;
  1206. }
  1207. };
  1208. /**
  1209. * Quickly scans a glob pattern and returns an object with a handful of
  1210. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  1211. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  1212. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  1213. *
  1214. * ```js
  1215. * const pm = require('picomatch');
  1216. * console.log(pm.scan('foo/bar/*.js'));
  1217. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  1218. * ```
  1219. * @param {String} `str`
  1220. * @param {Object} `options`
  1221. * @return {Object} Returns an object with tokens and regex source string.
  1222. * @api public
  1223. */
  1224. const scan = (input, options) => {
  1225. const opts = options || {};
  1226. const length = input.length - 1;
  1227. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  1228. const slashes = [];
  1229. const tokens = [];
  1230. const parts = [];
  1231. let str = input;
  1232. let index = -1;
  1233. let start = 0;
  1234. let lastIndex = 0;
  1235. let isBrace = false;
  1236. let isBracket = false;
  1237. let isGlob = false;
  1238. let isExtglob = false;
  1239. let isGlobstar = false;
  1240. let braceEscaped = false;
  1241. let backslashes = false;
  1242. let negated = false;
  1243. let negatedExtglob = false;
  1244. let finished = false;
  1245. let braces = 0;
  1246. let prev;
  1247. let code;
  1248. let token = { value: '', depth: 0, isGlob: false };
  1249. const eos = () => index >= length;
  1250. const peek = () => str.charCodeAt(index + 1);
  1251. const advance = () => {
  1252. prev = code;
  1253. return str.charCodeAt(++index);
  1254. };
  1255. while (index < length) {
  1256. code = advance();
  1257. let next;
  1258. if (code === CHAR_BACKWARD_SLASH) {
  1259. backslashes = token.backslashes = true;
  1260. code = advance();
  1261. if (code === CHAR_LEFT_CURLY_BRACE) {
  1262. braceEscaped = true;
  1263. }
  1264. continue;
  1265. }
  1266. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  1267. braces++;
  1268. while (eos() !== true && (code = advance())) {
  1269. if (code === CHAR_BACKWARD_SLASH) {
  1270. backslashes = token.backslashes = true;
  1271. advance();
  1272. continue;
  1273. }
  1274. if (code === CHAR_LEFT_CURLY_BRACE) {
  1275. braces++;
  1276. continue;
  1277. }
  1278. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  1279. isBrace = token.isBrace = true;
  1280. isGlob = token.isGlob = true;
  1281. finished = true;
  1282. if (scanToEnd === true) {
  1283. continue;
  1284. }
  1285. break;
  1286. }
  1287. if (braceEscaped !== true && code === CHAR_COMMA) {
  1288. isBrace = token.isBrace = true;
  1289. isGlob = token.isGlob = true;
  1290. finished = true;
  1291. if (scanToEnd === true) {
  1292. continue;
  1293. }
  1294. break;
  1295. }
  1296. if (code === CHAR_RIGHT_CURLY_BRACE) {
  1297. braces--;
  1298. if (braces === 0) {
  1299. braceEscaped = false;
  1300. isBrace = token.isBrace = true;
  1301. finished = true;
  1302. break;
  1303. }
  1304. }
  1305. }
  1306. if (scanToEnd === true) {
  1307. continue;
  1308. }
  1309. break;
  1310. }
  1311. if (code === CHAR_FORWARD_SLASH) {
  1312. slashes.push(index);
  1313. tokens.push(token);
  1314. token = { value: '', depth: 0, isGlob: false };
  1315. if (finished === true) continue;
  1316. if (prev === CHAR_DOT && index === (start + 1)) {
  1317. start += 2;
  1318. continue;
  1319. }
  1320. lastIndex = index + 1;
  1321. continue;
  1322. }
  1323. if (opts.noext !== true) {
  1324. const isExtglobChar = code === CHAR_PLUS
  1325. || code === CHAR_AT
  1326. || code === CHAR_ASTERISK
  1327. || code === CHAR_QUESTION_MARK
  1328. || code === CHAR_EXCLAMATION_MARK;
  1329. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  1330. isGlob = token.isGlob = true;
  1331. isExtglob = token.isExtglob = true;
  1332. finished = true;
  1333. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  1334. negatedExtglob = true;
  1335. }
  1336. if (scanToEnd === true) {
  1337. while (eos() !== true && (code = advance())) {
  1338. if (code === CHAR_BACKWARD_SLASH) {
  1339. backslashes = token.backslashes = true;
  1340. code = advance();
  1341. continue;
  1342. }
  1343. if (code === CHAR_RIGHT_PARENTHESES) {
  1344. isGlob = token.isGlob = true;
  1345. finished = true;
  1346. break;
  1347. }
  1348. }
  1349. continue;
  1350. }
  1351. break;
  1352. }
  1353. }
  1354. if (code === CHAR_ASTERISK) {
  1355. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  1356. isGlob = token.isGlob = true;
  1357. finished = true;
  1358. if (scanToEnd === true) {
  1359. continue;
  1360. }
  1361. break;
  1362. }
  1363. if (code === CHAR_QUESTION_MARK) {
  1364. isGlob = token.isGlob = true;
  1365. finished = true;
  1366. if (scanToEnd === true) {
  1367. continue;
  1368. }
  1369. break;
  1370. }
  1371. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  1372. while (eos() !== true && (next = advance())) {
  1373. if (next === CHAR_BACKWARD_SLASH) {
  1374. backslashes = token.backslashes = true;
  1375. advance();
  1376. continue;
  1377. }
  1378. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  1379. isBracket = token.isBracket = true;
  1380. isGlob = token.isGlob = true;
  1381. finished = true;
  1382. break;
  1383. }
  1384. }
  1385. if (scanToEnd === true) {
  1386. continue;
  1387. }
  1388. break;
  1389. }
  1390. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  1391. negated = token.negated = true;
  1392. start++;
  1393. continue;
  1394. }
  1395. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  1396. isGlob = token.isGlob = true;
  1397. if (scanToEnd === true) {
  1398. while (eos() !== true && (code = advance())) {
  1399. if (code === CHAR_LEFT_PARENTHESES) {
  1400. backslashes = token.backslashes = true;
  1401. code = advance();
  1402. continue;
  1403. }
  1404. if (code === CHAR_RIGHT_PARENTHESES) {
  1405. finished = true;
  1406. break;
  1407. }
  1408. }
  1409. continue;
  1410. }
  1411. break;
  1412. }
  1413. if (isGlob === true) {
  1414. finished = true;
  1415. if (scanToEnd === true) {
  1416. continue;
  1417. }
  1418. break;
  1419. }
  1420. }
  1421. if (opts.noext === true) {
  1422. isExtglob = false;
  1423. isGlob = false;
  1424. }
  1425. let base = str;
  1426. let prefix = '';
  1427. let glob = '';
  1428. if (start > 0) {
  1429. prefix = str.slice(0, start);
  1430. str = str.slice(start);
  1431. lastIndex -= start;
  1432. }
  1433. if (base && isGlob === true && lastIndex > 0) {
  1434. base = str.slice(0, lastIndex);
  1435. glob = str.slice(lastIndex);
  1436. } else if (isGlob === true) {
  1437. base = '';
  1438. glob = str;
  1439. } else {
  1440. base = str;
  1441. }
  1442. if (base && base !== '' && base !== '/' && base !== str) {
  1443. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  1444. base = base.slice(0, -1);
  1445. }
  1446. }
  1447. if (opts.unescape === true) {
  1448. if (glob) glob = utils.removeBackslashes(glob);
  1449. if (base && backslashes === true) {
  1450. base = utils.removeBackslashes(base);
  1451. }
  1452. }
  1453. const state = {
  1454. prefix,
  1455. input,
  1456. start,
  1457. base,
  1458. glob,
  1459. isBrace,
  1460. isBracket,
  1461. isGlob,
  1462. isExtglob,
  1463. isGlobstar,
  1464. negated,
  1465. negatedExtglob
  1466. };
  1467. if (opts.tokens === true) {
  1468. state.maxDepth = 0;
  1469. if (!isPathSeparator(code)) {
  1470. tokens.push(token);
  1471. }
  1472. state.tokens = tokens;
  1473. }
  1474. if (opts.parts === true || opts.tokens === true) {
  1475. let prevIndex;
  1476. for (let idx = 0; idx < slashes.length; idx++) {
  1477. const n = prevIndex ? prevIndex + 1 : start;
  1478. const i = slashes[idx];
  1479. const value = input.slice(n, i);
  1480. if (opts.tokens) {
  1481. if (idx === 0 && start !== 0) {
  1482. tokens[idx].isPrefix = true;
  1483. tokens[idx].value = prefix;
  1484. } else {
  1485. tokens[idx].value = value;
  1486. }
  1487. depth(tokens[idx]);
  1488. state.maxDepth += tokens[idx].depth;
  1489. }
  1490. if (idx !== 0 || value !== '') {
  1491. parts.push(value);
  1492. }
  1493. prevIndex = i;
  1494. }
  1495. if (prevIndex && prevIndex + 1 < input.length) {
  1496. const value = input.slice(prevIndex + 1);
  1497. parts.push(value);
  1498. if (opts.tokens) {
  1499. tokens[tokens.length - 1].value = value;
  1500. depth(tokens[tokens.length - 1]);
  1501. state.maxDepth += tokens[tokens.length - 1].depth;
  1502. }
  1503. }
  1504. state.slashes = slashes;
  1505. state.parts = parts;
  1506. }
  1507. return state;
  1508. };
  1509. scan_1 = scan;
  1510. return scan_1;
  1511. }
  1512. var parse_1;
  1513. var hasRequiredParse;
  1514. function requireParse () {
  1515. if (hasRequiredParse) return parse_1;
  1516. hasRequiredParse = 1;
  1517. const constants = /*@__PURE__*/ requireConstants();
  1518. const utils = /*@__PURE__*/ requireUtils();
  1519. /**
  1520. * Constants
  1521. */
  1522. const {
  1523. MAX_LENGTH,
  1524. POSIX_REGEX_SOURCE,
  1525. REGEX_NON_SPECIAL_CHARS,
  1526. REGEX_SPECIAL_CHARS_BACKREF,
  1527. REPLACEMENTS
  1528. } = constants;
  1529. /**
  1530. * Helpers
  1531. */
  1532. const expandRange = (args, options) => {
  1533. if (typeof options.expandRange === 'function') {
  1534. return options.expandRange(...args, options);
  1535. }
  1536. args.sort();
  1537. const value = `[${args.join('-')}]`;
  1538. return value;
  1539. };
  1540. /**
  1541. * Create the message for a syntax error
  1542. */
  1543. const syntaxError = (type, char) => {
  1544. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  1545. };
  1546. /**
  1547. * Parse the given input string.
  1548. * @param {String} input
  1549. * @param {Object} options
  1550. * @return {Object}
  1551. */
  1552. const parse = (input, options) => {
  1553. if (typeof input !== 'string') {
  1554. throw new TypeError('Expected a string');
  1555. }
  1556. input = REPLACEMENTS[input] || input;
  1557. const opts = { ...options };
  1558. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  1559. let len = input.length;
  1560. if (len > max) {
  1561. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1562. }
  1563. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  1564. const tokens = [bos];
  1565. const capture = opts.capture ? '' : '?:';
  1566. // create constants based on platform, for windows or posix
  1567. const PLATFORM_CHARS = constants.globChars(opts.windows);
  1568. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  1569. const {
  1570. DOT_LITERAL,
  1571. PLUS_LITERAL,
  1572. SLASH_LITERAL,
  1573. ONE_CHAR,
  1574. DOTS_SLASH,
  1575. NO_DOT,
  1576. NO_DOT_SLASH,
  1577. NO_DOTS_SLASH,
  1578. QMARK,
  1579. QMARK_NO_DOT,
  1580. STAR,
  1581. START_ANCHOR
  1582. } = PLATFORM_CHARS;
  1583. const globstar = opts => {
  1584. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1585. };
  1586. const nodot = opts.dot ? '' : NO_DOT;
  1587. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  1588. let star = opts.bash === true ? globstar(opts) : STAR;
  1589. if (opts.capture) {
  1590. star = `(${star})`;
  1591. }
  1592. // minimatch options support
  1593. if (typeof opts.noext === 'boolean') {
  1594. opts.noextglob = opts.noext;
  1595. }
  1596. const state = {
  1597. input,
  1598. index: -1,
  1599. start: 0,
  1600. dot: opts.dot === true,
  1601. consumed: '',
  1602. output: '',
  1603. prefix: '',
  1604. backtrack: false,
  1605. negated: false,
  1606. brackets: 0,
  1607. braces: 0,
  1608. parens: 0,
  1609. quotes: 0,
  1610. globstar: false,
  1611. tokens
  1612. };
  1613. input = utils.removePrefix(input, state);
  1614. len = input.length;
  1615. const extglobs = [];
  1616. const braces = [];
  1617. const stack = [];
  1618. let prev = bos;
  1619. let value;
  1620. /**
  1621. * Tokenizing helpers
  1622. */
  1623. const eos = () => state.index === len - 1;
  1624. const peek = state.peek = (n = 1) => input[state.index + n];
  1625. const advance = state.advance = () => input[++state.index] || '';
  1626. const remaining = () => input.slice(state.index + 1);
  1627. const consume = (value = '', num = 0) => {
  1628. state.consumed += value;
  1629. state.index += num;
  1630. };
  1631. const append = token => {
  1632. state.output += token.output != null ? token.output : token.value;
  1633. consume(token.value);
  1634. };
  1635. const negate = () => {
  1636. let count = 1;
  1637. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  1638. advance();
  1639. state.start++;
  1640. count++;
  1641. }
  1642. if (count % 2 === 0) {
  1643. return false;
  1644. }
  1645. state.negated = true;
  1646. state.start++;
  1647. return true;
  1648. };
  1649. const increment = type => {
  1650. state[type]++;
  1651. stack.push(type);
  1652. };
  1653. const decrement = type => {
  1654. state[type]--;
  1655. stack.pop();
  1656. };
  1657. /**
  1658. * Push tokens onto the tokens array. This helper speeds up
  1659. * tokenizing by 1) helping us avoid backtracking as much as possible,
  1660. * and 2) helping us avoid creating extra tokens when consecutive
  1661. * characters are plain text. This improves performance and simplifies
  1662. * lookbehinds.
  1663. */
  1664. const push = tok => {
  1665. if (prev.type === 'globstar') {
  1666. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  1667. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  1668. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  1669. state.output = state.output.slice(0, -prev.output.length);
  1670. prev.type = 'star';
  1671. prev.value = '*';
  1672. prev.output = star;
  1673. state.output += prev.output;
  1674. }
  1675. }
  1676. if (extglobs.length && tok.type !== 'paren') {
  1677. extglobs[extglobs.length - 1].inner += tok.value;
  1678. }
  1679. if (tok.value || tok.output) append(tok);
  1680. if (prev && prev.type === 'text' && tok.type === 'text') {
  1681. prev.output = (prev.output || prev.value) + tok.value;
  1682. prev.value += tok.value;
  1683. return;
  1684. }
  1685. tok.prev = prev;
  1686. tokens.push(tok);
  1687. prev = tok;
  1688. };
  1689. const extglobOpen = (type, value) => {
  1690. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1691. token.prev = prev;
  1692. token.parens = state.parens;
  1693. token.output = state.output;
  1694. const output = (opts.capture ? '(' : '') + token.open;
  1695. increment('parens');
  1696. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1697. push({ type: 'paren', extglob: true, value: advance(), output });
  1698. extglobs.push(token);
  1699. };
  1700. const extglobClose = token => {
  1701. let output = token.close + (opts.capture ? ')' : '');
  1702. let rest;
  1703. if (token.type === 'negate') {
  1704. let extglobStar = star;
  1705. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1706. extglobStar = globstar(opts);
  1707. }
  1708. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1709. output = token.close = `)$))${extglobStar}`;
  1710. }
  1711. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1712. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1713. // In this case, we need to parse the string and use it in the output of the original pattern.
  1714. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1715. //
  1716. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1717. const expression = parse(rest, { ...options, fastpaths: false }).output;
  1718. output = token.close = `)${expression})${extglobStar})`;
  1719. }
  1720. if (token.prev.type === 'bos') {
  1721. state.negatedExtglob = true;
  1722. }
  1723. }
  1724. push({ type: 'paren', extglob: true, value, output });
  1725. decrement('parens');
  1726. };
  1727. /**
  1728. * Fast paths
  1729. */
  1730. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1731. let backslashes = false;
  1732. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  1733. if (first === '\\') {
  1734. backslashes = true;
  1735. return m;
  1736. }
  1737. if (first === '?') {
  1738. if (esc) {
  1739. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1740. }
  1741. if (index === 0) {
  1742. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1743. }
  1744. return QMARK.repeat(chars.length);
  1745. }
  1746. if (first === '.') {
  1747. return DOT_LITERAL.repeat(chars.length);
  1748. }
  1749. if (first === '*') {
  1750. if (esc) {
  1751. return esc + first + (rest ? star : '');
  1752. }
  1753. return star;
  1754. }
  1755. return esc ? m : `\\${m}`;
  1756. });
  1757. if (backslashes === true) {
  1758. if (opts.unescape === true) {
  1759. output = output.replace(/\\/g, '');
  1760. } else {
  1761. output = output.replace(/\\+/g, m => {
  1762. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1763. });
  1764. }
  1765. }
  1766. if (output === input && opts.contains === true) {
  1767. state.output = input;
  1768. return state;
  1769. }
  1770. state.output = utils.wrapOutput(output, state, options);
  1771. return state;
  1772. }
  1773. /**
  1774. * Tokenize input until we reach end-of-string
  1775. */
  1776. while (!eos()) {
  1777. value = advance();
  1778. if (value === '\u0000') {
  1779. continue;
  1780. }
  1781. /**
  1782. * Escaped characters
  1783. */
  1784. if (value === '\\') {
  1785. const next = peek();
  1786. if (next === '/' && opts.bash !== true) {
  1787. continue;
  1788. }
  1789. if (next === '.' || next === ';') {
  1790. continue;
  1791. }
  1792. if (!next) {
  1793. value += '\\';
  1794. push({ type: 'text', value });
  1795. continue;
  1796. }
  1797. // collapse slashes to reduce potential for exploits
  1798. const match = /^\\+/.exec(remaining());
  1799. let slashes = 0;
  1800. if (match && match[0].length > 2) {
  1801. slashes = match[0].length;
  1802. state.index += slashes;
  1803. if (slashes % 2 !== 0) {
  1804. value += '\\';
  1805. }
  1806. }
  1807. if (opts.unescape === true) {
  1808. value = advance();
  1809. } else {
  1810. value += advance();
  1811. }
  1812. if (state.brackets === 0) {
  1813. push({ type: 'text', value });
  1814. continue;
  1815. }
  1816. }
  1817. /**
  1818. * If we're inside a regex character class, continue
  1819. * until we reach the closing bracket.
  1820. */
  1821. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1822. if (opts.posix !== false && value === ':') {
  1823. const inner = prev.value.slice(1);
  1824. if (inner.includes('[')) {
  1825. prev.posix = true;
  1826. if (inner.includes(':')) {
  1827. const idx = prev.value.lastIndexOf('[');
  1828. const pre = prev.value.slice(0, idx);
  1829. const rest = prev.value.slice(idx + 2);
  1830. const posix = POSIX_REGEX_SOURCE[rest];
  1831. if (posix) {
  1832. prev.value = pre + posix;
  1833. state.backtrack = true;
  1834. advance();
  1835. if (!bos.output && tokens.indexOf(prev) === 1) {
  1836. bos.output = ONE_CHAR;
  1837. }
  1838. continue;
  1839. }
  1840. }
  1841. }
  1842. }
  1843. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1844. value = `\\${value}`;
  1845. }
  1846. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1847. value = `\\${value}`;
  1848. }
  1849. if (opts.posix === true && value === '!' && prev.value === '[') {
  1850. value = '^';
  1851. }
  1852. prev.value += value;
  1853. append({ value });
  1854. continue;
  1855. }
  1856. /**
  1857. * If we're inside a quoted string, continue
  1858. * until we reach the closing double quote.
  1859. */
  1860. if (state.quotes === 1 && value !== '"') {
  1861. value = utils.escapeRegex(value);
  1862. prev.value += value;
  1863. append({ value });
  1864. continue;
  1865. }
  1866. /**
  1867. * Double quotes
  1868. */
  1869. if (value === '"') {
  1870. state.quotes = state.quotes === 1 ? 0 : 1;
  1871. if (opts.keepQuotes === true) {
  1872. push({ type: 'text', value });
  1873. }
  1874. continue;
  1875. }
  1876. /**
  1877. * Parentheses
  1878. */
  1879. if (value === '(') {
  1880. increment('parens');
  1881. push({ type: 'paren', value });
  1882. continue;
  1883. }
  1884. if (value === ')') {
  1885. if (state.parens === 0 && opts.strictBrackets === true) {
  1886. throw new SyntaxError(syntaxError('opening', '('));
  1887. }
  1888. const extglob = extglobs[extglobs.length - 1];
  1889. if (extglob && state.parens === extglob.parens + 1) {
  1890. extglobClose(extglobs.pop());
  1891. continue;
  1892. }
  1893. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1894. decrement('parens');
  1895. continue;
  1896. }
  1897. /**
  1898. * Square brackets
  1899. */
  1900. if (value === '[') {
  1901. if (opts.nobracket === true || !remaining().includes(']')) {
  1902. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1903. throw new SyntaxError(syntaxError('closing', ']'));
  1904. }
  1905. value = `\\${value}`;
  1906. } else {
  1907. increment('brackets');
  1908. }
  1909. push({ type: 'bracket', value });
  1910. continue;
  1911. }
  1912. if (value === ']') {
  1913. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1914. push({ type: 'text', value, output: `\\${value}` });
  1915. continue;
  1916. }
  1917. if (state.brackets === 0) {
  1918. if (opts.strictBrackets === true) {
  1919. throw new SyntaxError(syntaxError('opening', '['));
  1920. }
  1921. push({ type: 'text', value, output: `\\${value}` });
  1922. continue;
  1923. }
  1924. decrement('brackets');
  1925. const prevValue = prev.value.slice(1);
  1926. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1927. value = `/${value}`;
  1928. }
  1929. prev.value += value;
  1930. append({ value });
  1931. // when literal brackets are explicitly disabled
  1932. // assume we should match with a regex character class
  1933. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  1934. continue;
  1935. }
  1936. const escaped = utils.escapeRegex(prev.value);
  1937. state.output = state.output.slice(0, -prev.value.length);
  1938. // when literal brackets are explicitly enabled
  1939. // assume we should escape the brackets to match literal characters
  1940. if (opts.literalBrackets === true) {
  1941. state.output += escaped;
  1942. prev.value = escaped;
  1943. continue;
  1944. }
  1945. // when the user specifies nothing, try to match both
  1946. prev.value = `(${capture}${escaped}|${prev.value})`;
  1947. state.output += prev.value;
  1948. continue;
  1949. }
  1950. /**
  1951. * Braces
  1952. */
  1953. if (value === '{' && opts.nobrace !== true) {
  1954. increment('braces');
  1955. const open = {
  1956. type: 'brace',
  1957. value,
  1958. output: '(',
  1959. outputIndex: state.output.length,
  1960. tokensIndex: state.tokens.length
  1961. };
  1962. braces.push(open);
  1963. push(open);
  1964. continue;
  1965. }
  1966. if (value === '}') {
  1967. const brace = braces[braces.length - 1];
  1968. if (opts.nobrace === true || !brace) {
  1969. push({ type: 'text', value, output: value });
  1970. continue;
  1971. }
  1972. let output = ')';
  1973. if (brace.dots === true) {
  1974. const arr = tokens.slice();
  1975. const range = [];
  1976. for (let i = arr.length - 1; i >= 0; i--) {
  1977. tokens.pop();
  1978. if (arr[i].type === 'brace') {
  1979. break;
  1980. }
  1981. if (arr[i].type !== 'dots') {
  1982. range.unshift(arr[i].value);
  1983. }
  1984. }
  1985. output = expandRange(range, opts);
  1986. state.backtrack = true;
  1987. }
  1988. if (brace.comma !== true && brace.dots !== true) {
  1989. const out = state.output.slice(0, brace.outputIndex);
  1990. const toks = state.tokens.slice(brace.tokensIndex);
  1991. brace.value = brace.output = '\\{';
  1992. value = output = '\\}';
  1993. state.output = out;
  1994. for (const t of toks) {
  1995. state.output += (t.output || t.value);
  1996. }
  1997. }
  1998. push({ type: 'brace', value, output });
  1999. decrement('braces');
  2000. braces.pop();
  2001. continue;
  2002. }
  2003. /**
  2004. * Pipes
  2005. */
  2006. if (value === '|') {
  2007. if (extglobs.length > 0) {
  2008. extglobs[extglobs.length - 1].conditions++;
  2009. }
  2010. push({ type: 'text', value });
  2011. continue;
  2012. }
  2013. /**
  2014. * Commas
  2015. */
  2016. if (value === ',') {
  2017. let output = value;
  2018. const brace = braces[braces.length - 1];
  2019. if (brace && stack[stack.length - 1] === 'braces') {
  2020. brace.comma = true;
  2021. output = '|';
  2022. }
  2023. push({ type: 'comma', value, output });
  2024. continue;
  2025. }
  2026. /**
  2027. * Slashes
  2028. */
  2029. if (value === '/') {
  2030. // if the beginning of the glob is "./", advance the start
  2031. // to the current index, and don't add the "./" characters
  2032. // to the state. This greatly simplifies lookbehinds when
  2033. // checking for BOS characters like "!" and "." (not "./")
  2034. if (prev.type === 'dot' && state.index === state.start + 1) {
  2035. state.start = state.index + 1;
  2036. state.consumed = '';
  2037. state.output = '';
  2038. tokens.pop();
  2039. prev = bos; // reset "prev" to the first token
  2040. continue;
  2041. }
  2042. push({ type: 'slash', value, output: SLASH_LITERAL });
  2043. continue;
  2044. }
  2045. /**
  2046. * Dots
  2047. */
  2048. if (value === '.') {
  2049. if (state.braces > 0 && prev.type === 'dot') {
  2050. if (prev.value === '.') prev.output = DOT_LITERAL;
  2051. const brace = braces[braces.length - 1];
  2052. prev.type = 'dots';
  2053. prev.output += value;
  2054. prev.value += value;
  2055. brace.dots = true;
  2056. continue;
  2057. }
  2058. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  2059. push({ type: 'text', value, output: DOT_LITERAL });
  2060. continue;
  2061. }
  2062. push({ type: 'dot', value, output: DOT_LITERAL });
  2063. continue;
  2064. }
  2065. /**
  2066. * Question marks
  2067. */
  2068. if (value === '?') {
  2069. const isGroup = prev && prev.value === '(';
  2070. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2071. extglobOpen('qmark', value);
  2072. continue;
  2073. }
  2074. if (prev && prev.type === 'paren') {
  2075. const next = peek();
  2076. let output = value;
  2077. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  2078. output = `\\${value}`;
  2079. }
  2080. push({ type: 'text', value, output });
  2081. continue;
  2082. }
  2083. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  2084. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  2085. continue;
  2086. }
  2087. push({ type: 'qmark', value, output: QMARK });
  2088. continue;
  2089. }
  2090. /**
  2091. * Exclamation
  2092. */
  2093. if (value === '!') {
  2094. if (opts.noextglob !== true && peek() === '(') {
  2095. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  2096. extglobOpen('negate', value);
  2097. continue;
  2098. }
  2099. }
  2100. if (opts.nonegate !== true && state.index === 0) {
  2101. negate();
  2102. continue;
  2103. }
  2104. }
  2105. /**
  2106. * Plus
  2107. */
  2108. if (value === '+') {
  2109. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2110. extglobOpen('plus', value);
  2111. continue;
  2112. }
  2113. if ((prev && prev.value === '(') || opts.regex === false) {
  2114. push({ type: 'plus', value, output: PLUS_LITERAL });
  2115. continue;
  2116. }
  2117. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  2118. push({ type: 'plus', value });
  2119. continue;
  2120. }
  2121. push({ type: 'plus', value: PLUS_LITERAL });
  2122. continue;
  2123. }
  2124. /**
  2125. * Plain text
  2126. */
  2127. if (value === '@') {
  2128. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  2129. push({ type: 'at', extglob: true, value, output: '' });
  2130. continue;
  2131. }
  2132. push({ type: 'text', value });
  2133. continue;
  2134. }
  2135. /**
  2136. * Plain text
  2137. */
  2138. if (value !== '*') {
  2139. if (value === '$' || value === '^') {
  2140. value = `\\${value}`;
  2141. }
  2142. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  2143. if (match) {
  2144. value += match[0];
  2145. state.index += match[0].length;
  2146. }
  2147. push({ type: 'text', value });
  2148. continue;
  2149. }
  2150. /**
  2151. * Stars
  2152. */
  2153. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  2154. prev.type = 'star';
  2155. prev.star = true;
  2156. prev.value += value;
  2157. prev.output = star;
  2158. state.backtrack = true;
  2159. state.globstar = true;
  2160. consume(value);
  2161. continue;
  2162. }
  2163. let rest = remaining();
  2164. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  2165. extglobOpen('star', value);
  2166. continue;
  2167. }
  2168. if (prev.type === 'star') {
  2169. if (opts.noglobstar === true) {
  2170. consume(value);
  2171. continue;
  2172. }
  2173. const prior = prev.prev;
  2174. const before = prior.prev;
  2175. const isStart = prior.type === 'slash' || prior.type === 'bos';
  2176. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  2177. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  2178. push({ type: 'star', value, output: '' });
  2179. continue;
  2180. }
  2181. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  2182. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  2183. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  2184. push({ type: 'star', value, output: '' });
  2185. continue;
  2186. }
  2187. // strip consecutive `/**/`
  2188. while (rest.slice(0, 3) === '/**') {
  2189. const after = input[state.index + 4];
  2190. if (after && after !== '/') {
  2191. break;
  2192. }
  2193. rest = rest.slice(3);
  2194. consume('/**', 3);
  2195. }
  2196. if (prior.type === 'bos' && eos()) {
  2197. prev.type = 'globstar';
  2198. prev.value += value;
  2199. prev.output = globstar(opts);
  2200. state.output = prev.output;
  2201. state.globstar = true;
  2202. consume(value);
  2203. continue;
  2204. }
  2205. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  2206. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2207. prior.output = `(?:${prior.output}`;
  2208. prev.type = 'globstar';
  2209. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  2210. prev.value += value;
  2211. state.globstar = true;
  2212. state.output += prior.output + prev.output;
  2213. consume(value);
  2214. continue;
  2215. }
  2216. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  2217. const end = rest[1] !== void 0 ? '|$' : '';
  2218. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  2219. prior.output = `(?:${prior.output}`;
  2220. prev.type = 'globstar';
  2221. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  2222. prev.value += value;
  2223. state.output += prior.output + prev.output;
  2224. state.globstar = true;
  2225. consume(value + advance());
  2226. push({ type: 'slash', value: '/', output: '' });
  2227. continue;
  2228. }
  2229. if (prior.type === 'bos' && rest[0] === '/') {
  2230. prev.type = 'globstar';
  2231. prev.value += value;
  2232. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  2233. state.output = prev.output;
  2234. state.globstar = true;
  2235. consume(value + advance());
  2236. push({ type: 'slash', value: '/', output: '' });
  2237. continue;
  2238. }
  2239. // remove single star from output
  2240. state.output = state.output.slice(0, -prev.output.length);
  2241. // reset previous token to globstar
  2242. prev.type = 'globstar';
  2243. prev.output = globstar(opts);
  2244. prev.value += value;
  2245. // reset output with globstar
  2246. state.output += prev.output;
  2247. state.globstar = true;
  2248. consume(value);
  2249. continue;
  2250. }
  2251. const token = { type: 'star', value, output: star };
  2252. if (opts.bash === true) {
  2253. token.output = '.*?';
  2254. if (prev.type === 'bos' || prev.type === 'slash') {
  2255. token.output = nodot + token.output;
  2256. }
  2257. push(token);
  2258. continue;
  2259. }
  2260. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  2261. token.output = value;
  2262. push(token);
  2263. continue;
  2264. }
  2265. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  2266. if (prev.type === 'dot') {
  2267. state.output += NO_DOT_SLASH;
  2268. prev.output += NO_DOT_SLASH;
  2269. } else if (opts.dot === true) {
  2270. state.output += NO_DOTS_SLASH;
  2271. prev.output += NO_DOTS_SLASH;
  2272. } else {
  2273. state.output += nodot;
  2274. prev.output += nodot;
  2275. }
  2276. if (peek() !== '*') {
  2277. state.output += ONE_CHAR;
  2278. prev.output += ONE_CHAR;
  2279. }
  2280. }
  2281. push(token);
  2282. }
  2283. while (state.brackets > 0) {
  2284. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  2285. state.output = utils.escapeLast(state.output, '[');
  2286. decrement('brackets');
  2287. }
  2288. while (state.parens > 0) {
  2289. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  2290. state.output = utils.escapeLast(state.output, '(');
  2291. decrement('parens');
  2292. }
  2293. while (state.braces > 0) {
  2294. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  2295. state.output = utils.escapeLast(state.output, '{');
  2296. decrement('braces');
  2297. }
  2298. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  2299. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  2300. }
  2301. // rebuild the output if we had to backtrack at any point
  2302. if (state.backtrack === true) {
  2303. state.output = '';
  2304. for (const token of state.tokens) {
  2305. state.output += token.output != null ? token.output : token.value;
  2306. if (token.suffix) {
  2307. state.output += token.suffix;
  2308. }
  2309. }
  2310. }
  2311. return state;
  2312. };
  2313. /**
  2314. * Fast paths for creating regular expressions for common glob patterns.
  2315. * This can significantly speed up processing and has very little downside
  2316. * impact when none of the fast paths match.
  2317. */
  2318. parse.fastpaths = (input, options) => {
  2319. const opts = { ...options };
  2320. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2321. const len = input.length;
  2322. if (len > max) {
  2323. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2324. }
  2325. input = REPLACEMENTS[input] || input;
  2326. // create constants based on platform, for windows or posix
  2327. const {
  2328. DOT_LITERAL,
  2329. SLASH_LITERAL,
  2330. ONE_CHAR,
  2331. DOTS_SLASH,
  2332. NO_DOT,
  2333. NO_DOTS,
  2334. NO_DOTS_SLASH,
  2335. STAR,
  2336. START_ANCHOR
  2337. } = constants.globChars(opts.windows);
  2338. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  2339. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  2340. const capture = opts.capture ? '' : '?:';
  2341. const state = { negated: false, prefix: '' };
  2342. let star = opts.bash === true ? '.*?' : STAR;
  2343. if (opts.capture) {
  2344. star = `(${star})`;
  2345. }
  2346. const globstar = opts => {
  2347. if (opts.noglobstar === true) return star;
  2348. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2349. };
  2350. const create = str => {
  2351. switch (str) {
  2352. case '*':
  2353. return `${nodot}${ONE_CHAR}${star}`;
  2354. case '.*':
  2355. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  2356. case '*.*':
  2357. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2358. case '*/*':
  2359. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  2360. case '**':
  2361. return nodot + globstar(opts);
  2362. case '**/*':
  2363. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  2364. case '**/*.*':
  2365. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  2366. case '**/.*':
  2367. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  2368. default: {
  2369. const match = /^(.*?)\.(\w+)$/.exec(str);
  2370. if (!match) return;
  2371. const source = create(match[1]);
  2372. if (!source) return;
  2373. return source + DOT_LITERAL + match[2];
  2374. }
  2375. }
  2376. };
  2377. const output = utils.removePrefix(input, state);
  2378. let source = create(output);
  2379. if (source && opts.strictSlashes !== true) {
  2380. source += `${SLASH_LITERAL}?`;
  2381. }
  2382. return source;
  2383. };
  2384. parse_1 = parse;
  2385. return parse_1;
  2386. }
  2387. var picomatch_1$1;
  2388. var hasRequiredPicomatch$1;
  2389. function requirePicomatch$1 () {
  2390. if (hasRequiredPicomatch$1) return picomatch_1$1;
  2391. hasRequiredPicomatch$1 = 1;
  2392. const scan = /*@__PURE__*/ requireScan();
  2393. const parse = /*@__PURE__*/ requireParse();
  2394. const utils = /*@__PURE__*/ requireUtils();
  2395. const constants = /*@__PURE__*/ requireConstants();
  2396. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  2397. /**
  2398. * Creates a matcher function from one or more glob patterns. The
  2399. * returned function takes a string to match as its first argument,
  2400. * and returns true if the string is a match. The returned matcher
  2401. * function also takes a boolean as the second argument that, when true,
  2402. * returns an object with additional information.
  2403. *
  2404. * ```js
  2405. * const picomatch = require('picomatch');
  2406. * // picomatch(glob[, options]);
  2407. *
  2408. * const isMatch = picomatch('*.!(*a)');
  2409. * console.log(isMatch('a.a')); //=> false
  2410. * console.log(isMatch('a.b')); //=> true
  2411. * ```
  2412. * @name picomatch
  2413. * @param {String|Array} `globs` One or more glob patterns.
  2414. * @param {Object=} `options`
  2415. * @return {Function=} Returns a matcher function.
  2416. * @api public
  2417. */
  2418. const picomatch = (glob, options, returnState = false) => {
  2419. if (Array.isArray(glob)) {
  2420. const fns = glob.map(input => picomatch(input, options, returnState));
  2421. const arrayMatcher = str => {
  2422. for (const isMatch of fns) {
  2423. const state = isMatch(str);
  2424. if (state) return state;
  2425. }
  2426. return false;
  2427. };
  2428. return arrayMatcher;
  2429. }
  2430. const isState = isObject(glob) && glob.tokens && glob.input;
  2431. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  2432. throw new TypeError('Expected pattern to be a non-empty string');
  2433. }
  2434. const opts = options || {};
  2435. const posix = opts.windows;
  2436. const regex = isState
  2437. ? picomatch.compileRe(glob, options)
  2438. : picomatch.makeRe(glob, options, false, true);
  2439. const state = regex.state;
  2440. delete regex.state;
  2441. let isIgnored = () => false;
  2442. if (opts.ignore) {
  2443. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  2444. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  2445. }
  2446. const matcher = (input, returnObject = false) => {
  2447. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  2448. const result = { glob, state, regex, posix, input, output, match, isMatch };
  2449. if (typeof opts.onResult === 'function') {
  2450. opts.onResult(result);
  2451. }
  2452. if (isMatch === false) {
  2453. result.isMatch = false;
  2454. return returnObject ? result : false;
  2455. }
  2456. if (isIgnored(input)) {
  2457. if (typeof opts.onIgnore === 'function') {
  2458. opts.onIgnore(result);
  2459. }
  2460. result.isMatch = false;
  2461. return returnObject ? result : false;
  2462. }
  2463. if (typeof opts.onMatch === 'function') {
  2464. opts.onMatch(result);
  2465. }
  2466. return returnObject ? result : true;
  2467. };
  2468. if (returnState) {
  2469. matcher.state = state;
  2470. }
  2471. return matcher;
  2472. };
  2473. /**
  2474. * Test `input` with the given `regex`. This is used by the main
  2475. * `picomatch()` function to test the input string.
  2476. *
  2477. * ```js
  2478. * const picomatch = require('picomatch');
  2479. * // picomatch.test(input, regex[, options]);
  2480. *
  2481. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  2482. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  2483. * ```
  2484. * @param {String} `input` String to test.
  2485. * @param {RegExp} `regex`
  2486. * @return {Object} Returns an object with matching info.
  2487. * @api public
  2488. */
  2489. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  2490. if (typeof input !== 'string') {
  2491. throw new TypeError('Expected input to be a string');
  2492. }
  2493. if (input === '') {
  2494. return { isMatch: false, output: '' };
  2495. }
  2496. const opts = options || {};
  2497. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  2498. let match = input === glob;
  2499. let output = (match && format) ? format(input) : input;
  2500. if (match === false) {
  2501. output = format ? format(input) : input;
  2502. match = output === glob;
  2503. }
  2504. if (match === false || opts.capture === true) {
  2505. if (opts.matchBase === true || opts.basename === true) {
  2506. match = picomatch.matchBase(input, regex, options, posix);
  2507. } else {
  2508. match = regex.exec(output);
  2509. }
  2510. }
  2511. return { isMatch: Boolean(match), match, output };
  2512. };
  2513. /**
  2514. * Match the basename of a filepath.
  2515. *
  2516. * ```js
  2517. * const picomatch = require('picomatch');
  2518. * // picomatch.matchBase(input, glob[, options]);
  2519. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  2520. * ```
  2521. * @param {String} `input` String to test.
  2522. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  2523. * @return {Boolean}
  2524. * @api public
  2525. */
  2526. picomatch.matchBase = (input, glob, options) => {
  2527. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  2528. return regex.test(utils.basename(input));
  2529. };
  2530. /**
  2531. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  2532. *
  2533. * ```js
  2534. * const picomatch = require('picomatch');
  2535. * // picomatch.isMatch(string, patterns[, options]);
  2536. *
  2537. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  2538. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  2539. * ```
  2540. * @param {String|Array} str The string to test.
  2541. * @param {String|Array} patterns One or more glob patterns to use for matching.
  2542. * @param {Object} [options] See available [options](#options).
  2543. * @return {Boolean} Returns true if any patterns match `str`
  2544. * @api public
  2545. */
  2546. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  2547. /**
  2548. * Parse a glob pattern to create the source string for a regular
  2549. * expression.
  2550. *
  2551. * ```js
  2552. * const picomatch = require('picomatch');
  2553. * const result = picomatch.parse(pattern[, options]);
  2554. * ```
  2555. * @param {String} `pattern`
  2556. * @param {Object} `options`
  2557. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  2558. * @api public
  2559. */
  2560. picomatch.parse = (pattern, options) => {
  2561. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  2562. return parse(pattern, { ...options, fastpaths: false });
  2563. };
  2564. /**
  2565. * Scan a glob pattern to separate the pattern into segments.
  2566. *
  2567. * ```js
  2568. * const picomatch = require('picomatch');
  2569. * // picomatch.scan(input[, options]);
  2570. *
  2571. * const result = picomatch.scan('!./foo/*.js');
  2572. * console.log(result);
  2573. * { prefix: '!./',
  2574. * input: '!./foo/*.js',
  2575. * start: 3,
  2576. * base: 'foo',
  2577. * glob: '*.js',
  2578. * isBrace: false,
  2579. * isBracket: false,
  2580. * isGlob: true,
  2581. * isExtglob: false,
  2582. * isGlobstar: false,
  2583. * negated: true }
  2584. * ```
  2585. * @param {String} `input` Glob pattern to scan.
  2586. * @param {Object} `options`
  2587. * @return {Object} Returns an object with
  2588. * @api public
  2589. */
  2590. picomatch.scan = (input, options) => scan(input, options);
  2591. /**
  2592. * Compile a regular expression from the `state` object returned by the
  2593. * [parse()](#parse) method.
  2594. *
  2595. * @param {Object} `state`
  2596. * @param {Object} `options`
  2597. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  2598. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  2599. * @return {RegExp}
  2600. * @api public
  2601. */
  2602. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  2603. if (returnOutput === true) {
  2604. return state.output;
  2605. }
  2606. const opts = options || {};
  2607. const prepend = opts.contains ? '' : '^';
  2608. const append = opts.contains ? '' : '$';
  2609. let source = `${prepend}(?:${state.output})${append}`;
  2610. if (state && state.negated === true) {
  2611. source = `^(?!${source}).*$`;
  2612. }
  2613. const regex = picomatch.toRegex(source, options);
  2614. if (returnState === true) {
  2615. regex.state = state;
  2616. }
  2617. return regex;
  2618. };
  2619. /**
  2620. * Create a regular expression from a parsed glob pattern.
  2621. *
  2622. * ```js
  2623. * const picomatch = require('picomatch');
  2624. * const state = picomatch.parse('*.js');
  2625. * // picomatch.compileRe(state[, options]);
  2626. *
  2627. * console.log(picomatch.compileRe(state));
  2628. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2629. * ```
  2630. * @param {String} `state` The object returned from the `.parse` method.
  2631. * @param {Object} `options`
  2632. * @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.
  2633. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  2634. * @return {RegExp} Returns a regex created from the given pattern.
  2635. * @api public
  2636. */
  2637. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  2638. if (!input || typeof input !== 'string') {
  2639. throw new TypeError('Expected a non-empty string');
  2640. }
  2641. let parsed = { negated: false, fastpaths: true };
  2642. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  2643. parsed.output = parse.fastpaths(input, options);
  2644. }
  2645. if (!parsed.output) {
  2646. parsed = parse(input, options);
  2647. }
  2648. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  2649. };
  2650. /**
  2651. * Create a regular expression from the given regex source string.
  2652. *
  2653. * ```js
  2654. * const picomatch = require('picomatch');
  2655. * // picomatch.toRegex(source[, options]);
  2656. *
  2657. * const { output } = picomatch.parse('*.js');
  2658. * console.log(picomatch.toRegex(output));
  2659. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  2660. * ```
  2661. * @param {String} `source` Regular expression source string.
  2662. * @param {Object} `options`
  2663. * @return {RegExp}
  2664. * @api public
  2665. */
  2666. picomatch.toRegex = (source, options) => {
  2667. try {
  2668. const opts = options || {};
  2669. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  2670. } catch (err) {
  2671. if (options && options.debug === true) throw err;
  2672. return /$^/;
  2673. }
  2674. };
  2675. /**
  2676. * Picomatch constants.
  2677. * @return {Object}
  2678. */
  2679. picomatch.constants = constants;
  2680. /**
  2681. * Expose "picomatch"
  2682. */
  2683. picomatch_1$1 = picomatch;
  2684. return picomatch_1$1;
  2685. }
  2686. var picomatch_1;
  2687. var hasRequiredPicomatch;
  2688. function requirePicomatch () {
  2689. if (hasRequiredPicomatch) return picomatch_1;
  2690. hasRequiredPicomatch = 1;
  2691. const pico = /*@__PURE__*/ requirePicomatch$1();
  2692. const utils = /*@__PURE__*/ requireUtils();
  2693. function picomatch(glob, options, returnState = false) {
  2694. // default to os.platform()
  2695. if (options && (options.windows === null || options.windows === undefined)) {
  2696. // don't mutate the original options object
  2697. options = { ...options, windows: utils.isWindows() };
  2698. }
  2699. return pico(glob, options, returnState);
  2700. }
  2701. Object.assign(picomatch, pico);
  2702. picomatch_1 = picomatch;
  2703. return picomatch_1;
  2704. }
  2705. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  2706. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  2707. function getMatcherString$1(glob, cwd) {
  2708. if (glob.startsWith('**') || parseAst_js.isAbsolute(glob)) {
  2709. return parseAst_js.normalize(glob);
  2710. }
  2711. const resolved = path.resolve(cwd, glob);
  2712. return parseAst_js.normalize(resolved);
  2713. }
  2714. function patternToIdFilter(pattern) {
  2715. if (pattern instanceof RegExp) {
  2716. return (id) => {
  2717. const normalizedId = parseAst_js.normalize(id);
  2718. const result = pattern.test(normalizedId);
  2719. pattern.lastIndex = 0;
  2720. return result;
  2721. };
  2722. }
  2723. const cwd = process.cwd();
  2724. const glob = getMatcherString$1(pattern, cwd);
  2725. const matcher = pm(glob, { dot: true });
  2726. return (id) => {
  2727. const normalizedId = parseAst_js.normalize(id);
  2728. return matcher(normalizedId);
  2729. };
  2730. }
  2731. function patternToCodeFilter(pattern) {
  2732. if (pattern instanceof RegExp) {
  2733. return (code) => {
  2734. const result = pattern.test(code);
  2735. pattern.lastIndex = 0;
  2736. return result;
  2737. };
  2738. }
  2739. return (code) => code.includes(pattern);
  2740. }
  2741. function createFilter$1(exclude, include) {
  2742. if (!exclude && !include) {
  2743. return;
  2744. }
  2745. return input => {
  2746. if (exclude?.some(filter => filter(input))) {
  2747. return false;
  2748. }
  2749. if (include?.some(filter => filter(input))) {
  2750. return true;
  2751. }
  2752. return !(include && include.length > 0);
  2753. };
  2754. }
  2755. function normalizeFilter(filter) {
  2756. if (typeof filter === 'string' || filter instanceof RegExp) {
  2757. return {
  2758. include: [filter]
  2759. };
  2760. }
  2761. if (Array.isArray(filter)) {
  2762. return {
  2763. include: filter
  2764. };
  2765. }
  2766. return {
  2767. exclude: filter.exclude ? ensureArray$1(filter.exclude) : undefined,
  2768. include: filter.include ? ensureArray$1(filter.include) : undefined
  2769. };
  2770. }
  2771. function createIdFilter(filter) {
  2772. if (!filter)
  2773. return;
  2774. const { exclude, include } = normalizeFilter(filter);
  2775. const excludeFilter = exclude?.map(patternToIdFilter);
  2776. const includeFilter = include?.map(patternToIdFilter);
  2777. return createFilter$1(excludeFilter, includeFilter);
  2778. }
  2779. function createCodeFilter(filter) {
  2780. if (!filter)
  2781. return;
  2782. const { exclude, include } = normalizeFilter(filter);
  2783. const excludeFilter = exclude?.map(patternToCodeFilter);
  2784. const includeFilter = include?.map(patternToCodeFilter);
  2785. return createFilter$1(excludeFilter, includeFilter);
  2786. }
  2787. function createFilterForId(filter) {
  2788. const filterFunction = createIdFilter(filter);
  2789. return filterFunction ? id => !!filterFunction(id) : undefined;
  2790. }
  2791. function createFilterForTransform(idFilter, codeFilter) {
  2792. if (!idFilter && !codeFilter)
  2793. return;
  2794. const idFilterFunction = createIdFilter(idFilter);
  2795. const codeFilterFunction = createCodeFilter(codeFilter);
  2796. return (id, code) => {
  2797. let fallback = true;
  2798. if (idFilterFunction) {
  2799. fallback &&= idFilterFunction(id);
  2800. }
  2801. if (!fallback) {
  2802. return false;
  2803. }
  2804. if (codeFilterFunction) {
  2805. fallback &&= codeFilterFunction(code);
  2806. }
  2807. return fallback;
  2808. };
  2809. }
  2810. // This will make sure no input hook is omitted
  2811. const inputHookNames = {
  2812. buildEnd: 1,
  2813. buildStart: 1,
  2814. closeBundle: 1,
  2815. closeWatcher: 1,
  2816. load: 1,
  2817. moduleParsed: 1,
  2818. onLog: 1,
  2819. options: 1,
  2820. resolveDynamicImport: 1,
  2821. resolveId: 1,
  2822. shouldTransformCachedModule: 1,
  2823. transform: 1,
  2824. watchChange: 1
  2825. };
  2826. const inputHooks = Object.keys(inputHookNames);
  2827. class PluginDriver {
  2828. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  2829. this.graph = graph;
  2830. this.options = options;
  2831. this.pluginCache = pluginCache;
  2832. this.sortedPlugins = new Map();
  2833. this.unfulfilledActions = new Set();
  2834. this.compiledPluginFilters = {
  2835. idOnlyFilter: new WeakMap(),
  2836. transformFilter: new WeakMap()
  2837. };
  2838. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  2839. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  2840. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  2841. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  2842. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  2843. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  2844. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  2845. const existingPluginNames = new Set();
  2846. this.pluginContexts = new Map(this.plugins.map(plugin => [
  2847. plugin,
  2848. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  2849. ]));
  2850. if (basePluginDriver) {
  2851. for (const plugin of userPlugins) {
  2852. for (const hook of inputHooks) {
  2853. if (hook in plugin) {
  2854. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInputHookInOutputPlugin(plugin.name, hook));
  2855. }
  2856. }
  2857. }
  2858. }
  2859. }
  2860. createOutputPluginDriver(plugins) {
  2861. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  2862. }
  2863. getUnfulfilledHookActions() {
  2864. return this.unfulfilledActions;
  2865. }
  2866. // chains, first non-null result stops and returns
  2867. hookFirst(hookName, parameters, replaceContext, skipped) {
  2868. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  2869. }
  2870. // chains, first non-null result stops and returns result and last plugin
  2871. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  2872. for (const plugin of this.getSortedPlugins(hookName)) {
  2873. if (skipped?.has(plugin))
  2874. continue;
  2875. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  2876. if (result != null)
  2877. return [result, plugin];
  2878. }
  2879. return null;
  2880. }
  2881. // chains synchronously, first non-null result stops and returns
  2882. hookFirstSync(hookName, parameters, replaceContext) {
  2883. for (const plugin of this.getSortedPlugins(hookName)) {
  2884. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2885. if (result != null)
  2886. return result;
  2887. }
  2888. return null;
  2889. }
  2890. // parallel, ignores returns
  2891. async hookParallel(hookName, parameters, replaceContext) {
  2892. const parallelPromises = [];
  2893. for (const plugin of this.getSortedPlugins(hookName)) {
  2894. if (plugin[hookName].sequential) {
  2895. await Promise.all(parallelPromises);
  2896. parallelPromises.length = 0;
  2897. await this.runHook(hookName, parameters, plugin, replaceContext);
  2898. }
  2899. else {
  2900. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  2901. }
  2902. }
  2903. await Promise.all(parallelPromises);
  2904. }
  2905. // chains, reduces returned value, handling the reduced value as the first hook argument
  2906. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  2907. let promise = Promise.resolve(argument0);
  2908. for (const plugin of this.getSortedPlugins(hookName)) {
  2909. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  2910. }
  2911. return promise;
  2912. }
  2913. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  2914. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  2915. for (const plugin of this.getSortedPlugins(hookName)) {
  2916. const parameters = [argument0, ...rest];
  2917. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2918. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  2919. }
  2920. return argument0;
  2921. }
  2922. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  2923. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  2924. const results = [];
  2925. const parallelResults = [];
  2926. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  2927. if (plugin[hookName].sequential) {
  2928. results.push(...(await Promise.all(parallelResults)));
  2929. parallelResults.length = 0;
  2930. results.push(await this.runHook(hookName, parameters, plugin));
  2931. }
  2932. else {
  2933. parallelResults.push(this.runHook(hookName, parameters, plugin));
  2934. }
  2935. }
  2936. results.push(...(await Promise.all(parallelResults)));
  2937. return results.reduce(reducer, await initialValue);
  2938. }
  2939. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  2940. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  2941. let accumulator = initialValue;
  2942. for (const plugin of this.getSortedPlugins(hookName)) {
  2943. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  2944. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  2945. }
  2946. return accumulator;
  2947. }
  2948. // chains, ignores returns
  2949. hookSeq(hookName, parameters, replaceContext) {
  2950. let promise = Promise.resolve();
  2951. for (const plugin of this.getSortedPlugins(hookName)) {
  2952. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  2953. }
  2954. return promise.then(noReturn);
  2955. }
  2956. getSortedPlugins(hookName, validateHandler) {
  2957. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  2958. }
  2959. // Implementation signature
  2960. runHook(hookName, parameters, plugin, replaceContext) {
  2961. // We always filter for plugins that support the hook before running it
  2962. const hook = plugin[hookName];
  2963. const handler = typeof hook === 'object' ? hook.handler : hook;
  2964. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  2965. if (hookName === 'transform') {
  2966. const filter = hook.filter;
  2967. const hookParameters = parameters;
  2968. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  2969. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  2970. return Promise.resolve();
  2971. }
  2972. }
  2973. else if (hookName === 'resolveId' || hookName === 'load') {
  2974. const filter = hook.filter;
  2975. const hookParameters = parameters;
  2976. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  2977. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  2978. return Promise.resolve();
  2979. }
  2980. }
  2981. }
  2982. let context = this.pluginContexts.get(plugin);
  2983. if (replaceContext) {
  2984. context = replaceContext(context, plugin);
  2985. }
  2986. let action = null;
  2987. return Promise.resolve()
  2988. .then(() => {
  2989. if (typeof handler !== 'function') {
  2990. return handler;
  2991. }
  2992. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  2993. const hookResult = handler.apply(context, parameters);
  2994. if (!hookResult?.then) {
  2995. // short circuit for non-thenables and non-Promises
  2996. return hookResult;
  2997. }
  2998. // Track pending hook actions to properly error out when
  2999. // unfulfilled promises cause rollup to abruptly and confusingly
  3000. // exit with a successful 0 return code but without producing any
  3001. // output, errors or warnings.
  3002. action = [plugin.name, hookName, parameters];
  3003. this.unfulfilledActions.add(action);
  3004. // Although it would be more elegant to just return hookResult here
  3005. // and put the .then() handler just above the .catch() handler below,
  3006. // doing so would subtly change the defacto async event dispatch order
  3007. // which at least one test and some plugins in the wild may depend on.
  3008. return Promise.resolve(hookResult).then(result => {
  3009. // action was fulfilled
  3010. this.unfulfilledActions.delete(action);
  3011. return result;
  3012. });
  3013. })
  3014. .catch(error_ => {
  3015. if (action !== null) {
  3016. // action considered to be fulfilled since error being handled
  3017. this.unfulfilledActions.delete(action);
  3018. }
  3019. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  3020. });
  3021. }
  3022. /**
  3023. * Run a sync plugin hook and return the result.
  3024. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  3025. * @param args Arguments passed to the plugin hook.
  3026. * @param plugin The acutal plugin
  3027. * @param replaceContext When passed, the plugin context can be overridden.
  3028. */
  3029. runHookSync(hookName, parameters, plugin, replaceContext) {
  3030. const hook = plugin[hookName];
  3031. const handler = typeof hook === 'object' ? hook.handler : hook;
  3032. let context = this.pluginContexts.get(plugin);
  3033. if (replaceContext) {
  3034. context = replaceContext(context, plugin);
  3035. }
  3036. try {
  3037. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  3038. return handler.apply(context, parameters);
  3039. }
  3040. catch (error_) {
  3041. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  3042. }
  3043. }
  3044. }
  3045. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  3046. const pre = [];
  3047. const normal = [];
  3048. const post = [];
  3049. for (const plugin of plugins) {
  3050. const hook = plugin[hookName];
  3051. if (hook) {
  3052. if (typeof hook === 'object') {
  3053. validateHandler(hook.handler, hookName, plugin);
  3054. if (hook.order === 'pre') {
  3055. pre.push(plugin);
  3056. continue;
  3057. }
  3058. if (hook.order === 'post') {
  3059. post.push(plugin);
  3060. continue;
  3061. }
  3062. }
  3063. else {
  3064. validateHandler(hook, hookName, plugin);
  3065. }
  3066. normal.push(plugin);
  3067. }
  3068. }
  3069. return [...pre, ...normal, ...post];
  3070. }
  3071. function validateFunctionPluginHandler(handler, hookName, plugin) {
  3072. if (typeof handler !== 'function') {
  3073. parseAst_js.error(parseAst_js.logInvalidFunctionPluginHook(hookName, plugin.name));
  3074. }
  3075. }
  3076. function validateAddonPluginHandler(handler, hookName, plugin) {
  3077. if (typeof handler !== 'string' && typeof handler !== 'function') {
  3078. return parseAst_js.error(parseAst_js.logInvalidAddonPluginHook(hookName, plugin.name));
  3079. }
  3080. }
  3081. function noReturn() { }
  3082. function getLogger(plugins, onLog, watchMode, logLevel) {
  3083. plugins = getSortedValidatedPlugins('onLog', plugins);
  3084. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  3085. const logger = (level, log, skipped = parseAst_js.EMPTY_SET) => {
  3086. parseAst_js.augmentLogMessage(log);
  3087. const logPriority = parseAst_js.logLevelPriority[level];
  3088. if (logPriority < minimalPriority) {
  3089. return;
  3090. }
  3091. for (const plugin of plugins) {
  3092. if (skipped.has(plugin))
  3093. continue;
  3094. const { onLog: pluginOnLog } = plugin;
  3095. const getLogHandler = (level) => {
  3096. if (parseAst_js.logLevelPriority[level] < minimalPriority) {
  3097. return doNothing;
  3098. }
  3099. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  3100. };
  3101. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  3102. if (handler.call({
  3103. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG),
  3104. error: (log) => parseAst_js.error(normalizeLog(log)),
  3105. info: getLogHandler(parseAst_js.LOGLEVEL_INFO),
  3106. meta: { rollupVersion: version, watchMode },
  3107. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN)
  3108. }, level, log) === false) {
  3109. return;
  3110. }
  3111. }
  3112. onLog(level, log);
  3113. };
  3114. return logger;
  3115. }
  3116. const commandAliases = {
  3117. c: 'config',
  3118. d: 'dir',
  3119. e: 'external',
  3120. f: 'format',
  3121. g: 'globals',
  3122. h: 'help',
  3123. i: 'input',
  3124. m: 'sourcemap',
  3125. n: 'name',
  3126. o: 'file',
  3127. p: 'plugin',
  3128. v: 'version',
  3129. w: 'watch'
  3130. };
  3131. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  3132. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  3133. const command = getCommandOptions(rawCommandOptions);
  3134. const plugins = await normalizePluginOption(config.plugins);
  3135. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  3136. const onLog = getOnLog(config, logLevel, printLog);
  3137. const log = getLogger(plugins, onLog, watchMode, logLevel);
  3138. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  3139. if (command.output) {
  3140. Object.assign(command, command.output);
  3141. }
  3142. const outputOptionsArray = ensureArray$1(config.output);
  3143. if (outputOptionsArray.length === 0)
  3144. outputOptionsArray.push({});
  3145. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  3146. warnUnknownOptions(command, [
  3147. ...Object.keys(inputOptions).filter(option => option !== 'fs'),
  3148. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  3149. ...Object.keys(commandAliases),
  3150. 'bundleConfigAsCjs',
  3151. 'config',
  3152. 'configImportAttributesKey',
  3153. 'configPlugin',
  3154. 'environment',
  3155. 'failAfterWarnings',
  3156. 'filterLogs',
  3157. 'forceExit',
  3158. 'plugin',
  3159. 'silent',
  3160. 'stdin',
  3161. 'waitForBundleInput'
  3162. ], 'CLI flags', log, /^_$|output$|config/);
  3163. inputOptions.output = outputOptions;
  3164. return inputOptions;
  3165. }
  3166. function getCommandOptions(rawCommandOptions) {
  3167. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  3168. ? rawCommandOptions.external.split(',')
  3169. : [];
  3170. return {
  3171. ...rawCommandOptions,
  3172. external,
  3173. globals: typeof rawCommandOptions.globals === 'string'
  3174. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  3175. const [id, variableName] = globalDefinition.split(':');
  3176. globals[id] = variableName;
  3177. if (!external.includes(id)) {
  3178. external.push(id);
  3179. }
  3180. return globals;
  3181. }, Object.create(null))
  3182. : undefined
  3183. };
  3184. }
  3185. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  3186. const getOption = (name) => overrides[name] ?? config[name];
  3187. const inputOptions = {
  3188. cache: config.cache,
  3189. context: getOption('context'),
  3190. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  3191. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  3192. external: getExternal(config, overrides),
  3193. fs: getOption('fs'),
  3194. input: getOption('input') || [],
  3195. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ')),
  3196. logLevel: getOption('logLevel'),
  3197. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  3198. maxParallelFileOps: getOption('maxParallelFileOps'),
  3199. moduleContext: getOption('moduleContext'),
  3200. onLog,
  3201. onwarn: undefined,
  3202. perf: getOption('perf'),
  3203. plugins,
  3204. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  3205. preserveSymlinks: getOption('preserveSymlinks'),
  3206. shimMissingExports: getOption('shimMissingExports'),
  3207. strictDeprecations: getOption('strictDeprecations'),
  3208. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ')),
  3209. watch: getWatch(config, overrides)
  3210. };
  3211. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  3212. return inputOptions;
  3213. }
  3214. const getExternal = (config, overrides) => {
  3215. const configExternal = config.external;
  3216. return typeof configExternal === 'function'
  3217. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  3218. : [...ensureArray$1(configExternal), ...overrides.external];
  3219. };
  3220. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  3221. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  3222. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  3223. if (commandOption !== undefined) {
  3224. return commandOption && { ...configOption, ...commandOption };
  3225. }
  3226. return configOption;
  3227. };
  3228. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  3229. const isWatchEnabled = (optionValue) => {
  3230. if (Array.isArray(optionValue)) {
  3231. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  3232. }
  3233. return optionValue === true;
  3234. };
  3235. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  3236. if (!optionValue) {
  3237. return optionValue;
  3238. }
  3239. if (Array.isArray(optionValue)) {
  3240. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  3241. }
  3242. return objectifyValue(optionValue);
  3243. };
  3244. async function mergeOutputOptions(config, overrides, log) {
  3245. const getOption = (name) => overrides[name] ?? config[name];
  3246. const outputOptions = {
  3247. amd: getObjectOption(config, overrides, 'amd'),
  3248. assetFileNames: getOption('assetFileNames'),
  3249. banner: getOption('banner'),
  3250. chunkFileNames: getOption('chunkFileNames'),
  3251. compact: getOption('compact'),
  3252. dir: getOption('dir'),
  3253. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  3254. entryFileNames: getOption('entryFileNames'),
  3255. esModule: getOption('esModule'),
  3256. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  3257. exports: getOption('exports'),
  3258. extend: getOption('extend'),
  3259. externalImportAssertions: getOption('externalImportAssertions'),
  3260. externalImportAttributes: getOption('externalImportAttributes'),
  3261. externalLiveBindings: getOption('externalLiveBindings'),
  3262. file: getOption('file'),
  3263. footer: getOption('footer'),
  3264. format: getOption('format'),
  3265. freeze: getOption('freeze'),
  3266. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '')),
  3267. globals: getOption('globals'),
  3268. hashCharacters: getOption('hashCharacters'),
  3269. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  3270. importAttributesKey: getOption('importAttributesKey'),
  3271. indent: getOption('indent'),
  3272. inlineDynamicImports: getOption('inlineDynamicImports'),
  3273. interop: getOption('interop'),
  3274. intro: getOption('intro'),
  3275. manualChunks: getOption('manualChunks'),
  3276. minifyInternalExports: getOption('minifyInternalExports'),
  3277. name: getOption('name'),
  3278. noConflict: getOption('noConflict'),
  3279. onlyExplicitManualChunks: getOption('onlyExplicitManualChunks'),
  3280. outro: getOption('outro'),
  3281. paths: getOption('paths'),
  3282. plugins: await normalizePluginOption(config.plugins),
  3283. preserveModules: getOption('preserveModules'),
  3284. preserveModulesRoot: getOption('preserveModulesRoot'),
  3285. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  3286. sanitizeFileName: getOption('sanitizeFileName'),
  3287. sourcemap: getOption('sourcemap'),
  3288. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  3289. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  3290. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  3291. sourcemapFile: getOption('sourcemapFile'),
  3292. sourcemapFileNames: getOption('sourcemapFileNames'),
  3293. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  3294. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  3295. strict: getOption('strict'),
  3296. systemNullSetters: getOption('systemNullSetters'),
  3297. validate: getOption('validate'),
  3298. virtualDirname: getOption('virtualDirname')
  3299. };
  3300. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  3301. return outputOptions;
  3302. }
  3303. var picocolors = {exports: {}};
  3304. var hasRequiredPicocolors;
  3305. function requirePicocolors () {
  3306. if (hasRequiredPicocolors) return picocolors.exports;
  3307. hasRequiredPicocolors = 1;
  3308. let p = process || {}, argv = p.argv || [], env = p.env || {};
  3309. let isColorSupported =
  3310. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  3311. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  3312. let formatter = (open, close, replace = open) =>
  3313. input => {
  3314. let string = "" + input, index = string.indexOf(close, open.length);
  3315. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  3316. };
  3317. let replaceClose = (string, close, replace, index) => {
  3318. let result = "", cursor = 0;
  3319. do {
  3320. result += string.substring(cursor, index) + replace;
  3321. cursor = index + close.length;
  3322. index = string.indexOf(close, cursor);
  3323. } while (~index)
  3324. return result + string.substring(cursor)
  3325. };
  3326. let createColors = (enabled = isColorSupported) => {
  3327. let f = enabled ? formatter : () => String;
  3328. return {
  3329. isColorSupported: enabled,
  3330. reset: f("\x1b[0m", "\x1b[0m"),
  3331. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  3332. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  3333. italic: f("\x1b[3m", "\x1b[23m"),
  3334. underline: f("\x1b[4m", "\x1b[24m"),
  3335. inverse: f("\x1b[7m", "\x1b[27m"),
  3336. hidden: f("\x1b[8m", "\x1b[28m"),
  3337. strikethrough: f("\x1b[9m", "\x1b[29m"),
  3338. black: f("\x1b[30m", "\x1b[39m"),
  3339. red: f("\x1b[31m", "\x1b[39m"),
  3340. green: f("\x1b[32m", "\x1b[39m"),
  3341. yellow: f("\x1b[33m", "\x1b[39m"),
  3342. blue: f("\x1b[34m", "\x1b[39m"),
  3343. magenta: f("\x1b[35m", "\x1b[39m"),
  3344. cyan: f("\x1b[36m", "\x1b[39m"),
  3345. white: f("\x1b[37m", "\x1b[39m"),
  3346. gray: f("\x1b[90m", "\x1b[39m"),
  3347. bgBlack: f("\x1b[40m", "\x1b[49m"),
  3348. bgRed: f("\x1b[41m", "\x1b[49m"),
  3349. bgGreen: f("\x1b[42m", "\x1b[49m"),
  3350. bgYellow: f("\x1b[43m", "\x1b[49m"),
  3351. bgBlue: f("\x1b[44m", "\x1b[49m"),
  3352. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  3353. bgCyan: f("\x1b[46m", "\x1b[49m"),
  3354. bgWhite: f("\x1b[47m", "\x1b[49m"),
  3355. blackBright: f("\x1b[90m", "\x1b[39m"),
  3356. redBright: f("\x1b[91m", "\x1b[39m"),
  3357. greenBright: f("\x1b[92m", "\x1b[39m"),
  3358. yellowBright: f("\x1b[93m", "\x1b[39m"),
  3359. blueBright: f("\x1b[94m", "\x1b[39m"),
  3360. magentaBright: f("\x1b[95m", "\x1b[39m"),
  3361. cyanBright: f("\x1b[96m", "\x1b[39m"),
  3362. whiteBright: f("\x1b[97m", "\x1b[39m"),
  3363. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  3364. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  3365. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  3366. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  3367. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  3368. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  3369. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  3370. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  3371. }
  3372. };
  3373. picocolors.exports = createColors();
  3374. picocolors.exports.createColors = createColors;
  3375. return picocolors.exports;
  3376. }
  3377. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  3378. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  3379. // @see https://no-color.org
  3380. // @see https://www.npmjs.com/package/chalk
  3381. const { bold, cyan, dim, gray, green, red, underline, yellow } = pc.createColors(process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR);
  3382. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  3383. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  3384. function handleError(error, recover = false) {
  3385. const name = error.name || error.cause?.name;
  3386. const nameSection = name ? `${name}: ` : '';
  3387. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  3388. const message = `${pluginSection}${nameSection}${error.message}`;
  3389. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  3390. if (error.url) {
  3391. outputLines.push(cyan(error.url));
  3392. }
  3393. if (error.loc) {
  3394. outputLines.push(`${parseAst_js.relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  3395. }
  3396. else if (error.id) {
  3397. outputLines.push(parseAst_js.relativeId(error.id));
  3398. }
  3399. if (error.frame) {
  3400. outputLines.push(dim(error.frame));
  3401. }
  3402. if (error.stack) {
  3403. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  3404. }
  3405. // ES2022: Error.prototype.cause is optional
  3406. if (error.cause) {
  3407. let cause = error.cause;
  3408. const causeErrorLines = [];
  3409. let indent = '';
  3410. while (cause) {
  3411. indent += ' ';
  3412. const message = cause.stack || cause;
  3413. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  3414. cause = cause.cause;
  3415. }
  3416. outputLines.push(dim(causeErrorLines.join('\n')));
  3417. }
  3418. outputLines.push('', '');
  3419. stderr(outputLines.join('\n'));
  3420. if (!recover)
  3421. process$1.exit(1);
  3422. }
  3423. // src/vlq.ts
  3424. var comma = ",".charCodeAt(0);
  3425. var semicolon = ";".charCodeAt(0);
  3426. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3427. var intToChar = new Uint8Array(64);
  3428. var charToInt = new Uint8Array(128);
  3429. for (let i = 0; i < chars.length; i++) {
  3430. const c = chars.charCodeAt(i);
  3431. intToChar[i] = c;
  3432. charToInt[c] = i;
  3433. }
  3434. function decodeInteger(reader, relative) {
  3435. let value = 0;
  3436. let shift = 0;
  3437. let integer = 0;
  3438. do {
  3439. const c = reader.next();
  3440. integer = charToInt[c];
  3441. value |= (integer & 31) << shift;
  3442. shift += 5;
  3443. } while (integer & 32);
  3444. const shouldNegate = value & 1;
  3445. value >>>= 1;
  3446. if (shouldNegate) {
  3447. value = -2147483648 | -value;
  3448. }
  3449. return relative + value;
  3450. }
  3451. function encodeInteger(builder, num, relative) {
  3452. let delta = num - relative;
  3453. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  3454. do {
  3455. let clamped = delta & 31;
  3456. delta >>>= 5;
  3457. if (delta > 0) clamped |= 32;
  3458. builder.write(intToChar[clamped]);
  3459. } while (delta > 0);
  3460. return num;
  3461. }
  3462. function hasMoreVlq(reader, max) {
  3463. if (reader.pos >= max) return false;
  3464. return reader.peek() !== comma;
  3465. }
  3466. // src/strings.ts
  3467. var bufLength = 1024 * 16;
  3468. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  3469. decode(buf) {
  3470. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  3471. return out.toString();
  3472. }
  3473. } : {
  3474. decode(buf) {
  3475. let out = "";
  3476. for (let i = 0; i < buf.length; i++) {
  3477. out += String.fromCharCode(buf[i]);
  3478. }
  3479. return out;
  3480. }
  3481. };
  3482. var StringWriter = class {
  3483. constructor() {
  3484. this.pos = 0;
  3485. this.out = "";
  3486. this.buffer = new Uint8Array(bufLength);
  3487. }
  3488. write(v) {
  3489. const { buffer } = this;
  3490. buffer[this.pos++] = v;
  3491. if (this.pos === bufLength) {
  3492. this.out += td.decode(buffer);
  3493. this.pos = 0;
  3494. }
  3495. }
  3496. flush() {
  3497. const { buffer, out, pos } = this;
  3498. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  3499. }
  3500. };
  3501. var StringReader = class {
  3502. constructor(buffer) {
  3503. this.pos = 0;
  3504. this.buffer = buffer;
  3505. }
  3506. next() {
  3507. return this.buffer.charCodeAt(this.pos++);
  3508. }
  3509. peek() {
  3510. return this.buffer.charCodeAt(this.pos);
  3511. }
  3512. indexOf(char) {
  3513. const { buffer, pos } = this;
  3514. const idx = buffer.indexOf(char, pos);
  3515. return idx === -1 ? buffer.length : idx;
  3516. }
  3517. };
  3518. // src/sourcemap-codec.ts
  3519. function decode(mappings) {
  3520. const { length } = mappings;
  3521. const reader = new StringReader(mappings);
  3522. const decoded = [];
  3523. let genColumn = 0;
  3524. let sourcesIndex = 0;
  3525. let sourceLine = 0;
  3526. let sourceColumn = 0;
  3527. let namesIndex = 0;
  3528. do {
  3529. const semi = reader.indexOf(";");
  3530. const line = [];
  3531. let sorted = true;
  3532. let lastCol = 0;
  3533. genColumn = 0;
  3534. while (reader.pos < semi) {
  3535. let seg;
  3536. genColumn = decodeInteger(reader, genColumn);
  3537. if (genColumn < lastCol) sorted = false;
  3538. lastCol = genColumn;
  3539. if (hasMoreVlq(reader, semi)) {
  3540. sourcesIndex = decodeInteger(reader, sourcesIndex);
  3541. sourceLine = decodeInteger(reader, sourceLine);
  3542. sourceColumn = decodeInteger(reader, sourceColumn);
  3543. if (hasMoreVlq(reader, semi)) {
  3544. namesIndex = decodeInteger(reader, namesIndex);
  3545. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  3546. } else {
  3547. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  3548. }
  3549. } else {
  3550. seg = [genColumn];
  3551. }
  3552. line.push(seg);
  3553. reader.pos++;
  3554. }
  3555. if (!sorted) sort(line);
  3556. decoded.push(line);
  3557. reader.pos = semi + 1;
  3558. } while (reader.pos <= length);
  3559. return decoded;
  3560. }
  3561. function sort(line) {
  3562. line.sort(sortComparator);
  3563. }
  3564. function sortComparator(a, b) {
  3565. return a[0] - b[0];
  3566. }
  3567. function encode(decoded) {
  3568. const writer = new StringWriter();
  3569. let sourcesIndex = 0;
  3570. let sourceLine = 0;
  3571. let sourceColumn = 0;
  3572. let namesIndex = 0;
  3573. for (let i = 0; i < decoded.length; i++) {
  3574. const line = decoded[i];
  3575. if (i > 0) writer.write(semicolon);
  3576. if (line.length === 0) continue;
  3577. let genColumn = 0;
  3578. for (let j = 0; j < line.length; j++) {
  3579. const segment = line[j];
  3580. if (j > 0) writer.write(comma);
  3581. genColumn = encodeInteger(writer, segment[0], genColumn);
  3582. if (segment.length === 1) continue;
  3583. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  3584. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  3585. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  3586. if (segment.length === 4) continue;
  3587. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  3588. }
  3589. }
  3590. return writer.flush();
  3591. }
  3592. class BitSet {
  3593. constructor(arg) {
  3594. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  3595. }
  3596. add(n) {
  3597. this.bits[n >> 5] |= 1 << (n & 31);
  3598. }
  3599. has(n) {
  3600. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  3601. }
  3602. }
  3603. let Chunk$1 = class Chunk {
  3604. constructor(start, end, content) {
  3605. this.start = start;
  3606. this.end = end;
  3607. this.original = content;
  3608. this.intro = '';
  3609. this.outro = '';
  3610. this.content = content;
  3611. this.storeName = false;
  3612. this.edited = false;
  3613. {
  3614. this.previous = null;
  3615. this.next = null;
  3616. }
  3617. }
  3618. appendLeft(content) {
  3619. this.outro += content;
  3620. }
  3621. appendRight(content) {
  3622. this.intro = this.intro + content;
  3623. }
  3624. clone() {
  3625. const chunk = new Chunk(this.start, this.end, this.original);
  3626. chunk.intro = this.intro;
  3627. chunk.outro = this.outro;
  3628. chunk.content = this.content;
  3629. chunk.storeName = this.storeName;
  3630. chunk.edited = this.edited;
  3631. return chunk;
  3632. }
  3633. contains(index) {
  3634. return this.start < index && index < this.end;
  3635. }
  3636. eachNext(fn) {
  3637. let chunk = this;
  3638. while (chunk) {
  3639. fn(chunk);
  3640. chunk = chunk.next;
  3641. }
  3642. }
  3643. eachPrevious(fn) {
  3644. let chunk = this;
  3645. while (chunk) {
  3646. fn(chunk);
  3647. chunk = chunk.previous;
  3648. }
  3649. }
  3650. edit(content, storeName, contentOnly) {
  3651. this.content = content;
  3652. if (!contentOnly) {
  3653. this.intro = '';
  3654. this.outro = '';
  3655. }
  3656. this.storeName = storeName;
  3657. this.edited = true;
  3658. return this;
  3659. }
  3660. prependLeft(content) {
  3661. this.outro = content + this.outro;
  3662. }
  3663. prependRight(content) {
  3664. this.intro = content + this.intro;
  3665. }
  3666. reset() {
  3667. this.intro = '';
  3668. this.outro = '';
  3669. if (this.edited) {
  3670. this.content = this.original;
  3671. this.storeName = false;
  3672. this.edited = false;
  3673. }
  3674. }
  3675. split(index) {
  3676. const sliceIndex = index - this.start;
  3677. const originalBefore = this.original.slice(0, sliceIndex);
  3678. const originalAfter = this.original.slice(sliceIndex);
  3679. this.original = originalBefore;
  3680. const newChunk = new Chunk(index, this.end, originalAfter);
  3681. newChunk.outro = this.outro;
  3682. this.outro = '';
  3683. this.end = index;
  3684. if (this.edited) {
  3685. // after split we should save the edit content record into the correct chunk
  3686. // to make sure sourcemap correct
  3687. // For example:
  3688. // ' test'.trim()
  3689. // split -> ' ' + 'test'
  3690. // ✔️ edit -> '' + 'test'
  3691. // ✖️ edit -> 'test' + ''
  3692. // TODO is this block necessary?...
  3693. newChunk.edit('', false);
  3694. this.content = '';
  3695. } else {
  3696. this.content = originalBefore;
  3697. }
  3698. newChunk.next = this.next;
  3699. if (newChunk.next) newChunk.next.previous = newChunk;
  3700. newChunk.previous = this;
  3701. this.next = newChunk;
  3702. return newChunk;
  3703. }
  3704. toString() {
  3705. return this.intro + this.content + this.outro;
  3706. }
  3707. trimEnd(rx) {
  3708. this.outro = this.outro.replace(rx, '');
  3709. if (this.outro.length) return true;
  3710. const trimmed = this.content.replace(rx, '');
  3711. if (trimmed.length) {
  3712. if (trimmed !== this.content) {
  3713. this.split(this.start + trimmed.length).edit('', undefined, true);
  3714. if (this.edited) {
  3715. // save the change, if it has been edited
  3716. this.edit(trimmed, this.storeName, true);
  3717. }
  3718. }
  3719. return true;
  3720. } else {
  3721. this.edit('', undefined, true);
  3722. this.intro = this.intro.replace(rx, '');
  3723. if (this.intro.length) return true;
  3724. }
  3725. }
  3726. trimStart(rx) {
  3727. this.intro = this.intro.replace(rx, '');
  3728. if (this.intro.length) return true;
  3729. const trimmed = this.content.replace(rx, '');
  3730. if (trimmed.length) {
  3731. if (trimmed !== this.content) {
  3732. const newChunk = this.split(this.end - trimmed.length);
  3733. if (this.edited) {
  3734. // save the change, if it has been edited
  3735. newChunk.edit(trimmed, this.storeName, true);
  3736. }
  3737. this.edit('', undefined, true);
  3738. }
  3739. return true;
  3740. } else {
  3741. this.edit('', undefined, true);
  3742. this.outro = this.outro.replace(rx, '');
  3743. if (this.outro.length) return true;
  3744. }
  3745. }
  3746. };
  3747. function getBtoa() {
  3748. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  3749. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  3750. } else if (typeof Buffer === 'function') {
  3751. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  3752. } else {
  3753. return () => {
  3754. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  3755. };
  3756. }
  3757. }
  3758. const btoa = /*#__PURE__*/ getBtoa();
  3759. class SourceMap {
  3760. constructor(properties) {
  3761. this.version = 3;
  3762. this.file = properties.file;
  3763. this.sources = properties.sources;
  3764. this.sourcesContent = properties.sourcesContent;
  3765. this.names = properties.names;
  3766. this.mappings = encode(properties.mappings);
  3767. if (typeof properties.x_google_ignoreList !== 'undefined') {
  3768. this.x_google_ignoreList = properties.x_google_ignoreList;
  3769. }
  3770. if (typeof properties.debugId !== 'undefined') {
  3771. this.debugId = properties.debugId;
  3772. }
  3773. }
  3774. toString() {
  3775. return JSON.stringify(this);
  3776. }
  3777. toUrl() {
  3778. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  3779. }
  3780. }
  3781. function guessIndent(code) {
  3782. const lines = code.split('\n');
  3783. const tabbed = lines.filter((line) => /^\t+/.test(line));
  3784. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  3785. if (tabbed.length === 0 && spaced.length === 0) {
  3786. return null;
  3787. }
  3788. // More lines tabbed than spaced? Assume tabs, and
  3789. // default to tabs in the case of a tie (or nothing
  3790. // to go on)
  3791. if (tabbed.length >= spaced.length) {
  3792. return '\t';
  3793. }
  3794. // Otherwise, we need to guess the multiple
  3795. const min = spaced.reduce((previous, current) => {
  3796. const numSpaces = /^ +/.exec(current)[0].length;
  3797. return Math.min(numSpaces, previous);
  3798. }, Infinity);
  3799. return new Array(min + 1).join(' ');
  3800. }
  3801. function getRelativePath(from, to) {
  3802. const fromParts = from.split(/[/\\]/);
  3803. const toParts = to.split(/[/\\]/);
  3804. fromParts.pop(); // get dirname
  3805. while (fromParts[0] === toParts[0]) {
  3806. fromParts.shift();
  3807. toParts.shift();
  3808. }
  3809. if (fromParts.length) {
  3810. let i = fromParts.length;
  3811. while (i--) fromParts[i] = '..';
  3812. }
  3813. return fromParts.concat(toParts).join('/');
  3814. }
  3815. const toString = Object.prototype.toString;
  3816. function isObject(thing) {
  3817. return toString.call(thing) === '[object Object]';
  3818. }
  3819. function getLocator(source) {
  3820. const originalLines = source.split('\n');
  3821. const lineOffsets = [];
  3822. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  3823. lineOffsets.push(pos);
  3824. pos += originalLines[i].length + 1;
  3825. }
  3826. return function locate(index) {
  3827. let i = 0;
  3828. let j = lineOffsets.length;
  3829. while (i < j) {
  3830. const m = (i + j) >> 1;
  3831. if (index < lineOffsets[m]) {
  3832. j = m;
  3833. } else {
  3834. i = m + 1;
  3835. }
  3836. }
  3837. const line = i - 1;
  3838. const column = index - lineOffsets[line];
  3839. return { line, column };
  3840. };
  3841. }
  3842. const wordRegex = /\w/;
  3843. class Mappings {
  3844. constructor(hires) {
  3845. this.hires = hires;
  3846. this.generatedCodeLine = 0;
  3847. this.generatedCodeColumn = 0;
  3848. this.raw = [];
  3849. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  3850. this.pending = null;
  3851. }
  3852. addEdit(sourceIndex, content, loc, nameIndex) {
  3853. if (content.length) {
  3854. const contentLengthMinusOne = content.length - 1;
  3855. let contentLineEnd = content.indexOf('\n', 0);
  3856. let previousContentLineEnd = -1;
  3857. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  3858. // else code afterwards would fill one line too many
  3859. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  3860. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3861. if (nameIndex >= 0) {
  3862. segment.push(nameIndex);
  3863. }
  3864. this.rawSegments.push(segment);
  3865. this.generatedCodeLine += 1;
  3866. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3867. this.generatedCodeColumn = 0;
  3868. previousContentLineEnd = contentLineEnd;
  3869. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  3870. }
  3871. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3872. if (nameIndex >= 0) {
  3873. segment.push(nameIndex);
  3874. }
  3875. this.rawSegments.push(segment);
  3876. this.advance(content.slice(previousContentLineEnd + 1));
  3877. } else if (this.pending) {
  3878. this.rawSegments.push(this.pending);
  3879. this.advance(content);
  3880. }
  3881. this.pending = null;
  3882. }
  3883. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  3884. let originalCharIndex = chunk.start;
  3885. let first = true;
  3886. // when iterating each char, check if it's in a word boundary
  3887. let charInHiresBoundary = false;
  3888. while (originalCharIndex < chunk.end) {
  3889. if (original[originalCharIndex] === '\n') {
  3890. loc.line += 1;
  3891. loc.column = 0;
  3892. this.generatedCodeLine += 1;
  3893. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3894. this.generatedCodeColumn = 0;
  3895. first = true;
  3896. charInHiresBoundary = false;
  3897. } else {
  3898. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  3899. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  3900. if (this.hires === 'boundary') {
  3901. // in hires "boundary", group segments per word boundary than per char
  3902. if (wordRegex.test(original[originalCharIndex])) {
  3903. // for first char in the boundary found, start the boundary by pushing a segment
  3904. if (!charInHiresBoundary) {
  3905. this.rawSegments.push(segment);
  3906. charInHiresBoundary = true;
  3907. }
  3908. } else {
  3909. // for non-word char, end the boundary by pushing a segment
  3910. this.rawSegments.push(segment);
  3911. charInHiresBoundary = false;
  3912. }
  3913. } else {
  3914. this.rawSegments.push(segment);
  3915. }
  3916. }
  3917. loc.column += 1;
  3918. this.generatedCodeColumn += 1;
  3919. first = false;
  3920. }
  3921. originalCharIndex += 1;
  3922. }
  3923. this.pending = null;
  3924. }
  3925. advance(str) {
  3926. if (!str) return;
  3927. const lines = str.split('\n');
  3928. if (lines.length > 1) {
  3929. for (let i = 0; i < lines.length - 1; i++) {
  3930. this.generatedCodeLine++;
  3931. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  3932. }
  3933. this.generatedCodeColumn = 0;
  3934. }
  3935. this.generatedCodeColumn += lines[lines.length - 1].length;
  3936. }
  3937. }
  3938. const n = '\n';
  3939. const warned = {
  3940. insertLeft: false,
  3941. insertRight: false,
  3942. storeName: false,
  3943. };
  3944. class MagicString {
  3945. constructor(string, options = {}) {
  3946. const chunk = new Chunk$1(0, string.length, string);
  3947. Object.defineProperties(this, {
  3948. original: { writable: true, value: string },
  3949. outro: { writable: true, value: '' },
  3950. intro: { writable: true, value: '' },
  3951. firstChunk: { writable: true, value: chunk },
  3952. lastChunk: { writable: true, value: chunk },
  3953. lastSearchedChunk: { writable: true, value: chunk },
  3954. byStart: { writable: true, value: {} },
  3955. byEnd: { writable: true, value: {} },
  3956. filename: { writable: true, value: options.filename },
  3957. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  3958. sourcemapLocations: { writable: true, value: new BitSet() },
  3959. storedNames: { writable: true, value: {} },
  3960. indentStr: { writable: true, value: undefined },
  3961. ignoreList: { writable: true, value: options.ignoreList },
  3962. offset: { writable: true, value: options.offset || 0 },
  3963. });
  3964. this.byStart[0] = chunk;
  3965. this.byEnd[string.length] = chunk;
  3966. }
  3967. addSourcemapLocation(char) {
  3968. this.sourcemapLocations.add(char);
  3969. }
  3970. append(content) {
  3971. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  3972. this.outro += content;
  3973. return this;
  3974. }
  3975. appendLeft(index, content) {
  3976. index = index + this.offset;
  3977. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3978. this._split(index);
  3979. const chunk = this.byEnd[index];
  3980. if (chunk) {
  3981. chunk.appendLeft(content);
  3982. } else {
  3983. this.intro += content;
  3984. }
  3985. return this;
  3986. }
  3987. appendRight(index, content) {
  3988. index = index + this.offset;
  3989. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3990. this._split(index);
  3991. const chunk = this.byStart[index];
  3992. if (chunk) {
  3993. chunk.appendRight(content);
  3994. } else {
  3995. this.outro += content;
  3996. }
  3997. return this;
  3998. }
  3999. clone() {
  4000. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  4001. let originalChunk = this.firstChunk;
  4002. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  4003. while (originalChunk) {
  4004. cloned.byStart[clonedChunk.start] = clonedChunk;
  4005. cloned.byEnd[clonedChunk.end] = clonedChunk;
  4006. const nextOriginalChunk = originalChunk.next;
  4007. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  4008. if (nextClonedChunk) {
  4009. clonedChunk.next = nextClonedChunk;
  4010. nextClonedChunk.previous = clonedChunk;
  4011. clonedChunk = nextClonedChunk;
  4012. }
  4013. originalChunk = nextOriginalChunk;
  4014. }
  4015. cloned.lastChunk = clonedChunk;
  4016. if (this.indentExclusionRanges) {
  4017. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  4018. }
  4019. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  4020. cloned.intro = this.intro;
  4021. cloned.outro = this.outro;
  4022. return cloned;
  4023. }
  4024. generateDecodedMap(options) {
  4025. options = options || {};
  4026. const sourceIndex = 0;
  4027. const names = Object.keys(this.storedNames);
  4028. const mappings = new Mappings(options.hires);
  4029. const locate = getLocator(this.original);
  4030. if (this.intro) {
  4031. mappings.advance(this.intro);
  4032. }
  4033. this.firstChunk.eachNext((chunk) => {
  4034. const loc = locate(chunk.start);
  4035. if (chunk.intro.length) mappings.advance(chunk.intro);
  4036. if (chunk.edited) {
  4037. mappings.addEdit(
  4038. sourceIndex,
  4039. chunk.content,
  4040. loc,
  4041. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4042. );
  4043. } else {
  4044. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  4045. }
  4046. if (chunk.outro.length) mappings.advance(chunk.outro);
  4047. });
  4048. if (this.outro) {
  4049. mappings.advance(this.outro);
  4050. }
  4051. return {
  4052. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4053. sources: [
  4054. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  4055. ],
  4056. sourcesContent: options.includeContent ? [this.original] : undefined,
  4057. names,
  4058. mappings: mappings.raw,
  4059. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  4060. };
  4061. }
  4062. generateMap(options) {
  4063. return new SourceMap(this.generateDecodedMap(options));
  4064. }
  4065. _ensureindentStr() {
  4066. if (this.indentStr === undefined) {
  4067. this.indentStr = guessIndent(this.original);
  4068. }
  4069. }
  4070. _getRawIndentString() {
  4071. this._ensureindentStr();
  4072. return this.indentStr;
  4073. }
  4074. getIndentString() {
  4075. this._ensureindentStr();
  4076. return this.indentStr === null ? '\t' : this.indentStr;
  4077. }
  4078. indent(indentStr, options) {
  4079. const pattern = /^[^\r\n]/gm;
  4080. if (isObject(indentStr)) {
  4081. options = indentStr;
  4082. indentStr = undefined;
  4083. }
  4084. if (indentStr === undefined) {
  4085. this._ensureindentStr();
  4086. indentStr = this.indentStr || '\t';
  4087. }
  4088. if (indentStr === '') return this; // noop
  4089. options = options || {};
  4090. // Process exclusion ranges
  4091. const isExcluded = {};
  4092. if (options.exclude) {
  4093. const exclusions =
  4094. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  4095. exclusions.forEach((exclusion) => {
  4096. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  4097. isExcluded[i] = true;
  4098. }
  4099. });
  4100. }
  4101. let shouldIndentNextCharacter = options.indentStart !== false;
  4102. const replacer = (match) => {
  4103. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  4104. shouldIndentNextCharacter = true;
  4105. return match;
  4106. };
  4107. this.intro = this.intro.replace(pattern, replacer);
  4108. let charIndex = 0;
  4109. let chunk = this.firstChunk;
  4110. while (chunk) {
  4111. const end = chunk.end;
  4112. if (chunk.edited) {
  4113. if (!isExcluded[charIndex]) {
  4114. chunk.content = chunk.content.replace(pattern, replacer);
  4115. if (chunk.content.length) {
  4116. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  4117. }
  4118. }
  4119. } else {
  4120. charIndex = chunk.start;
  4121. while (charIndex < end) {
  4122. if (!isExcluded[charIndex]) {
  4123. const char = this.original[charIndex];
  4124. if (char === '\n') {
  4125. shouldIndentNextCharacter = true;
  4126. } else if (char !== '\r' && shouldIndentNextCharacter) {
  4127. shouldIndentNextCharacter = false;
  4128. if (charIndex === chunk.start) {
  4129. chunk.prependRight(indentStr);
  4130. } else {
  4131. this._splitChunk(chunk, charIndex);
  4132. chunk = chunk.next;
  4133. chunk.prependRight(indentStr);
  4134. }
  4135. }
  4136. }
  4137. charIndex += 1;
  4138. }
  4139. }
  4140. charIndex = chunk.end;
  4141. chunk = chunk.next;
  4142. }
  4143. this.outro = this.outro.replace(pattern, replacer);
  4144. return this;
  4145. }
  4146. insert() {
  4147. throw new Error(
  4148. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  4149. );
  4150. }
  4151. insertLeft(index, content) {
  4152. if (!warned.insertLeft) {
  4153. console.warn(
  4154. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  4155. );
  4156. warned.insertLeft = true;
  4157. }
  4158. return this.appendLeft(index, content);
  4159. }
  4160. insertRight(index, content) {
  4161. if (!warned.insertRight) {
  4162. console.warn(
  4163. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  4164. );
  4165. warned.insertRight = true;
  4166. }
  4167. return this.prependRight(index, content);
  4168. }
  4169. move(start, end, index) {
  4170. start = start + this.offset;
  4171. end = end + this.offset;
  4172. index = index + this.offset;
  4173. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  4174. this._split(start);
  4175. this._split(end);
  4176. this._split(index);
  4177. const first = this.byStart[start];
  4178. const last = this.byEnd[end];
  4179. const oldLeft = first.previous;
  4180. const oldRight = last.next;
  4181. const newRight = this.byStart[index];
  4182. if (!newRight && last === this.lastChunk) return this;
  4183. const newLeft = newRight ? newRight.previous : this.lastChunk;
  4184. if (oldLeft) oldLeft.next = oldRight;
  4185. if (oldRight) oldRight.previous = oldLeft;
  4186. if (newLeft) newLeft.next = first;
  4187. if (newRight) newRight.previous = last;
  4188. if (!first.previous) this.firstChunk = last.next;
  4189. if (!last.next) {
  4190. this.lastChunk = first.previous;
  4191. this.lastChunk.next = null;
  4192. }
  4193. first.previous = newLeft;
  4194. last.next = newRight || null;
  4195. if (!newLeft) this.firstChunk = first;
  4196. if (!newRight) this.lastChunk = last;
  4197. return this;
  4198. }
  4199. overwrite(start, end, content, options) {
  4200. options = options || {};
  4201. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  4202. }
  4203. update(start, end, content, options) {
  4204. start = start + this.offset;
  4205. end = end + this.offset;
  4206. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  4207. if (this.original.length !== 0) {
  4208. while (start < 0) start += this.original.length;
  4209. while (end < 0) end += this.original.length;
  4210. }
  4211. if (end > this.original.length) throw new Error('end is out of bounds');
  4212. if (start === end)
  4213. throw new Error(
  4214. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  4215. );
  4216. this._split(start);
  4217. this._split(end);
  4218. if (options === true) {
  4219. if (!warned.storeName) {
  4220. console.warn(
  4221. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  4222. );
  4223. warned.storeName = true;
  4224. }
  4225. options = { storeName: true };
  4226. }
  4227. const storeName = options !== undefined ? options.storeName : false;
  4228. const overwrite = options !== undefined ? options.overwrite : false;
  4229. if (storeName) {
  4230. const original = this.original.slice(start, end);
  4231. Object.defineProperty(this.storedNames, original, {
  4232. writable: true,
  4233. value: true,
  4234. enumerable: true,
  4235. });
  4236. }
  4237. const first = this.byStart[start];
  4238. const last = this.byEnd[end];
  4239. if (first) {
  4240. let chunk = first;
  4241. while (chunk !== last) {
  4242. if (chunk.next !== this.byStart[chunk.end]) {
  4243. throw new Error('Cannot overwrite across a split point');
  4244. }
  4245. chunk = chunk.next;
  4246. chunk.edit('', false);
  4247. }
  4248. first.edit(content, storeName, !overwrite);
  4249. } else {
  4250. // must be inserting at the end
  4251. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  4252. // TODO last chunk in the array may not be the last chunk, if it's moved...
  4253. last.next = newChunk;
  4254. newChunk.previous = last;
  4255. }
  4256. return this;
  4257. }
  4258. prepend(content) {
  4259. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  4260. this.intro = content + this.intro;
  4261. return this;
  4262. }
  4263. prependLeft(index, content) {
  4264. index = index + this.offset;
  4265. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4266. this._split(index);
  4267. const chunk = this.byEnd[index];
  4268. if (chunk) {
  4269. chunk.prependLeft(content);
  4270. } else {
  4271. this.intro = content + this.intro;
  4272. }
  4273. return this;
  4274. }
  4275. prependRight(index, content) {
  4276. index = index + this.offset;
  4277. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  4278. this._split(index);
  4279. const chunk = this.byStart[index];
  4280. if (chunk) {
  4281. chunk.prependRight(content);
  4282. } else {
  4283. this.outro = content + this.outro;
  4284. }
  4285. return this;
  4286. }
  4287. remove(start, end) {
  4288. start = start + this.offset;
  4289. end = end + this.offset;
  4290. if (this.original.length !== 0) {
  4291. while (start < 0) start += this.original.length;
  4292. while (end < 0) end += this.original.length;
  4293. }
  4294. if (start === end) return this;
  4295. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4296. if (start > end) throw new Error('end must be greater than start');
  4297. this._split(start);
  4298. this._split(end);
  4299. let chunk = this.byStart[start];
  4300. while (chunk) {
  4301. chunk.intro = '';
  4302. chunk.outro = '';
  4303. chunk.edit('');
  4304. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4305. }
  4306. return this;
  4307. }
  4308. reset(start, end) {
  4309. start = start + this.offset;
  4310. end = end + this.offset;
  4311. if (this.original.length !== 0) {
  4312. while (start < 0) start += this.original.length;
  4313. while (end < 0) end += this.original.length;
  4314. }
  4315. if (start === end) return this;
  4316. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  4317. if (start > end) throw new Error('end must be greater than start');
  4318. this._split(start);
  4319. this._split(end);
  4320. let chunk = this.byStart[start];
  4321. while (chunk) {
  4322. chunk.reset();
  4323. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  4324. }
  4325. return this;
  4326. }
  4327. lastChar() {
  4328. if (this.outro.length) return this.outro[this.outro.length - 1];
  4329. let chunk = this.lastChunk;
  4330. do {
  4331. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  4332. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  4333. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  4334. } while ((chunk = chunk.previous));
  4335. if (this.intro.length) return this.intro[this.intro.length - 1];
  4336. return '';
  4337. }
  4338. lastLine() {
  4339. let lineIndex = this.outro.lastIndexOf(n);
  4340. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  4341. let lineStr = this.outro;
  4342. let chunk = this.lastChunk;
  4343. do {
  4344. if (chunk.outro.length > 0) {
  4345. lineIndex = chunk.outro.lastIndexOf(n);
  4346. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  4347. lineStr = chunk.outro + lineStr;
  4348. }
  4349. if (chunk.content.length > 0) {
  4350. lineIndex = chunk.content.lastIndexOf(n);
  4351. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  4352. lineStr = chunk.content + lineStr;
  4353. }
  4354. if (chunk.intro.length > 0) {
  4355. lineIndex = chunk.intro.lastIndexOf(n);
  4356. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  4357. lineStr = chunk.intro + lineStr;
  4358. }
  4359. } while ((chunk = chunk.previous));
  4360. lineIndex = this.intro.lastIndexOf(n);
  4361. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  4362. return this.intro + lineStr;
  4363. }
  4364. slice(start = 0, end = this.original.length - this.offset) {
  4365. start = start + this.offset;
  4366. end = end + this.offset;
  4367. if (this.original.length !== 0) {
  4368. while (start < 0) start += this.original.length;
  4369. while (end < 0) end += this.original.length;
  4370. }
  4371. let result = '';
  4372. // find start chunk
  4373. let chunk = this.firstChunk;
  4374. while (chunk && (chunk.start > start || chunk.end <= start)) {
  4375. // found end chunk before start
  4376. if (chunk.start < end && chunk.end >= end) {
  4377. return result;
  4378. }
  4379. chunk = chunk.next;
  4380. }
  4381. if (chunk && chunk.edited && chunk.start !== start)
  4382. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  4383. const startChunk = chunk;
  4384. while (chunk) {
  4385. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  4386. result += chunk.intro;
  4387. }
  4388. const containsEnd = chunk.start < end && chunk.end >= end;
  4389. if (containsEnd && chunk.edited && chunk.end !== end)
  4390. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  4391. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  4392. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  4393. result += chunk.content.slice(sliceStart, sliceEnd);
  4394. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  4395. result += chunk.outro;
  4396. }
  4397. if (containsEnd) {
  4398. break;
  4399. }
  4400. chunk = chunk.next;
  4401. }
  4402. return result;
  4403. }
  4404. // TODO deprecate this? not really very useful
  4405. snip(start, end) {
  4406. const clone = this.clone();
  4407. clone.remove(0, start);
  4408. clone.remove(end, clone.original.length);
  4409. return clone;
  4410. }
  4411. _split(index) {
  4412. if (this.byStart[index] || this.byEnd[index]) return;
  4413. let chunk = this.lastSearchedChunk;
  4414. let previousChunk = chunk;
  4415. const searchForward = index > chunk.end;
  4416. while (chunk) {
  4417. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  4418. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  4419. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  4420. if (chunk === previousChunk) return;
  4421. previousChunk = chunk;
  4422. }
  4423. }
  4424. _splitChunk(chunk, index) {
  4425. if (chunk.edited && chunk.content.length) {
  4426. // zero-length edited chunks are a special case (overlapping replacements)
  4427. const loc = getLocator(this.original)(index);
  4428. throw new Error(
  4429. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  4430. );
  4431. }
  4432. const newChunk = chunk.split(index);
  4433. this.byEnd[index] = chunk;
  4434. this.byStart[index] = newChunk;
  4435. this.byEnd[newChunk.end] = newChunk;
  4436. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  4437. this.lastSearchedChunk = chunk;
  4438. return true;
  4439. }
  4440. toString() {
  4441. let str = this.intro;
  4442. let chunk = this.firstChunk;
  4443. while (chunk) {
  4444. str += chunk.toString();
  4445. chunk = chunk.next;
  4446. }
  4447. return str + this.outro;
  4448. }
  4449. isEmpty() {
  4450. let chunk = this.firstChunk;
  4451. do {
  4452. if (
  4453. (chunk.intro.length && chunk.intro.trim()) ||
  4454. (chunk.content.length && chunk.content.trim()) ||
  4455. (chunk.outro.length && chunk.outro.trim())
  4456. )
  4457. return false;
  4458. } while ((chunk = chunk.next));
  4459. return true;
  4460. }
  4461. length() {
  4462. let chunk = this.firstChunk;
  4463. let length = 0;
  4464. do {
  4465. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  4466. } while ((chunk = chunk.next));
  4467. return length;
  4468. }
  4469. trimLines() {
  4470. return this.trim('[\\r\\n]');
  4471. }
  4472. trim(charType) {
  4473. return this.trimStart(charType).trimEnd(charType);
  4474. }
  4475. trimEndAborted(charType) {
  4476. const rx = new RegExp((charType || '\\s') + '+$');
  4477. this.outro = this.outro.replace(rx, '');
  4478. if (this.outro.length) return true;
  4479. let chunk = this.lastChunk;
  4480. do {
  4481. const end = chunk.end;
  4482. const aborted = chunk.trimEnd(rx);
  4483. // if chunk was trimmed, we have a new lastChunk
  4484. if (chunk.end !== end) {
  4485. if (this.lastChunk === chunk) {
  4486. this.lastChunk = chunk.next;
  4487. }
  4488. this.byEnd[chunk.end] = chunk;
  4489. this.byStart[chunk.next.start] = chunk.next;
  4490. this.byEnd[chunk.next.end] = chunk.next;
  4491. }
  4492. if (aborted) return true;
  4493. chunk = chunk.previous;
  4494. } while (chunk);
  4495. return false;
  4496. }
  4497. trimEnd(charType) {
  4498. this.trimEndAborted(charType);
  4499. return this;
  4500. }
  4501. trimStartAborted(charType) {
  4502. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4503. this.intro = this.intro.replace(rx, '');
  4504. if (this.intro.length) return true;
  4505. let chunk = this.firstChunk;
  4506. do {
  4507. const end = chunk.end;
  4508. const aborted = chunk.trimStart(rx);
  4509. if (chunk.end !== end) {
  4510. // special case...
  4511. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  4512. this.byEnd[chunk.end] = chunk;
  4513. this.byStart[chunk.next.start] = chunk.next;
  4514. this.byEnd[chunk.next.end] = chunk.next;
  4515. }
  4516. if (aborted) return true;
  4517. chunk = chunk.next;
  4518. } while (chunk);
  4519. return false;
  4520. }
  4521. trimStart(charType) {
  4522. this.trimStartAborted(charType);
  4523. return this;
  4524. }
  4525. hasChanged() {
  4526. return this.original !== this.toString();
  4527. }
  4528. _replaceRegexp(searchValue, replacement) {
  4529. function getReplacement(match, str) {
  4530. if (typeof replacement === 'string') {
  4531. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  4532. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  4533. if (i === '$') return '$';
  4534. if (i === '&') return match[0];
  4535. const num = +i;
  4536. if (num < match.length) return match[+i];
  4537. return `$${i}`;
  4538. });
  4539. } else {
  4540. return replacement(...match, match.index, str, match.groups);
  4541. }
  4542. }
  4543. function matchAll(re, str) {
  4544. let match;
  4545. const matches = [];
  4546. while ((match = re.exec(str))) {
  4547. matches.push(match);
  4548. }
  4549. return matches;
  4550. }
  4551. if (searchValue.global) {
  4552. const matches = matchAll(searchValue, this.original);
  4553. matches.forEach((match) => {
  4554. if (match.index != null) {
  4555. const replacement = getReplacement(match, this.original);
  4556. if (replacement !== match[0]) {
  4557. this.overwrite(match.index, match.index + match[0].length, replacement);
  4558. }
  4559. }
  4560. });
  4561. } else {
  4562. const match = this.original.match(searchValue);
  4563. if (match && match.index != null) {
  4564. const replacement = getReplacement(match, this.original);
  4565. if (replacement !== match[0]) {
  4566. this.overwrite(match.index, match.index + match[0].length, replacement);
  4567. }
  4568. }
  4569. }
  4570. return this;
  4571. }
  4572. _replaceString(string, replacement) {
  4573. const { original } = this;
  4574. const index = original.indexOf(string);
  4575. if (index !== -1) {
  4576. if (typeof replacement === 'function') {
  4577. replacement = replacement(string, index, original);
  4578. }
  4579. if (string !== replacement) {
  4580. this.overwrite(index, index + string.length, replacement);
  4581. }
  4582. }
  4583. return this;
  4584. }
  4585. replace(searchValue, replacement) {
  4586. if (typeof searchValue === 'string') {
  4587. return this._replaceString(searchValue, replacement);
  4588. }
  4589. return this._replaceRegexp(searchValue, replacement);
  4590. }
  4591. _replaceAllString(string, replacement) {
  4592. const { original } = this;
  4593. const stringLength = string.length;
  4594. for (
  4595. let index = original.indexOf(string);
  4596. index !== -1;
  4597. index = original.indexOf(string, index + stringLength)
  4598. ) {
  4599. const previous = original.slice(index, index + stringLength);
  4600. let _replacement = replacement;
  4601. if (typeof replacement === 'function') {
  4602. _replacement = replacement(previous, index, original);
  4603. }
  4604. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  4605. }
  4606. return this;
  4607. }
  4608. replaceAll(searchValue, replacement) {
  4609. if (typeof searchValue === 'string') {
  4610. return this._replaceAllString(searchValue, replacement);
  4611. }
  4612. if (!searchValue.global) {
  4613. throw new TypeError(
  4614. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  4615. );
  4616. }
  4617. return this._replaceRegexp(searchValue, replacement);
  4618. }
  4619. }
  4620. const hasOwnProp = Object.prototype.hasOwnProperty;
  4621. let Bundle$1 = class Bundle {
  4622. constructor(options = {}) {
  4623. this.intro = options.intro || '';
  4624. this.separator = options.separator !== undefined ? options.separator : '\n';
  4625. this.sources = [];
  4626. this.uniqueSources = [];
  4627. this.uniqueSourceIndexByFilename = {};
  4628. }
  4629. addSource(source) {
  4630. if (source instanceof MagicString) {
  4631. return this.addSource({
  4632. content: source,
  4633. filename: source.filename,
  4634. separator: this.separator,
  4635. });
  4636. }
  4637. if (!isObject(source) || !source.content) {
  4638. throw new Error(
  4639. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  4640. );
  4641. }
  4642. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  4643. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  4644. });
  4645. if (source.separator === undefined) {
  4646. // TODO there's a bunch of this sort of thing, needs cleaning up
  4647. source.separator = this.separator;
  4648. }
  4649. if (source.filename) {
  4650. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  4651. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  4652. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  4653. } else {
  4654. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  4655. if (source.content.original !== uniqueSource.content) {
  4656. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  4657. }
  4658. }
  4659. }
  4660. this.sources.push(source);
  4661. return this;
  4662. }
  4663. append(str, options) {
  4664. this.addSource({
  4665. content: new MagicString(str),
  4666. separator: (options && options.separator) || '',
  4667. });
  4668. return this;
  4669. }
  4670. clone() {
  4671. const bundle = new Bundle({
  4672. intro: this.intro,
  4673. separator: this.separator,
  4674. });
  4675. this.sources.forEach((source) => {
  4676. bundle.addSource({
  4677. filename: source.filename,
  4678. content: source.content.clone(),
  4679. separator: source.separator,
  4680. });
  4681. });
  4682. return bundle;
  4683. }
  4684. generateDecodedMap(options = {}) {
  4685. const names = [];
  4686. let x_google_ignoreList = undefined;
  4687. this.sources.forEach((source) => {
  4688. Object.keys(source.content.storedNames).forEach((name) => {
  4689. if (!~names.indexOf(name)) names.push(name);
  4690. });
  4691. });
  4692. const mappings = new Mappings(options.hires);
  4693. if (this.intro) {
  4694. mappings.advance(this.intro);
  4695. }
  4696. this.sources.forEach((source, i) => {
  4697. if (i > 0) {
  4698. mappings.advance(this.separator);
  4699. }
  4700. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  4701. const magicString = source.content;
  4702. const locate = getLocator(magicString.original);
  4703. if (magicString.intro) {
  4704. mappings.advance(magicString.intro);
  4705. }
  4706. magicString.firstChunk.eachNext((chunk) => {
  4707. const loc = locate(chunk.start);
  4708. if (chunk.intro.length) mappings.advance(chunk.intro);
  4709. if (source.filename) {
  4710. if (chunk.edited) {
  4711. mappings.addEdit(
  4712. sourceIndex,
  4713. chunk.content,
  4714. loc,
  4715. chunk.storeName ? names.indexOf(chunk.original) : -1,
  4716. );
  4717. } else {
  4718. mappings.addUneditedChunk(
  4719. sourceIndex,
  4720. chunk,
  4721. magicString.original,
  4722. loc,
  4723. magicString.sourcemapLocations,
  4724. );
  4725. }
  4726. } else {
  4727. mappings.advance(chunk.content);
  4728. }
  4729. if (chunk.outro.length) mappings.advance(chunk.outro);
  4730. });
  4731. if (magicString.outro) {
  4732. mappings.advance(magicString.outro);
  4733. }
  4734. if (source.ignoreList && sourceIndex !== -1) {
  4735. if (x_google_ignoreList === undefined) {
  4736. x_google_ignoreList = [];
  4737. }
  4738. x_google_ignoreList.push(sourceIndex);
  4739. }
  4740. });
  4741. return {
  4742. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  4743. sources: this.uniqueSources.map((source) => {
  4744. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  4745. }),
  4746. sourcesContent: this.uniqueSources.map((source) => {
  4747. return options.includeContent ? source.content : null;
  4748. }),
  4749. names,
  4750. mappings: mappings.raw,
  4751. x_google_ignoreList,
  4752. };
  4753. }
  4754. generateMap(options) {
  4755. return new SourceMap(this.generateDecodedMap(options));
  4756. }
  4757. getIndentString() {
  4758. const indentStringCounts = {};
  4759. this.sources.forEach((source) => {
  4760. const indentStr = source.content._getRawIndentString();
  4761. if (indentStr === null) return;
  4762. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  4763. indentStringCounts[indentStr] += 1;
  4764. });
  4765. return (
  4766. Object.keys(indentStringCounts).sort((a, b) => {
  4767. return indentStringCounts[a] - indentStringCounts[b];
  4768. })[0] || '\t'
  4769. );
  4770. }
  4771. indent(indentStr) {
  4772. if (!arguments.length) {
  4773. indentStr = this.getIndentString();
  4774. }
  4775. if (indentStr === '') return this; // noop
  4776. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  4777. this.sources.forEach((source, i) => {
  4778. const separator = source.separator !== undefined ? source.separator : this.separator;
  4779. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  4780. source.content.indent(indentStr, {
  4781. exclude: source.indentExclusionRanges,
  4782. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  4783. });
  4784. trailingNewline = source.content.lastChar() === '\n';
  4785. });
  4786. if (this.intro) {
  4787. this.intro =
  4788. indentStr +
  4789. this.intro.replace(/^[^\n]/gm, (match, index) => {
  4790. return index > 0 ? indentStr + match : match;
  4791. });
  4792. }
  4793. return this;
  4794. }
  4795. prepend(str) {
  4796. this.intro = str + this.intro;
  4797. return this;
  4798. }
  4799. toString() {
  4800. const body = this.sources
  4801. .map((source, i) => {
  4802. const separator = source.separator !== undefined ? source.separator : this.separator;
  4803. const str = (i > 0 ? separator : '') + source.content.toString();
  4804. return str;
  4805. })
  4806. .join('');
  4807. return this.intro + body;
  4808. }
  4809. isEmpty() {
  4810. if (this.intro.length && this.intro.trim()) return false;
  4811. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  4812. return true;
  4813. }
  4814. length() {
  4815. return this.sources.reduce(
  4816. (length, source) => length + source.content.length(),
  4817. this.intro.length,
  4818. );
  4819. }
  4820. trimLines() {
  4821. return this.trim('[\\r\\n]');
  4822. }
  4823. trim(charType) {
  4824. return this.trimStart(charType).trimEnd(charType);
  4825. }
  4826. trimStart(charType) {
  4827. const rx = new RegExp('^' + (charType || '\\s') + '+');
  4828. this.intro = this.intro.replace(rx, '');
  4829. if (!this.intro) {
  4830. let source;
  4831. let i = 0;
  4832. do {
  4833. source = this.sources[i++];
  4834. if (!source) {
  4835. break;
  4836. }
  4837. } while (!source.content.trimStartAborted(charType));
  4838. }
  4839. return this;
  4840. }
  4841. trimEnd(charType) {
  4842. const rx = new RegExp((charType || '\\s') + '+$');
  4843. let source;
  4844. let i = this.sources.length - 1;
  4845. do {
  4846. source = this.sources[i--];
  4847. if (!source) {
  4848. this.intro = this.intro.replace(rx, '');
  4849. break;
  4850. }
  4851. } while (!source.content.trimEndAborted(charType));
  4852. return this;
  4853. }
  4854. };
  4855. function treeshakeNode(node, code, start, end) {
  4856. code.remove(start, end);
  4857. node.removeAnnotations(code);
  4858. }
  4859. const NO_SEMICOLON = { isNoStatement: true };
  4860. // This assumes there are only white-space and comments between start and the string we are looking for
  4861. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  4862. let searchPos, charCodeAfterSlash;
  4863. searchPos = code.indexOf(searchString, start);
  4864. while (true) {
  4865. start = code.indexOf('/', start);
  4866. if (start === -1 || start >= searchPos)
  4867. return searchPos;
  4868. charCodeAfterSlash = code.charCodeAt(++start);
  4869. ++start;
  4870. // With our assumption, '/' always starts a comment. Determine comment type:
  4871. start =
  4872. charCodeAfterSlash === 47 /*"/"*/
  4873. ? code.indexOf('\n', start) + 1
  4874. : code.indexOf('*/', start) + 2;
  4875. if (start > searchPos) {
  4876. searchPos = code.indexOf(searchString, start);
  4877. }
  4878. }
  4879. }
  4880. const NON_WHITESPACE = /\S/g;
  4881. function findNonWhiteSpace(code, index) {
  4882. NON_WHITESPACE.lastIndex = index;
  4883. const result = NON_WHITESPACE.exec(code);
  4884. return result.index;
  4885. }
  4886. const WHITESPACE = /\s/;
  4887. function findLastWhiteSpaceReverse(code, start, end) {
  4888. while (true) {
  4889. if (start >= end) {
  4890. return end;
  4891. }
  4892. if (WHITESPACE.test(code[end - 1])) {
  4893. end--;
  4894. }
  4895. else {
  4896. return end;
  4897. }
  4898. }
  4899. }
  4900. // This assumes "code" only contains white-space and comments
  4901. // Returns position of line-comment if applicable
  4902. function findFirstLineBreakOutsideComment(code) {
  4903. let lineBreakPos, charCodeAfterSlash, start = 0;
  4904. lineBreakPos = code.indexOf('\n', start);
  4905. while (true) {
  4906. start = code.indexOf('/', start);
  4907. if (start === -1 || start > lineBreakPos)
  4908. return [lineBreakPos, lineBreakPos + 1];
  4909. // With our assumption, '/' always starts a comment. Determine comment type:
  4910. charCodeAfterSlash = code.charCodeAt(start + 1);
  4911. if (charCodeAfterSlash === 47 /*"/"*/)
  4912. return [start, lineBreakPos + 1];
  4913. start = code.indexOf('*/', start + 2) + 2;
  4914. if (start > lineBreakPos) {
  4915. lineBreakPos = code.indexOf('\n', start);
  4916. }
  4917. }
  4918. }
  4919. function renderStatementList(statements, code, start, end, options) {
  4920. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  4921. let nextNode = statements[0];
  4922. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  4923. if (nextNodeNeedsBoundaries) {
  4924. nextNodeStart =
  4925. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  4926. }
  4927. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  4928. currentNode = nextNode;
  4929. currentNodeStart = nextNodeStart;
  4930. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  4931. nextNode = statements[nextIndex];
  4932. nextNodeNeedsBoundaries =
  4933. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  4934. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  4935. nextNodeStart =
  4936. currentNode.end +
  4937. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  4938. if (currentNode.included) {
  4939. if (currentNodeNeedsBoundaries) {
  4940. currentNode.render(code, options, {
  4941. end: nextNodeStart,
  4942. start: currentNodeStart
  4943. });
  4944. }
  4945. else {
  4946. currentNode.render(code, options);
  4947. }
  4948. }
  4949. else {
  4950. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  4951. }
  4952. }
  4953. else {
  4954. currentNode.render(code, options);
  4955. }
  4956. }
  4957. }
  4958. // This assumes that the first character is not part of the first node
  4959. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  4960. const splitUpNodes = [];
  4961. let node, nextNodeStart, contentEnd, char;
  4962. let separator = start - 1;
  4963. for (const nextNode of nodes) {
  4964. if (node !== undefined) {
  4965. separator =
  4966. node.end +
  4967. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  4968. }
  4969. nextNodeStart = contentEnd =
  4970. separator +
  4971. 1 +
  4972. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  4973. while (((char = code.original.charCodeAt(nextNodeStart)),
  4974. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  4975. nextNodeStart++;
  4976. if (node !== undefined) {
  4977. splitUpNodes.push({
  4978. contentEnd,
  4979. end: nextNodeStart,
  4980. node,
  4981. separator,
  4982. start
  4983. });
  4984. }
  4985. node = nextNode;
  4986. start = nextNodeStart;
  4987. }
  4988. splitUpNodes.push({
  4989. contentEnd: end,
  4990. end,
  4991. node: node,
  4992. separator: null,
  4993. start
  4994. });
  4995. return splitUpNodes;
  4996. }
  4997. // This assumes there are only white-space and comments between start and end
  4998. function removeLineBreaks(code, start, end) {
  4999. while (true) {
  5000. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  5001. if (removeStart === -1) {
  5002. break;
  5003. }
  5004. code.remove(start + removeStart, (start += removeEnd));
  5005. }
  5006. }
  5007. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  5008. if (exportedVariables.length === 1 &&
  5009. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  5010. const variable = exportedVariables[0];
  5011. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  5012. }
  5013. else {
  5014. const fields = [];
  5015. for (const variable of exportedVariables) {
  5016. for (const exportName of exportNamesByVariable.get(variable)) {
  5017. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  5018. }
  5019. }
  5020. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  5021. }
  5022. }
  5023. // This is only invoked if there is exactly one export name
  5024. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  5025. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  5026. code.appendLeft(expressionEnd, ')');
  5027. }
  5028. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  5029. const { _, getDirectReturnIifeLeft } = options.snippets;
  5030. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  5031. code.appendLeft(expressionEnd, ')');
  5032. }
  5033. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  5034. const { _, getPropertyAccess } = options.snippets;
  5035. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  5036. if (needsParens) {
  5037. code.prependRight(expressionStart, '(');
  5038. code.appendLeft(expressionEnd, ')');
  5039. }
  5040. }
  5041. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  5042. const { _ } = options.snippets;
  5043. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  5044. if (needsParens) {
  5045. code.prependRight(expressionStart, '(');
  5046. code.appendLeft(expressionEnd, ')');
  5047. }
  5048. }
  5049. const UnknownKey = Symbol('Unknown Key');
  5050. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  5051. const UnknownInteger = Symbol('Unknown Integer');
  5052. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  5053. const EMPTY_PATH = [];
  5054. const UNKNOWN_PATH = [UnknownKey];
  5055. // For deoptimizations, this means we are modifying an unknown property but did
  5056. // not lose track of the object or are creating a setter/getter;
  5057. // For assignment effects it means we do not check for setter/getter effects
  5058. // but only if something is mutated that is included, which is relevant for
  5059. // Object.defineProperty
  5060. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  5061. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  5062. const EntitiesKey = Symbol('Entities');
  5063. class EntityPathTracker {
  5064. constructor() {
  5065. this.entityPaths = Object.create(null, {
  5066. [EntitiesKey]: { value: new Set() }
  5067. });
  5068. }
  5069. trackEntityAtPathAndGetIfTracked(path, entity) {
  5070. const trackedEntities = this.getEntities(path);
  5071. if (trackedEntities.has(entity))
  5072. return true;
  5073. trackedEntities.add(entity);
  5074. return false;
  5075. }
  5076. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  5077. const trackedEntities = this.getEntities(path);
  5078. if (trackedEntities.has(entity))
  5079. return returnIfTracked;
  5080. trackedEntities.add(entity);
  5081. const result = onUntracked();
  5082. trackedEntities.delete(entity);
  5083. return result;
  5084. }
  5085. getEntities(path) {
  5086. let currentPaths = this.entityPaths;
  5087. for (const pathSegment of path) {
  5088. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5089. [EntitiesKey]: { value: new Set() }
  5090. });
  5091. }
  5092. return currentPaths[EntitiesKey];
  5093. }
  5094. }
  5095. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  5096. class DiscriminatedPathTracker {
  5097. constructor() {
  5098. this.entityPaths = Object.create(null, {
  5099. [EntitiesKey]: { value: new Map() }
  5100. });
  5101. }
  5102. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  5103. let currentPaths = this.entityPaths;
  5104. for (const pathSegment of path) {
  5105. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  5106. [EntitiesKey]: { value: new Map() }
  5107. });
  5108. }
  5109. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  5110. if (trackedEntities.has(entity))
  5111. return true;
  5112. trackedEntities.add(entity);
  5113. return false;
  5114. }
  5115. }
  5116. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: parseAst_js.EMPTY_OBJECT });
  5117. class IncludedFullPathTracker {
  5118. constructor() {
  5119. this.includedPaths = null;
  5120. }
  5121. includePathAndGetIfIncluded(path) {
  5122. let included = true;
  5123. let parent = this;
  5124. let parentSegment = 'includedPaths';
  5125. let currentPaths = (this.includedPaths ||=
  5126. ((included = false), Object.create(null)));
  5127. for (const pathSegment of path) {
  5128. // This means from here, all paths are included
  5129. if (currentPaths[UnknownKey]) {
  5130. return true;
  5131. }
  5132. // Including UnknownKey automatically includes all nested paths.
  5133. // From above, we know that UnknownKey is not included yet.
  5134. if (typeof pathSegment === 'symbol') {
  5135. // Hopefully, this saves some memory over just setting
  5136. // currentPaths[UnknownKey] = EMPTY_OBJECT
  5137. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  5138. return false;
  5139. }
  5140. parent = currentPaths;
  5141. parentSegment = pathSegment;
  5142. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  5143. }
  5144. return included;
  5145. }
  5146. }
  5147. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  5148. [UnknownKey]: true
  5149. });
  5150. class IncludedTopLevelPathTracker {
  5151. constructor() {
  5152. this.includedPaths = null;
  5153. }
  5154. includePathAndGetIfIncluded(path) {
  5155. let included = true;
  5156. const includedPaths = (this.includedPaths ||=
  5157. ((included = false), Object.create(null)));
  5158. if (includedPaths[UnknownKey]) {
  5159. return true;
  5160. }
  5161. const [firstPathSegment, secondPathSegment] = path;
  5162. if (!firstPathSegment) {
  5163. return included;
  5164. }
  5165. if (typeof firstPathSegment === 'symbol') {
  5166. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  5167. return false;
  5168. }
  5169. if (secondPathSegment) {
  5170. if (includedPaths[firstPathSegment] === UnknownKey) {
  5171. return true;
  5172. }
  5173. includedPaths[firstPathSegment] = UnknownKey;
  5174. return false;
  5175. }
  5176. if (includedPaths[firstPathSegment]) {
  5177. return true;
  5178. }
  5179. includedPaths[firstPathSegment] = true;
  5180. return false;
  5181. }
  5182. includeAllPaths(entity, context, basePath) {
  5183. const { includedPaths } = this;
  5184. if (includedPaths) {
  5185. if (includedPaths[UnknownKey]) {
  5186. entity.includePath([...basePath, UnknownKey], context);
  5187. }
  5188. else {
  5189. const inclusionEntries = Object.entries(includedPaths);
  5190. if (inclusionEntries.length === 0) {
  5191. entity.includePath(basePath, context);
  5192. }
  5193. else {
  5194. for (const [key, value] of inclusionEntries) {
  5195. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  5196. }
  5197. }
  5198. }
  5199. }
  5200. }
  5201. }
  5202. /** @import { Node } from 'estree' */
  5203. /**
  5204. * @param {Node} node
  5205. * @param {Node} parent
  5206. * @returns {boolean}
  5207. */
  5208. function is_reference(node, parent) {
  5209. if (node.type === 'MemberExpression') {
  5210. return !node.computed && is_reference(node.object, node);
  5211. }
  5212. if (node.type !== 'Identifier') return false;
  5213. switch (parent?.type) {
  5214. // disregard `bar` in `foo.bar`
  5215. case 'MemberExpression':
  5216. return parent.computed || node === parent.object;
  5217. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5218. case 'MethodDefinition':
  5219. return parent.computed;
  5220. // disregard the `meta` in `import.meta`
  5221. case 'MetaProperty':
  5222. return parent.meta === node;
  5223. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5224. case 'PropertyDefinition':
  5225. return parent.computed || node === parent.value;
  5226. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5227. case 'Property':
  5228. return parent.computed || node === parent.value;
  5229. // disregard the `bar` in `export { foo as bar }` or
  5230. // the foo in `import { foo as bar }`
  5231. case 'ExportSpecifier':
  5232. case 'ImportSpecifier':
  5233. return node === parent.local;
  5234. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5235. case 'LabeledStatement':
  5236. case 'BreakStatement':
  5237. case 'ContinueStatement':
  5238. return false;
  5239. default:
  5240. return true;
  5241. }
  5242. }
  5243. function createInclusionContext() {
  5244. return {
  5245. brokenFlow: false,
  5246. hasBreak: false,
  5247. hasContinue: false,
  5248. includedCallArguments: new Set(),
  5249. includedLabels: new Set()
  5250. };
  5251. }
  5252. function createHasEffectsContext() {
  5253. return {
  5254. accessed: new EntityPathTracker(),
  5255. assigned: new EntityPathTracker(),
  5256. brokenFlow: false,
  5257. called: new DiscriminatedPathTracker(),
  5258. hasBreak: false,
  5259. hasContinue: false,
  5260. ignore: {
  5261. breaks: false,
  5262. continues: false,
  5263. labels: new Set(),
  5264. returnYield: false,
  5265. this: false
  5266. },
  5267. includedLabels: new Set(),
  5268. instantiated: new DiscriminatedPathTracker(),
  5269. replacedVariableInits: new Map()
  5270. };
  5271. }
  5272. function isFlagSet(flags, flag) {
  5273. return (flags & flag) !== 0;
  5274. }
  5275. function setFlag(flags, flag, value) {
  5276. return (flags & ~flag) | (-value & flag);
  5277. }
  5278. const UnknownValue = Symbol('Unknown Value');
  5279. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  5280. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  5281. class ExpressionEntity {
  5282. constructor() {
  5283. this.flags = 0;
  5284. }
  5285. get included() {
  5286. return isFlagSet(this.flags, 1 /* Flag.included */);
  5287. }
  5288. set included(value) {
  5289. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  5290. }
  5291. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  5292. deoptimizeInteraction(interaction);
  5293. }
  5294. deoptimizePath(_path) { }
  5295. /**
  5296. * If possible it returns a stringifyable literal value for this node that
  5297. * can be used for inlining or comparing values. Otherwise, it should return
  5298. * UnknownValue.
  5299. */
  5300. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  5301. return UnknownValue;
  5302. }
  5303. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  5304. return UNKNOWN_RETURN_EXPRESSION;
  5305. }
  5306. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  5307. return true;
  5308. }
  5309. include(context, _includeChildrenRecursively, _options) {
  5310. if (!this.included)
  5311. this.includeNode(context);
  5312. }
  5313. includeNode(_context) {
  5314. this.included = true;
  5315. }
  5316. includePath(_path, context) {
  5317. if (!this.included)
  5318. this.includeNode(context);
  5319. }
  5320. /* We are both including and including an unknown path here as the former
  5321. * ensures that nested nodes are included while the latter ensures that all
  5322. * paths of the expression are included.
  5323. * */
  5324. includeCallArguments(interaction, context) {
  5325. includeInteraction(interaction, context);
  5326. }
  5327. shouldBeIncluded(_context) {
  5328. return true;
  5329. }
  5330. }
  5331. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  5332. })();
  5333. const UNKNOWN_RETURN_EXPRESSION = [
  5334. UNKNOWN_EXPRESSION,
  5335. false
  5336. ];
  5337. const deoptimizeInteraction = (interaction) => {
  5338. for (const argument of interaction.args) {
  5339. argument?.deoptimizePath(UNKNOWN_PATH);
  5340. }
  5341. };
  5342. const includeInteraction = (interaction, context) => {
  5343. // We do not re-include the "this" argument as we expect this is already
  5344. // re-included at the call site
  5345. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  5346. includeInteractionWithoutThis(interaction, context);
  5347. };
  5348. const includeInteractionWithoutThis = ({ args }, context) => {
  5349. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5350. const argument = args[argumentIndex];
  5351. if (argument) {
  5352. argument.includePath(UNKNOWN_PATH, context);
  5353. argument.include(context, false);
  5354. }
  5355. }
  5356. };
  5357. const INTERACTION_ACCESSED = 0;
  5358. const INTERACTION_ASSIGNED = 1;
  5359. const INTERACTION_CALLED = 2;
  5360. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  5361. args: [null],
  5362. type: INTERACTION_ACCESSED
  5363. };
  5364. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  5365. args: [null, UNKNOWN_EXPRESSION],
  5366. type: INTERACTION_ASSIGNED
  5367. };
  5368. // While this is technically a call without arguments, we can compare against
  5369. // this reference in places where precise values or this argument would make a
  5370. // difference
  5371. const NODE_INTERACTION_UNKNOWN_CALL = {
  5372. args: [null],
  5373. type: INTERACTION_CALLED,
  5374. withNew: false
  5375. };
  5376. const PureFunctionKey = Symbol('PureFunction');
  5377. const getPureFunctions = ({ treeshake }) => {
  5378. const pureFunctions = Object.create(null);
  5379. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  5380. let currentFunctions = pureFunctions;
  5381. for (const pathSegment of functionName.split('.')) {
  5382. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  5383. }
  5384. currentFunctions[PureFunctionKey] = true;
  5385. }
  5386. return pureFunctions;
  5387. };
  5388. class Variable extends ExpressionEntity {
  5389. markReassigned() {
  5390. this.isReassigned = true;
  5391. }
  5392. constructor(name) {
  5393. super();
  5394. this.name = name;
  5395. this.alwaysRendered = false;
  5396. this.forbiddenNames = null;
  5397. this.globalName = null;
  5398. this.initReached = false;
  5399. this.isId = false;
  5400. this.kind = null;
  5401. this.renderBaseName = null;
  5402. this.renderName = null;
  5403. this.isReassigned = false;
  5404. this.onlyFunctionCallUsed = true;
  5405. }
  5406. /**
  5407. * Binds identifiers that reference this variable to this variable.
  5408. * Necessary to be able to change variable names.
  5409. */
  5410. addReference(_identifier) { }
  5411. /**
  5412. * Check if the identifier variable is only used as function call
  5413. * @returns true if the variable is only used as function call
  5414. */
  5415. getOnlyFunctionCallUsed() {
  5416. return this.onlyFunctionCallUsed;
  5417. }
  5418. /**
  5419. * Collect the places where the identifier variable is used
  5420. * @param usedPlace Where the variable is used
  5421. */
  5422. addUsedPlace(usedPlace) {
  5423. const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
  5424. usedPlace.parent.callee === usedPlace;
  5425. if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
  5426. this.onlyFunctionCallUsed = false;
  5427. }
  5428. }
  5429. /**
  5430. * Prevent this variable from being renamed to this name to avoid name
  5431. * collisions
  5432. */
  5433. forbidName(name) {
  5434. (this.forbiddenNames ||= new Set()).add(name);
  5435. }
  5436. getBaseVariableName() {
  5437. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  5438. this.renderBaseName ||
  5439. this.renderName ||
  5440. this.name);
  5441. }
  5442. getName(getPropertyAccess, useOriginalName) {
  5443. if (this.globalName) {
  5444. return this.globalName;
  5445. }
  5446. if (useOriginalName?.(this)) {
  5447. return this.name;
  5448. }
  5449. if (this.renderedLikeHoisted) {
  5450. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  5451. }
  5452. const name = this.renderName || this.name;
  5453. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  5454. }
  5455. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  5456. return type !== INTERACTION_ACCESSED || path.length > 0;
  5457. }
  5458. /**
  5459. * Marks this variable as being part of the bundle, which is usually the case
  5460. * when one of its identifiers becomes part of the bundle. Returns true if it
  5461. * has not been included previously. Once a variable is included, it should
  5462. * take care all its declarations are included.
  5463. */
  5464. includePath(path, context) {
  5465. this.included = true;
  5466. this.renderedLikeHoisted?.includePath(path, context);
  5467. }
  5468. /**
  5469. * Links the rendered name of this variable to another variable and includes
  5470. * this variable if the other variable is included.
  5471. */
  5472. renderLikeHoisted(variable) {
  5473. this.renderedLikeHoisted = variable;
  5474. }
  5475. markCalledFromTryStatement() { }
  5476. setRenderNames(baseName, name) {
  5477. this.renderBaseName = baseName;
  5478. this.renderName = name;
  5479. }
  5480. }
  5481. class ExternalVariable extends Variable {
  5482. constructor(module, name) {
  5483. super(name);
  5484. this.referenced = false;
  5485. this.module = module;
  5486. this.isNamespace = name === '*';
  5487. }
  5488. addReference(identifier) {
  5489. this.referenced = true;
  5490. if (this.name === 'default' || this.name === '*') {
  5491. this.module.suggestName(identifier.name);
  5492. }
  5493. }
  5494. hasEffectsOnInteractionAtPath(path, { type }) {
  5495. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  5496. }
  5497. includePath(path, context) {
  5498. super.includePath(path, context);
  5499. this.module.used = true;
  5500. }
  5501. }
  5502. function cacheObjectGetters(object, getterProperties) {
  5503. for (const property of getterProperties) {
  5504. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  5505. Object.defineProperty(object, property, {
  5506. get() {
  5507. const value = propertyGetter.call(object);
  5508. // This replaces the getter with a fixed value for subsequent calls
  5509. Object.defineProperty(object, property, { value });
  5510. return value;
  5511. }
  5512. });
  5513. }
  5514. }
  5515. const RESERVED_NAMES = new Set([
  5516. 'await',
  5517. 'break',
  5518. 'case',
  5519. 'catch',
  5520. 'class',
  5521. 'const',
  5522. 'continue',
  5523. 'debugger',
  5524. 'default',
  5525. 'delete',
  5526. 'do',
  5527. 'else',
  5528. 'enum',
  5529. 'eval',
  5530. 'export',
  5531. 'extends',
  5532. 'false',
  5533. 'finally',
  5534. 'for',
  5535. 'function',
  5536. 'if',
  5537. 'implements',
  5538. 'import',
  5539. 'in',
  5540. 'instanceof',
  5541. 'interface',
  5542. 'let',
  5543. 'NaN',
  5544. 'new',
  5545. 'null',
  5546. 'package',
  5547. 'private',
  5548. 'protected',
  5549. 'public',
  5550. 'return',
  5551. 'static',
  5552. 'super',
  5553. 'switch',
  5554. 'this',
  5555. 'throw',
  5556. 'true',
  5557. 'try',
  5558. 'typeof',
  5559. 'undefined',
  5560. 'var',
  5561. 'void',
  5562. 'while',
  5563. 'with',
  5564. 'yield'
  5565. ]);
  5566. const illegalCharacters = /[^\w$]/g;
  5567. const startsWithDigit = (value) => /\d/.test(value[0]);
  5568. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  5569. function isLegal(value) {
  5570. if (needsEscape(value)) {
  5571. return false;
  5572. }
  5573. return !illegalCharacters.test(value);
  5574. }
  5575. function makeLegal(value) {
  5576. value = value
  5577. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  5578. .replace(illegalCharacters, '_');
  5579. if (needsEscape(value))
  5580. value = `_${value}`;
  5581. return value || '_';
  5582. }
  5583. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  5584. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  5585. function stringifyObjectKeyIfNeeded(key) {
  5586. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5587. return key === '__proto__' ? '["__proto__"]' : key;
  5588. }
  5589. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  5590. return key;
  5591. }
  5592. return JSON.stringify(key);
  5593. }
  5594. function stringifyIdentifierIfNeeded(key) {
  5595. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  5596. return key;
  5597. }
  5598. return JSON.stringify(key);
  5599. }
  5600. class ExternalModule {
  5601. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  5602. this.options = options;
  5603. this.id = id;
  5604. this.renormalizeRenderPath = renormalizeRenderPath;
  5605. this.dynamicImporters = [];
  5606. this.execIndex = Infinity;
  5607. this.exportedVariables = new Map();
  5608. this.importers = [];
  5609. this.reexported = false;
  5610. this.used = false;
  5611. this.declarations = new Map();
  5612. this.mostCommonSuggestion = 0;
  5613. this.nameSuggestions = new Map();
  5614. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  5615. const { importers, dynamicImporters } = this;
  5616. this.info = {
  5617. ast: null,
  5618. attributes,
  5619. code: null,
  5620. dynamicallyImportedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5621. dynamicallyImportedIds: parseAst_js.EMPTY_ARRAY,
  5622. get dynamicImporters() {
  5623. return dynamicImporters.sort();
  5624. },
  5625. exportedBindings: null,
  5626. exports: null,
  5627. hasDefaultExport: null,
  5628. id,
  5629. implicitlyLoadedAfterOneOf: parseAst_js.EMPTY_ARRAY,
  5630. implicitlyLoadedBefore: parseAst_js.EMPTY_ARRAY,
  5631. importedIdResolutions: parseAst_js.EMPTY_ARRAY,
  5632. importedIds: parseAst_js.EMPTY_ARRAY,
  5633. get importers() {
  5634. return importers.sort();
  5635. },
  5636. isEntry: false,
  5637. isExternal: true,
  5638. isIncluded: null,
  5639. meta,
  5640. moduleSideEffects,
  5641. syntheticNamedExports: false
  5642. };
  5643. }
  5644. cacheInfoGetters() {
  5645. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  5646. }
  5647. getVariableForExportName(name) {
  5648. const declaration = this.declarations.get(name);
  5649. if (declaration)
  5650. return [declaration];
  5651. const externalVariable = new ExternalVariable(this, name);
  5652. this.declarations.set(name, externalVariable);
  5653. this.exportedVariables.set(externalVariable, name);
  5654. return [externalVariable];
  5655. }
  5656. suggestName(name) {
  5657. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  5658. this.nameSuggestions.set(name, value);
  5659. if (value > this.mostCommonSuggestion) {
  5660. this.mostCommonSuggestion = value;
  5661. this.suggestedVariableName = name;
  5662. }
  5663. }
  5664. warnUnusedImports() {
  5665. const unused = [...this.declarations]
  5666. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  5667. .map(([name]) => name);
  5668. if (unused.length === 0)
  5669. return;
  5670. const importersSet = new Set();
  5671. for (const name of unused) {
  5672. for (const importer of this.declarations.get(name).module.importers) {
  5673. importersSet.add(importer);
  5674. }
  5675. }
  5676. const importersArray = [...importersSet];
  5677. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnusedExternalImports(this.id, unused, importersArray));
  5678. }
  5679. }
  5680. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  5681. baseModule.isExecuted = true;
  5682. const modules = [baseModule];
  5683. const visitedModules = new Set();
  5684. for (const module of modules) {
  5685. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  5686. if (!(dependency instanceof ExternalModule) &&
  5687. !dependency.isExecuted &&
  5688. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  5689. !visitedModules.has(dependency.id)) {
  5690. dependency.isExecuted = true;
  5691. visitedModules.add(dependency.id);
  5692. modules.push(dependency);
  5693. }
  5694. }
  5695. }
  5696. }
  5697. // This file is generated by scripts/generate-child-node-keys.js.
  5698. // Do not edit this file directly.
  5699. const childNodeKeys = {
  5700. ArrayExpression: ['elements'],
  5701. ArrayPattern: ['elements'],
  5702. ArrowFunctionExpression: ['params', 'body'],
  5703. AssignmentExpression: ['left', 'right'],
  5704. AssignmentPattern: ['left', 'right'],
  5705. AwaitExpression: ['argument'],
  5706. BinaryExpression: ['left', 'right'],
  5707. BlockStatement: ['body'],
  5708. BreakStatement: ['label'],
  5709. CallExpression: ['callee', 'arguments'],
  5710. CatchClause: ['param', 'body'],
  5711. ChainExpression: ['expression'],
  5712. ClassBody: ['body'],
  5713. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  5714. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  5715. ConditionalExpression: ['test', 'consequent', 'alternate'],
  5716. ContinueStatement: ['label'],
  5717. DebuggerStatement: [],
  5718. Decorator: ['expression'],
  5719. DoWhileStatement: ['body', 'test'],
  5720. EmptyStatement: [],
  5721. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  5722. ExportDefaultDeclaration: ['declaration'],
  5723. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  5724. ExportSpecifier: ['local', 'exported'],
  5725. ExpressionStatement: ['expression'],
  5726. ForInStatement: ['left', 'right', 'body'],
  5727. ForOfStatement: ['left', 'right', 'body'],
  5728. ForStatement: ['init', 'test', 'update', 'body'],
  5729. FunctionDeclaration: ['id', 'params', 'body'],
  5730. FunctionExpression: ['id', 'params', 'body'],
  5731. Identifier: [],
  5732. IfStatement: ['test', 'consequent', 'alternate'],
  5733. ImportAttribute: ['key', 'value'],
  5734. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  5735. ImportDefaultSpecifier: ['local'],
  5736. ImportExpression: ['source', 'options'],
  5737. ImportNamespaceSpecifier: ['local'],
  5738. ImportSpecifier: ['imported', 'local'],
  5739. JSXAttribute: ['name', 'value'],
  5740. JSXClosingElement: ['name'],
  5741. JSXClosingFragment: [],
  5742. JSXElement: ['openingElement', 'children', 'closingElement'],
  5743. JSXEmptyExpression: [],
  5744. JSXExpressionContainer: ['expression'],
  5745. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  5746. JSXIdentifier: [],
  5747. JSXMemberExpression: ['object', 'property'],
  5748. JSXNamespacedName: ['namespace', 'name'],
  5749. JSXOpeningElement: ['name', 'attributes'],
  5750. JSXOpeningFragment: [],
  5751. JSXSpreadAttribute: ['argument'],
  5752. JSXSpreadChild: ['expression'],
  5753. JSXText: [],
  5754. LabeledStatement: ['label', 'body'],
  5755. Literal: [],
  5756. LogicalExpression: ['left', 'right'],
  5757. MemberExpression: ['object', 'property'],
  5758. MetaProperty: ['meta', 'property'],
  5759. MethodDefinition: ['decorators', 'key', 'value'],
  5760. NewExpression: ['callee', 'arguments'],
  5761. ObjectExpression: ['properties'],
  5762. ObjectPattern: ['properties'],
  5763. PanicError: [],
  5764. ParseError: [],
  5765. PrivateIdentifier: [],
  5766. Program: ['body'],
  5767. Property: ['key', 'value'],
  5768. PropertyDefinition: ['decorators', 'key', 'value'],
  5769. RestElement: ['argument'],
  5770. ReturnStatement: ['argument'],
  5771. SequenceExpression: ['expressions'],
  5772. SpreadElement: ['argument'],
  5773. StaticBlock: ['body'],
  5774. Super: [],
  5775. SwitchCase: ['test', 'consequent'],
  5776. SwitchStatement: ['discriminant', 'cases'],
  5777. TaggedTemplateExpression: ['tag', 'quasi'],
  5778. TemplateElement: [],
  5779. TemplateLiteral: ['quasis', 'expressions'],
  5780. ThisExpression: [],
  5781. ThrowStatement: ['argument'],
  5782. TryStatement: ['block', 'handler', 'finalizer'],
  5783. UnaryExpression: ['argument'],
  5784. UpdateExpression: ['argument'],
  5785. VariableDeclaration: ['declarations'],
  5786. VariableDeclarator: ['id', 'init'],
  5787. WhileStatement: ['test', 'body'],
  5788. YieldExpression: ['argument']
  5789. };
  5790. const INCLUDE_PARAMETERS = 'variables';
  5791. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  5792. class NodeBase extends ExpressionEntity {
  5793. /**
  5794. * Nodes can apply custom deoptimizations once they become part of the
  5795. * executed code. To do this, they must initialize this as false, implement
  5796. * applyDeoptimizations and call this from include and hasEffects if they have
  5797. * custom handlers
  5798. */
  5799. get deoptimized() {
  5800. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  5801. }
  5802. set deoptimized(value) {
  5803. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  5804. }
  5805. constructor(parent, parentScope) {
  5806. super();
  5807. this.parent = parent;
  5808. this.scope = parentScope;
  5809. this.createScope(parentScope);
  5810. }
  5811. addExportedVariables(_variables, _exportNamesByVariable) { }
  5812. /**
  5813. * Override this to bind assignments to variables and do any initialisations
  5814. * that require the scopes to be populated with variables.
  5815. */
  5816. bind() {
  5817. for (const key of childNodeKeys[this.type]) {
  5818. const value = this[key];
  5819. if (Array.isArray(value)) {
  5820. for (const child of value) {
  5821. child?.bind();
  5822. }
  5823. }
  5824. else if (value) {
  5825. value.bind();
  5826. }
  5827. }
  5828. }
  5829. /**
  5830. * Override if this node should receive a different scope than the parent
  5831. * scope.
  5832. */
  5833. createScope(parentScope) {
  5834. this.scope = parentScope;
  5835. }
  5836. hasEffects(context) {
  5837. if (!this.deoptimized)
  5838. this.applyDeoptimizations();
  5839. for (const key of childNodeKeys[this.type]) {
  5840. const value = this[key];
  5841. if (value === null)
  5842. continue;
  5843. if (Array.isArray(value)) {
  5844. for (const child of value) {
  5845. if (child?.hasEffects(context))
  5846. return true;
  5847. }
  5848. }
  5849. else if (value.hasEffects(context))
  5850. return true;
  5851. }
  5852. return false;
  5853. }
  5854. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  5855. return (this.hasEffects(context) ||
  5856. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  5857. }
  5858. include(context, includeChildrenRecursively, _options) {
  5859. if (!this.included)
  5860. this.includeNode(context);
  5861. for (const key of childNodeKeys[this.type]) {
  5862. const value = this[key];
  5863. if (value === null)
  5864. continue;
  5865. if (Array.isArray(value)) {
  5866. for (const child of value) {
  5867. child?.include(context, includeChildrenRecursively);
  5868. }
  5869. }
  5870. else {
  5871. value.include(context, includeChildrenRecursively);
  5872. }
  5873. }
  5874. }
  5875. includeNode(context) {
  5876. this.included = true;
  5877. if (!this.deoptimized)
  5878. this.applyDeoptimizations();
  5879. for (const key of childNodeKeys[this.type]) {
  5880. const value = this[key];
  5881. if (value === null)
  5882. continue;
  5883. if (Array.isArray(value)) {
  5884. for (const child of value) {
  5885. child?.includePath(UNKNOWN_PATH, context);
  5886. }
  5887. }
  5888. else {
  5889. value.includePath(UNKNOWN_PATH, context);
  5890. }
  5891. }
  5892. }
  5893. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  5894. this.include(context, includeChildrenRecursively);
  5895. }
  5896. /**
  5897. * Override to perform special initialisation steps after the scope is
  5898. * initialised
  5899. */
  5900. initialise() {
  5901. this.scope.context.magicString.addSourcemapLocation(this.start);
  5902. this.scope.context.magicString.addSourcemapLocation(this.end);
  5903. }
  5904. parseNode(esTreeNode) {
  5905. for (const [key, value] of Object.entries(esTreeNode)) {
  5906. // Skip properties defined on the class already.
  5907. // This way, we can override this function to add custom initialisation and then call super.parseNode
  5908. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  5909. // in bitfields. Those are still assigned from the value in the esTreeNode.
  5910. if (this.hasOwnProperty(key))
  5911. continue;
  5912. if (key.charCodeAt(0) === 95 /* _ */) {
  5913. if (key === parseAst_js.ANNOTATION_KEY) {
  5914. this.annotations = value;
  5915. }
  5916. else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
  5917. this.invalidAnnotations = value;
  5918. }
  5919. }
  5920. else if (typeof value !== 'object' || value === null) {
  5921. this[key] = value;
  5922. }
  5923. else if (Array.isArray(value)) {
  5924. this[key] = new Array(value.length);
  5925. let index = 0;
  5926. for (const child of value) {
  5927. this[key][index++] =
  5928. child === null
  5929. ? null
  5930. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  5931. }
  5932. }
  5933. else {
  5934. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  5935. }
  5936. }
  5937. // extend child keys for unknown node types
  5938. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  5939. this.initialise();
  5940. return this;
  5941. }
  5942. removeAnnotations(code) {
  5943. if (this.annotations) {
  5944. for (const annotation of this.annotations) {
  5945. code.remove(annotation.start, annotation.end);
  5946. }
  5947. }
  5948. }
  5949. render(code, options) {
  5950. for (const key of childNodeKeys[this.type]) {
  5951. const value = this[key];
  5952. if (value === null)
  5953. continue;
  5954. if (Array.isArray(value)) {
  5955. for (const child of value) {
  5956. child?.render(code, options);
  5957. }
  5958. }
  5959. else {
  5960. value.render(code, options);
  5961. }
  5962. }
  5963. }
  5964. setAssignedValue(value) {
  5965. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  5966. }
  5967. shouldBeIncluded(context) {
  5968. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  5969. }
  5970. /**
  5971. * Just deoptimize everything by default so that when e.g. we do not track
  5972. * something properly, it is deoptimized.
  5973. * @protected
  5974. */
  5975. applyDeoptimizations() {
  5976. this.deoptimized = true;
  5977. for (const key of childNodeKeys[this.type]) {
  5978. const value = this[key];
  5979. if (value === null)
  5980. continue;
  5981. if (Array.isArray(value)) {
  5982. for (const child of value) {
  5983. child?.deoptimizePath(UNKNOWN_PATH);
  5984. }
  5985. }
  5986. else {
  5987. value.deoptimizePath(UNKNOWN_PATH);
  5988. }
  5989. }
  5990. this.scope.context.requestTreeshakingPass();
  5991. }
  5992. }
  5993. function createChildNodeKeysForNode(esTreeNode) {
  5994. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  5995. }
  5996. function onlyIncludeSelf() {
  5997. this.included = true;
  5998. if (!this.deoptimized)
  5999. this.applyDeoptimizations();
  6000. }
  6001. function onlyIncludeSelfNoDeoptimize() {
  6002. this.included = true;
  6003. }
  6004. function doNotDeoptimize() {
  6005. this.deoptimized = true;
  6006. }
  6007. function isObjectExpressionNode(node) {
  6008. return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
  6009. }
  6010. function isPropertyNode(node) {
  6011. return node instanceof NodeBase && node.type === parseAst_js.Property;
  6012. }
  6013. function isArrowFunctionExpressionNode(node) {
  6014. return node instanceof NodeBase && node.type === parseAst_js.ArrowFunctionExpression;
  6015. }
  6016. function isFunctionExpressionNode(node) {
  6017. return node instanceof NodeBase && node.type === parseAst_js.FunctionExpression;
  6018. }
  6019. function isCallExpressionNode(node) {
  6020. return node instanceof NodeBase && node.type === parseAst_js.CallExpression;
  6021. }
  6022. function isMemberExpressionNode(node) {
  6023. return node instanceof NodeBase && node.type === parseAst_js.MemberExpression;
  6024. }
  6025. function isImportExpressionNode(node) {
  6026. return node instanceof NodeBase && node.type === parseAst_js.ImportExpression;
  6027. }
  6028. function isAwaitExpressionNode(node) {
  6029. return node instanceof NodeBase && node.type === parseAst_js.AwaitExpression;
  6030. }
  6031. function isIdentifierNode(node) {
  6032. return node instanceof NodeBase && node.type === parseAst_js.Identifier;
  6033. }
  6034. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  6035. return Object.create(inheritedDescriptions, memberDescriptions);
  6036. }
  6037. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  6038. getLiteralValueAtPath(path) {
  6039. return path.length > 0 ? UnknownValue : undefined;
  6040. }
  6041. })();
  6042. const returnsUnknown = {
  6043. value: {
  6044. hasEffectsWhenCalled: null,
  6045. returns: UNKNOWN_EXPRESSION
  6046. }
  6047. };
  6048. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  6049. getReturnExpressionWhenCalledAtPath(path) {
  6050. if (path.length === 1) {
  6051. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  6052. }
  6053. return UNKNOWN_RETURN_EXPRESSION;
  6054. }
  6055. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6056. if (interaction.type === INTERACTION_ACCESSED) {
  6057. return path.length > 1;
  6058. }
  6059. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6060. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  6061. }
  6062. return true;
  6063. }
  6064. })();
  6065. const returnsBoolean = {
  6066. value: {
  6067. hasEffectsWhenCalled: null,
  6068. returns: UNKNOWN_LITERAL_BOOLEAN
  6069. }
  6070. };
  6071. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  6072. getReturnExpressionWhenCalledAtPath(path) {
  6073. if (path.length === 1) {
  6074. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  6075. }
  6076. return UNKNOWN_RETURN_EXPRESSION;
  6077. }
  6078. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6079. if (interaction.type === INTERACTION_ACCESSED) {
  6080. return path.length > 1;
  6081. }
  6082. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6083. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  6084. }
  6085. return true;
  6086. }
  6087. })();
  6088. const returnsNumber = {
  6089. value: {
  6090. hasEffectsWhenCalled: null,
  6091. returns: UNKNOWN_LITERAL_NUMBER
  6092. }
  6093. };
  6094. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  6095. getReturnExpressionWhenCalledAtPath(path) {
  6096. if (path.length === 1) {
  6097. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  6098. }
  6099. return UNKNOWN_RETURN_EXPRESSION;
  6100. }
  6101. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6102. if (interaction.type === INTERACTION_ACCESSED) {
  6103. return path.length > 1;
  6104. }
  6105. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6106. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  6107. }
  6108. return true;
  6109. }
  6110. })();
  6111. const returnsString = {
  6112. value: {
  6113. hasEffectsWhenCalled: null,
  6114. returns: UNKNOWN_LITERAL_STRING
  6115. }
  6116. };
  6117. const stringReplace = {
  6118. value: {
  6119. hasEffectsWhenCalled({ args }, context) {
  6120. const argument1 = args[2];
  6121. return (args.length < 3 ||
  6122. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  6123. deoptimizeCache() { }
  6124. }) === 'symbol' &&
  6125. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  6126. },
  6127. returns: UNKNOWN_LITERAL_STRING
  6128. }
  6129. };
  6130. const objectMembers = assembleMemberDescriptions({
  6131. hasOwnProperty: returnsBoolean,
  6132. isPrototypeOf: returnsBoolean,
  6133. propertyIsEnumerable: returnsBoolean,
  6134. toLocaleString: returnsString,
  6135. toString: returnsString,
  6136. valueOf: returnsUnknown
  6137. });
  6138. const literalBooleanMembers = assembleMemberDescriptions({
  6139. valueOf: returnsBoolean
  6140. }, objectMembers);
  6141. const literalNumberMembers = assembleMemberDescriptions({
  6142. toExponential: returnsString,
  6143. toFixed: returnsString,
  6144. toLocaleString: returnsString,
  6145. toPrecision: returnsString,
  6146. valueOf: returnsNumber
  6147. }, objectMembers);
  6148. /**
  6149. * RegExp are stateful when they have the global or sticky flags set.
  6150. * But if we actually don't use them, the side effect does not matter.
  6151. * the check logic in `hasEffectsOnInteractionAtPath`.
  6152. */
  6153. const literalRegExpMembers = assembleMemberDescriptions({
  6154. exec: returnsUnknown,
  6155. test: returnsBoolean
  6156. }, objectMembers);
  6157. const literalStringMembers = assembleMemberDescriptions({
  6158. anchor: returnsString,
  6159. at: returnsUnknown,
  6160. big: returnsString,
  6161. blink: returnsString,
  6162. bold: returnsString,
  6163. charAt: returnsString,
  6164. charCodeAt: returnsNumber,
  6165. codePointAt: returnsUnknown,
  6166. concat: returnsString,
  6167. endsWith: returnsBoolean,
  6168. fixed: returnsString,
  6169. fontcolor: returnsString,
  6170. fontsize: returnsString,
  6171. includes: returnsBoolean,
  6172. indexOf: returnsNumber,
  6173. italics: returnsString,
  6174. lastIndexOf: returnsNumber,
  6175. link: returnsString,
  6176. localeCompare: returnsNumber,
  6177. match: returnsUnknown,
  6178. matchAll: returnsUnknown,
  6179. normalize: returnsString,
  6180. padEnd: returnsString,
  6181. padStart: returnsString,
  6182. repeat: returnsString,
  6183. replace: stringReplace,
  6184. replaceAll: stringReplace,
  6185. search: returnsNumber,
  6186. slice: returnsString,
  6187. small: returnsString,
  6188. split: returnsUnknown,
  6189. startsWith: returnsBoolean,
  6190. strike: returnsString,
  6191. sub: returnsString,
  6192. substr: returnsString,
  6193. substring: returnsString,
  6194. sup: returnsString,
  6195. toLocaleLowerCase: returnsString,
  6196. toLocaleUpperCase: returnsString,
  6197. toLowerCase: returnsString,
  6198. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  6199. toUpperCase: returnsString,
  6200. trim: returnsString,
  6201. trimEnd: returnsString,
  6202. trimLeft: returnsString,
  6203. trimRight: returnsString,
  6204. trimStart: returnsString,
  6205. valueOf: returnsString
  6206. }, objectMembers);
  6207. function getLiteralMembersForValue(value) {
  6208. if (value instanceof RegExp) {
  6209. return literalRegExpMembers;
  6210. }
  6211. switch (typeof value) {
  6212. case 'boolean': {
  6213. return literalBooleanMembers;
  6214. }
  6215. case 'number': {
  6216. return literalNumberMembers;
  6217. }
  6218. case 'string': {
  6219. return literalStringMembers;
  6220. }
  6221. }
  6222. return Object.create(null);
  6223. }
  6224. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  6225. if (typeof memberName !== 'string' || !members[memberName]) {
  6226. return true;
  6227. }
  6228. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  6229. }
  6230. function getMemberReturnExpressionWhenCalled(members, memberName) {
  6231. if (typeof memberName !== 'string' || !members[memberName])
  6232. return UNKNOWN_RETURN_EXPRESSION;
  6233. return [members[memberName].returns, false];
  6234. }
  6235. class Method extends ExpressionEntity {
  6236. constructor(description) {
  6237. super();
  6238. this.description = description;
  6239. }
  6240. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  6241. if (type === INTERACTION_CALLED && path.length === 0) {
  6242. if (this.description.mutatesSelfAsArray) {
  6243. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6244. }
  6245. if (this.description.mutatesArgs) {
  6246. for (let index = 1; index < args.length; index++) {
  6247. args[index].deoptimizePath(UNKNOWN_PATH);
  6248. }
  6249. }
  6250. }
  6251. }
  6252. getReturnExpressionWhenCalledAtPath(path, { args }) {
  6253. if (path.length > 0) {
  6254. return UNKNOWN_RETURN_EXPRESSION;
  6255. }
  6256. return [
  6257. this.description.returnsPrimitive ||
  6258. (this.description.returns === 'self'
  6259. ? args[0] || UNKNOWN_EXPRESSION
  6260. : this.description.returns()),
  6261. false
  6262. ];
  6263. }
  6264. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  6265. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  6266. return true;
  6267. }
  6268. if (type === INTERACTION_CALLED) {
  6269. if (this.description.mutatesSelfAsArray === true &&
  6270. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  6271. return true;
  6272. }
  6273. if (this.description.callsArgs) {
  6274. for (const argumentIndex of this.description.callsArgs) {
  6275. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  6276. return true;
  6277. }
  6278. }
  6279. }
  6280. }
  6281. return false;
  6282. }
  6283. }
  6284. const METHOD_RETURNS_BOOLEAN = [
  6285. new Method({
  6286. callsArgs: null,
  6287. mutatesArgs: false,
  6288. mutatesSelfAsArray: false,
  6289. returns: null,
  6290. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6291. })
  6292. ];
  6293. const METHOD_RETURNS_STRING = [
  6294. new Method({
  6295. callsArgs: null,
  6296. mutatesArgs: false,
  6297. mutatesSelfAsArray: false,
  6298. returns: null,
  6299. returnsPrimitive: UNKNOWN_LITERAL_STRING
  6300. })
  6301. ];
  6302. const METHOD_RETURNS_NUMBER = [
  6303. new Method({
  6304. callsArgs: null,
  6305. mutatesArgs: false,
  6306. mutatesSelfAsArray: false,
  6307. returns: null,
  6308. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6309. })
  6310. ];
  6311. const METHOD_RETURNS_UNKNOWN = [
  6312. new Method({
  6313. callsArgs: null,
  6314. mutatesArgs: false,
  6315. mutatesSelfAsArray: false,
  6316. returns: null,
  6317. returnsPrimitive: UNKNOWN_EXPRESSION
  6318. })
  6319. ];
  6320. const INTEGER_REG_EXP = /^\d+$/;
  6321. class ObjectEntity extends ExpressionEntity {
  6322. get hasLostTrack() {
  6323. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  6324. }
  6325. set hasLostTrack(value) {
  6326. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  6327. }
  6328. get hasUnknownDeoptimizedInteger() {
  6329. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  6330. }
  6331. set hasUnknownDeoptimizedInteger(value) {
  6332. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  6333. }
  6334. get hasUnknownDeoptimizedProperty() {
  6335. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  6336. }
  6337. set hasUnknownDeoptimizedProperty(value) {
  6338. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  6339. }
  6340. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  6341. // and we assume there are no setters or getters
  6342. constructor(properties, prototypeExpression, immutable = false) {
  6343. super();
  6344. this.prototypeExpression = prototypeExpression;
  6345. this.immutable = immutable;
  6346. this.additionalExpressionsToBeDeoptimized = new Set();
  6347. this.allProperties = [];
  6348. this.deoptimizedPaths = Object.create(null);
  6349. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  6350. this.gettersByKey = Object.create(null);
  6351. this.propertiesAndGettersByKey = Object.create(null);
  6352. this.propertiesAndSettersByKey = Object.create(null);
  6353. this.settersByKey = Object.create(null);
  6354. this.unknownIntegerProps = [];
  6355. this.unmatchableGetters = [];
  6356. this.unmatchablePropertiesAndGetters = [];
  6357. this.unmatchablePropertiesAndSetters = [];
  6358. this.unmatchableSetters = [];
  6359. if (Array.isArray(properties)) {
  6360. this.buildPropertyMaps(properties);
  6361. }
  6362. else {
  6363. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  6364. for (const propertiesForKey of Object.values(properties)) {
  6365. this.allProperties.push(...propertiesForKey);
  6366. }
  6367. }
  6368. }
  6369. deoptimizeAllProperties(noAccessors) {
  6370. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  6371. if (noAccessors) {
  6372. this.hasUnknownDeoptimizedProperty = true;
  6373. }
  6374. else {
  6375. this.hasLostTrack = true;
  6376. }
  6377. if (isDeoptimized) {
  6378. return;
  6379. }
  6380. for (const properties of [
  6381. ...Object.values(this.propertiesAndGettersByKey),
  6382. ...Object.values(this.settersByKey)
  6383. ]) {
  6384. for (const property of properties) {
  6385. property.deoptimizePath(UNKNOWN_PATH);
  6386. }
  6387. }
  6388. // While the prototype itself cannot be mutated, each property can
  6389. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  6390. this.deoptimizeCachedEntities();
  6391. }
  6392. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6393. const [key, ...subPath] = path;
  6394. const { args, type } = interaction;
  6395. if (this.hasLostTrack ||
  6396. // single paths that are deoptimized will not become getters or setters
  6397. ((type === INTERACTION_CALLED || path.length > 1) &&
  6398. (this.hasUnknownDeoptimizedProperty ||
  6399. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  6400. deoptimizeInteraction(interaction);
  6401. return;
  6402. }
  6403. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  6404. ? [
  6405. this.propertiesAndGettersByKey,
  6406. this.propertiesAndGettersByKey,
  6407. this.unmatchablePropertiesAndGetters
  6408. ]
  6409. : type === INTERACTION_ACCESSED
  6410. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6411. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6412. if (typeof key === 'string') {
  6413. if (propertiesForExactMatchByKey[key]) {
  6414. const properties = relevantPropertiesByKey[key];
  6415. if (properties) {
  6416. for (const property of properties) {
  6417. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6418. }
  6419. }
  6420. if (!this.immutable) {
  6421. for (const argument of args) {
  6422. if (argument) {
  6423. this.additionalExpressionsToBeDeoptimized.add(argument);
  6424. }
  6425. }
  6426. }
  6427. return;
  6428. }
  6429. for (const property of relevantUnmatchableProperties) {
  6430. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6431. }
  6432. if (INTEGER_REG_EXP.test(key)) {
  6433. for (const property of this.unknownIntegerProps) {
  6434. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6435. }
  6436. }
  6437. }
  6438. else {
  6439. for (const properties of [
  6440. ...Object.values(relevantPropertiesByKey),
  6441. relevantUnmatchableProperties
  6442. ]) {
  6443. for (const property of properties) {
  6444. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6445. }
  6446. }
  6447. for (const property of this.unknownIntegerProps) {
  6448. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6449. }
  6450. }
  6451. if (!this.immutable) {
  6452. for (const argument of args) {
  6453. if (argument) {
  6454. this.additionalExpressionsToBeDeoptimized.add(argument);
  6455. }
  6456. }
  6457. }
  6458. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6459. }
  6460. deoptimizeIntegerProperties() {
  6461. if (this.hasLostTrack ||
  6462. this.hasUnknownDeoptimizedProperty ||
  6463. this.hasUnknownDeoptimizedInteger) {
  6464. return;
  6465. }
  6466. this.hasUnknownDeoptimizedInteger = true;
  6467. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  6468. if (INTEGER_REG_EXP.test(key)) {
  6469. for (const property of propertiesAndGetters) {
  6470. property.deoptimizePath(UNKNOWN_PATH);
  6471. }
  6472. }
  6473. }
  6474. this.deoptimizeCachedIntegerEntities();
  6475. }
  6476. // Assumption: If only a specific path is deoptimized, no accessors are created
  6477. deoptimizePath(path) {
  6478. if (this.hasLostTrack || this.immutable) {
  6479. return;
  6480. }
  6481. const key = path[0];
  6482. if (path.length === 1) {
  6483. if (key === UnknownInteger) {
  6484. return this.deoptimizeIntegerProperties();
  6485. }
  6486. else if (typeof key !== 'string') {
  6487. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  6488. }
  6489. if (!this.deoptimizedPaths[key]) {
  6490. this.deoptimizedPaths[key] = true;
  6491. // we only deoptimizeCache exact matches as in all other cases,
  6492. // we do not return a literal value or return expression
  6493. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  6494. if (expressionsToBeDeoptimized) {
  6495. for (const expression of expressionsToBeDeoptimized) {
  6496. expression.deoptimizeCache();
  6497. }
  6498. }
  6499. }
  6500. }
  6501. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  6502. for (const property of typeof key === 'string'
  6503. ? [
  6504. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  6505. ...(this.settersByKey[key] || this.unmatchableSetters)
  6506. ]
  6507. : this.allProperties) {
  6508. property.deoptimizePath(subPath);
  6509. }
  6510. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  6511. }
  6512. getLiteralValueAtPath(path, recursionTracker, origin) {
  6513. if (path.length === 0) {
  6514. // This should actually be "UnknownTruthyValue". However, this currently
  6515. // causes an issue with TypeScript enums in files with moduleSideEffects:
  6516. // false because we cannot properly track whether a "var" has been
  6517. // initialized. This should be reverted once we can properly track this.
  6518. // return UnknownTruthyValue;
  6519. return UnknownValue;
  6520. }
  6521. const key = path[0];
  6522. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6523. if (expressionAtPath) {
  6524. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  6525. }
  6526. if (this.prototypeExpression) {
  6527. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6528. }
  6529. if (path.length === 1) {
  6530. return undefined;
  6531. }
  6532. return UnknownValue;
  6533. }
  6534. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6535. if (path.length === 0) {
  6536. return UNKNOWN_RETURN_EXPRESSION;
  6537. }
  6538. const [key, ...subPath] = path;
  6539. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  6540. if (expressionAtPath) {
  6541. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  6542. }
  6543. if (this.prototypeExpression) {
  6544. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6545. }
  6546. return UNKNOWN_RETURN_EXPRESSION;
  6547. }
  6548. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6549. const [key, ...subPath] = path;
  6550. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  6551. const expressionAtPath = this.getMemberExpression(key);
  6552. if (expressionAtPath) {
  6553. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  6554. }
  6555. if (this.prototypeExpression) {
  6556. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6557. }
  6558. return true;
  6559. }
  6560. if (key === UnknownNonAccessorKey)
  6561. return false;
  6562. if (this.hasLostTrack)
  6563. return true;
  6564. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  6565. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6566. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6567. if (typeof key === 'string') {
  6568. if (propertiesAndAccessorsByKey[key]) {
  6569. const accessors = accessorsByKey[key];
  6570. if (accessors) {
  6571. for (const accessor of accessors) {
  6572. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6573. return true;
  6574. }
  6575. }
  6576. return false;
  6577. }
  6578. for (const accessor of unmatchableAccessors) {
  6579. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  6580. return true;
  6581. }
  6582. }
  6583. }
  6584. else {
  6585. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  6586. for (const accessor of accessors) {
  6587. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  6588. return true;
  6589. }
  6590. }
  6591. }
  6592. if (this.prototypeExpression) {
  6593. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  6594. }
  6595. return false;
  6596. }
  6597. include(context, includeChildrenRecursively) {
  6598. this.included = true;
  6599. for (const property of this.allProperties) {
  6600. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  6601. property.include(context, includeChildrenRecursively);
  6602. }
  6603. }
  6604. this.prototypeExpression?.include(context, includeChildrenRecursively);
  6605. }
  6606. includePath(path, context) {
  6607. this.included = true;
  6608. if (path.length === 0)
  6609. return;
  6610. const [key, ...subPath] = path;
  6611. const [includedMembers, includedPath] = typeof key === 'string'
  6612. ? [
  6613. new Set([
  6614. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  6615. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  6616. ]),
  6617. subPath
  6618. ]
  6619. : [this.allProperties, UNKNOWN_PATH];
  6620. for (const property of includedMembers) {
  6621. property.includePath(includedPath, context);
  6622. }
  6623. this.prototypeExpression?.includePath(path, context);
  6624. }
  6625. buildPropertyMaps(properties) {
  6626. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  6627. for (let index = properties.length - 1; index >= 0; index--) {
  6628. const { key, kind, property } = properties[index];
  6629. allProperties.push(property);
  6630. if (typeof key === 'string') {
  6631. if (kind === 'set') {
  6632. if (!propertiesAndSettersByKey[key]) {
  6633. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6634. settersByKey[key] = [property, ...unmatchableSetters];
  6635. }
  6636. }
  6637. else if (kind === 'get') {
  6638. if (!propertiesAndGettersByKey[key]) {
  6639. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6640. gettersByKey[key] = [property, ...unmatchableGetters];
  6641. }
  6642. }
  6643. else {
  6644. if (!propertiesAndSettersByKey[key]) {
  6645. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  6646. }
  6647. if (!propertiesAndGettersByKey[key]) {
  6648. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  6649. }
  6650. }
  6651. }
  6652. else {
  6653. if (key === UnknownInteger) {
  6654. unknownIntegerProps.push(property);
  6655. continue;
  6656. }
  6657. if (kind === 'set')
  6658. unmatchableSetters.push(property);
  6659. if (kind === 'get')
  6660. unmatchableGetters.push(property);
  6661. if (kind !== 'get')
  6662. unmatchablePropertiesAndSetters.push(property);
  6663. if (kind !== 'set')
  6664. unmatchablePropertiesAndGetters.push(property);
  6665. }
  6666. }
  6667. }
  6668. deoptimizeCachedEntities() {
  6669. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  6670. for (const expression of expressionsToBeDeoptimized) {
  6671. expression.deoptimizeCache();
  6672. }
  6673. }
  6674. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6675. expression.deoptimizePath(UNKNOWN_PATH);
  6676. }
  6677. }
  6678. deoptimizeCachedIntegerEntities() {
  6679. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  6680. if (INTEGER_REG_EXP.test(key)) {
  6681. for (const expression of expressionsToBeDeoptimized) {
  6682. expression.deoptimizeCache();
  6683. }
  6684. }
  6685. }
  6686. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  6687. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6688. }
  6689. }
  6690. getMemberExpression(key) {
  6691. if (this.hasLostTrack ||
  6692. this.hasUnknownDeoptimizedProperty ||
  6693. typeof key !== 'string' ||
  6694. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  6695. this.deoptimizedPaths[key]) {
  6696. return UNKNOWN_EXPRESSION;
  6697. }
  6698. const properties = this.propertiesAndGettersByKey[key];
  6699. if (properties?.length === 1) {
  6700. return properties[0];
  6701. }
  6702. if (properties ||
  6703. this.unmatchablePropertiesAndGetters.length > 0 ||
  6704. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  6705. return UNKNOWN_EXPRESSION;
  6706. }
  6707. return null;
  6708. }
  6709. getMemberExpressionAndTrackDeopt(key, origin) {
  6710. if (typeof key !== 'string') {
  6711. return UNKNOWN_EXPRESSION;
  6712. }
  6713. const expression = this.getMemberExpression(key);
  6714. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  6715. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  6716. this.expressionsToBeDeoptimizedByKey[key] || []);
  6717. expressionsToBeDeoptimized.push(origin);
  6718. }
  6719. return expression;
  6720. }
  6721. }
  6722. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  6723. // This makes sure unknown properties are not handled as "undefined" but as
  6724. // "unknown" but without access side effects. An exception is done for numeric
  6725. // properties as we do not expect new builtin properties to be numbers, this
  6726. // will improve tree-shaking for out-of-bounds array properties
  6727. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  6728. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6729. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  6730. deoptimizeInteraction(interaction);
  6731. }
  6732. }
  6733. getLiteralValueAtPath(path) {
  6734. // We ignore number properties as we do not expect new properties to be
  6735. // numbers and also want to keep handling out-of-bound array elements as
  6736. // "undefined"
  6737. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  6738. }
  6739. hasEffectsOnInteractionAtPath(path, { type }) {
  6740. return path.length > 1 || type === INTERACTION_CALLED;
  6741. }
  6742. })();
  6743. const OBJECT_PROTOTYPE = new ObjectEntity({
  6744. __proto__: null,
  6745. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  6746. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  6747. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  6748. toLocaleString: METHOD_RETURNS_STRING,
  6749. toString: METHOD_RETURNS_STRING,
  6750. valueOf: METHOD_RETURNS_UNKNOWN
  6751. }, OBJECT_PROTOTYPE_FALLBACK, true);
  6752. const NEW_ARRAY_PROPERTIES = [
  6753. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  6754. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6755. ];
  6756. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  6757. new Method({
  6758. callsArgs: [0],
  6759. mutatesArgs: false,
  6760. mutatesSelfAsArray: 'deopt-only',
  6761. returns: null,
  6762. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6763. })
  6764. ];
  6765. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  6766. new Method({
  6767. callsArgs: [0],
  6768. mutatesArgs: false,
  6769. mutatesSelfAsArray: 'deopt-only',
  6770. returns: null,
  6771. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6772. })
  6773. ];
  6774. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  6775. new Method({
  6776. callsArgs: null,
  6777. mutatesArgs: false,
  6778. mutatesSelfAsArray: true,
  6779. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6780. returnsPrimitive: null
  6781. })
  6782. ];
  6783. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6784. new Method({
  6785. callsArgs: null,
  6786. mutatesArgs: false,
  6787. mutatesSelfAsArray: 'deopt-only',
  6788. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6789. returnsPrimitive: null
  6790. })
  6791. ];
  6792. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  6793. new Method({
  6794. callsArgs: [0],
  6795. mutatesArgs: false,
  6796. mutatesSelfAsArray: 'deopt-only',
  6797. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  6798. returnsPrimitive: null
  6799. })
  6800. ];
  6801. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  6802. new Method({
  6803. callsArgs: null,
  6804. mutatesArgs: true,
  6805. mutatesSelfAsArray: true,
  6806. returns: null,
  6807. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6808. })
  6809. ];
  6810. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  6811. new Method({
  6812. callsArgs: null,
  6813. mutatesArgs: false,
  6814. mutatesSelfAsArray: true,
  6815. returns: null,
  6816. returnsPrimitive: UNKNOWN_EXPRESSION
  6817. })
  6818. ];
  6819. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6820. new Method({
  6821. callsArgs: null,
  6822. mutatesArgs: false,
  6823. mutatesSelfAsArray: 'deopt-only',
  6824. returns: null,
  6825. returnsPrimitive: UNKNOWN_EXPRESSION
  6826. })
  6827. ];
  6828. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  6829. new Method({
  6830. callsArgs: [0],
  6831. mutatesArgs: false,
  6832. mutatesSelfAsArray: 'deopt-only',
  6833. returns: null,
  6834. returnsPrimitive: UNKNOWN_EXPRESSION
  6835. })
  6836. ];
  6837. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  6838. new Method({
  6839. callsArgs: null,
  6840. mutatesArgs: false,
  6841. mutatesSelfAsArray: true,
  6842. returns: 'self',
  6843. returnsPrimitive: null
  6844. })
  6845. ];
  6846. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  6847. new Method({
  6848. callsArgs: [0],
  6849. mutatesArgs: false,
  6850. mutatesSelfAsArray: true,
  6851. returns: 'self',
  6852. returnsPrimitive: null
  6853. })
  6854. ];
  6855. const ARRAY_PROTOTYPE = new ObjectEntity({
  6856. __proto__: null,
  6857. // We assume that accessors have effects as we do not track the accessed value afterwards
  6858. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  6859. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6860. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  6861. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6862. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6863. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  6864. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6865. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6866. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6867. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6868. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  6869. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6870. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6871. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6872. includes: METHOD_RETURNS_BOOLEAN,
  6873. indexOf: METHOD_RETURNS_NUMBER,
  6874. join: METHOD_RETURNS_STRING,
  6875. keys: METHOD_RETURNS_UNKNOWN,
  6876. lastIndexOf: METHOD_RETURNS_NUMBER,
  6877. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6878. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6879. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  6880. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6881. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  6882. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  6883. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  6884. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  6885. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  6886. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  6887. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  6888. toLocaleString: METHOD_RETURNS_STRING,
  6889. toString: METHOD_RETURNS_STRING,
  6890. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  6891. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  6892. }, OBJECT_PROTOTYPE, true);
  6893. class SpreadElement extends NodeBase {
  6894. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6895. if (path.length > 0) {
  6896. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  6897. }
  6898. }
  6899. hasEffects(context) {
  6900. if (!this.deoptimized)
  6901. this.applyDeoptimizations();
  6902. const { propertyReadSideEffects } = this.scope.context.options
  6903. .treeshake;
  6904. return (this.argument.hasEffects(context) ||
  6905. (propertyReadSideEffects &&
  6906. (propertyReadSideEffects === 'always' ||
  6907. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  6908. }
  6909. includeNode(context) {
  6910. this.included = true;
  6911. if (!this.deoptimized)
  6912. this.applyDeoptimizations();
  6913. this.argument.includePath(UNKNOWN_PATH, context);
  6914. }
  6915. applyDeoptimizations() {
  6916. this.deoptimized = true;
  6917. // Only properties of properties of the argument could become subject to reassignment
  6918. // This will also reassign the return values of iterators
  6919. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  6920. this.scope.context.requestTreeshakingPass();
  6921. }
  6922. }
  6923. class ArrayExpression extends NodeBase {
  6924. constructor() {
  6925. super(...arguments);
  6926. this.objectEntity = null;
  6927. }
  6928. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6929. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6930. }
  6931. deoptimizePath(path) {
  6932. this.getObjectEntity().deoptimizePath(path);
  6933. }
  6934. getLiteralValueAtPath(path, recursionTracker, origin) {
  6935. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6936. }
  6937. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6938. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6939. }
  6940. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6941. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6942. }
  6943. includeNode(context) {
  6944. this.included = true;
  6945. if (!this.deoptimized)
  6946. this.applyDeoptimizations();
  6947. for (const element of this.elements) {
  6948. if (element) {
  6949. element?.includePath(UNKNOWN_PATH, context);
  6950. }
  6951. }
  6952. }
  6953. applyDeoptimizations() {
  6954. this.deoptimized = true;
  6955. let hasSpread = false;
  6956. for (let index = 0; index < this.elements.length; index++) {
  6957. const element = this.elements[index];
  6958. if (element && (hasSpread || element instanceof SpreadElement)) {
  6959. hasSpread = true;
  6960. element.deoptimizePath(UNKNOWN_PATH);
  6961. }
  6962. }
  6963. this.scope.context.requestTreeshakingPass();
  6964. }
  6965. getObjectEntity() {
  6966. if (this.objectEntity !== null) {
  6967. return this.objectEntity;
  6968. }
  6969. const properties = [
  6970. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  6971. ];
  6972. let hasSpread = false;
  6973. for (let index = 0; index < this.elements.length; index++) {
  6974. const element = this.elements[index];
  6975. if (hasSpread || element instanceof SpreadElement) {
  6976. if (element) {
  6977. hasSpread = true;
  6978. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  6979. }
  6980. }
  6981. else if (element) {
  6982. properties.push({ key: String(index), kind: 'init', property: element });
  6983. }
  6984. else {
  6985. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  6986. }
  6987. }
  6988. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  6989. }
  6990. }
  6991. /* eslint sort-keys: "off" */
  6992. const ValueProperties = Symbol('Value Properties');
  6993. const getUnknownValue = () => UnknownValue;
  6994. const returnFalse = () => false;
  6995. const returnTrue = () => true;
  6996. const PURE = {
  6997. deoptimizeArgumentsOnCall: doNothing,
  6998. getLiteralValue: getUnknownValue,
  6999. hasEffectsWhenCalled: returnFalse
  7000. };
  7001. const IMPURE = {
  7002. deoptimizeArgumentsOnCall: doNothing,
  7003. getLiteralValue: getUnknownValue,
  7004. hasEffectsWhenCalled: returnTrue
  7005. };
  7006. const PURE_WITH_ARRAY = {
  7007. deoptimizeArgumentsOnCall: doNothing,
  7008. getLiteralValue: getUnknownValue,
  7009. hasEffectsWhenCalled({ args }) {
  7010. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  7011. }
  7012. };
  7013. const GETTER_ACCESS = {
  7014. deoptimizeArgumentsOnCall: doNothing,
  7015. getLiteralValue: getUnknownValue,
  7016. hasEffectsWhenCalled({ args }, context) {
  7017. const [_thisArgument, firstArgument] = args;
  7018. return (!(firstArgument instanceof ExpressionEntity) ||
  7019. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7020. }
  7021. };
  7022. // We use shortened variables to reduce file size here
  7023. /* OBJECT */
  7024. const O = {
  7025. __proto__: null,
  7026. [ValueProperties]: IMPURE
  7027. };
  7028. /* PURE FUNCTION */
  7029. const PF = {
  7030. __proto__: null,
  7031. [ValueProperties]: PURE
  7032. };
  7033. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  7034. const PF_NO_GETTER = {
  7035. __proto__: null,
  7036. [ValueProperties]: GETTER_ACCESS
  7037. };
  7038. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  7039. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  7040. __proto__: null,
  7041. [ValueProperties]: {
  7042. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  7043. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  7044. },
  7045. getLiteralValue: getUnknownValue,
  7046. hasEffectsWhenCalled({ args }, context) {
  7047. return (args.length <= 1 ||
  7048. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  7049. }
  7050. }
  7051. };
  7052. /* CONSTRUCTOR */
  7053. const C = {
  7054. __proto__: null,
  7055. [ValueProperties]: IMPURE,
  7056. prototype: O
  7057. };
  7058. /* PURE CONSTRUCTOR */
  7059. const PC = {
  7060. __proto__: null,
  7061. [ValueProperties]: PURE,
  7062. prototype: O
  7063. };
  7064. const PC_WITH_ARRAY = {
  7065. __proto__: null,
  7066. [ValueProperties]: PURE_WITH_ARRAY,
  7067. prototype: O
  7068. };
  7069. const ARRAY_TYPE = {
  7070. __proto__: null,
  7071. [ValueProperties]: PURE,
  7072. from: O,
  7073. of: PF,
  7074. prototype: O
  7075. };
  7076. const INTL_MEMBER = {
  7077. __proto__: null,
  7078. [ValueProperties]: PURE,
  7079. supportedLocalesOf: PC
  7080. };
  7081. const knownGlobals = {
  7082. // Placeholders for global objects to avoid shape mutations
  7083. global: O,
  7084. globalThis: O,
  7085. self: O,
  7086. window: O,
  7087. // Common globals
  7088. __proto__: null,
  7089. [ValueProperties]: IMPURE,
  7090. Array: {
  7091. __proto__: null,
  7092. [ValueProperties]: IMPURE,
  7093. from: O,
  7094. isArray: PF,
  7095. of: PF,
  7096. prototype: O
  7097. },
  7098. ArrayBuffer: {
  7099. __proto__: null,
  7100. [ValueProperties]: PURE,
  7101. isView: PF,
  7102. prototype: O
  7103. },
  7104. AggregateError: PC_WITH_ARRAY,
  7105. Atomics: O,
  7106. BigInt: C,
  7107. BigInt64Array: C,
  7108. BigUint64Array: C,
  7109. Boolean: PC,
  7110. constructor: C,
  7111. DataView: PC,
  7112. Date: {
  7113. __proto__: null,
  7114. [ValueProperties]: PURE,
  7115. now: PF,
  7116. parse: PF,
  7117. prototype: O,
  7118. UTC: PF
  7119. },
  7120. decodeURI: PF,
  7121. decodeURIComponent: PF,
  7122. encodeURI: PF,
  7123. encodeURIComponent: PF,
  7124. Error: PC,
  7125. escape: PF,
  7126. eval: O,
  7127. EvalError: PC,
  7128. FinalizationRegistry: C,
  7129. Float32Array: ARRAY_TYPE,
  7130. Float64Array: ARRAY_TYPE,
  7131. Function: C,
  7132. hasOwnProperty: O,
  7133. Infinity: O,
  7134. Int16Array: ARRAY_TYPE,
  7135. Int32Array: ARRAY_TYPE,
  7136. Int8Array: ARRAY_TYPE,
  7137. isFinite: PF,
  7138. isNaN: PF,
  7139. isPrototypeOf: O,
  7140. JSON: O,
  7141. Map: PC_WITH_ARRAY,
  7142. Math: {
  7143. __proto__: null,
  7144. [ValueProperties]: IMPURE,
  7145. abs: PF,
  7146. acos: PF,
  7147. acosh: PF,
  7148. asin: PF,
  7149. asinh: PF,
  7150. atan: PF,
  7151. atan2: PF,
  7152. atanh: PF,
  7153. cbrt: PF,
  7154. ceil: PF,
  7155. clz32: PF,
  7156. cos: PF,
  7157. cosh: PF,
  7158. exp: PF,
  7159. expm1: PF,
  7160. floor: PF,
  7161. fround: PF,
  7162. hypot: PF,
  7163. imul: PF,
  7164. log: PF,
  7165. log10: PF,
  7166. log1p: PF,
  7167. log2: PF,
  7168. max: PF,
  7169. min: PF,
  7170. pow: PF,
  7171. random: PF,
  7172. round: PF,
  7173. sign: PF,
  7174. sin: PF,
  7175. sinh: PF,
  7176. sqrt: PF,
  7177. tan: PF,
  7178. tanh: PF,
  7179. trunc: PF
  7180. },
  7181. NaN: O,
  7182. Number: {
  7183. __proto__: null,
  7184. [ValueProperties]: PURE,
  7185. isFinite: PF,
  7186. isInteger: PF,
  7187. isNaN: PF,
  7188. isSafeInteger: PF,
  7189. parseFloat: PF,
  7190. parseInt: PF,
  7191. prototype: O
  7192. },
  7193. Object: {
  7194. __proto__: null,
  7195. [ValueProperties]: PURE,
  7196. create: PF,
  7197. // Technically those can throw in certain situations, but we ignore this as
  7198. // code that relies on this will hopefully wrap this in a try-catch, which
  7199. // deoptimizes everything anyway
  7200. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  7201. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  7202. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  7203. getOwnPropertyDescriptor: PF,
  7204. getOwnPropertyDescriptors: PF,
  7205. getOwnPropertyNames: PF,
  7206. getOwnPropertySymbols: PF,
  7207. getPrototypeOf: PF,
  7208. hasOwn: PF,
  7209. is: PF,
  7210. isExtensible: PF,
  7211. isFrozen: PF,
  7212. isSealed: PF,
  7213. keys: PF,
  7214. fromEntries: O,
  7215. entries: PF_NO_GETTER,
  7216. values: PF_NO_GETTER,
  7217. prototype: O
  7218. },
  7219. parseFloat: PF,
  7220. parseInt: PF,
  7221. Promise: {
  7222. __proto__: null,
  7223. [ValueProperties]: IMPURE,
  7224. all: O,
  7225. allSettled: O,
  7226. any: O,
  7227. prototype: O,
  7228. race: O,
  7229. reject: O,
  7230. resolve: O
  7231. },
  7232. propertyIsEnumerable: O,
  7233. Proxy: {
  7234. __proto__: null,
  7235. [ValueProperties]: {
  7236. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  7237. if (isObjectExpressionNode(parameter)) {
  7238. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  7239. if (!hasSpreadElement) {
  7240. for (const property of parameter.properties) {
  7241. property.deoptimizeArgumentsOnInteractionAtPath({
  7242. args: [null, target],
  7243. type: INTERACTION_CALLED,
  7244. withNew: false
  7245. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  7246. }
  7247. return;
  7248. }
  7249. }
  7250. target.deoptimizePath(UNKNOWN_PATH);
  7251. },
  7252. getLiteralValue: getUnknownValue,
  7253. hasEffectsWhenCalled: returnTrue
  7254. }
  7255. },
  7256. RangeError: PC,
  7257. ReferenceError: PC,
  7258. Reflect: O,
  7259. RegExp: PC,
  7260. Set: PC_WITH_ARRAY,
  7261. SharedArrayBuffer: C,
  7262. String: {
  7263. __proto__: null,
  7264. [ValueProperties]: PURE,
  7265. fromCharCode: PF,
  7266. fromCodePoint: PF,
  7267. prototype: O,
  7268. raw: PF
  7269. },
  7270. Symbol: {
  7271. __proto__: null,
  7272. [ValueProperties]: PURE,
  7273. for: PF,
  7274. keyFor: PF,
  7275. prototype: O,
  7276. toStringTag: {
  7277. __proto__: null,
  7278. [ValueProperties]: {
  7279. deoptimizeArgumentsOnCall: doNothing,
  7280. getLiteralValue() {
  7281. return SymbolToStringTag;
  7282. },
  7283. hasEffectsWhenCalled: returnTrue
  7284. }
  7285. }
  7286. },
  7287. SyntaxError: PC,
  7288. toLocaleString: O,
  7289. toString: O,
  7290. TypeError: PC,
  7291. Uint16Array: ARRAY_TYPE,
  7292. Uint32Array: ARRAY_TYPE,
  7293. Uint8Array: ARRAY_TYPE,
  7294. Uint8ClampedArray: ARRAY_TYPE,
  7295. // Technically, this is a global, but it needs special handling
  7296. // undefined: ?,
  7297. unescape: PF,
  7298. URIError: PC,
  7299. valueOf: O,
  7300. WeakMap: PC_WITH_ARRAY,
  7301. WeakRef: C,
  7302. WeakSet: PC_WITH_ARRAY,
  7303. // Additional globals shared by Node and Browser that are not strictly part of the language
  7304. clearInterval: C,
  7305. clearTimeout: C,
  7306. console: {
  7307. __proto__: null,
  7308. [ValueProperties]: IMPURE,
  7309. assert: C,
  7310. clear: C,
  7311. count: C,
  7312. countReset: C,
  7313. debug: C,
  7314. dir: C,
  7315. dirxml: C,
  7316. error: C,
  7317. exception: C,
  7318. group: C,
  7319. groupCollapsed: C,
  7320. groupEnd: C,
  7321. info: C,
  7322. log: C,
  7323. table: C,
  7324. time: C,
  7325. timeEnd: C,
  7326. timeLog: C,
  7327. trace: C,
  7328. warn: C
  7329. },
  7330. Intl: {
  7331. __proto__: null,
  7332. [ValueProperties]: IMPURE,
  7333. Collator: INTL_MEMBER,
  7334. DateTimeFormat: INTL_MEMBER,
  7335. DisplayNames: INTL_MEMBER,
  7336. ListFormat: INTL_MEMBER,
  7337. Locale: INTL_MEMBER,
  7338. NumberFormat: INTL_MEMBER,
  7339. PluralRules: INTL_MEMBER,
  7340. RelativeTimeFormat: INTL_MEMBER,
  7341. Segmenter: INTL_MEMBER
  7342. },
  7343. setInterval: C,
  7344. setTimeout: C,
  7345. TextDecoder: C,
  7346. TextEncoder: C,
  7347. URL: {
  7348. __proto__: null,
  7349. [ValueProperties]: IMPURE,
  7350. prototype: O,
  7351. canParse: PF
  7352. },
  7353. URLSearchParams: C,
  7354. // Browser specific globals
  7355. AbortController: C,
  7356. AbortSignal: C,
  7357. addEventListener: O,
  7358. alert: O,
  7359. AnalyserNode: C,
  7360. Animation: C,
  7361. AnimationEvent: C,
  7362. applicationCache: O,
  7363. ApplicationCache: C,
  7364. ApplicationCacheErrorEvent: C,
  7365. atob: O,
  7366. Attr: C,
  7367. Audio: C,
  7368. AudioBuffer: C,
  7369. AudioBufferSourceNode: C,
  7370. AudioContext: C,
  7371. AudioDestinationNode: C,
  7372. AudioListener: C,
  7373. AudioNode: C,
  7374. AudioParam: C,
  7375. AudioProcessingEvent: C,
  7376. AudioScheduledSourceNode: C,
  7377. AudioWorkletNode: C,
  7378. BarProp: C,
  7379. BaseAudioContext: C,
  7380. BatteryManager: C,
  7381. BeforeUnloadEvent: C,
  7382. BiquadFilterNode: C,
  7383. Blob: C,
  7384. BlobEvent: C,
  7385. blur: O,
  7386. BroadcastChannel: C,
  7387. btoa: O,
  7388. ByteLengthQueuingStrategy: C,
  7389. Cache: C,
  7390. caches: O,
  7391. CacheStorage: C,
  7392. cancelAnimationFrame: O,
  7393. cancelIdleCallback: O,
  7394. CanvasCaptureMediaStreamTrack: C,
  7395. CanvasGradient: C,
  7396. CanvasPattern: C,
  7397. CanvasRenderingContext2D: C,
  7398. ChannelMergerNode: C,
  7399. ChannelSplitterNode: C,
  7400. CharacterData: C,
  7401. clientInformation: O,
  7402. ClipboardEvent: C,
  7403. close: O,
  7404. closed: O,
  7405. CloseEvent: C,
  7406. Comment: C,
  7407. CompositionEvent: C,
  7408. confirm: O,
  7409. ConstantSourceNode: C,
  7410. ConvolverNode: C,
  7411. CountQueuingStrategy: C,
  7412. createImageBitmap: O,
  7413. Credential: C,
  7414. CredentialsContainer: C,
  7415. crypto: O,
  7416. Crypto: C,
  7417. CryptoKey: C,
  7418. CSS: C,
  7419. CSSConditionRule: C,
  7420. CSSFontFaceRule: C,
  7421. CSSGroupingRule: C,
  7422. CSSImportRule: C,
  7423. CSSKeyframeRule: C,
  7424. CSSKeyframesRule: C,
  7425. CSSMediaRule: C,
  7426. CSSNamespaceRule: C,
  7427. CSSPageRule: C,
  7428. CSSRule: C,
  7429. CSSRuleList: C,
  7430. CSSStyleDeclaration: C,
  7431. CSSStyleRule: C,
  7432. CSSStyleSheet: C,
  7433. CSSSupportsRule: C,
  7434. CustomElementRegistry: C,
  7435. customElements: O,
  7436. CustomEvent: {
  7437. __proto__: null,
  7438. [ValueProperties]: {
  7439. deoptimizeArgumentsOnCall({ args }) {
  7440. args[2]?.deoptimizePath(['detail']);
  7441. },
  7442. getLiteralValue: getUnknownValue,
  7443. hasEffectsWhenCalled: returnFalse
  7444. },
  7445. prototype: O
  7446. },
  7447. DataTransfer: C,
  7448. DataTransferItem: C,
  7449. DataTransferItemList: C,
  7450. defaultstatus: O,
  7451. defaultStatus: O,
  7452. DelayNode: C,
  7453. DeviceMotionEvent: C,
  7454. DeviceOrientationEvent: C,
  7455. devicePixelRatio: O,
  7456. dispatchEvent: O,
  7457. document: O,
  7458. Document: C,
  7459. DocumentFragment: C,
  7460. DocumentType: C,
  7461. DOMError: C,
  7462. DOMException: C,
  7463. DOMImplementation: C,
  7464. DOMMatrix: C,
  7465. DOMMatrixReadOnly: C,
  7466. DOMParser: C,
  7467. DOMPoint: C,
  7468. DOMPointReadOnly: C,
  7469. DOMQuad: C,
  7470. DOMRect: C,
  7471. DOMRectReadOnly: C,
  7472. DOMStringList: C,
  7473. DOMStringMap: C,
  7474. DOMTokenList: C,
  7475. DragEvent: C,
  7476. DynamicsCompressorNode: C,
  7477. Element: C,
  7478. ErrorEvent: C,
  7479. Event: C,
  7480. EventSource: C,
  7481. EventTarget: C,
  7482. external: O,
  7483. fetch: O,
  7484. File: C,
  7485. FileList: C,
  7486. FileReader: C,
  7487. find: O,
  7488. focus: O,
  7489. FocusEvent: C,
  7490. FontFace: C,
  7491. FontFaceSetLoadEvent: C,
  7492. FormData: C,
  7493. frames: O,
  7494. GainNode: C,
  7495. Gamepad: C,
  7496. GamepadButton: C,
  7497. GamepadEvent: C,
  7498. getComputedStyle: O,
  7499. getSelection: O,
  7500. HashChangeEvent: C,
  7501. Headers: C,
  7502. history: O,
  7503. History: C,
  7504. HTMLAllCollection: C,
  7505. HTMLAnchorElement: C,
  7506. HTMLAreaElement: C,
  7507. HTMLAudioElement: C,
  7508. HTMLBaseElement: C,
  7509. HTMLBodyElement: C,
  7510. HTMLBRElement: C,
  7511. HTMLButtonElement: C,
  7512. HTMLCanvasElement: C,
  7513. HTMLCollection: C,
  7514. HTMLContentElement: C,
  7515. HTMLDataElement: C,
  7516. HTMLDataListElement: C,
  7517. HTMLDetailsElement: C,
  7518. HTMLDialogElement: C,
  7519. HTMLDirectoryElement: C,
  7520. HTMLDivElement: C,
  7521. HTMLDListElement: C,
  7522. HTMLDocument: C,
  7523. HTMLElement: C,
  7524. HTMLEmbedElement: C,
  7525. HTMLFieldSetElement: C,
  7526. HTMLFontElement: C,
  7527. HTMLFormControlsCollection: C,
  7528. HTMLFormElement: C,
  7529. HTMLFrameElement: C,
  7530. HTMLFrameSetElement: C,
  7531. HTMLHeadElement: C,
  7532. HTMLHeadingElement: C,
  7533. HTMLHRElement: C,
  7534. HTMLHtmlElement: C,
  7535. HTMLIFrameElement: C,
  7536. HTMLImageElement: C,
  7537. HTMLInputElement: C,
  7538. HTMLLabelElement: C,
  7539. HTMLLegendElement: C,
  7540. HTMLLIElement: C,
  7541. HTMLLinkElement: C,
  7542. HTMLMapElement: C,
  7543. HTMLMarqueeElement: C,
  7544. HTMLMediaElement: C,
  7545. HTMLMenuElement: C,
  7546. HTMLMetaElement: C,
  7547. HTMLMeterElement: C,
  7548. HTMLModElement: C,
  7549. HTMLObjectElement: C,
  7550. HTMLOListElement: C,
  7551. HTMLOptGroupElement: C,
  7552. HTMLOptionElement: C,
  7553. HTMLOptionsCollection: C,
  7554. HTMLOutputElement: C,
  7555. HTMLParagraphElement: C,
  7556. HTMLParamElement: C,
  7557. HTMLPictureElement: C,
  7558. HTMLPreElement: C,
  7559. HTMLProgressElement: C,
  7560. HTMLQuoteElement: C,
  7561. HTMLScriptElement: C,
  7562. HTMLSelectElement: C,
  7563. HTMLShadowElement: C,
  7564. HTMLSlotElement: C,
  7565. HTMLSourceElement: C,
  7566. HTMLSpanElement: C,
  7567. HTMLStyleElement: C,
  7568. HTMLTableCaptionElement: C,
  7569. HTMLTableCellElement: C,
  7570. HTMLTableColElement: C,
  7571. HTMLTableElement: C,
  7572. HTMLTableRowElement: C,
  7573. HTMLTableSectionElement: C,
  7574. HTMLTemplateElement: C,
  7575. HTMLTextAreaElement: C,
  7576. HTMLTimeElement: C,
  7577. HTMLTitleElement: C,
  7578. HTMLTrackElement: C,
  7579. HTMLUListElement: C,
  7580. HTMLUnknownElement: C,
  7581. HTMLVideoElement: C,
  7582. IDBCursor: C,
  7583. IDBCursorWithValue: C,
  7584. IDBDatabase: C,
  7585. IDBFactory: C,
  7586. IDBIndex: C,
  7587. IDBKeyRange: C,
  7588. IDBObjectStore: C,
  7589. IDBOpenDBRequest: C,
  7590. IDBRequest: C,
  7591. IDBTransaction: C,
  7592. IDBVersionChangeEvent: C,
  7593. IdleDeadline: C,
  7594. IIRFilterNode: C,
  7595. Image: C,
  7596. ImageBitmap: C,
  7597. ImageBitmapRenderingContext: C,
  7598. ImageCapture: C,
  7599. ImageData: C,
  7600. indexedDB: O,
  7601. innerHeight: O,
  7602. innerWidth: O,
  7603. InputEvent: C,
  7604. IntersectionObserver: C,
  7605. IntersectionObserverEntry: C,
  7606. isSecureContext: O,
  7607. KeyboardEvent: C,
  7608. KeyframeEffect: C,
  7609. length: O,
  7610. localStorage: O,
  7611. location: O,
  7612. Location: C,
  7613. locationbar: O,
  7614. matchMedia: O,
  7615. MediaDeviceInfo: C,
  7616. MediaDevices: C,
  7617. MediaElementAudioSourceNode: C,
  7618. MediaEncryptedEvent: C,
  7619. MediaError: C,
  7620. MediaKeyMessageEvent: C,
  7621. MediaKeySession: C,
  7622. MediaKeyStatusMap: C,
  7623. MediaKeySystemAccess: C,
  7624. MediaList: C,
  7625. MediaQueryList: C,
  7626. MediaQueryListEvent: C,
  7627. MediaRecorder: C,
  7628. MediaSettingsRange: C,
  7629. MediaSource: C,
  7630. MediaStream: C,
  7631. MediaStreamAudioDestinationNode: C,
  7632. MediaStreamAudioSourceNode: C,
  7633. MediaStreamEvent: C,
  7634. MediaStreamTrack: C,
  7635. MediaStreamTrackEvent: C,
  7636. menubar: O,
  7637. MessageChannel: C,
  7638. MessageEvent: C,
  7639. MessagePort: C,
  7640. MIDIAccess: C,
  7641. MIDIConnectionEvent: C,
  7642. MIDIInput: C,
  7643. MIDIInputMap: C,
  7644. MIDIMessageEvent: C,
  7645. MIDIOutput: C,
  7646. MIDIOutputMap: C,
  7647. MIDIPort: C,
  7648. MimeType: C,
  7649. MimeTypeArray: C,
  7650. MouseEvent: C,
  7651. moveBy: O,
  7652. moveTo: O,
  7653. MutationEvent: C,
  7654. MutationObserver: C,
  7655. MutationRecord: C,
  7656. name: O,
  7657. NamedNodeMap: C,
  7658. NavigationPreloadManager: C,
  7659. navigator: O,
  7660. Navigator: C,
  7661. NetworkInformation: C,
  7662. Node: C,
  7663. NodeFilter: O,
  7664. NodeIterator: C,
  7665. NodeList: C,
  7666. Notification: C,
  7667. OfflineAudioCompletionEvent: C,
  7668. OfflineAudioContext: C,
  7669. offscreenBuffering: O,
  7670. OffscreenCanvas: C,
  7671. open: O,
  7672. openDatabase: O,
  7673. Option: C,
  7674. origin: O,
  7675. OscillatorNode: C,
  7676. outerHeight: O,
  7677. outerWidth: O,
  7678. PageTransitionEvent: C,
  7679. pageXOffset: O,
  7680. pageYOffset: O,
  7681. PannerNode: C,
  7682. parent: O,
  7683. Path2D: C,
  7684. PaymentAddress: C,
  7685. PaymentRequest: C,
  7686. PaymentRequestUpdateEvent: C,
  7687. PaymentResponse: C,
  7688. performance: O,
  7689. Performance: C,
  7690. PerformanceEntry: C,
  7691. PerformanceLongTaskTiming: C,
  7692. PerformanceMark: C,
  7693. PerformanceMeasure: C,
  7694. PerformanceNavigation: C,
  7695. PerformanceNavigationTiming: C,
  7696. PerformanceObserver: C,
  7697. PerformanceObserverEntryList: C,
  7698. PerformancePaintTiming: C,
  7699. PerformanceResourceTiming: C,
  7700. PerformanceTiming: C,
  7701. PeriodicWave: C,
  7702. Permissions: C,
  7703. PermissionStatus: C,
  7704. personalbar: O,
  7705. PhotoCapabilities: C,
  7706. Plugin: C,
  7707. PluginArray: C,
  7708. PointerEvent: C,
  7709. PopStateEvent: C,
  7710. postMessage: O,
  7711. Presentation: C,
  7712. PresentationAvailability: C,
  7713. PresentationConnection: C,
  7714. PresentationConnectionAvailableEvent: C,
  7715. PresentationConnectionCloseEvent: C,
  7716. PresentationConnectionList: C,
  7717. PresentationReceiver: C,
  7718. PresentationRequest: C,
  7719. print: O,
  7720. ProcessingInstruction: C,
  7721. ProgressEvent: C,
  7722. PromiseRejectionEvent: C,
  7723. prompt: O,
  7724. PushManager: C,
  7725. PushSubscription: C,
  7726. PushSubscriptionOptions: C,
  7727. queueMicrotask: O,
  7728. RadioNodeList: C,
  7729. Range: C,
  7730. ReadableStream: C,
  7731. RemotePlayback: C,
  7732. removeEventListener: O,
  7733. Request: C,
  7734. requestAnimationFrame: O,
  7735. requestIdleCallback: O,
  7736. resizeBy: O,
  7737. ResizeObserver: C,
  7738. ResizeObserverEntry: C,
  7739. resizeTo: O,
  7740. Response: C,
  7741. RTCCertificate: C,
  7742. RTCDataChannel: C,
  7743. RTCDataChannelEvent: C,
  7744. RTCDtlsTransport: C,
  7745. RTCIceCandidate: C,
  7746. RTCIceTransport: C,
  7747. RTCPeerConnection: C,
  7748. RTCPeerConnectionIceEvent: C,
  7749. RTCRtpReceiver: C,
  7750. RTCRtpSender: C,
  7751. RTCSctpTransport: C,
  7752. RTCSessionDescription: C,
  7753. RTCStatsReport: C,
  7754. RTCTrackEvent: C,
  7755. screen: O,
  7756. Screen: C,
  7757. screenLeft: O,
  7758. ScreenOrientation: C,
  7759. screenTop: O,
  7760. screenX: O,
  7761. screenY: O,
  7762. ScriptProcessorNode: C,
  7763. scroll: O,
  7764. scrollbars: O,
  7765. scrollBy: O,
  7766. scrollTo: O,
  7767. scrollX: O,
  7768. scrollY: O,
  7769. SecurityPolicyViolationEvent: C,
  7770. Selection: C,
  7771. ServiceWorker: C,
  7772. ServiceWorkerContainer: C,
  7773. ServiceWorkerRegistration: C,
  7774. sessionStorage: O,
  7775. ShadowRoot: C,
  7776. SharedWorker: C,
  7777. SourceBuffer: C,
  7778. SourceBufferList: C,
  7779. speechSynthesis: O,
  7780. SpeechSynthesisEvent: C,
  7781. SpeechSynthesisUtterance: C,
  7782. StaticRange: C,
  7783. status: O,
  7784. statusbar: O,
  7785. StereoPannerNode: C,
  7786. stop: O,
  7787. Storage: C,
  7788. StorageEvent: C,
  7789. StorageManager: C,
  7790. styleMedia: O,
  7791. StyleSheet: C,
  7792. StyleSheetList: C,
  7793. SubtleCrypto: C,
  7794. SVGAElement: C,
  7795. SVGAngle: C,
  7796. SVGAnimatedAngle: C,
  7797. SVGAnimatedBoolean: C,
  7798. SVGAnimatedEnumeration: C,
  7799. SVGAnimatedInteger: C,
  7800. SVGAnimatedLength: C,
  7801. SVGAnimatedLengthList: C,
  7802. SVGAnimatedNumber: C,
  7803. SVGAnimatedNumberList: C,
  7804. SVGAnimatedPreserveAspectRatio: C,
  7805. SVGAnimatedRect: C,
  7806. SVGAnimatedString: C,
  7807. SVGAnimatedTransformList: C,
  7808. SVGAnimateElement: C,
  7809. SVGAnimateMotionElement: C,
  7810. SVGAnimateTransformElement: C,
  7811. SVGAnimationElement: C,
  7812. SVGCircleElement: C,
  7813. SVGClipPathElement: C,
  7814. SVGComponentTransferFunctionElement: C,
  7815. SVGDefsElement: C,
  7816. SVGDescElement: C,
  7817. SVGDiscardElement: C,
  7818. SVGElement: C,
  7819. SVGEllipseElement: C,
  7820. SVGFEBlendElement: C,
  7821. SVGFEColorMatrixElement: C,
  7822. SVGFEComponentTransferElement: C,
  7823. SVGFECompositeElement: C,
  7824. SVGFEConvolveMatrixElement: C,
  7825. SVGFEDiffuseLightingElement: C,
  7826. SVGFEDisplacementMapElement: C,
  7827. SVGFEDistantLightElement: C,
  7828. SVGFEDropShadowElement: C,
  7829. SVGFEFloodElement: C,
  7830. SVGFEFuncAElement: C,
  7831. SVGFEFuncBElement: C,
  7832. SVGFEFuncGElement: C,
  7833. SVGFEFuncRElement: C,
  7834. SVGFEGaussianBlurElement: C,
  7835. SVGFEImageElement: C,
  7836. SVGFEMergeElement: C,
  7837. SVGFEMergeNodeElement: C,
  7838. SVGFEMorphologyElement: C,
  7839. SVGFEOffsetElement: C,
  7840. SVGFEPointLightElement: C,
  7841. SVGFESpecularLightingElement: C,
  7842. SVGFESpotLightElement: C,
  7843. SVGFETileElement: C,
  7844. SVGFETurbulenceElement: C,
  7845. SVGFilterElement: C,
  7846. SVGForeignObjectElement: C,
  7847. SVGGElement: C,
  7848. SVGGeometryElement: C,
  7849. SVGGradientElement: C,
  7850. SVGGraphicsElement: C,
  7851. SVGImageElement: C,
  7852. SVGLength: C,
  7853. SVGLengthList: C,
  7854. SVGLinearGradientElement: C,
  7855. SVGLineElement: C,
  7856. SVGMarkerElement: C,
  7857. SVGMaskElement: C,
  7858. SVGMatrix: C,
  7859. SVGMetadataElement: C,
  7860. SVGMPathElement: C,
  7861. SVGNumber: C,
  7862. SVGNumberList: C,
  7863. SVGPathElement: C,
  7864. SVGPatternElement: C,
  7865. SVGPoint: C,
  7866. SVGPointList: C,
  7867. SVGPolygonElement: C,
  7868. SVGPolylineElement: C,
  7869. SVGPreserveAspectRatio: C,
  7870. SVGRadialGradientElement: C,
  7871. SVGRect: C,
  7872. SVGRectElement: C,
  7873. SVGScriptElement: C,
  7874. SVGSetElement: C,
  7875. SVGStopElement: C,
  7876. SVGStringList: C,
  7877. SVGStyleElement: C,
  7878. SVGSVGElement: C,
  7879. SVGSwitchElement: C,
  7880. SVGSymbolElement: C,
  7881. SVGTextContentElement: C,
  7882. SVGTextElement: C,
  7883. SVGTextPathElement: C,
  7884. SVGTextPositioningElement: C,
  7885. SVGTitleElement: C,
  7886. SVGTransform: C,
  7887. SVGTransformList: C,
  7888. SVGTSpanElement: C,
  7889. SVGUnitTypes: C,
  7890. SVGUseElement: C,
  7891. SVGViewElement: C,
  7892. TaskAttributionTiming: C,
  7893. Text: C,
  7894. TextEvent: C,
  7895. TextMetrics: C,
  7896. TextTrack: C,
  7897. TextTrackCue: C,
  7898. TextTrackCueList: C,
  7899. TextTrackList: C,
  7900. TimeRanges: C,
  7901. toolbar: O,
  7902. top: O,
  7903. Touch: C,
  7904. TouchEvent: C,
  7905. TouchList: C,
  7906. TrackEvent: C,
  7907. TransitionEvent: C,
  7908. TreeWalker: C,
  7909. UIEvent: C,
  7910. ValidityState: C,
  7911. visualViewport: O,
  7912. VisualViewport: C,
  7913. VTTCue: C,
  7914. WaveShaperNode: C,
  7915. WebAssembly: O,
  7916. WebGL2RenderingContext: C,
  7917. WebGLActiveInfo: C,
  7918. WebGLBuffer: C,
  7919. WebGLContextEvent: C,
  7920. WebGLFramebuffer: C,
  7921. WebGLProgram: C,
  7922. WebGLQuery: C,
  7923. WebGLRenderbuffer: C,
  7924. WebGLRenderingContext: C,
  7925. WebGLSampler: C,
  7926. WebGLShader: C,
  7927. WebGLShaderPrecisionFormat: C,
  7928. WebGLSync: C,
  7929. WebGLTexture: C,
  7930. WebGLTransformFeedback: C,
  7931. WebGLUniformLocation: C,
  7932. WebGLVertexArrayObject: C,
  7933. WebSocket: C,
  7934. WheelEvent: C,
  7935. Window: C,
  7936. Worker: C,
  7937. WritableStream: C,
  7938. XMLDocument: C,
  7939. XMLHttpRequest: C,
  7940. XMLHttpRequestEventTarget: C,
  7941. XMLHttpRequestUpload: C,
  7942. XMLSerializer: C,
  7943. XPathEvaluator: C,
  7944. XPathExpression: C,
  7945. XPathResult: C,
  7946. XSLTProcessor: C
  7947. };
  7948. for (const global of ['window', 'global', 'self', 'globalThis']) {
  7949. knownGlobals[global] = knownGlobals;
  7950. }
  7951. function getGlobalAtPath(path) {
  7952. let currentGlobal = knownGlobals;
  7953. for (const pathSegment of path) {
  7954. if (typeof pathSegment !== 'string') {
  7955. return null;
  7956. }
  7957. currentGlobal = currentGlobal[pathSegment];
  7958. if (!currentGlobal) {
  7959. return null;
  7960. }
  7961. }
  7962. return currentGlobal[ValueProperties];
  7963. }
  7964. class GlobalVariable extends Variable {
  7965. constructor(name) {
  7966. super(name);
  7967. // Ensure we use live-bindings for globals as we do not know if they have
  7968. // been reassigned
  7969. this.markReassigned();
  7970. }
  7971. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7972. switch (interaction.type) {
  7973. // While there is no point in testing these cases as at the moment, they
  7974. // are also covered via other means, we keep them for completeness
  7975. case INTERACTION_ACCESSED:
  7976. case INTERACTION_ASSIGNED: {
  7977. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  7978. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7979. }
  7980. return;
  7981. }
  7982. case INTERACTION_CALLED: {
  7983. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7984. if (globalAtPath) {
  7985. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  7986. }
  7987. else {
  7988. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7989. }
  7990. return;
  7991. }
  7992. }
  7993. }
  7994. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  7995. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7996. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  7997. }
  7998. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7999. switch (interaction.type) {
  8000. case INTERACTION_ACCESSED: {
  8001. if (path.length === 0) {
  8002. // Technically, "undefined" is a global variable of sorts
  8003. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  8004. }
  8005. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  8006. }
  8007. case INTERACTION_ASSIGNED: {
  8008. return true;
  8009. }
  8010. case INTERACTION_CALLED: {
  8011. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8012. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  8013. }
  8014. }
  8015. }
  8016. }
  8017. // To avoid infinite recursions
  8018. const MAX_PATH_DEPTH = 6;
  8019. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  8020. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  8021. const limitConcatenatedPathDepth = (path1, path2) => {
  8022. const { length: length1 } = path1;
  8023. const { length: length2 } = path2;
  8024. return length1 === 0
  8025. ? path2
  8026. : length2 === 0
  8027. ? path1
  8028. : length1 + length2 > MAX_PATH_DEPTH
  8029. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  8030. : [...path1, ...path2];
  8031. };
  8032. class LocalVariable extends Variable {
  8033. constructor(name, declarator, init,
  8034. /** if this is non-empty, the actual init is this path of this.init */
  8035. initPath, context, kind) {
  8036. super(name);
  8037. this.init = init;
  8038. this.initPath = initPath;
  8039. this.kind = kind;
  8040. this.calledFromTryStatement = false;
  8041. this.additionalInitializers = null;
  8042. this.includedPathTracker = new IncludedFullPathTracker();
  8043. this.expressionsToBeDeoptimized = [];
  8044. this.declarations = declarator ? [declarator] : [];
  8045. this.deoptimizationTracker = context.deoptimizationTracker;
  8046. this.module = context.module;
  8047. }
  8048. addDeclaration(identifier, init) {
  8049. this.declarations.push(identifier);
  8050. this.markInitializersForDeoptimization().push(init);
  8051. }
  8052. consolidateInitializers() {
  8053. if (this.additionalInitializers) {
  8054. for (const initializer of this.additionalInitializers) {
  8055. initializer.deoptimizePath(UNKNOWN_PATH);
  8056. }
  8057. }
  8058. }
  8059. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8060. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8061. deoptimizeInteraction(interaction);
  8062. return;
  8063. }
  8064. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8065. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  8066. }, undefined);
  8067. }
  8068. deoptimizePath(path) {
  8069. if (this.isReassigned ||
  8070. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8071. return;
  8072. }
  8073. if (path.length === 0) {
  8074. this.markReassigned();
  8075. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  8076. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  8077. for (const expression of expressionsToBeDeoptimized) {
  8078. expression.deoptimizeCache();
  8079. }
  8080. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  8081. }
  8082. else {
  8083. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  8084. }
  8085. }
  8086. getLiteralValueAtPath(path, recursionTracker, origin) {
  8087. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8088. return UnknownValue;
  8089. }
  8090. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8091. this.expressionsToBeDeoptimized.push(origin);
  8092. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  8093. }, UnknownValue);
  8094. }
  8095. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8096. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8097. return UNKNOWN_RETURN_EXPRESSION;
  8098. }
  8099. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  8100. this.expressionsToBeDeoptimized.push(origin);
  8101. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  8102. }, UNKNOWN_RETURN_EXPRESSION);
  8103. }
  8104. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8105. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  8106. return true;
  8107. }
  8108. switch (interaction.type) {
  8109. case INTERACTION_ACCESSED: {
  8110. if (this.isReassigned)
  8111. return true;
  8112. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  8113. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8114. }
  8115. case INTERACTION_ASSIGNED: {
  8116. if (this.included)
  8117. return true;
  8118. if (path.length === 0)
  8119. return false;
  8120. if (this.isReassigned)
  8121. return true;
  8122. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  8123. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8124. }
  8125. case INTERACTION_CALLED: {
  8126. if (this.isReassigned)
  8127. return true;
  8128. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  8129. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  8130. }
  8131. }
  8132. }
  8133. includePath(path, context) {
  8134. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  8135. this.module.scope.context.requestTreeshakingPass();
  8136. if (!this.included) {
  8137. // This will reduce the number of tree-shaking passes by eagerly
  8138. // including inits. By pushing this here instead of directly including
  8139. // we avoid deep call stacks.
  8140. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  8141. }
  8142. super.includePath(path, context);
  8143. for (const declaration of this.declarations) {
  8144. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  8145. if (!declaration.included)
  8146. declaration.include(context, false);
  8147. let node = declaration.parent;
  8148. while (!node.included) {
  8149. // We do not want to properly include parents in case they are part of a dead branch
  8150. // in which case .include() might pull in more dead code
  8151. node.includeNode(context);
  8152. if (node.type === parseAst_js.Program)
  8153. break;
  8154. node = node.parent;
  8155. }
  8156. /**
  8157. * import('foo').then(m => {
  8158. * console.log(m.foo)
  8159. * })
  8160. */
  8161. if (this.kind === 'parameter' &&
  8162. (isArrowFunctionExpressionNode(declaration.parent) ||
  8163. isFunctionExpressionNode(declaration.parent)) &&
  8164. isCallExpressionNode(declaration.parent.parent) &&
  8165. isMemberExpressionNode(declaration.parent.parent.callee) &&
  8166. isIdentifierNode(declaration.parent.parent.callee.property) &&
  8167. declaration.parent.parent.callee.property.name === 'then' &&
  8168. isImportExpressionNode(declaration.parent.parent.callee.object)) {
  8169. declaration.parent.parent.callee.object.includePath(path, context);
  8170. }
  8171. }
  8172. // We need to make sure we include the correct path of the init
  8173. if (path.length > 0) {
  8174. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  8175. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  8176. }
  8177. }
  8178. }
  8179. includeCallArguments(interaction, context) {
  8180. if (this.isReassigned ||
  8181. context.includedCallArguments.has(this.init) ||
  8182. // This can be removed again once we can include arguments when called at
  8183. // a specific path
  8184. this.initPath.length > 0) {
  8185. includeInteraction(interaction, context);
  8186. }
  8187. else {
  8188. context.includedCallArguments.add(this.init);
  8189. this.init.includeCallArguments(interaction, context);
  8190. context.includedCallArguments.delete(this.init);
  8191. }
  8192. }
  8193. markCalledFromTryStatement() {
  8194. this.calledFromTryStatement = true;
  8195. }
  8196. markInitializersForDeoptimization() {
  8197. if (this.additionalInitializers === null) {
  8198. this.additionalInitializers = [this.init];
  8199. this.init = UNKNOWN_EXPRESSION;
  8200. this.markReassigned();
  8201. }
  8202. return this.additionalInitializers;
  8203. }
  8204. }
  8205. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  8206. class IdentifierBase extends NodeBase {
  8207. constructor() {
  8208. super(...arguments);
  8209. this.variable = null;
  8210. this.isVariableReference = false;
  8211. }
  8212. get isTDZAccess() {
  8213. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  8214. return null;
  8215. }
  8216. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  8217. }
  8218. set isTDZAccess(value) {
  8219. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  8220. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  8221. }
  8222. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8223. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8224. }
  8225. deoptimizePath(path) {
  8226. if (path.length === 0 && !this.scope.contains(this.name)) {
  8227. this.disallowImportReassignment();
  8228. }
  8229. // We keep conditional chaining because an unknown Node could have an
  8230. // Identifier as property that might be deoptimized by default
  8231. this.variable?.deoptimizePath(path);
  8232. }
  8233. getLiteralValueAtPath(path, recursionTracker, origin) {
  8234. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  8235. }
  8236. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8237. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8238. return [expression, isPure || this.isPureFunction(path)];
  8239. }
  8240. hasEffects(context) {
  8241. if (!this.deoptimized)
  8242. this.applyDeoptimizations();
  8243. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  8244. return true;
  8245. }
  8246. return (this.scope.context.options.treeshake
  8247. .unknownGlobalSideEffects &&
  8248. this.variable instanceof GlobalVariable &&
  8249. !this.isPureFunction(EMPTY_PATH) &&
  8250. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8251. }
  8252. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8253. switch (interaction.type) {
  8254. case INTERACTION_ACCESSED: {
  8255. return (this.variable !== null &&
  8256. !this.isPureFunction(path) &&
  8257. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8258. }
  8259. case INTERACTION_ASSIGNED: {
  8260. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  8261. }
  8262. case INTERACTION_CALLED: {
  8263. return (!this.isPureFunction(path) &&
  8264. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  8265. }
  8266. }
  8267. }
  8268. include(context, includeChildrenRecursively) {
  8269. if (!this.included)
  8270. this.includeNode(context);
  8271. if (includeChildrenRecursively) {
  8272. this.variable?.includePath(UNKNOWN_PATH, context);
  8273. }
  8274. }
  8275. includeNode(context) {
  8276. this.included = true;
  8277. if (!this.deoptimized)
  8278. this.applyDeoptimizations();
  8279. if (this.variable !== null) {
  8280. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8281. }
  8282. }
  8283. includePath(path, context) {
  8284. if (!this.included) {
  8285. this.included = true;
  8286. if (!this.deoptimized)
  8287. this.applyDeoptimizations();
  8288. if (this.variable !== null) {
  8289. this.scope.context.includeVariableInModule(this.variable, path, context);
  8290. }
  8291. }
  8292. else if (path.length > 0) {
  8293. this.variable?.includePath(path, context);
  8294. }
  8295. }
  8296. includeCallArguments(interaction, context) {
  8297. this.variable.includeCallArguments(interaction, context);
  8298. }
  8299. isPossibleTDZ() {
  8300. // return cached value to avoid issues with the next tree-shaking pass
  8301. const cachedTdzAccess = this.isTDZAccess;
  8302. if (cachedTdzAccess !== null)
  8303. return cachedTdzAccess;
  8304. if (!(this.variable instanceof LocalVariable &&
  8305. this.variable.kind &&
  8306. tdzVariableKinds.has(this.variable.kind) &&
  8307. // We ignore modules that did not receive a treeshaking pass yet as that
  8308. // causes many false positives due to circular dependencies or disabled
  8309. // moduleSideEffects.
  8310. this.variable.module.hasTreeShakingPassStarted)) {
  8311. return (this.isTDZAccess = false);
  8312. }
  8313. let decl_id;
  8314. if (this.variable.declarations &&
  8315. this.variable.declarations.length === 1 &&
  8316. (decl_id = this.variable.declarations[0]) &&
  8317. this.start < decl_id.start &&
  8318. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  8319. // a variable accessed before its declaration
  8320. // in the same function or at top level of module
  8321. return (this.isTDZAccess = true);
  8322. }
  8323. if (!this.variable.initReached) {
  8324. // Either a const/let TDZ violation or
  8325. // var use before declaration was encountered.
  8326. return (this.isTDZAccess = true);
  8327. }
  8328. return (this.isTDZAccess = false);
  8329. }
  8330. applyDeoptimizations() {
  8331. this.deoptimized = true;
  8332. if (this.variable instanceof LocalVariable) {
  8333. // When accessing a variable from a module without side effects, this
  8334. // means we use an export of that module and therefore need to potentially
  8335. // include it in the bundle.
  8336. if (!this.variable.module.isExecuted) {
  8337. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  8338. }
  8339. this.variable.consolidateInitializers();
  8340. this.scope.context.requestTreeshakingPass();
  8341. }
  8342. if (this.isVariableReference) {
  8343. this.variable.addUsedPlace(this);
  8344. this.scope.context.requestTreeshakingPass();
  8345. }
  8346. }
  8347. disallowImportReassignment() {
  8348. return this.scope.context.error(parseAst_js.logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  8349. }
  8350. getVariableRespectingTDZ() {
  8351. if (this.isPossibleTDZ()) {
  8352. return UNKNOWN_EXPRESSION;
  8353. }
  8354. return this.variable;
  8355. }
  8356. isPureFunction(path) {
  8357. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  8358. for (const segment of path) {
  8359. if (currentPureFunction) {
  8360. if (currentPureFunction[PureFunctionKey]) {
  8361. return true;
  8362. }
  8363. currentPureFunction = currentPureFunction[segment];
  8364. }
  8365. else {
  8366. return false;
  8367. }
  8368. }
  8369. return currentPureFunction?.[PureFunctionKey];
  8370. }
  8371. }
  8372. function closestParentFunctionOrProgram(node) {
  8373. while (node && !/^Program|Function/.test(node.type)) {
  8374. node = node.parent;
  8375. }
  8376. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  8377. return node;
  8378. }
  8379. class ObjectMember extends ExpressionEntity {
  8380. constructor(object, path) {
  8381. super();
  8382. this.object = object;
  8383. this.path = path;
  8384. }
  8385. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8386. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  8387. }
  8388. deoptimizePath(path) {
  8389. this.object.deoptimizePath([...this.path, ...path]);
  8390. }
  8391. getLiteralValueAtPath(path, recursionTracker, origin) {
  8392. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  8393. }
  8394. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8395. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  8396. }
  8397. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8398. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  8399. }
  8400. }
  8401. class Identifier extends IdentifierBase {
  8402. constructor() {
  8403. super(...arguments);
  8404. this.variable = null;
  8405. }
  8406. get isDestructuringDeoptimized() {
  8407. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  8408. }
  8409. set isDestructuringDeoptimized(value) {
  8410. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  8411. }
  8412. addExportedVariables(variables, exportNamesByVariable) {
  8413. if (exportNamesByVariable.has(this.variable)) {
  8414. variables.push(this.variable);
  8415. }
  8416. }
  8417. bind() {
  8418. if (!this.variable && is_reference(this, this.parent)) {
  8419. this.variable = this.scope.findVariable(this.name);
  8420. this.variable.addReference(this);
  8421. this.isVariableReference = true;
  8422. }
  8423. }
  8424. declare(kind, destructuredInitPath, init) {
  8425. let variable;
  8426. const { treeshake } = this.scope.context.options;
  8427. if (kind === 'parameter') {
  8428. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  8429. }
  8430. else {
  8431. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  8432. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  8433. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  8434. variable.markInitializersForDeoptimization();
  8435. }
  8436. }
  8437. return [(this.variable = variable)];
  8438. }
  8439. deoptimizeAssignment(destructuredInitPath, init) {
  8440. this.deoptimizePath(EMPTY_PATH);
  8441. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  8442. }
  8443. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  8444. return (destructuredInitPath.length > 0 &&
  8445. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8446. }
  8447. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  8448. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  8449. this.isDestructuringDeoptimized = true;
  8450. init.deoptimizeArgumentsOnInteractionAtPath({
  8451. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  8452. type: INTERACTION_ACCESSED
  8453. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  8454. }
  8455. const { propertyReadSideEffects } = this.scope.context.options
  8456. .treeshake;
  8457. let included = this.included;
  8458. if ((included ||=
  8459. destructuredInitPath.length > 0 &&
  8460. !context.brokenFlow &&
  8461. propertyReadSideEffects &&
  8462. (propertyReadSideEffects === 'always' ||
  8463. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  8464. if (this.variable && !this.variable.included) {
  8465. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8466. }
  8467. init.includePath(destructuredInitPath, context);
  8468. }
  8469. if (!this.included && included) {
  8470. this.includeNode(context);
  8471. }
  8472. return this.included;
  8473. }
  8474. markDeclarationReached() {
  8475. this.variable.initReached = true;
  8476. }
  8477. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = parseAst_js.BLANK) {
  8478. if (this.variable) {
  8479. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  8480. if (name !== this.name) {
  8481. code.overwrite(this.start, this.end, name, {
  8482. contentOnly: true,
  8483. storeName: true
  8484. });
  8485. if (isShorthandProperty) {
  8486. code.prependRight(this.start, `${this.name}: `);
  8487. }
  8488. }
  8489. // In strict mode, any variable named "eval" must be the actual "eval" function
  8490. if (name === 'eval' &&
  8491. renderedParentType === parseAst_js.CallExpression &&
  8492. isCalleeOfRenderedParent) {
  8493. code.appendRight(this.start, '0, ');
  8494. }
  8495. }
  8496. }
  8497. }
  8498. function getSafeName(baseName, usedNames, forbiddenNames) {
  8499. let safeName = baseName;
  8500. let count = 1;
  8501. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  8502. safeName = `${baseName}$${toBase64(count++)}`;
  8503. }
  8504. usedNames.add(safeName);
  8505. return safeName;
  8506. }
  8507. class Scope {
  8508. constructor() {
  8509. this.children = [];
  8510. this.variables = new Map();
  8511. }
  8512. /*
  8513. Redeclaration rules:
  8514. - var can redeclare var
  8515. - in function scopes, function and var can redeclare function and var
  8516. - var is hoisted across scopes, function remains in the scope it is declared
  8517. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  8518. - function cannot redeclare catch scope parameters
  8519. - var can redeclare catch scope parameters in a way
  8520. - if the parameter is an identifier and not a pattern
  8521. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  8522. - const, let, class, and function except in the cases above cannot redeclare anything
  8523. */
  8524. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  8525. const name = identifier.name;
  8526. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  8527. if (existingVariable) {
  8528. if (kind === 'var' && existingVariable.kind === 'var') {
  8529. existingVariable.addDeclaration(identifier, init);
  8530. return existingVariable;
  8531. }
  8532. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  8533. }
  8534. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  8535. this.variables.set(name, newVariable);
  8536. return newVariable;
  8537. }
  8538. addHoistedVariable(name, variable) {
  8539. (this.hoistedVariables ||= new Map()).set(name, variable);
  8540. }
  8541. contains(name) {
  8542. return this.variables.has(name);
  8543. }
  8544. findVariable(_name) {
  8545. /* istanbul ignore next */
  8546. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  8547. }
  8548. }
  8549. class ChildScope extends Scope {
  8550. constructor(parent, context) {
  8551. super();
  8552. this.parent = parent;
  8553. this.context = context;
  8554. this.accessedOutsideVariables = new Map();
  8555. parent.children.push(this);
  8556. }
  8557. addAccessedDynamicImport(importExpression) {
  8558. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  8559. if (this.parent instanceof ChildScope) {
  8560. this.parent.addAccessedDynamicImport(importExpression);
  8561. }
  8562. }
  8563. addAccessedGlobals(globals, accessedGlobalsByScope) {
  8564. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  8565. for (const name of globals) {
  8566. accessedGlobals.add(name);
  8567. }
  8568. accessedGlobalsByScope.set(this, accessedGlobals);
  8569. if (this.parent instanceof ChildScope) {
  8570. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  8571. }
  8572. }
  8573. addNamespaceMemberAccess(name, variable) {
  8574. this.accessedOutsideVariables.set(name, variable);
  8575. this.parent.addNamespaceMemberAccess(name, variable);
  8576. }
  8577. addReturnExpression(expression) {
  8578. if (this.parent instanceof ChildScope) {
  8579. this.parent.addReturnExpression(expression);
  8580. }
  8581. }
  8582. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  8583. for (const variable of this.accessedOutsideVariables.values()) {
  8584. if (variable.included) {
  8585. usedNames.add(variable.getBaseVariableName());
  8586. if (format === 'system' && exportNamesByVariable.has(variable)) {
  8587. usedNames.add('exports');
  8588. }
  8589. }
  8590. }
  8591. const accessedGlobals = accessedGlobalsByScope.get(this);
  8592. if (accessedGlobals) {
  8593. for (const name of accessedGlobals) {
  8594. usedNames.add(name);
  8595. }
  8596. }
  8597. }
  8598. contains(name) {
  8599. return this.variables.has(name) || this.parent.contains(name);
  8600. }
  8601. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8602. const usedNames = new Set();
  8603. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  8604. if (this.accessedDynamicImports) {
  8605. for (const importExpression of this.accessedDynamicImports) {
  8606. if (importExpression.inlineNamespace) {
  8607. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  8608. }
  8609. }
  8610. }
  8611. for (const [name, variable] of this.variables) {
  8612. if (variable.included || variable.alwaysRendered) {
  8613. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  8614. }
  8615. }
  8616. for (const scope of this.children) {
  8617. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8618. }
  8619. }
  8620. findLexicalBoundary() {
  8621. return this.parent.findLexicalBoundary();
  8622. }
  8623. findGlobal(name) {
  8624. const variable = this.parent.findVariable(name);
  8625. this.accessedOutsideVariables.set(name, variable);
  8626. return variable;
  8627. }
  8628. findVariable(name) {
  8629. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8630. if (knownVariable) {
  8631. return knownVariable;
  8632. }
  8633. const variable = this.parent.findVariable(name);
  8634. this.accessedOutsideVariables.set(name, variable);
  8635. return variable;
  8636. }
  8637. }
  8638. function checkEffectForNodes(nodes, context) {
  8639. for (const node of nodes) {
  8640. if (node.hasEffects(context)) {
  8641. return true;
  8642. }
  8643. }
  8644. return false;
  8645. }
  8646. class MethodBase extends NodeBase {
  8647. constructor() {
  8648. super(...arguments);
  8649. this.accessedValue = null;
  8650. }
  8651. get computed() {
  8652. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  8653. }
  8654. set computed(value) {
  8655. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  8656. }
  8657. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8658. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8659. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8660. args: interaction.args,
  8661. type: INTERACTION_CALLED,
  8662. withNew: false
  8663. }, EMPTY_PATH, recursionTracker);
  8664. }
  8665. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8666. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  8667. args: interaction.args,
  8668. type: INTERACTION_CALLED,
  8669. withNew: false
  8670. }, EMPTY_PATH, recursionTracker);
  8671. }
  8672. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8673. }
  8674. // As getter properties directly receive their values from fixed function
  8675. // expressions, there is no known situation where a getter is deoptimized.
  8676. deoptimizeCache() { }
  8677. deoptimizePath(path) {
  8678. this.getAccessedValue()[0].deoptimizePath(path);
  8679. }
  8680. getLiteralValueAtPath(path, recursionTracker, origin) {
  8681. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  8682. }
  8683. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8684. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8685. }
  8686. hasEffects(context) {
  8687. return this.key.hasEffects(context);
  8688. }
  8689. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8690. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8691. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8692. args: interaction.args,
  8693. type: INTERACTION_CALLED,
  8694. withNew: false
  8695. }, context);
  8696. }
  8697. // setters are only called for empty paths
  8698. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8699. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8700. args: interaction.args,
  8701. type: INTERACTION_CALLED,
  8702. withNew: false
  8703. }, context);
  8704. }
  8705. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  8706. }
  8707. getAccessedValue() {
  8708. if (this.accessedValue === null) {
  8709. if (this.kind === 'get') {
  8710. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  8711. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8712. }
  8713. else {
  8714. return (this.accessedValue = [this.value, false]);
  8715. }
  8716. }
  8717. return this.accessedValue;
  8718. }
  8719. }
  8720. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  8721. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  8722. class MethodDefinition extends MethodBase {
  8723. hasEffects(context) {
  8724. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  8725. }
  8726. }
  8727. class BlockScope extends ChildScope {
  8728. constructor(parent) {
  8729. super(parent, parent.context);
  8730. }
  8731. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  8732. if (kind === 'var') {
  8733. const name = identifier.name;
  8734. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  8735. if (existingVariable) {
  8736. if (existingVariable.kind === 'var' ||
  8737. (kind === 'var' && existingVariable.kind === 'parameter')) {
  8738. existingVariable.addDeclaration(identifier, init);
  8739. return existingVariable;
  8740. }
  8741. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  8742. }
  8743. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  8744. // Necessary to make sure the init is deoptimized for conditional declarations.
  8745. // We cannot call deoptimizePath here.
  8746. declaredVariable.markInitializersForDeoptimization();
  8747. // We add the variable to this and all parent scopes to reliably detect conflicts
  8748. this.addHoistedVariable(name, declaredVariable);
  8749. return declaredVariable;
  8750. }
  8751. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  8752. }
  8753. }
  8754. class StaticBlock extends NodeBase {
  8755. createScope(parentScope) {
  8756. this.scope = new BlockScope(parentScope);
  8757. }
  8758. hasEffects(context) {
  8759. for (const node of this.body) {
  8760. if (node.hasEffects(context))
  8761. return true;
  8762. }
  8763. return false;
  8764. }
  8765. include(context, includeChildrenRecursively) {
  8766. this.included = true;
  8767. for (const node of this.body) {
  8768. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8769. node.include(context, includeChildrenRecursively);
  8770. }
  8771. }
  8772. render(code, options) {
  8773. if (this.body.length > 0) {
  8774. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  8775. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  8776. }
  8777. else {
  8778. super.render(code, options);
  8779. }
  8780. }
  8781. }
  8782. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  8783. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  8784. function isStaticBlock(statement) {
  8785. return statement.type === parseAst_js.StaticBlock;
  8786. }
  8787. class ClassNode extends NodeBase {
  8788. constructor() {
  8789. super(...arguments);
  8790. this.objectEntity = null;
  8791. }
  8792. createScope(parentScope) {
  8793. this.scope = new ChildScope(parentScope, parentScope.context);
  8794. }
  8795. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8796. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8797. }
  8798. deoptimizeCache() {
  8799. this.getObjectEntity().deoptimizeAllProperties();
  8800. }
  8801. deoptimizePath(path) {
  8802. this.getObjectEntity().deoptimizePath(path);
  8803. }
  8804. getLiteralValueAtPath(path, recursionTracker, origin) {
  8805. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8806. }
  8807. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8808. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8809. }
  8810. hasEffects(context) {
  8811. if (!this.deoptimized)
  8812. this.applyDeoptimizations();
  8813. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  8814. this.id?.markDeclarationReached();
  8815. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  8816. }
  8817. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8818. return interaction.type === INTERACTION_CALLED && path.length === 0
  8819. ? !interaction.withNew ||
  8820. (this.classConstructor === null
  8821. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  8822. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8823. false
  8824. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8825. }
  8826. include(context, includeChildrenRecursively) {
  8827. if (!this.included)
  8828. this.includeNode(context);
  8829. this.superClass?.include(context, includeChildrenRecursively);
  8830. this.body.include(context, includeChildrenRecursively);
  8831. for (const decorator of this.decorators)
  8832. decorator.include(context, includeChildrenRecursively);
  8833. if (this.id) {
  8834. this.id.markDeclarationReached();
  8835. this.id.include(context, includeChildrenRecursively);
  8836. }
  8837. }
  8838. initialise() {
  8839. super.initialise();
  8840. this.id?.declare('class', EMPTY_PATH, this);
  8841. for (const method of this.body.body) {
  8842. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8843. this.classConstructor = method;
  8844. return;
  8845. }
  8846. }
  8847. this.classConstructor = null;
  8848. }
  8849. applyDeoptimizations() {
  8850. this.deoptimized = true;
  8851. for (const definition of this.body.body) {
  8852. if (!isStaticBlock(definition) &&
  8853. !(definition.static ||
  8854. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8855. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8856. definition.deoptimizePath(UNKNOWN_PATH);
  8857. }
  8858. }
  8859. this.scope.context.requestTreeshakingPass();
  8860. }
  8861. getObjectEntity() {
  8862. if (this.objectEntity !== null) {
  8863. return this.objectEntity;
  8864. }
  8865. const staticProperties = [];
  8866. const dynamicMethods = [];
  8867. for (const definition of this.body.body) {
  8868. if (isStaticBlock(definition))
  8869. continue;
  8870. const properties = definition.static ? staticProperties : dynamicMethods;
  8871. const definitionKind = definition.kind;
  8872. // Note that class fields do not end up on the prototype
  8873. if (properties === dynamicMethods && !definitionKind)
  8874. continue;
  8875. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8876. let key;
  8877. if (definition.computed) {
  8878. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8879. if (typeof keyValue === 'symbol') {
  8880. properties.push({ key: UnknownKey, kind, property: definition });
  8881. continue;
  8882. }
  8883. else {
  8884. key = String(keyValue);
  8885. }
  8886. }
  8887. else {
  8888. key =
  8889. definition.key instanceof Identifier
  8890. ? definition.key.name
  8891. : String(definition.key.value);
  8892. }
  8893. properties.push({ key, kind, property: definition });
  8894. }
  8895. staticProperties.unshift({
  8896. key: 'prototype',
  8897. kind: 'init',
  8898. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  8899. });
  8900. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8901. }
  8902. }
  8903. ClassNode.prototype.includeNode = onlyIncludeSelf;
  8904. class ClassDeclaration extends ClassNode {
  8905. initialise() {
  8906. super.initialise();
  8907. if (this.id !== null) {
  8908. this.id.variable.isId = true;
  8909. }
  8910. }
  8911. parseNode(esTreeNode) {
  8912. if (esTreeNode.id !== null) {
  8913. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  8914. }
  8915. return super.parseNode(esTreeNode);
  8916. }
  8917. render(code, options) {
  8918. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  8919. if (this.id) {
  8920. const { variable, name } = this.id;
  8921. if (format === 'system' && exportNamesByVariable.has(variable)) {
  8922. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  8923. }
  8924. const renderedVariable = variable.getName(getPropertyAccess);
  8925. if (renderedVariable !== name) {
  8926. this.decorators.map(decorator => decorator.render(code, options));
  8927. this.superClass?.render(code, options);
  8928. this.body.render(code, {
  8929. ...options,
  8930. useOriginalName: (_variable) => _variable === variable
  8931. });
  8932. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  8933. code.prependLeft(this.end, ';');
  8934. return;
  8935. }
  8936. }
  8937. super.render(code, options);
  8938. }
  8939. applyDeoptimizations() {
  8940. super.applyDeoptimizations();
  8941. const { id, scope } = this;
  8942. if (id) {
  8943. const { name, variable } = id;
  8944. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  8945. if (accessedVariable !== variable) {
  8946. accessedVariable.forbidName(name);
  8947. }
  8948. }
  8949. }
  8950. }
  8951. }
  8952. class ArgumentsVariable extends LocalVariable {
  8953. constructor(context) {
  8954. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  8955. }
  8956. addArgumentToBeDeoptimized(_argument) { }
  8957. // Only If there is at least one reference, then we need to track all
  8958. // arguments in order to be able to deoptimize them.
  8959. addReference() {
  8960. this.deoptimizedArguments = [];
  8961. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  8962. }
  8963. hasEffectsOnInteractionAtPath(path, { type }) {
  8964. return type !== INTERACTION_ACCESSED || path.length > 1;
  8965. }
  8966. includePath(path, context) {
  8967. super.includePath(path, context);
  8968. for (const argument of this.deoptimizedArguments) {
  8969. argument.deoptimizePath(UNKNOWN_PATH);
  8970. }
  8971. this.deoptimizedArguments.length = 0;
  8972. }
  8973. }
  8974. function addArgumentToBeDeoptimized(argument) {
  8975. if (this.included) {
  8976. argument.deoptimizePath(UNKNOWN_PATH);
  8977. }
  8978. else {
  8979. this.deoptimizedArguments?.push(argument);
  8980. }
  8981. }
  8982. const MAX_TRACKED_INTERACTIONS = 20;
  8983. const NO_INTERACTIONS = parseAst_js.EMPTY_ARRAY;
  8984. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  8985. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  8986. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  8987. class ParameterVariable extends LocalVariable {
  8988. constructor(name, declarator, argumentPath, context) {
  8989. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  8990. this.includedPathTracker = new IncludedTopLevelPathTracker();
  8991. this.argumentsToBeDeoptimized = new Set();
  8992. this.deoptimizationInteractions = [];
  8993. this.deoptimizations = new EntityPathTracker();
  8994. this.deoptimizedFields = new Set();
  8995. this.expressionsDependingOnKnownValue = [];
  8996. this.knownValue = null;
  8997. this.knownValueLiteral = UnknownValue;
  8998. }
  8999. addArgumentForDeoptimization(entity) {
  9000. this.updateKnownValue(entity);
  9001. if (entity === UNKNOWN_EXPRESSION) {
  9002. // As unknown expressions fully deoptimize all interactions, we can clear
  9003. // the interaction cache at this point provided we keep this optimization
  9004. // in mind when adding new interactions
  9005. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  9006. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  9007. for (const { interaction } of this.deoptimizationInteractions) {
  9008. deoptimizeInteraction(interaction);
  9009. }
  9010. this.deoptimizationInteractions = NO_INTERACTIONS;
  9011. }
  9012. }
  9013. else if (this.deoptimizedFields.has(UnknownKey)) {
  9014. // This means that we already deoptimized all interactions and no longer
  9015. // track them
  9016. entity.deoptimizePath([...this.initPath, UnknownKey]);
  9017. }
  9018. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  9019. this.argumentsToBeDeoptimized.add(entity);
  9020. for (const field of this.deoptimizedFields) {
  9021. entity.deoptimizePath([...this.initPath, field]);
  9022. }
  9023. for (const { interaction, path } of this.deoptimizationInteractions) {
  9024. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  9025. }
  9026. }
  9027. }
  9028. /** This says we should not make assumptions about the value of the parameter.
  9029. * This is different from deoptimization that will also cause argument values
  9030. * to be deoptimized. */
  9031. markReassigned() {
  9032. if (this.isReassigned) {
  9033. return;
  9034. }
  9035. super.markReassigned();
  9036. for (const expression of this.expressionsDependingOnKnownValue) {
  9037. expression.deoptimizeCache();
  9038. }
  9039. this.expressionsDependingOnKnownValue = parseAst_js.EMPTY_ARRAY;
  9040. }
  9041. deoptimizeCache() {
  9042. this.markReassigned();
  9043. }
  9044. /**
  9045. * Update the known value of the parameter variable.
  9046. * Must be called for every function call, so it can track all the arguments,
  9047. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  9048. * @param argument The argument of the function call
  9049. */
  9050. updateKnownValue(argument) {
  9051. if (this.isReassigned) {
  9052. return;
  9053. }
  9054. if (this.knownValue === null) {
  9055. this.knownValue = argument;
  9056. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  9057. return;
  9058. }
  9059. // the same literal or identifier, do nothing
  9060. if (this.knownValue === argument ||
  9061. (this.knownValue instanceof Identifier &&
  9062. argument instanceof Identifier &&
  9063. this.knownValue.variable === argument.variable)) {
  9064. return;
  9065. }
  9066. const { knownValueLiteral } = this;
  9067. if (typeof knownValueLiteral === 'symbol' ||
  9068. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  9069. knownValueLiteral) {
  9070. this.markReassigned();
  9071. }
  9072. }
  9073. /**
  9074. * This function freezes the known value of the parameter variable,
  9075. * so the optimization starts with a certain ExpressionEntity.
  9076. * The optimization can be undone by calling `markReassigned`.
  9077. * @returns the frozen value
  9078. */
  9079. getKnownValue() {
  9080. return this.knownValue || UNKNOWN_EXPRESSION;
  9081. }
  9082. getLiteralValueAtPath(path, recursionTracker, origin) {
  9083. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9084. return UnknownValue;
  9085. }
  9086. const knownValue = this.getKnownValue();
  9087. this.expressionsDependingOnKnownValue.push(origin);
  9088. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  9089. }
  9090. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9091. const { type } = interaction;
  9092. if (this.isReassigned ||
  9093. type === INTERACTION_ASSIGNED ||
  9094. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  9095. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  9096. }
  9097. return (!(type === INTERACTION_CALLED
  9098. ? (interaction.withNew
  9099. ? context.instantiated
  9100. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  9101. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  9102. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  9103. }
  9104. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  9105. // For performance reasons, we fully deoptimize all deeper interactions
  9106. if (path.length >= 2 ||
  9107. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  9108. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  9109. (path.length === 1 &&
  9110. (this.deoptimizedFields.has(UnknownKey) ||
  9111. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  9112. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  9113. deoptimizeInteraction(interaction);
  9114. return;
  9115. }
  9116. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  9117. for (const entity of this.argumentsToBeDeoptimized) {
  9118. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  9119. }
  9120. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  9121. this.deoptimizationInteractions.push({
  9122. interaction,
  9123. path
  9124. });
  9125. }
  9126. }
  9127. }
  9128. deoptimizePath(path) {
  9129. if (path.length === 0) {
  9130. this.markReassigned();
  9131. return;
  9132. }
  9133. if (this.deoptimizedFields.has(UnknownKey)) {
  9134. return;
  9135. }
  9136. const key = path[0];
  9137. if (this.deoptimizedFields.has(key)) {
  9138. return;
  9139. }
  9140. this.deoptimizedFields.add(key);
  9141. for (const entity of this.argumentsToBeDeoptimized) {
  9142. // We do not need a recursion tracker here as we already track whether
  9143. // this field is deoptimized
  9144. entity.deoptimizePath([...this.initPath, key]);
  9145. }
  9146. if (key === UnknownKey) {
  9147. // save some memory
  9148. this.deoptimizationInteractions = NO_INTERACTIONS;
  9149. this.deoptimizations = EMPTY_PATH_TRACKER;
  9150. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  9151. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  9152. }
  9153. }
  9154. getReturnExpressionWhenCalledAtPath(path) {
  9155. // We deoptimize everything that is called as that will trivially deoptimize
  9156. // the corresponding return expressions as well and avoid badly performing
  9157. // and complicated alternatives
  9158. if (path.length === 0) {
  9159. this.deoptimizePath(UNKNOWN_PATH);
  9160. }
  9161. else if (!this.deoptimizedFields.has(path[0])) {
  9162. this.deoptimizePath([path[0]]);
  9163. }
  9164. return UNKNOWN_RETURN_EXPRESSION;
  9165. }
  9166. includeArgumentPaths(entity, context) {
  9167. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  9168. }
  9169. }
  9170. class ThisVariable extends ParameterVariable {
  9171. constructor(context) {
  9172. super('this', null, EMPTY_PATH, context);
  9173. }
  9174. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9175. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  9176. }
  9177. }
  9178. class CatchBodyScope extends ChildScope {
  9179. constructor(parent) {
  9180. super(parent, parent.context);
  9181. this.parent = parent;
  9182. }
  9183. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9184. if (kind === 'var') {
  9185. const name = identifier.name;
  9186. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9187. if (existingVariable) {
  9188. const existingKind = existingVariable.kind;
  9189. if (existingKind === 'parameter' &&
  9190. // If this is a destructured parameter, it is forbidden to redeclare
  9191. existingVariable.declarations[0].parent.type === parseAst_js.CatchClause) {
  9192. // If this is a var with the same name as the catch scope parameter,
  9193. // the assignment actually goes to the parameter and the var is
  9194. // hoisted without assignment. Locally, it is shadowed by the
  9195. // parameter
  9196. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  9197. // To avoid the need to rewrite the declaration, we link the variable
  9198. // names. If we ever implement a logic that splits initialization and
  9199. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  9200. // removed again.
  9201. // We do not need to check whether there already is a linked
  9202. // variable because then declaredVariable would be that linked
  9203. // variable.
  9204. existingVariable.renderLikeHoisted(declaredVariable);
  9205. this.addHoistedVariable(name, declaredVariable);
  9206. return declaredVariable;
  9207. }
  9208. if (existingKind === 'var') {
  9209. existingVariable.addDeclaration(identifier, init);
  9210. return existingVariable;
  9211. }
  9212. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9213. }
  9214. // We only add parameters to parameter scopes
  9215. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9216. // Necessary to make sure the init is deoptimized for conditional declarations.
  9217. // We cannot call deoptimizePath here.
  9218. declaredVariable.markInitializersForDeoptimization();
  9219. // We add the variable to this and all parent scopes to reliably detect conflicts
  9220. this.addHoistedVariable(name, declaredVariable);
  9221. return declaredVariable;
  9222. }
  9223. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  9224. }
  9225. }
  9226. class FunctionBodyScope extends ChildScope {
  9227. constructor(parent) {
  9228. super(parent, parent.context);
  9229. }
  9230. // There is stuff that is only allowed in function scopes, i.e. functions can
  9231. // be redeclared, functions and var can redeclare each other
  9232. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  9233. const name = identifier.name;
  9234. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  9235. if (existingVariable) {
  9236. const existingKind = existingVariable.kind;
  9237. if ((kind === 'var' || kind === 'function') &&
  9238. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  9239. existingVariable.addDeclaration(identifier, init);
  9240. return existingVariable;
  9241. }
  9242. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  9243. }
  9244. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  9245. this.variables.set(name, newVariable);
  9246. return newVariable;
  9247. }
  9248. }
  9249. class ParameterScope extends ChildScope {
  9250. constructor(parent, isCatchScope) {
  9251. super(parent, parent.context);
  9252. this.hasRest = false;
  9253. this.parameters = [];
  9254. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  9255. }
  9256. /**
  9257. * Adds a parameter to this scope. Parameters must be added in the correct
  9258. * order, i.e. from left to right.
  9259. */
  9260. addParameterDeclaration(identifier, argumentPath) {
  9261. const { name, start } = identifier;
  9262. const existingParameter = this.variables.get(name);
  9263. if (existingParameter) {
  9264. return this.context.error(parseAst_js.logDuplicateArgumentNameError(name), start);
  9265. }
  9266. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  9267. this.variables.set(name, variable);
  9268. // We also add it to the body scope to detect name conflicts with local
  9269. // variables. We still need the intermediate scope, though, as parameter
  9270. // defaults are NOT taken from the body scope but from the parameters or
  9271. // outside scope.
  9272. this.bodyScope.addHoistedVariable(name, variable);
  9273. return variable;
  9274. }
  9275. addParameterVariables(parameters, hasRest) {
  9276. this.parameters = parameters;
  9277. for (const parameterList of parameters) {
  9278. for (const parameter of parameterList) {
  9279. parameter.alwaysRendered = true;
  9280. }
  9281. }
  9282. this.hasRest = hasRest;
  9283. }
  9284. includeCallArguments({ args }, context) {
  9285. let calledFromTryStatement = false;
  9286. let argumentIncluded = false;
  9287. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  9288. let lastExplicitlyIncludedIndex = args.length - 1;
  9289. // If there is a SpreadElement, we need to include all arguments after it
  9290. // because we no longer know which argument corresponds to which parameter.
  9291. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9292. const argument = args[argumentIndex];
  9293. if (argument instanceof SpreadElement && !argumentIncluded) {
  9294. argumentIncluded = true;
  9295. lastExplicitlyIncludedIndex = argumentIndex - 1;
  9296. }
  9297. if (argumentIncluded) {
  9298. argument.includePath(UNKNOWN_PATH, context);
  9299. argument.include(context, false);
  9300. }
  9301. }
  9302. // Now we go backwards either starting from the last argument or before the
  9303. // first SpreadElement to ensure all arguments before are included as needed
  9304. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  9305. const parameterVariables = this.parameters[index - 1] || restParameter;
  9306. const argument = args[index];
  9307. if (parameterVariables) {
  9308. calledFromTryStatement = false;
  9309. if (parameterVariables.length === 0) {
  9310. // handle empty destructuring to avoid destructuring undefined
  9311. argumentIncluded = true;
  9312. }
  9313. else {
  9314. for (const parameterVariable of parameterVariables) {
  9315. if (parameterVariable.calledFromTryStatement) {
  9316. calledFromTryStatement = true;
  9317. }
  9318. if (parameterVariable.included) {
  9319. argumentIncluded = true;
  9320. if (calledFromTryStatement) {
  9321. argument.include(context, true);
  9322. }
  9323. else {
  9324. parameterVariable.includeArgumentPaths(argument, context);
  9325. argument.include(context, false);
  9326. }
  9327. }
  9328. }
  9329. }
  9330. }
  9331. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  9332. argumentIncluded = true;
  9333. argument.include(context, calledFromTryStatement);
  9334. }
  9335. }
  9336. }
  9337. }
  9338. class ReturnValueScope extends ParameterScope {
  9339. constructor() {
  9340. super(...arguments);
  9341. this.returnExpression = null;
  9342. this.returnExpressions = [];
  9343. }
  9344. addReturnExpression(expression) {
  9345. this.returnExpressions.push(expression);
  9346. }
  9347. deoptimizeArgumentsOnCall({ args }) {
  9348. const { parameters } = this;
  9349. let position = 0;
  9350. for (; position < args.length - 1; position++) {
  9351. // Only the "this" argument arg[0] can be null
  9352. const argument = args[position + 1];
  9353. if (argument instanceof SpreadElement) {
  9354. // This deoptimizes the current and remaining parameters and arguments
  9355. for (; position < parameters.length; position++) {
  9356. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  9357. for (const variable of parameters[position]) {
  9358. variable.markReassigned();
  9359. }
  9360. }
  9361. break;
  9362. }
  9363. if (this.hasRest && position >= parameters.length - 1) {
  9364. argument.deoptimizePath(UNKNOWN_PATH);
  9365. }
  9366. else {
  9367. const variables = parameters[position];
  9368. if (variables) {
  9369. for (const variable of variables) {
  9370. variable.addArgumentForDeoptimization(argument);
  9371. }
  9372. }
  9373. this.addArgumentToBeDeoptimized(argument);
  9374. }
  9375. }
  9376. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  9377. for (; position < nonRestParameterLength; position++) {
  9378. for (const variable of parameters[position]) {
  9379. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  9380. }
  9381. }
  9382. }
  9383. getReturnExpression() {
  9384. if (this.returnExpression === null)
  9385. this.updateReturnExpression();
  9386. return this.returnExpression;
  9387. }
  9388. deoptimizeAllParameters() {
  9389. for (const parameter of this.parameters) {
  9390. for (const variable of parameter) {
  9391. variable.deoptimizePath(UNKNOWN_PATH);
  9392. variable.markReassigned();
  9393. }
  9394. }
  9395. }
  9396. reassignAllParameters() {
  9397. for (const parameter of this.parameters) {
  9398. for (const variable of parameter) {
  9399. variable.markReassigned();
  9400. }
  9401. }
  9402. }
  9403. addArgumentToBeDeoptimized(_argument) { }
  9404. updateReturnExpression() {
  9405. if (this.returnExpressions.length === 1) {
  9406. this.returnExpression = this.returnExpressions[0];
  9407. }
  9408. else {
  9409. this.returnExpression = UNKNOWN_EXPRESSION;
  9410. for (const expression of this.returnExpressions) {
  9411. expression.deoptimizePath(UNKNOWN_PATH);
  9412. }
  9413. }
  9414. }
  9415. }
  9416. class FunctionScope extends ReturnValueScope {
  9417. constructor(parent, functionNode) {
  9418. super(parent, false);
  9419. this.functionNode = functionNode;
  9420. const { context } = parent;
  9421. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  9422. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  9423. }
  9424. findLexicalBoundary() {
  9425. return this;
  9426. }
  9427. includeCallArguments(interaction, context) {
  9428. super.includeCallArguments(interaction, context);
  9429. if (this.argumentsVariable.included) {
  9430. const { args } = interaction;
  9431. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  9432. const argument = args[argumentIndex];
  9433. if (argument) {
  9434. argument.includePath(UNKNOWN_PATH, context);
  9435. argument.include(context, false);
  9436. }
  9437. }
  9438. }
  9439. }
  9440. addArgumentToBeDeoptimized(argument) {
  9441. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  9442. }
  9443. }
  9444. class ExpressionStatement extends NodeBase {
  9445. initialise() {
  9446. super.initialise();
  9447. if (this.directive &&
  9448. this.directive !== 'use strict' &&
  9449. this.parent.type === parseAst_js.Program) {
  9450. this.scope.context.log(parseAst_js.LOGLEVEL_WARN,
  9451. // This is necessary, because either way (deleting or not) can lead to errors.
  9452. parseAst_js.logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  9453. }
  9454. }
  9455. removeAnnotations(code) {
  9456. this.expression.removeAnnotations(code);
  9457. }
  9458. render(code, options) {
  9459. super.render(code, options);
  9460. if (code.original[this.end - 1] !== ';') {
  9461. code.appendLeft(this.end, ';');
  9462. }
  9463. }
  9464. shouldBeIncluded(context) {
  9465. if (this.directive && this.directive !== 'use strict')
  9466. return this.parent.type !== parseAst_js.Program;
  9467. return super.shouldBeIncluded(context);
  9468. }
  9469. }
  9470. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9471. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9472. class BlockStatement extends NodeBase {
  9473. get deoptimizeBody() {
  9474. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  9475. }
  9476. set deoptimizeBody(value) {
  9477. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  9478. }
  9479. get directlyIncluded() {
  9480. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  9481. }
  9482. set directlyIncluded(value) {
  9483. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  9484. }
  9485. addImplicitReturnExpressionToScope() {
  9486. const lastStatement = this.body[this.body.length - 1];
  9487. if (!lastStatement || lastStatement.type !== parseAst_js.ReturnStatement) {
  9488. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  9489. }
  9490. }
  9491. createScope(parentScope) {
  9492. this.scope = this.parent.preventChildBlockScope
  9493. ? parentScope
  9494. : new BlockScope(parentScope);
  9495. }
  9496. hasEffects(context) {
  9497. if (this.deoptimizeBody)
  9498. return true;
  9499. for (const node of this.body) {
  9500. if (context.brokenFlow)
  9501. break;
  9502. if (node.hasEffects(context))
  9503. return true;
  9504. }
  9505. return false;
  9506. }
  9507. include(context, includeChildrenRecursively) {
  9508. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  9509. this.included = true;
  9510. this.directlyIncluded = true;
  9511. if (this.deoptimizeBody)
  9512. includeChildrenRecursively = true;
  9513. for (const node of this.body) {
  9514. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9515. node.include(context, includeChildrenRecursively);
  9516. }
  9517. }
  9518. }
  9519. initialise() {
  9520. super.initialise();
  9521. this.scope.context.magicString.addSourcemapLocation(this.end - 1);
  9522. const firstBodyStatement = this.body[0];
  9523. this.deoptimizeBody =
  9524. firstBodyStatement instanceof ExpressionStatement &&
  9525. firstBodyStatement.directive === 'use asm';
  9526. }
  9527. render(code, options) {
  9528. if (this.body.length > 0) {
  9529. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  9530. }
  9531. else {
  9532. super.render(code, options);
  9533. }
  9534. }
  9535. }
  9536. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9537. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  9538. class RestElement extends NodeBase {
  9539. constructor() {
  9540. super(...arguments);
  9541. this.declarationInit = null;
  9542. }
  9543. addExportedVariables(variables, exportNamesByVariable) {
  9544. this.argument.addExportedVariables(variables, exportNamesByVariable);
  9545. }
  9546. declare(kind, destructuredInitPath, init) {
  9547. this.declarationInit = init;
  9548. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  9549. }
  9550. deoptimizeAssignment(destructuredInitPath, init) {
  9551. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  9552. }
  9553. deoptimizePath(path) {
  9554. if (path.length === 0) {
  9555. this.argument.deoptimizePath(EMPTY_PATH);
  9556. }
  9557. }
  9558. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9559. return (path.length > 0 ||
  9560. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9561. }
  9562. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  9563. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  9564. }
  9565. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  9566. const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init);
  9567. if (!this.included && included) {
  9568. this.includeNode(context);
  9569. }
  9570. return this.included;
  9571. }
  9572. include(context, includeChildrenRecursively) {
  9573. if (!this.included)
  9574. this.includeNode(context);
  9575. // This should just include the identifier, its properties should be
  9576. // included where the variable is used.
  9577. this.argument.include(context, includeChildrenRecursively);
  9578. }
  9579. markDeclarationReached() {
  9580. this.argument.markDeclarationReached();
  9581. }
  9582. applyDeoptimizations() {
  9583. this.deoptimized = true;
  9584. if (this.declarationInit !== null) {
  9585. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  9586. this.scope.context.requestTreeshakingPass();
  9587. }
  9588. }
  9589. }
  9590. RestElement.prototype.includeNode = onlyIncludeSelf;
  9591. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  9592. ? destructuredInitPath
  9593. : [...destructuredInitPath, UnknownKey];
  9594. class FunctionBase extends NodeBase {
  9595. constructor() {
  9596. super(...arguments);
  9597. this.parameterVariableValuesDeoptimized = false;
  9598. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  9599. }
  9600. get async() {
  9601. return isFlagSet(this.flags, 256 /* Flag.async */);
  9602. }
  9603. set async(value) {
  9604. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  9605. }
  9606. get deoptimizedReturn() {
  9607. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  9608. }
  9609. set deoptimizedReturn(value) {
  9610. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  9611. }
  9612. get generator() {
  9613. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  9614. }
  9615. set generator(value) {
  9616. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  9617. }
  9618. get hasCachedEffects() {
  9619. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  9620. }
  9621. set hasCachedEffects(value) {
  9622. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  9623. }
  9624. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9625. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  9626. this.scope.deoptimizeArgumentsOnCall(interaction);
  9627. }
  9628. else {
  9629. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9630. }
  9631. }
  9632. deoptimizePath(path) {
  9633. this.getObjectEntity().deoptimizePath(path);
  9634. if (path.length === 1 && path[0] === UnknownKey) {
  9635. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  9636. // which means the return expression and parameters need to be reassigned
  9637. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9638. this.scope.deoptimizeAllParameters();
  9639. }
  9640. }
  9641. getLiteralValueAtPath(path, recursionTracker, origin) {
  9642. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9643. }
  9644. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9645. if (path.length > 0) {
  9646. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9647. }
  9648. if (this.async) {
  9649. if (!this.deoptimizedReturn) {
  9650. this.deoptimizedReturn = true;
  9651. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9652. this.scope.context.requestTreeshakingPass();
  9653. }
  9654. return UNKNOWN_RETURN_EXPRESSION;
  9655. }
  9656. return [this.scope.getReturnExpression(), false];
  9657. }
  9658. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9659. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  9660. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9661. }
  9662. if (this.hasCachedEffects) {
  9663. return true;
  9664. }
  9665. if (this.async) {
  9666. const { propertyReadSideEffects } = this.scope.context.options
  9667. .treeshake;
  9668. const returnExpression = this.scope.getReturnExpression();
  9669. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  9670. (propertyReadSideEffects &&
  9671. (propertyReadSideEffects === 'always' ||
  9672. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  9673. this.hasCachedEffects = true;
  9674. return true;
  9675. }
  9676. }
  9677. const { propertyReadSideEffects } = this.scope.context.options
  9678. .treeshake;
  9679. for (let index = 0; index < this.params.length; index++) {
  9680. const parameter = this.params[index];
  9681. if (parameter.hasEffects(context) ||
  9682. (propertyReadSideEffects &&
  9683. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  9684. this.hasCachedEffects = true;
  9685. return true;
  9686. }
  9687. }
  9688. return false;
  9689. }
  9690. /**
  9691. * If the function (expression or declaration) is only used as function calls
  9692. */
  9693. onlyFunctionCallUsed() {
  9694. let variable = null;
  9695. if (this.parent.type === parseAst_js.VariableDeclarator) {
  9696. variable = this.parent.id.variable ?? null;
  9697. }
  9698. if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
  9699. variable = this.parent.variable;
  9700. }
  9701. return variable?.getOnlyFunctionCallUsed() ?? false;
  9702. }
  9703. include(context, includeChildrenRecursively) {
  9704. if (!this.included)
  9705. this.includeNode(context);
  9706. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  9707. this.parameterVariableValuesDeoptimized = true;
  9708. this.scope.reassignAllParameters();
  9709. }
  9710. const { brokenFlow } = context;
  9711. context.brokenFlow = false;
  9712. this.body.include(context, includeChildrenRecursively);
  9713. context.brokenFlow = brokenFlow;
  9714. }
  9715. initialise() {
  9716. super.initialise();
  9717. if (this.body instanceof BlockStatement) {
  9718. this.body.addImplicitReturnExpressionToScope();
  9719. }
  9720. else {
  9721. this.scope.addReturnExpression(this.body);
  9722. }
  9723. if (this.annotations &&
  9724. this.scope.context.options.treeshake.annotations) {
  9725. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  9726. }
  9727. }
  9728. parseNode(esTreeNode) {
  9729. const { body, params } = esTreeNode;
  9730. const { scope } = this;
  9731. const { bodyScope, context } = scope;
  9732. // We need to ensure that parameters are declared before the body is parsed
  9733. // so that the scope already knows all parameters and can detect conflicts
  9734. // when parsing the body.
  9735. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  9736. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  9737. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  9738. return super.parseNode(esTreeNode);
  9739. }
  9740. }
  9741. FunctionBase.prototype.preventChildBlockScope = true;
  9742. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9743. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  9744. class FunctionNode extends FunctionBase {
  9745. constructor() {
  9746. super(...arguments);
  9747. this.objectEntity = null;
  9748. }
  9749. createScope(parentScope) {
  9750. this.scope = new FunctionScope(parentScope, this);
  9751. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  9752. // This makes sure that all deoptimizations of "this" are applied to the
  9753. // constructed entity.
  9754. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  9755. }
  9756. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9757. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9758. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  9759. // args[0] is the "this" argument
  9760. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  9761. }
  9762. }
  9763. hasEffects(context) {
  9764. if (this.annotationNoSideEffects) {
  9765. return false;
  9766. }
  9767. return !!this.id?.hasEffects(context);
  9768. }
  9769. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9770. if (this.annotationNoSideEffects &&
  9771. path.length === 0 &&
  9772. interaction.type === INTERACTION_CALLED) {
  9773. return false;
  9774. }
  9775. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  9776. return true;
  9777. }
  9778. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  9779. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  9780. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  9781. const { brokenFlow, ignore, replacedVariableInits } = context;
  9782. context.ignore = {
  9783. breaks: false,
  9784. continues: false,
  9785. labels: new Set(),
  9786. returnYield: true,
  9787. this: interaction.withNew
  9788. };
  9789. if (this.body.hasEffects(context)) {
  9790. this.hasCachedEffects = true;
  9791. return true;
  9792. }
  9793. context.brokenFlow = brokenFlow;
  9794. if (thisInit) {
  9795. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  9796. }
  9797. else {
  9798. replacedVariableInits.delete(this.scope.thisVariable);
  9799. }
  9800. context.ignore = ignore;
  9801. }
  9802. return false;
  9803. }
  9804. include(context, includeChildrenRecursively) {
  9805. super.include(context, includeChildrenRecursively);
  9806. this.id?.include(context, includeChildrenRecursively);
  9807. const hasArguments = this.scope.argumentsVariable.included;
  9808. for (const parameter of this.params) {
  9809. if (!(parameter instanceof Identifier) || hasArguments) {
  9810. parameter.include(context, includeChildrenRecursively);
  9811. }
  9812. }
  9813. }
  9814. includeNode(context) {
  9815. this.included = true;
  9816. const hasArguments = this.scope.argumentsVariable.included;
  9817. for (const parameter of this.params) {
  9818. if (!(parameter instanceof Identifier) || hasArguments) {
  9819. parameter.includePath(UNKNOWN_PATH, context);
  9820. }
  9821. }
  9822. }
  9823. initialise() {
  9824. super.initialise();
  9825. this.id?.declare('function', EMPTY_PATH, this);
  9826. }
  9827. getObjectEntity() {
  9828. if (this.objectEntity !== null) {
  9829. return this.objectEntity;
  9830. }
  9831. return (this.objectEntity = new ObjectEntity([
  9832. {
  9833. key: 'prototype',
  9834. kind: 'init',
  9835. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  9836. }
  9837. ], OBJECT_PROTOTYPE));
  9838. }
  9839. }
  9840. class FunctionDeclaration extends FunctionNode {
  9841. initialise() {
  9842. super.initialise();
  9843. if (this.id !== null) {
  9844. this.id.variable.isId = true;
  9845. }
  9846. }
  9847. onlyFunctionCallUsed() {
  9848. // call super.onlyFunctionCallUsed for export default anonymous function
  9849. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  9850. }
  9851. parseNode(esTreeNode) {
  9852. if (esTreeNode.id !== null) {
  9853. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  9854. }
  9855. return super.parseNode(esTreeNode);
  9856. }
  9857. }
  9858. // The header ends at the first non-white-space after "default"
  9859. function getDeclarationStart(code, start) {
  9860. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  9861. }
  9862. function getFunctionIdInsertPosition(code, start) {
  9863. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  9864. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  9865. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  9866. if (generatorStarPos === -1) {
  9867. return declarationEnd;
  9868. }
  9869. return declarationEnd + generatorStarPos + 1;
  9870. }
  9871. class ExportDefaultDeclaration extends NodeBase {
  9872. include(context, includeChildrenRecursively) {
  9873. this.included = true;
  9874. this.declaration.include(context, includeChildrenRecursively);
  9875. if (includeChildrenRecursively) {
  9876. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  9877. }
  9878. }
  9879. includePath(path, context) {
  9880. this.included = true;
  9881. this.declaration.includePath(path, context);
  9882. }
  9883. initialise() {
  9884. super.initialise();
  9885. const declaration = this.declaration;
  9886. this.declarationName =
  9887. (declaration.id && declaration.id.name) || this.declaration.name;
  9888. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  9889. this.scope.context.addExport(this);
  9890. }
  9891. removeAnnotations(code) {
  9892. this.declaration.removeAnnotations(code);
  9893. }
  9894. render(code, options, nodeRenderOptions) {
  9895. const { start, end } = nodeRenderOptions;
  9896. const declarationStart = getDeclarationStart(code.original, this.start);
  9897. if (this.declaration instanceof FunctionDeclaration) {
  9898. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9899. ? getFunctionIdInsertPosition(code.original, declarationStart)
  9900. : null, options);
  9901. }
  9902. else if (this.declaration instanceof ClassDeclaration) {
  9903. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9904. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  9905. : null, options);
  9906. }
  9907. else if (this.variable.getOriginalVariable() !== this.variable) {
  9908. // Remove altogether to prevent re-declaring the same variable
  9909. treeshakeNode(this, code, start, end);
  9910. return;
  9911. }
  9912. else if (this.variable.included) {
  9913. this.renderVariableDeclaration(code, declarationStart, options);
  9914. }
  9915. else {
  9916. code.remove(this.start, declarationStart);
  9917. this.declaration.render(code, options, {
  9918. renderedSurroundingElement: parseAst_js.ExpressionStatement
  9919. });
  9920. if (code.original[this.end - 1] !== ';') {
  9921. code.appendLeft(this.end, ';');
  9922. }
  9923. return;
  9924. }
  9925. this.declaration.render(code, options);
  9926. }
  9927. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  9928. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  9929. const name = this.variable.getName(getPropertyAccess);
  9930. // Remove `export default`
  9931. code.remove(this.start, declarationStart);
  9932. if (idInsertPosition !== null) {
  9933. code.appendLeft(idInsertPosition, ` ${name}`);
  9934. }
  9935. if (format === 'system' &&
  9936. this.declaration instanceof ClassDeclaration &&
  9937. exportNamesByVariable.has(this.variable)) {
  9938. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  9939. }
  9940. }
  9941. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  9942. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  9943. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  9944. if (systemExportNames) {
  9945. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  9946. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  9947. }
  9948. else {
  9949. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9950. if (!hasTrailingSemicolon) {
  9951. code.appendLeft(this.end, ';');
  9952. }
  9953. }
  9954. }
  9955. }
  9956. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9957. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  9958. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  9959. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  9960. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  9961. const backSlashRegEx = /\\/g;
  9962. function escapeId(id) {
  9963. if (!needsEscapeRegEx.test(id))
  9964. return id;
  9965. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  9966. }
  9967. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9968. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  9969. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9970. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  9971. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9972. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9973. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9974. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  9975. const defaultInteropHelpersByInteropType = {
  9976. auto: INTEROP_DEFAULT_VARIABLE,
  9977. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  9978. default: null,
  9979. defaultOnly: null,
  9980. esModule: null
  9981. };
  9982. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9983. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  9984. const namespaceInteropHelpersByInteropType = {
  9985. auto: INTEROP_NAMESPACE_VARIABLE,
  9986. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  9987. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9988. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9989. esModule: null
  9990. };
  9991. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  9992. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  9993. const usedHelpers = new Set(additionalHelpers);
  9994. for (const variable of HELPER_NAMES) {
  9995. if (accessedGlobals.has(variable)) {
  9996. usedHelpers.add(variable);
  9997. }
  9998. }
  9999. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  10000. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  10001. : '').join('');
  10002. };
  10003. const HELPER_GENERATORS = {
  10004. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  10005. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  10006. },
  10007. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  10008. const { _, getDirectReturnFunction, n } = snippets;
  10009. const [left, right] = getDirectReturnFunction(['e'], {
  10010. functionReturn: true,
  10011. lineBreakIndent: null,
  10012. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  10013. });
  10014. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  10015. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10016. },
  10017. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  10018. const { _, getDirectReturnFunction, n } = snippets;
  10019. const [left, right] = getDirectReturnFunction(['e'], {
  10020. functionReturn: true,
  10021. lineBreakIndent: null,
  10022. name: INTEROP_DEFAULT_VARIABLE
  10023. });
  10024. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  10025. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10026. },
  10027. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  10028. const { _, getDirectReturnFunction, n } = snippets;
  10029. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10030. const [left, right] = getDirectReturnFunction(['e'], {
  10031. functionReturn: true,
  10032. lineBreakIndent: null,
  10033. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  10034. });
  10035. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10036. }
  10037. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  10038. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  10039. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10040. `}${n}${n}`);
  10041. },
  10042. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  10043. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  10044. const [left, right] = getDirectReturnFunction(['e'], {
  10045. functionReturn: true,
  10046. lineBreakIndent: null,
  10047. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10048. });
  10049. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  10050. [null, `__proto__:${_}null`],
  10051. ['default', 'e']
  10052. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10053. },
  10054. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10055. const { _, n } = snippets;
  10056. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10057. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10058. `}${n}${n}`);
  10059. },
  10060. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  10061. const { _, getDirectReturnFunction, n } = snippets;
  10062. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10063. const [left, right] = getDirectReturnFunction(['e'], {
  10064. functionReturn: true,
  10065. lineBreakIndent: null,
  10066. name: INTEROP_NAMESPACE_VARIABLE
  10067. });
  10068. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10069. }
  10070. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10071. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10072. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  10073. `}${n}${n}`);
  10074. },
  10075. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  10076. const { _, cnst, n } = snippets;
  10077. const useForEach = cnst === 'var' && liveBindings;
  10078. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10079. `${t}${loopOverNamespaces(`{${n}` +
  10080. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10081. (liveBindings
  10082. ? useForEach
  10083. ? copyOwnPropertyLiveBinding
  10084. : copyPropertyLiveBinding
  10085. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10086. `${t}${t}${t}}${n}` +
  10087. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10088. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  10089. `}${n}${n}`);
  10090. }
  10091. };
  10092. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10093. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10094. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10095. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  10096. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10097. const copyProperty = `{${n}` +
  10098. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10099. `${index}${t}}`;
  10100. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  10101. `${index}if${_}(e)${_}{${n}` +
  10102. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10103. `${index}}${n}` +
  10104. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10105. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10106. };
  10107. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10108. ? `for${_}(${cnst} k in e)${_}${body}`
  10109. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10110. isAsync: false,
  10111. name: null
  10112. })}${body})${s}`;
  10113. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10114. if (useForEach) {
  10115. const [left, right] = getDirectReturnFunction(['e'], {
  10116. functionReturn: false,
  10117. lineBreakIndent: { base: t, t },
  10118. name: null
  10119. });
  10120. return (`m.forEach(${left}` +
  10121. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10122. isAsync: false,
  10123. name: null
  10124. })}${body})${right});`);
  10125. }
  10126. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10127. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10128. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10129. };
  10130. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10131. const { _, n } = snippets;
  10132. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10133. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10134. `${index}}${n}`);
  10135. };
  10136. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10137. const [left, right] = getDirectReturnFunction([], {
  10138. functionReturn: true,
  10139. lineBreakIndent: null,
  10140. name: null
  10141. });
  10142. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10143. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10144. `${index}${t}enumerable:${_}true,${n}` +
  10145. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10146. `${index}});${n}`);
  10147. };
  10148. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10149. const [left, right] = getDirectReturnFunction([], {
  10150. functionReturn: true,
  10151. lineBreakIndent: null,
  10152. name: null
  10153. });
  10154. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10155. `${index}if${_}(d)${_}{${n}` +
  10156. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10157. `${index}${t}${t}enumerable:${_}true,${n}` +
  10158. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10159. `${index}${t}});${n}` +
  10160. `${index}}${n}`);
  10161. };
  10162. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10163. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10164. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  10165. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10166. : fragment;
  10167. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10168. function getToStringTagValue(getObject) {
  10169. return getObject([['value', "'Module'"]], {
  10170. lineBreakIndent: null
  10171. });
  10172. }
  10173. class Literal extends NodeBase {
  10174. deoptimizeArgumentsOnInteractionAtPath() { }
  10175. getLiteralValueAtPath(path) {
  10176. if (path.length > 0 ||
  10177. // unknown literals can also be null but do not start with an "n"
  10178. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  10179. typeof this.value === 'bigint' ||
  10180. // to support shims for regular expressions
  10181. this.scope.context.code.charCodeAt(this.start) === 47) {
  10182. return UnknownValue;
  10183. }
  10184. return this.value;
  10185. }
  10186. getReturnExpressionWhenCalledAtPath(path) {
  10187. if (path.length !== 1)
  10188. return UNKNOWN_RETURN_EXPRESSION;
  10189. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  10190. }
  10191. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10192. switch (interaction.type) {
  10193. case INTERACTION_ACCESSED: {
  10194. return path.length > (this.value === null ? 0 : 1);
  10195. }
  10196. case INTERACTION_ASSIGNED: {
  10197. return true;
  10198. }
  10199. case INTERACTION_CALLED: {
  10200. if (this.included &&
  10201. this.value instanceof RegExp &&
  10202. (this.value.global || this.value.sticky)) {
  10203. return true;
  10204. }
  10205. return (path.length !== 1 ||
  10206. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  10207. }
  10208. }
  10209. }
  10210. initialise() {
  10211. super.initialise();
  10212. this.members = getLiteralMembersForValue(this.value);
  10213. }
  10214. parseNode(esTreeNode) {
  10215. this.value = esTreeNode.value;
  10216. this.regex = esTreeNode.regex;
  10217. return super.parseNode(esTreeNode);
  10218. }
  10219. render(code) {
  10220. if (typeof this.value === 'string') {
  10221. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  10222. }
  10223. }
  10224. }
  10225. Literal.prototype.includeNode = onlyIncludeSelf;
  10226. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  10227. if ('getLiteralValueAtPathAsChainElement' in object) {
  10228. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  10229. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  10230. return IS_SKIPPED_CHAIN;
  10231. }
  10232. }
  10233. else if (element.optional &&
  10234. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  10235. return IS_SKIPPED_CHAIN;
  10236. }
  10237. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  10238. }
  10239. function getResolvablePropertyKey(memberExpression) {
  10240. return memberExpression.computed
  10241. ? getResolvableComputedPropertyKey(memberExpression.property)
  10242. : memberExpression.property.name;
  10243. }
  10244. function getResolvableComputedPropertyKey(propertyKey) {
  10245. if (propertyKey instanceof Literal) {
  10246. return String(propertyKey.value);
  10247. }
  10248. return null;
  10249. }
  10250. function getPathIfNotComputed(memberExpression) {
  10251. const nextPathKey = memberExpression.propertyKey;
  10252. const object = memberExpression.object;
  10253. if (typeof nextPathKey === 'string') {
  10254. if (object instanceof Identifier) {
  10255. return [
  10256. { key: object.name, pos: object.start },
  10257. { key: nextPathKey, pos: memberExpression.property.start }
  10258. ];
  10259. }
  10260. if (object instanceof MemberExpression) {
  10261. const parentPath = getPathIfNotComputed(object);
  10262. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  10263. }
  10264. }
  10265. return null;
  10266. }
  10267. function getStringFromPath(path) {
  10268. let pathString = path[0].key;
  10269. for (let index = 1; index < path.length; index++) {
  10270. pathString += '.' + path[index].key;
  10271. }
  10272. return pathString;
  10273. }
  10274. class MemberExpression extends NodeBase {
  10275. constructor() {
  10276. super(...arguments);
  10277. this.variable = null;
  10278. this.expressionsToBeDeoptimized = [];
  10279. }
  10280. get computed() {
  10281. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  10282. }
  10283. set computed(value) {
  10284. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  10285. }
  10286. get optional() {
  10287. return isFlagSet(this.flags, 128 /* Flag.optional */);
  10288. }
  10289. set optional(value) {
  10290. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  10291. }
  10292. get assignmentDeoptimized() {
  10293. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  10294. }
  10295. set assignmentDeoptimized(value) {
  10296. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  10297. }
  10298. get bound() {
  10299. return isFlagSet(this.flags, 32 /* Flag.bound */);
  10300. }
  10301. set bound(value) {
  10302. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  10303. }
  10304. get isUndefined() {
  10305. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  10306. }
  10307. set isUndefined(value) {
  10308. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  10309. }
  10310. bind() {
  10311. this.bound = true;
  10312. const path = getPathIfNotComputed(this);
  10313. const baseVariable = path && this.scope.findVariable(path[0].key);
  10314. if (baseVariable?.isNamespace) {
  10315. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  10316. if (!resolvedVariable) {
  10317. super.bind();
  10318. }
  10319. else if (resolvedVariable === 'undefined') {
  10320. this.isUndefined = true;
  10321. }
  10322. else {
  10323. this.variable = resolvedVariable;
  10324. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  10325. }
  10326. }
  10327. else {
  10328. super.bind();
  10329. }
  10330. }
  10331. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10332. if (this.variable) {
  10333. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10334. }
  10335. else if (!this.isUndefined) {
  10336. if (path.length < MAX_PATH_DEPTH) {
  10337. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  10338. }
  10339. else {
  10340. deoptimizeInteraction(interaction);
  10341. }
  10342. }
  10343. }
  10344. deoptimizeAssignment(destructuredInitPath, init) {
  10345. this.deoptimizePath(EMPTY_PATH);
  10346. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  10347. }
  10348. deoptimizeCache() {
  10349. if (this.propertyKey === this.dynamicPropertyKey)
  10350. return;
  10351. const { expressionsToBeDeoptimized, object } = this;
  10352. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  10353. this.dynamicPropertyKey = this.propertyKey;
  10354. object.deoptimizePath(UNKNOWN_PATH);
  10355. if (this.included) {
  10356. object.includePath(UNKNOWN_PATH, createInclusionContext());
  10357. }
  10358. for (const expression of expressionsToBeDeoptimized) {
  10359. expression.deoptimizeCache();
  10360. }
  10361. }
  10362. deoptimizePath(path) {
  10363. if (path.length === 0)
  10364. this.disallowNamespaceReassignment();
  10365. if (this.variable) {
  10366. this.variable.deoptimizePath(path);
  10367. }
  10368. else if (!this.isUndefined) {
  10369. const { propertyKey } = this;
  10370. this.object.deoptimizePath([
  10371. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  10372. ...(path.length < MAX_PATH_DEPTH
  10373. ? path
  10374. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10375. ]);
  10376. }
  10377. }
  10378. getLiteralValueAtPath(path, recursionTracker, origin) {
  10379. if (this.variable) {
  10380. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10381. }
  10382. if (this.isUndefined) {
  10383. return undefined;
  10384. }
  10385. const propertyKey = this.getDynamicPropertyKey();
  10386. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10387. if (propertyKey !== this.propertyKey)
  10388. this.expressionsToBeDeoptimized.push(origin);
  10389. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  10390. }
  10391. return UnknownValue;
  10392. }
  10393. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  10394. if (this.variable) {
  10395. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10396. }
  10397. if (this.isUndefined) {
  10398. return undefined;
  10399. }
  10400. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  10401. }
  10402. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10403. if (this.variable) {
  10404. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10405. }
  10406. if (this.isUndefined) {
  10407. return [UNDEFINED_EXPRESSION, false];
  10408. }
  10409. const propertyKey = this.getDynamicPropertyKey();
  10410. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10411. if (propertyKey !== this.propertyKey)
  10412. this.expressionsToBeDeoptimized.push(origin);
  10413. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  10414. }
  10415. return UNKNOWN_RETURN_EXPRESSION;
  10416. }
  10417. hasEffects(context) {
  10418. if (!this.deoptimized)
  10419. this.applyDeoptimizations();
  10420. return (this.property.hasEffects(context) ||
  10421. this.object.hasEffects(context) ||
  10422. this.hasAccessEffect(context));
  10423. }
  10424. hasEffectsAsChainElement(context) {
  10425. if (this.variable || this.isUndefined)
  10426. return this.hasEffects(context);
  10427. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  10428. ? this.object.hasEffectsAsChainElement(context)
  10429. : this.object.hasEffects(context);
  10430. if (objectHasEffects === IS_SKIPPED_CHAIN)
  10431. return IS_SKIPPED_CHAIN;
  10432. if (this.optional &&
  10433. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  10434. return objectHasEffects || IS_SKIPPED_CHAIN;
  10435. }
  10436. // We only apply deoptimizations lazily once we know we are not skipping
  10437. if (!this.deoptimized)
  10438. this.applyDeoptimizations();
  10439. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  10440. }
  10441. hasEffectsAsAssignmentTarget(context, checkAccess) {
  10442. if (checkAccess && !this.deoptimized)
  10443. this.applyDeoptimizations();
  10444. if (!this.assignmentDeoptimized)
  10445. this.applyAssignmentDeoptimization();
  10446. return (this.property.hasEffects(context) ||
  10447. this.object.hasEffects(context) ||
  10448. (checkAccess && this.hasAccessEffect(context)) ||
  10449. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  10450. }
  10451. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10452. if (this.variable) {
  10453. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10454. }
  10455. if (this.isUndefined) {
  10456. return true;
  10457. }
  10458. if (path.length < MAX_PATH_DEPTH) {
  10459. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  10460. }
  10461. return true;
  10462. }
  10463. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10464. return (destructuredInitPath.length > 0 &&
  10465. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  10466. }
  10467. include(context, includeChildrenRecursively) {
  10468. if (!this.included)
  10469. this.includeNode(context);
  10470. this.object.include(context, includeChildrenRecursively);
  10471. this.property.include(context, includeChildrenRecursively);
  10472. }
  10473. includeNode(context) {
  10474. this.included = true;
  10475. if (!this.deoptimized)
  10476. this.applyDeoptimizations();
  10477. if (this.variable) {
  10478. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10479. }
  10480. else if (!this.isUndefined) {
  10481. this.object.includePath([this.propertyKey], context);
  10482. }
  10483. }
  10484. includeNodeAsAssignmentTarget(context) {
  10485. this.included = true;
  10486. if (!this.assignmentDeoptimized)
  10487. this.applyAssignmentDeoptimization();
  10488. if (this.variable) {
  10489. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  10490. }
  10491. else if (!this.isUndefined) {
  10492. this.object.includePath([this.propertyKey], context);
  10493. }
  10494. }
  10495. includePath(path, context) {
  10496. if (!this.included)
  10497. this.includeNode(context);
  10498. if (this.variable) {
  10499. this.variable?.includePath(path, context);
  10500. }
  10501. else if (!this.isUndefined) {
  10502. this.object.includePath([
  10503. this.propertyKey,
  10504. ...(path.length < MAX_PATH_DEPTH
  10505. ? path
  10506. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  10507. ], context);
  10508. }
  10509. }
  10510. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  10511. if (!this.included)
  10512. this.includeNodeAsAssignmentTarget(context);
  10513. if (deoptimizeAccess && !this.deoptimized)
  10514. this.applyDeoptimizations();
  10515. this.object.include(context, includeChildrenRecursively);
  10516. this.property.include(context, includeChildrenRecursively);
  10517. }
  10518. includeCallArguments(interaction, context) {
  10519. if (this.variable) {
  10520. this.variable.includeCallArguments(interaction, context);
  10521. }
  10522. else {
  10523. if (isImportExpressionNode(this.object) ||
  10524. /**
  10525. * const c = await import('foo')
  10526. * c.foo();
  10527. */
  10528. (this.object.variable &&
  10529. !this.object.variable.isReassigned &&
  10530. this.object.variable instanceof LocalVariable &&
  10531. isAwaitExpressionNode(this.object.variable.init) &&
  10532. isImportExpressionNode(this.object.variable.init.argument))) {
  10533. includeInteractionWithoutThis(interaction, context);
  10534. }
  10535. else {
  10536. includeInteraction(interaction, context);
  10537. }
  10538. }
  10539. }
  10540. includeDestructuredIfNecessary() {
  10541. /* istanbul ignore next */
  10542. this.scope.context.error({
  10543. message: 'includeDestructuredIfNecessary is currently not supported for MemberExpressions'
  10544. }, this.start);
  10545. }
  10546. initialise() {
  10547. super.initialise();
  10548. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  10549. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  10550. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  10551. }
  10552. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = parseAst_js.BLANK) {
  10553. if (this.variable || this.isUndefined) {
  10554. const { snippets: { getPropertyAccess } } = options;
  10555. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  10556. if (renderedParentType && isCalleeOfRenderedParent)
  10557. replacement = '0, ' + replacement;
  10558. code.overwrite(this.start, this.end, replacement, {
  10559. contentOnly: true,
  10560. storeName: true
  10561. });
  10562. }
  10563. else {
  10564. if (renderedParentType && isCalleeOfRenderedParent) {
  10565. code.appendRight(this.start, '0, ');
  10566. }
  10567. this.object.render(code, options, { renderedSurroundingElement });
  10568. this.property.render(code, options);
  10569. }
  10570. }
  10571. setAssignedValue(value) {
  10572. this.assignmentInteraction = {
  10573. args: [this.object, value],
  10574. type: INTERACTION_ASSIGNED
  10575. };
  10576. }
  10577. applyDeoptimizations() {
  10578. this.deoptimized = true;
  10579. const { propertyReadSideEffects } = this.scope.context.options
  10580. .treeshake;
  10581. if (
  10582. // Namespaces are not bound and should not be deoptimized
  10583. this.bound &&
  10584. propertyReadSideEffects &&
  10585. !(this.variable || this.isUndefined)) {
  10586. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10587. this.scope.context.requestTreeshakingPass();
  10588. }
  10589. if (this.variable) {
  10590. this.variable.addUsedPlace(this);
  10591. this.scope.context.requestTreeshakingPass();
  10592. }
  10593. }
  10594. applyAssignmentDeoptimization() {
  10595. this.assignmentDeoptimized = true;
  10596. const { propertyReadSideEffects } = this.scope.context.options
  10597. .treeshake;
  10598. if (
  10599. // Namespaces are not bound and should not be deoptimized
  10600. this.bound &&
  10601. propertyReadSideEffects &&
  10602. !(this.variable || this.isUndefined)) {
  10603. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  10604. this.scope.context.requestTreeshakingPass();
  10605. }
  10606. }
  10607. disallowNamespaceReassignment() {
  10608. if (this.object instanceof Identifier) {
  10609. const variable = this.scope.findVariable(this.object.name);
  10610. if (variable.isNamespace) {
  10611. if (this.variable) {
  10612. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  10613. }
  10614. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  10615. }
  10616. }
  10617. }
  10618. getDynamicPropertyKey() {
  10619. if (this.dynamicPropertyKey === null) {
  10620. this.dynamicPropertyKey = this.propertyKey;
  10621. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10622. return (this.dynamicPropertyKey =
  10623. value === SymbolToStringTag
  10624. ? value
  10625. : typeof value === 'symbol'
  10626. ? UnknownKey
  10627. : String(value));
  10628. }
  10629. return this.dynamicPropertyKey;
  10630. }
  10631. hasAccessEffect(context) {
  10632. const { propertyReadSideEffects } = this.scope.context.options
  10633. .treeshake;
  10634. return (!(this.variable || this.isUndefined) &&
  10635. propertyReadSideEffects &&
  10636. (propertyReadSideEffects === 'always' ||
  10637. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  10638. }
  10639. }
  10640. function resolveNamespaceVariables(baseVariable, path, astContext) {
  10641. if (path.length === 0)
  10642. return baseVariable;
  10643. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  10644. return null;
  10645. const exportName = path[0].key;
  10646. const [variable, options] = baseVariable.context.traceExport(exportName);
  10647. if (!variable) {
  10648. if (path.length === 1) {
  10649. const fileName = baseVariable.context.fileName;
  10650. astContext.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(exportName, astContext.module.id, fileName, !!options?.missingButExportExists), path[0].pos);
  10651. return 'undefined';
  10652. }
  10653. return null;
  10654. }
  10655. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  10656. }
  10657. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10658. const FILE_OBJ_PREFIX = 'ROLLUP_FILE_URL_OBJ_';
  10659. const IMPORT = 'import';
  10660. class MetaProperty extends NodeBase {
  10661. constructor() {
  10662. super(...arguments);
  10663. this.metaProperty = null;
  10664. this.preliminaryChunkId = null;
  10665. this.referenceId = null;
  10666. }
  10667. getReferencedFileName(outputPluginDriver) {
  10668. const { meta: { name }, metaProperty } = this;
  10669. if (name === IMPORT) {
  10670. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  10671. return outputPluginDriver.getFileName(metaProperty.slice(FILE_OBJ_PREFIX.length));
  10672. }
  10673. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  10674. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10675. }
  10676. }
  10677. return null;
  10678. }
  10679. hasEffects() {
  10680. return false;
  10681. }
  10682. hasEffectsOnInteractionAtPath(path, { type }) {
  10683. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10684. }
  10685. include() {
  10686. if (!this.included)
  10687. this.includeNode();
  10688. }
  10689. includeNode() {
  10690. this.included = true;
  10691. if (this.meta.name === IMPORT) {
  10692. this.scope.context.addImportMeta(this);
  10693. const parent = this.parent;
  10694. const metaProperty = (this.metaProperty =
  10695. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10696. ? parent.propertyKey
  10697. : null);
  10698. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  10699. this.referenceId = metaProperty.slice(FILE_OBJ_PREFIX.length);
  10700. }
  10701. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  10702. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10703. }
  10704. }
  10705. }
  10706. render(code, renderOptions) {
  10707. const { format, pluginDriver, snippets } = renderOptions;
  10708. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  10709. const { id: moduleId } = module;
  10710. if (name !== IMPORT)
  10711. return;
  10712. const chunkId = preliminaryChunkId;
  10713. if (referenceId) {
  10714. const fileName = pluginDriver.getFileName(referenceId);
  10715. const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
  10716. const isUrlObject = !!metaProperty?.startsWith(FILE_OBJ_PREFIX);
  10717. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  10718. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  10719. ]) || relativeUrlMechanisms[format](relativePath, isUrlObject);
  10720. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10721. return;
  10722. }
  10723. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  10724. metaProperty,
  10725. { chunkId, format, moduleId }
  10726. ]);
  10727. if (!replacement) {
  10728. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  10729. renderOptions.accessedDocumentCurrentScript ||=
  10730. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  10731. }
  10732. if (typeof replacement === 'string') {
  10733. if (parent instanceof MemberExpression) {
  10734. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10735. }
  10736. else {
  10737. code.overwrite(start, end, replacement, { contentOnly: true });
  10738. }
  10739. }
  10740. }
  10741. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  10742. this.preliminaryChunkId = preliminaryChunkId;
  10743. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) || this.metaProperty?.startsWith(FILE_OBJ_PREFIX)
  10744. ? accessedFileUrlGlobals
  10745. : accessedMetaUrlGlobals)[format];
  10746. if (accessedGlobals.length > 0) {
  10747. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10748. }
  10749. }
  10750. }
  10751. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  10752. const accessedMetaUrlGlobals = {
  10753. amd: ['document', 'module', 'URL'],
  10754. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10755. es: [],
  10756. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  10757. system: ['module'],
  10758. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  10759. };
  10760. const accessedFileUrlGlobals = {
  10761. amd: ['document', 'require', 'URL'],
  10762. cjs: ['document', 'require', 'URL'],
  10763. es: [],
  10764. iife: ['document', 'URL'],
  10765. system: ['module', 'URL'],
  10766. umd: ['document', 'require', 'URL']
  10767. };
  10768. const getResolveUrl = (path, asObject, URL = 'URL') => `new ${URL}(${path})${asObject ? '' : '.href'}`;
  10769. 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);
  10770. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  10771. const urlMechanism = getUrl(chunkId);
  10772. return property === null
  10773. ? `({ url: ${urlMechanism} })`
  10774. : property === 'url'
  10775. ? urlMechanism
  10776. : 'undefined';
  10777. };
  10778. const getFileUrlFromFullPath = (path, asObject) => `require('u' + 'rl').pathToFileURL(${path})${asObject ? '' : '.href'}`;
  10779. const getFileUrlFromRelativePath = (path, asObject) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`, asObject);
  10780. 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)`;
  10781. const relativeUrlMechanisms = {
  10782. amd: (relativePath, asObject) => {
  10783. if (relativePath[0] !== '.')
  10784. relativePath = './' + relativePath;
  10785. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`, asObject);
  10786. },
  10787. cjs: (relativePath, asObject) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject)})`,
  10788. es: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`, asObject),
  10789. iife: (relativePath, asObject) => getRelativeUrlFromDocument(relativePath, asObject),
  10790. system: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`, asObject),
  10791. umd: (relativePath, asObject) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject, true)})`
  10792. };
  10793. const importMetaMechanisms = {
  10794. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`, false)),
  10795. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId)})`),
  10796. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10797. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  10798. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId, true)})`)
  10799. };
  10800. class UndefinedVariable extends Variable {
  10801. constructor() {
  10802. super('undefined');
  10803. }
  10804. getLiteralValueAtPath() {
  10805. return undefined;
  10806. }
  10807. }
  10808. class ExportDefaultVariable extends LocalVariable {
  10809. constructor(name, exportDefaultDeclaration, context) {
  10810. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  10811. this.hasId = false;
  10812. this.originalId = null;
  10813. this.originalVariable = null;
  10814. const declaration = exportDefaultDeclaration.declaration;
  10815. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10816. declaration.id) {
  10817. this.hasId = true;
  10818. this.originalId = declaration.id;
  10819. }
  10820. else if (declaration instanceof Identifier) {
  10821. this.originalId = declaration;
  10822. }
  10823. }
  10824. addReference(identifier) {
  10825. if (!this.hasId) {
  10826. this.name = identifier.name;
  10827. }
  10828. }
  10829. addUsedPlace(usedPlace) {
  10830. const original = this.getOriginalVariable();
  10831. if (original === this) {
  10832. super.addUsedPlace(usedPlace);
  10833. }
  10834. else {
  10835. original.addUsedPlace(usedPlace);
  10836. }
  10837. }
  10838. forbidName(name) {
  10839. const original = this.getOriginalVariable();
  10840. if (original === this) {
  10841. super.forbidName(name);
  10842. }
  10843. else {
  10844. original.forbidName(name);
  10845. }
  10846. }
  10847. getAssignedVariableName() {
  10848. return (this.originalId && this.originalId.name) || null;
  10849. }
  10850. getBaseVariableName() {
  10851. const original = this.getOriginalVariable();
  10852. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  10853. }
  10854. getDirectOriginalVariable() {
  10855. return this.originalId &&
  10856. (this.hasId ||
  10857. !(this.originalId.isPossibleTDZ() ||
  10858. this.originalId.variable.isReassigned ||
  10859. this.originalId.variable instanceof UndefinedVariable ||
  10860. // this avoids a circular dependency
  10861. 'syntheticNamespace' in this.originalId.variable))
  10862. ? this.originalId.variable
  10863. : null;
  10864. }
  10865. getName(getPropertyAccess) {
  10866. const original = this.getOriginalVariable();
  10867. return original === this
  10868. ? super.getName(getPropertyAccess)
  10869. : original.getName(getPropertyAccess);
  10870. }
  10871. getOriginalVariable() {
  10872. if (this.originalVariable)
  10873. return this.originalVariable;
  10874. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10875. let original = this;
  10876. let currentVariable;
  10877. const checkedVariables = new Set();
  10878. do {
  10879. checkedVariables.add(original);
  10880. currentVariable = original;
  10881. original = currentVariable.getDirectOriginalVariable();
  10882. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10883. return (this.originalVariable = original || currentVariable);
  10884. }
  10885. }
  10886. class NamespaceVariable extends Variable {
  10887. constructor(context) {
  10888. super(context.getModuleName());
  10889. this.memberVariables = null;
  10890. this.mergedNamespaces = [];
  10891. this.referencedEarly = false;
  10892. this.references = [];
  10893. this.context = context;
  10894. this.module = context.module;
  10895. }
  10896. addReference(identifier) {
  10897. this.references.push(identifier);
  10898. this.name = identifier.name;
  10899. }
  10900. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10901. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  10902. const key = path[0];
  10903. if (typeof key === 'string') {
  10904. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  10905. }
  10906. else {
  10907. deoptimizeInteraction(interaction);
  10908. }
  10909. }
  10910. }
  10911. deoptimizePath(path) {
  10912. if (path.length > 1) {
  10913. const key = path[0];
  10914. if (typeof key === 'string') {
  10915. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  10916. }
  10917. }
  10918. }
  10919. getLiteralValueAtPath(path) {
  10920. if (path[0] === SymbolToStringTag) {
  10921. return 'Module';
  10922. }
  10923. return UnknownValue;
  10924. }
  10925. getMemberVariables() {
  10926. if (this.memberVariables) {
  10927. return this.memberVariables;
  10928. }
  10929. const memberVariables = Object.create(null);
  10930. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  10931. for (const name of sortedExports) {
  10932. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  10933. const [exportedVariable] = this.context.traceExport(name);
  10934. if (exportedVariable) {
  10935. memberVariables[name] = exportedVariable;
  10936. }
  10937. }
  10938. }
  10939. return (this.memberVariables = memberVariables);
  10940. }
  10941. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10942. const { type } = interaction;
  10943. if (path.length === 0) {
  10944. // This can only be a call anyway
  10945. return true;
  10946. }
  10947. if (path.length === 1 && type !== INTERACTION_CALLED) {
  10948. return type === INTERACTION_ASSIGNED;
  10949. }
  10950. const key = path[0];
  10951. if (typeof key !== 'string') {
  10952. return true;
  10953. }
  10954. const memberVariable = this.getMemberVariables()[key];
  10955. return (!memberVariable ||
  10956. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  10957. }
  10958. includePath(path, context) {
  10959. super.includePath(path, context);
  10960. this.context.includeAllExports();
  10961. }
  10962. prepare(accessedGlobalsByScope) {
  10963. if (this.mergedNamespaces.length > 0) {
  10964. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  10965. }
  10966. }
  10967. renderBlock(options) {
  10968. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  10969. const memberVariables = this.getMemberVariables();
  10970. const members = Object.entries(memberVariables)
  10971. .filter(([_, variable]) => variable.included)
  10972. .map(([name, variable]) => {
  10973. if (this.referencedEarly || variable.isReassigned || variable === this) {
  10974. return [
  10975. null,
  10976. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  10977. ];
  10978. }
  10979. return [name, variable.getName(getPropertyAccess)];
  10980. });
  10981. members.unshift([null, `__proto__:${_}null`]);
  10982. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  10983. if (this.mergedNamespaces.length > 0) {
  10984. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  10985. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  10986. }
  10987. else {
  10988. // The helper to merge namespaces will also take care of freezing and toStringTag
  10989. if (symbols) {
  10990. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  10991. }
  10992. if (freeze) {
  10993. output = `/*#__PURE__*/Object.freeze(${output})`;
  10994. }
  10995. }
  10996. const name = this.getName(getPropertyAccess);
  10997. output = `${cnst} ${name}${_}=${_}${output};`;
  10998. if (format === 'system' && exportNamesByVariable.has(this)) {
  10999. output += `${n}${getSystemExportStatement([this], options)};`;
  11000. }
  11001. return output;
  11002. }
  11003. renderFirst() {
  11004. return this.referencedEarly;
  11005. }
  11006. setMergedNamespaces(mergedNamespaces) {
  11007. this.mergedNamespaces = mergedNamespaces;
  11008. const moduleExecIndex = this.context.getModuleExecIndex();
  11009. for (const identifier of this.references) {
  11010. const { context } = identifier.scope;
  11011. if (context.getModuleExecIndex() <= moduleExecIndex) {
  11012. this.referencedEarly = true;
  11013. break;
  11014. }
  11015. }
  11016. }
  11017. }
  11018. NamespaceVariable.prototype.isNamespace = true;
  11019. class SyntheticNamedExportVariable extends Variable {
  11020. constructor(context, name, syntheticNamespace) {
  11021. super(name);
  11022. this.baseVariable = null;
  11023. this.context = context;
  11024. this.module = context.module;
  11025. this.syntheticNamespace = syntheticNamespace;
  11026. }
  11027. getBaseVariable() {
  11028. if (this.baseVariable)
  11029. return this.baseVariable;
  11030. let baseVariable = this.syntheticNamespace;
  11031. while (baseVariable instanceof ExportDefaultVariable ||
  11032. baseVariable instanceof SyntheticNamedExportVariable) {
  11033. if (baseVariable instanceof ExportDefaultVariable) {
  11034. const original = baseVariable.getOriginalVariable();
  11035. if (original === baseVariable)
  11036. break;
  11037. baseVariable = original;
  11038. }
  11039. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11040. baseVariable = baseVariable.syntheticNamespace;
  11041. }
  11042. }
  11043. return (this.baseVariable = baseVariable);
  11044. }
  11045. getBaseVariableName() {
  11046. return this.syntheticNamespace.getBaseVariableName();
  11047. }
  11048. getName(getPropertyAccess) {
  11049. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11050. }
  11051. includePath(path, context) {
  11052. super.includePath(path, context);
  11053. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  11054. }
  11055. setRenderNames(baseName, name) {
  11056. super.setRenderNames(baseName, name);
  11057. }
  11058. }
  11059. class ExternalChunk {
  11060. constructor(module, options, inputBase) {
  11061. this.options = options;
  11062. this.inputBase = inputBase;
  11063. this.defaultVariableName = '';
  11064. this.namespaceVariableName = '';
  11065. this.variableName = '';
  11066. this.fileName = null;
  11067. this.importAttributes = null;
  11068. this.id = module.id;
  11069. this.moduleInfo = module.info;
  11070. this.renormalizeRenderPath = module.renormalizeRenderPath;
  11071. this.suggestedVariableName = module.suggestedVariableName;
  11072. }
  11073. getFileName() {
  11074. if (this.fileName) {
  11075. return this.fileName;
  11076. }
  11077. const { paths } = this.options;
  11078. return (this.fileName =
  11079. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  11080. (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
  11081. }
  11082. getImportAttributes(snippets) {
  11083. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  11084. this.options.externalImportAttributes &&
  11085. this.moduleInfo.attributes, snippets));
  11086. }
  11087. getImportPath(importer) {
  11088. return escapeId(this.renormalizeRenderPath
  11089. ? parseAst_js.getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  11090. : this.getFileName());
  11091. }
  11092. }
  11093. function formatAttributes(attributes, { getObject }) {
  11094. if (!attributes) {
  11095. return null;
  11096. }
  11097. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  11098. if (assertionEntries.length > 0) {
  11099. return getObject(assertionEntries, { lineBreakIndent: null });
  11100. }
  11101. return null;
  11102. }
  11103. function removeJsExtension(name) {
  11104. return name.endsWith('.js') ? name.slice(0, -3) : name;
  11105. }
  11106. function getCompleteAmdId(options, chunkId) {
  11107. if (options.autoId) {
  11108. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  11109. }
  11110. return options.id ?? '';
  11111. }
  11112. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  11113. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  11114. if (!namedExportsMode) {
  11115. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  11116. }
  11117. let exportBlock = '';
  11118. if (namedExportsMode) {
  11119. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11120. if (!reexports) {
  11121. continue;
  11122. }
  11123. for (const specifier of reexports) {
  11124. if (specifier.reexported !== '*') {
  11125. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11126. if (exportBlock)
  11127. exportBlock += n;
  11128. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  11129. const [left, right] = getDirectReturnFunction([], {
  11130. functionReturn: true,
  11131. lineBreakIndent: null,
  11132. name: null
  11133. });
  11134. exportBlock +=
  11135. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  11136. `${t}enumerable:${_}true,${n}` +
  11137. `${t}get:${_}${left}${importName}${right}${n}});`;
  11138. }
  11139. else if (specifier.reexported === '__proto__') {
  11140. exportBlock +=
  11141. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11142. `${t}enumerable:${_}true,${n}` +
  11143. `${t}value:${_}${importName}${n}});`;
  11144. }
  11145. else {
  11146. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  11147. }
  11148. }
  11149. }
  11150. }
  11151. }
  11152. for (const { exported, local } of exports) {
  11153. const lhs = `exports${getPropertyAccess(exported)}`;
  11154. const rhs = local;
  11155. if (lhs !== rhs) {
  11156. if (exportBlock)
  11157. exportBlock += n;
  11158. exportBlock +=
  11159. exported === '__proto__'
  11160. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  11161. `${t}enumerable:${_}true,${n}` +
  11162. `${t}value:${_}${rhs}${n}});`
  11163. : `${lhs}${_}=${_}${rhs};`;
  11164. }
  11165. }
  11166. if (namedExportsMode) {
  11167. for (const { name, reexports } of dependencies) {
  11168. if (!reexports) {
  11169. continue;
  11170. }
  11171. for (const specifier of reexports) {
  11172. if (specifier.reexported === '*') {
  11173. if (exportBlock)
  11174. exportBlock += n;
  11175. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  11176. const protoString = "'__proto__'";
  11177. exportBlock +=
  11178. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  11179. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  11180. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  11181. `${t}${t}enumerable:${_}true,${n}` +
  11182. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  11183. `${t}});${n}${n}`;
  11184. }
  11185. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  11186. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  11187. isAsync: false,
  11188. name: null
  11189. })}${copyPropertyIfNecessary});`;
  11190. }
  11191. }
  11192. }
  11193. }
  11194. if (exportBlock) {
  11195. return `${n}${n}${exportBlock}`;
  11196. }
  11197. return '';
  11198. }
  11199. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  11200. if (exports.length > 0) {
  11201. return exports[0].local;
  11202. }
  11203. else {
  11204. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11205. if (reexports) {
  11206. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  11207. }
  11208. }
  11209. }
  11210. }
  11211. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  11212. if (imported === 'default') {
  11213. if (!isChunk) {
  11214. const moduleInterop = interop(moduleId);
  11215. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  11216. ? defaultVariableName
  11217. : moduleVariableName;
  11218. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  11219. ? `${variableName}${getPropertyAccess('default')}`
  11220. : variableName;
  11221. }
  11222. return depNamedExportsMode
  11223. ? `${moduleVariableName}${getPropertyAccess('default')}`
  11224. : moduleVariableName;
  11225. }
  11226. if (imported === '*') {
  11227. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  11228. ? namespaceVariableName
  11229. : moduleVariableName;
  11230. }
  11231. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  11232. }
  11233. function getEsModuleValue(getObject) {
  11234. return getObject([['value', 'true']], {
  11235. lineBreakIndent: null
  11236. });
  11237. }
  11238. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  11239. if (hasNamedExports) {
  11240. if (addEsModule) {
  11241. if (addNamespaceToStringTag) {
  11242. return `Object.defineProperties(exports,${_}${getObject([
  11243. ['__esModule', getEsModuleValue(getObject)],
  11244. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  11245. ], {
  11246. lineBreakIndent: null
  11247. })});`;
  11248. }
  11249. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  11250. }
  11251. if (addNamespaceToStringTag) {
  11252. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  11253. }
  11254. }
  11255. return '';
  11256. }
  11257. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  11258. if (needsLiveBinding) {
  11259. const [left, right] = getDirectReturnFunction([], {
  11260. functionReturn: true,
  11261. lineBreakIndent: null,
  11262. name: null
  11263. });
  11264. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  11265. `${t}${t}enumerable:${_}true,${n}` +
  11266. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  11267. }
  11268. return `exports[k]${_}=${_}${name}[k]`;
  11269. };
  11270. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  11271. const { _, cnst, n } = snippets;
  11272. const neededInteropHelpers = new Set();
  11273. const interopStatements = [];
  11274. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  11275. neededInteropHelpers.add(helper);
  11276. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  11277. };
  11278. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  11279. if (isChunk) {
  11280. for (const { imported, reexported } of [
  11281. ...(imports || []),
  11282. ...(reexports || [])
  11283. ]) {
  11284. if (imported === '*' && reexported !== '*') {
  11285. if (!namedExportsMode) {
  11286. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  11287. }
  11288. break;
  11289. }
  11290. }
  11291. }
  11292. else {
  11293. const moduleInterop = interop(importPath);
  11294. let hasDefault = false;
  11295. let hasNamespace = false;
  11296. for (const { imported, reexported } of [
  11297. ...(imports || []),
  11298. ...(reexports || [])
  11299. ]) {
  11300. let helper;
  11301. let variableName;
  11302. if (imported === 'default') {
  11303. if (!hasDefault) {
  11304. hasDefault = true;
  11305. if (defaultVariableName !== namespaceVariableName) {
  11306. variableName = defaultVariableName;
  11307. helper = defaultInteropHelpersByInteropType[moduleInterop];
  11308. }
  11309. }
  11310. }
  11311. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  11312. hasNamespace = true;
  11313. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  11314. variableName = namespaceVariableName;
  11315. }
  11316. if (helper) {
  11317. addInteropStatement(variableName, helper, name);
  11318. }
  11319. }
  11320. }
  11321. }
  11322. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  11323. }
  11324. function addJsExtension(name) {
  11325. return name.endsWith('.js') ? name : name + '.js';
  11326. }
  11327. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  11328. // The assumption is that this makes sense for all relative ids:
  11329. // https://requirejs.org/docs/api.html#jsfiles
  11330. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  11331. if (id[0] !== '.') {
  11332. return id;
  11333. }
  11334. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  11335. }
  11336. const builtinModules = [
  11337. "node:assert",
  11338. "assert",
  11339. "node:assert/strict",
  11340. "assert/strict",
  11341. "node:async_hooks",
  11342. "async_hooks",
  11343. "node:buffer",
  11344. "buffer",
  11345. "node:child_process",
  11346. "child_process",
  11347. "node:cluster",
  11348. "cluster",
  11349. "node:console",
  11350. "console",
  11351. "node:constants",
  11352. "constants",
  11353. "node:crypto",
  11354. "crypto",
  11355. "node:dgram",
  11356. "dgram",
  11357. "node:diagnostics_channel",
  11358. "diagnostics_channel",
  11359. "node:dns",
  11360. "dns",
  11361. "node:dns/promises",
  11362. "dns/promises",
  11363. "node:domain",
  11364. "domain",
  11365. "node:events",
  11366. "events",
  11367. "node:fs",
  11368. "fs",
  11369. "node:fs/promises",
  11370. "fs/promises",
  11371. "node:http",
  11372. "http",
  11373. "node:http2",
  11374. "http2",
  11375. "node:https",
  11376. "https",
  11377. "node:inspector",
  11378. "inspector",
  11379. "node:inspector/promises",
  11380. "inspector/promises",
  11381. "node:module",
  11382. "module",
  11383. "node:net",
  11384. "net",
  11385. "node:os",
  11386. "os",
  11387. "node:path",
  11388. "path",
  11389. "node:path/posix",
  11390. "path/posix",
  11391. "node:path/win32",
  11392. "path/win32",
  11393. "node:perf_hooks",
  11394. "perf_hooks",
  11395. "node:process",
  11396. "process",
  11397. "node:querystring",
  11398. "querystring",
  11399. "node:quic",
  11400. "node:readline",
  11401. "readline",
  11402. "node:readline/promises",
  11403. "readline/promises",
  11404. "node:repl",
  11405. "repl",
  11406. "node:sea",
  11407. "node:sqlite",
  11408. "node:stream",
  11409. "stream",
  11410. "node:stream/consumers",
  11411. "stream/consumers",
  11412. "node:stream/promises",
  11413. "stream/promises",
  11414. "node:stream/web",
  11415. "stream/web",
  11416. "node:string_decoder",
  11417. "string_decoder",
  11418. "node:test",
  11419. "node:test/reporters",
  11420. "node:timers",
  11421. "timers",
  11422. "node:timers/promises",
  11423. "timers/promises",
  11424. "node:tls",
  11425. "tls",
  11426. "node:trace_events",
  11427. "trace_events",
  11428. "node:tty",
  11429. "tty",
  11430. "node:url",
  11431. "url",
  11432. "node:util",
  11433. "util",
  11434. "node:util/types",
  11435. "util/types",
  11436. "node:v8",
  11437. "v8",
  11438. "node:vm",
  11439. "vm",
  11440. "node:wasi",
  11441. "wasi",
  11442. "node:worker_threads",
  11443. "worker_threads",
  11444. "node:zlib",
  11445. "zlib"
  11446. ];
  11447. const nodeBuiltins = new Set(builtinModules);
  11448. function warnOnBuiltins(log, dependencies) {
  11449. const externalBuiltins = dependencies
  11450. .map(({ importPath }) => importPath)
  11451. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  11452. if (externalBuiltins.length === 0)
  11453. return;
  11454. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNodeBuiltins(externalBuiltins));
  11455. }
  11456. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  11457. warnOnBuiltins(log, dependencies);
  11458. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  11459. const parameters = dependencies.map(m => m.name);
  11460. const { n, getNonArrowFunctionIntro, _ } = snippets;
  11461. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  11462. parameters.unshift(`exports`);
  11463. deps.unshift(`'exports'`);
  11464. }
  11465. if (accessedGlobals.has('require')) {
  11466. parameters.unshift('require');
  11467. deps.unshift(`'require'`);
  11468. }
  11469. if (accessedGlobals.has('module')) {
  11470. parameters.unshift('module');
  11471. deps.unshift(`'module'`);
  11472. }
  11473. const completeAmdId = getCompleteAmdId(amd, id);
  11474. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  11475. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  11476. const useStrict = strict ? `${_}'use strict';` : '';
  11477. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  11478. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11479. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11480. if (namespaceMarkers) {
  11481. namespaceMarkers = n + n + namespaceMarkers;
  11482. }
  11483. magicString
  11484. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11485. .indent(t)
  11486. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11487. // cf. https://v8.dev/blog/preparser#pife
  11488. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  11489. isAsync: false,
  11490. name: null
  11491. })}{${useStrict}${n}${n}`)
  11492. .append(`${n}${n}}));`);
  11493. }
  11494. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  11495. const { _, n } = snippets;
  11496. const useStrict = strict ? `'use strict';${n}${n}` : '';
  11497. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  11498. if (namespaceMarkers) {
  11499. namespaceMarkers += n + n;
  11500. }
  11501. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  11502. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  11503. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  11504. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  11505. magicString.append(`${exportBlock}${outro}`);
  11506. }
  11507. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  11508. let importBlock = '';
  11509. let definingVariable = false;
  11510. for (const { importPath, name, reexports, imports } of dependencies) {
  11511. if (!reexports && !imports) {
  11512. if (importBlock) {
  11513. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  11514. }
  11515. definingVariable = false;
  11516. importBlock += `require('${importPath}')`;
  11517. }
  11518. else {
  11519. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  11520. definingVariable = true;
  11521. importBlock += `${name}${_}=${_}require('${importPath}')`;
  11522. }
  11523. }
  11524. if (importBlock) {
  11525. return `${importBlock};${n}${n}`;
  11526. }
  11527. return '';
  11528. }
  11529. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  11530. const { n } = snippets;
  11531. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  11532. if (importBlock.length > 0)
  11533. intro += importBlock.join(n) + n + n;
  11534. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  11535. if (intro)
  11536. magicString.prepend(intro);
  11537. const exportBlock = getExportBlock(exports, snippets);
  11538. if (exportBlock.length > 0)
  11539. magicString.append(n + n + exportBlock.join(n).trim());
  11540. if (outro)
  11541. magicString.append(outro);
  11542. magicString.trim();
  11543. }
  11544. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  11545. const importBlock = [];
  11546. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  11547. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  11548. const pathWithAssertion = `'${importPath}'${assertion};`;
  11549. if (!reexports && !imports) {
  11550. importBlock.push(`import${_}${pathWithAssertion}`);
  11551. continue;
  11552. }
  11553. if (imports) {
  11554. let defaultImport = null;
  11555. let starImport = null;
  11556. const importedNames = [];
  11557. for (const specifier of imports) {
  11558. if (specifier.imported === 'default') {
  11559. defaultImport = specifier;
  11560. }
  11561. else if (specifier.imported === '*') {
  11562. starImport = specifier;
  11563. }
  11564. else {
  11565. importedNames.push(specifier);
  11566. }
  11567. }
  11568. if (starImport) {
  11569. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  11570. }
  11571. if (defaultImport && importedNames.length === 0) {
  11572. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  11573. }
  11574. else if (importedNames.length > 0) {
  11575. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  11576. .map(specifier => specifier.imported === specifier.local
  11577. ? specifier.imported
  11578. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  11579. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11580. }
  11581. }
  11582. if (reexports) {
  11583. let starExport = null;
  11584. const namespaceReexports = [];
  11585. const namedReexports = [];
  11586. for (const specifier of reexports) {
  11587. if (specifier.reexported === '*') {
  11588. starExport = specifier;
  11589. }
  11590. else if (specifier.imported === '*') {
  11591. namespaceReexports.push(specifier);
  11592. }
  11593. else {
  11594. namedReexports.push(specifier);
  11595. }
  11596. }
  11597. if (starExport) {
  11598. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  11599. }
  11600. if (namespaceReexports.length > 0) {
  11601. if (!imports ||
  11602. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  11603. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  11604. }
  11605. for (const specifier of namespaceReexports) {
  11606. importBlock.push(`export${_}{${_}${name === specifier.reexported
  11607. ? name
  11608. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  11609. }
  11610. }
  11611. if (namedReexports.length > 0) {
  11612. importBlock.push(`export${_}{${_}${namedReexports
  11613. .map(specifier => specifier.imported === specifier.reexported
  11614. ? stringifyIdentifierIfNeeded(specifier.imported)
  11615. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  11616. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  11617. }
  11618. }
  11619. }
  11620. return importBlock;
  11621. }
  11622. function getExportBlock(exports, { _, cnst }) {
  11623. const exportBlock = [];
  11624. const exportDeclaration = new Array(exports.length);
  11625. let index = 0;
  11626. for (const specifier of exports) {
  11627. if (specifier.expression) {
  11628. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  11629. }
  11630. exportDeclaration[index++] =
  11631. specifier.exported === specifier.local
  11632. ? specifier.local
  11633. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  11634. }
  11635. if (exportDeclaration.length > 0) {
  11636. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  11637. }
  11638. return exportBlock;
  11639. }
  11640. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  11641. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  11642. const parts = name.split('.');
  11643. // Check if the key exists in the object's prototype.
  11644. const isReserved = parts[0] in Object.prototype;
  11645. if (log && isReserved) {
  11646. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  11647. }
  11648. parts[0] =
  11649. (typeof globals === 'function'
  11650. ? globals(parts[0])
  11651. : isReserved
  11652. ? parts[0]
  11653. : globals[parts[0]]) || parts[0];
  11654. parts.pop();
  11655. let propertyPath = root;
  11656. return (parts
  11657. .map(part => {
  11658. propertyPath += getPropertyAccess(part);
  11659. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  11660. })
  11661. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  11662. }
  11663. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  11664. const parts = deepName.split('.');
  11665. // Check if the key exists in the object's prototype.
  11666. const isReserved = parts[0] in Object.prototype;
  11667. if (log && isReserved) {
  11668. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  11669. }
  11670. parts[0] =
  11671. (typeof globals === 'function'
  11672. ? globals(parts[0])
  11673. : isReserved
  11674. ? parts[0]
  11675. : globals[parts[0]]) || parts[0];
  11676. const last = parts.pop();
  11677. let propertyPath = root;
  11678. let deepAssignment = [
  11679. ...parts.map(part => {
  11680. propertyPath += getPropertyAccess(part);
  11681. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  11682. }),
  11683. `${propertyPath}${getPropertyAccess(last)}`
  11684. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  11685. if (parts.length > 0) {
  11686. deepAssignment = `(${deepAssignment})`;
  11687. }
  11688. return deepAssignment;
  11689. }
  11690. function trimEmptyImports(dependencies) {
  11691. let index = dependencies.length;
  11692. while (index--) {
  11693. const { imports, reexports } = dependencies[index];
  11694. if (imports || reexports) {
  11695. return dependencies.slice(0, index + 1);
  11696. }
  11697. }
  11698. return [];
  11699. }
  11700. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  11701. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  11702. const isNamespaced = name && name.includes('.');
  11703. const useVariableAssignment = !extend && !isNamespaced;
  11704. if (name && useVariableAssignment && !isLegal(name)) {
  11705. return parseAst_js.error(parseAst_js.logIllegalIdentifierAsName(name));
  11706. }
  11707. warnOnBuiltins(log, dependencies);
  11708. const external = trimEmptyImports(dependencies);
  11709. const deps = external.map(dep => dep.globalName || 'null');
  11710. const parameters = external.map(m => m.name);
  11711. if (hasExports && !name) {
  11712. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNameOptionForIifeExport());
  11713. }
  11714. if (hasExports && (namedExportsMode || exports[0]?.local === 'exports.default')) {
  11715. if (extend) {
  11716. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  11717. parameters.unshift('exports');
  11718. }
  11719. else {
  11720. deps.unshift('{}');
  11721. parameters.unshift('exports');
  11722. }
  11723. }
  11724. const useStrict = strict ? `${t}'use strict';${n}` : '';
  11725. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  11726. magicString.prepend(`${intro}${interopBlock}`);
  11727. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  11728. isAsync: false,
  11729. name: null
  11730. })}{${n}${useStrict}${n}`;
  11731. if (hasExports) {
  11732. if (name && !(extend && namedExportsMode)) {
  11733. wrapperIntro =
  11734. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  11735. `${_}=${_}${wrapperIntro}`;
  11736. }
  11737. if (isNamespaced) {
  11738. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  11739. }
  11740. }
  11741. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  11742. if (hasExports && !extend && namedExportsMode) {
  11743. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  11744. }
  11745. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  11746. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  11747. if (namespaceMarkers) {
  11748. namespaceMarkers = n + n + namespaceMarkers;
  11749. }
  11750. magicString
  11751. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  11752. .indent(t)
  11753. .prepend(wrapperIntro)
  11754. .append(wrapperOutro);
  11755. }
  11756. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11757. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  11758. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  11759. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  11760. const registeredName = name ? `'${name}',${_}` : '';
  11761. const wrapperParameters = accessedGlobals.has('module')
  11762. ? ['exports', 'module']
  11763. : hasExports
  11764. ? ['exports']
  11765. : [];
  11766. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11767. // cf. https://v8.dev/blog/preparser#pife
  11768. let wrapperStart = `System.register(${registeredName}[` +
  11769. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  11770. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  11771. isAsync: false,
  11772. name: null
  11773. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  11774. getStarExcludesBlock(starExcludes, t, snippets) +
  11775. getImportBindingsBlock(importBindings, t, snippets) +
  11776. `${n}${t}return${_}{${setters.length > 0
  11777. ? `${n}${t}${t}setters:${_}[${setters
  11778. .map(setter => setter
  11779. ? `${getFunctionIntro(['module'], {
  11780. isAsync: false,
  11781. name: null
  11782. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  11783. : systemNullSetters
  11784. ? `null`
  11785. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  11786. .join(`,${_}`)}],`
  11787. : ''}${n}`;
  11788. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  11789. isAsync: usesTopLevelAwait,
  11790. name: null
  11791. })}{${n}${n}`;
  11792. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  11793. magicString
  11794. .prepend(intro +
  11795. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  11796. getHoistedExportsBlock(exports, t, snippets))
  11797. .append(`${outro}${n}${n}` +
  11798. getSyntheticExportsBlock(exports, t, snippets) +
  11799. getMissingExportsBlock(exports, t, snippets))
  11800. .indent(`${t}${t}${t}`)
  11801. .append(wrapperEnd)
  11802. .prepend(wrapperStart);
  11803. }
  11804. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  11805. const importBindings = [];
  11806. const setters = [];
  11807. let starExcludes = null;
  11808. for (const { imports, reexports } of dependencies) {
  11809. const setter = [];
  11810. if (imports) {
  11811. for (const specifier of imports) {
  11812. importBindings.push(specifier.local);
  11813. if (specifier.imported === '*') {
  11814. setter.push(`${specifier.local}${_}=${_}module;`);
  11815. }
  11816. else {
  11817. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  11818. }
  11819. }
  11820. }
  11821. if (reexports) {
  11822. const reexportedNames = [];
  11823. let hasStarReexport = false;
  11824. for (const { imported, reexported } of reexports) {
  11825. if (reexported === '*') {
  11826. hasStarReexport = true;
  11827. }
  11828. else {
  11829. reexportedNames.push([
  11830. reexported,
  11831. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  11832. ]);
  11833. }
  11834. }
  11835. if (reexportedNames.length > 1 || hasStarReexport) {
  11836. if (hasStarReexport) {
  11837. if (!starExcludes) {
  11838. starExcludes = getStarExcludes({ dependencies, exports });
  11839. }
  11840. reexportedNames.unshift([null, `__proto__:${_}null`]);
  11841. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  11842. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  11843. }
  11844. else {
  11845. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  11846. setter.push(`exports(${exportMapping});`);
  11847. }
  11848. }
  11849. else {
  11850. const [key, value] = reexportedNames[0];
  11851. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  11852. }
  11853. }
  11854. setters.push(setter.join(`${n}${t}${t}${t}`));
  11855. }
  11856. return { importBindings, setters, starExcludes };
  11857. }
  11858. const getStarExcludes = ({ dependencies, exports }) => {
  11859. const starExcludes = new Set(exports.map(expt => expt.exported));
  11860. starExcludes.add('default');
  11861. for (const { reexports } of dependencies) {
  11862. if (reexports) {
  11863. for (const reexport of reexports) {
  11864. if (reexport.reexported !== '*')
  11865. starExcludes.add(reexport.reexported);
  11866. }
  11867. }
  11868. }
  11869. return starExcludes;
  11870. };
  11871. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  11872. if (starExcludes) {
  11873. const fields = [...starExcludes].map(property => [
  11874. property,
  11875. '1'
  11876. ]);
  11877. fields.unshift([null, `__proto__:${_}null`]);
  11878. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  11879. lineBreakIndent: { base: t, t }
  11880. })};`;
  11881. }
  11882. return '';
  11883. };
  11884. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  11885. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  11886. function getExportsBlock(exports, t, { _, n }) {
  11887. if (exports.length === 0) {
  11888. return '';
  11889. }
  11890. if (exports.length === 1) {
  11891. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  11892. }
  11893. return (`exports({${n}` +
  11894. exports
  11895. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  11896. .join(`,${n}`) +
  11897. `${n}});${n}${n}`);
  11898. }
  11899. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  11900. .filter(expt => expt.expression)
  11901. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  11902. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  11903. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  11904. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  11905. function globalProperty(name, globalVariable, getPropertyAccess) {
  11906. if (!name)
  11907. return 'null';
  11908. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  11909. }
  11910. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  11911. let propertyPath = globalVariable;
  11912. return name
  11913. .split('.')
  11914. .map(part => (propertyPath += getPropertyAccess(part)))
  11915. .join(`${_}&&${_}`);
  11916. }
  11917. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  11918. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  11919. const factoryVariable = compact ? 'f' : 'factory';
  11920. const globalVariable = compact ? 'g' : 'global';
  11921. if (hasExports && !name) {
  11922. return parseAst_js.error(parseAst_js.logMissingNameOptionForUmdExport());
  11923. }
  11924. warnOnBuiltins(log, dependencies);
  11925. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  11926. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  11927. const trimmedImports = trimEmptyImports(dependencies);
  11928. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  11929. const factoryParameters = trimmedImports.map(m => m.name);
  11930. if ((hasExports || noConflict) &&
  11931. (namedExportsMode || (hasExports && exports[0]?.local === 'exports.default'))) {
  11932. amdDeps.unshift(`'exports'`);
  11933. cjsDeps.unshift(`exports`);
  11934. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  11935. factoryParameters.unshift('exports');
  11936. }
  11937. const completeAmdId = getCompleteAmdId(amd, id);
  11938. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  11939. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  11940. const define = amd.define;
  11941. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  11942. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  11943. let iifeExport;
  11944. if (noConflict) {
  11945. const noConflictExportsVariable = compact ? 'e' : 'exports';
  11946. let factory;
  11947. if (!namedExportsMode && hasExports) {
  11948. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  11949. }
  11950. else {
  11951. const module = globalDeps.shift();
  11952. factory =
  11953. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  11954. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  11955. }
  11956. iifeExport =
  11957. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  11958. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  11959. `${t}${t}${factory}${n}` +
  11960. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  11961. isAsync: false,
  11962. name: null
  11963. })}{${_}` +
  11964. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  11965. `${t}})()`;
  11966. }
  11967. else {
  11968. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  11969. if (!namedExportsMode && hasExports) {
  11970. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  11971. }
  11972. }
  11973. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  11974. const wrapperParameters = [factoryVariable];
  11975. if (iifeNeedsGlobal) {
  11976. wrapperParameters.unshift(globalVariable);
  11977. }
  11978. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  11979. const iifeStart = iifeNeedsGlobal
  11980. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  11981. : '';
  11982. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  11983. const cjsIntro = iifeNeedsGlobal
  11984. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  11985. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  11986. : '';
  11987. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  11988. cjsIntro +
  11989. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  11990. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  11991. // factory function should be wrapped by parentheses to avoid lazy parsing,
  11992. // cf. https://v8.dev/blog/preparser#pife
  11993. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  11994. isAsync: false,
  11995. name: null
  11996. })}{${useStrict}${n}`;
  11997. const wrapperOutro = n + n + '}));';
  11998. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  11999. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  12000. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  12001. if (namespaceMarkers) {
  12002. namespaceMarkers = n + n + namespaceMarkers;
  12003. }
  12004. magicString
  12005. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  12006. .trim()
  12007. .indent(t)
  12008. .append(wrapperOutro)
  12009. .prepend(wrapperIntro);
  12010. }
  12011. const finalisers = { amd, cjs, es, iife, system, umd };
  12012. const extractors = {
  12013. ArrayPattern(names, param) {
  12014. for (const element of param.elements) {
  12015. if (element)
  12016. extractors[element.type](names, element);
  12017. }
  12018. },
  12019. AssignmentPattern(names, param) {
  12020. extractors[param.left.type](names, param.left);
  12021. },
  12022. Identifier(names, param) {
  12023. names.push(param.name);
  12024. },
  12025. MemberExpression() { },
  12026. ObjectPattern(names, param) {
  12027. for (const prop of param.properties) {
  12028. // @ts-ignore Typescript reports that this is not a valid type
  12029. if (prop.type === 'RestElement') {
  12030. extractors.RestElement(names, prop);
  12031. }
  12032. else {
  12033. extractors[prop.value.type](names, prop.value);
  12034. }
  12035. }
  12036. },
  12037. RestElement(names, param) {
  12038. extractors[param.argument.type](names, param.argument);
  12039. }
  12040. };
  12041. const extractAssignedNames = function extractAssignedNames(param) {
  12042. const names = [];
  12043. extractors[param.type](names, param);
  12044. return names;
  12045. };
  12046. // Helper since Typescript can't detect readonly arrays with Array.isArray
  12047. function isArray(arg) {
  12048. return Array.isArray(arg);
  12049. }
  12050. function ensureArray(thing) {
  12051. if (isArray(thing))
  12052. return thing;
  12053. if (thing == null)
  12054. return [];
  12055. return [thing];
  12056. }
  12057. const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
  12058. const normalizePath = function normalizePath(filename) {
  12059. return filename.replace(normalizePathRegExp, require$$0.posix.sep);
  12060. };
  12061. function getMatcherString(id, resolutionBase) {
  12062. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
  12063. return normalizePath(id);
  12064. }
  12065. // resolve('') is valid and will default to process.cwd()
  12066. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  12067. // escape all possible (posix + win) path characters that might interfere with regex
  12068. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  12069. // Note that we use posix.join because:
  12070. // 1. the basePath has been normalized to use /
  12071. // 2. the incoming glob (id) matcher, also uses /
  12072. // otherwise Node will force backslash (\) on windows
  12073. return require$$0.posix.join(basePath, normalizePath(id));
  12074. }
  12075. const createFilter = function createFilter(include, exclude, options) {
  12076. const resolutionBase = options && options.resolve;
  12077. const getMatcher = (id) => id instanceof RegExp
  12078. ? id
  12079. : {
  12080. test: (what) => {
  12081. // this refactor is a tad overly verbose but makes for easy debugging
  12082. const pattern = getMatcherString(id, resolutionBase);
  12083. const fn = pm(pattern, { dot: true });
  12084. const result = fn(what);
  12085. return result;
  12086. }
  12087. };
  12088. const includeMatchers = ensureArray(include).map(getMatcher);
  12089. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  12090. if (!includeMatchers.length && !excludeMatchers.length)
  12091. return (id) => typeof id === 'string' && !id.includes('\0');
  12092. return function result(id) {
  12093. if (typeof id !== 'string')
  12094. return false;
  12095. if (id.includes('\0'))
  12096. return false;
  12097. const pathId = normalizePath(id);
  12098. for (let i = 0; i < excludeMatchers.length; ++i) {
  12099. const matcher = excludeMatchers[i];
  12100. if (matcher instanceof RegExp) {
  12101. matcher.lastIndex = 0;
  12102. }
  12103. if (matcher.test(pathId))
  12104. return false;
  12105. }
  12106. for (let i = 0; i < includeMatchers.length; ++i) {
  12107. const matcher = includeMatchers[i];
  12108. if (matcher instanceof RegExp) {
  12109. matcher.lastIndex = 0;
  12110. }
  12111. if (matcher.test(pathId))
  12112. return true;
  12113. }
  12114. return !includeMatchers.length;
  12115. };
  12116. };
  12117. 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';
  12118. 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';
  12119. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  12120. forbiddenIdentifiers.add('');
  12121. class ArrayPattern extends NodeBase {
  12122. addExportedVariables(variables, exportNamesByVariable) {
  12123. for (const element of this.elements) {
  12124. element?.addExportedVariables(variables, exportNamesByVariable);
  12125. }
  12126. }
  12127. declare(kind, destructuredInitPath, init) {
  12128. const variables = [];
  12129. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12130. for (const element of this.elements) {
  12131. if (element !== null) {
  12132. variables.push(...element.declare(kind, includedPatternPath, init));
  12133. }
  12134. }
  12135. return variables;
  12136. }
  12137. deoptimizeAssignment(destructuredInitPath, init) {
  12138. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12139. for (const element of this.elements) {
  12140. element?.deoptimizeAssignment(includedPatternPath, init);
  12141. }
  12142. }
  12143. // Patterns can only be deoptimized at the empty path at the moment
  12144. deoptimizePath() {
  12145. for (const element of this.elements) {
  12146. element?.deoptimizePath(EMPTY_PATH);
  12147. }
  12148. }
  12149. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12150. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12151. for (const element of this.elements) {
  12152. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  12153. return true;
  12154. }
  12155. }
  12156. return false;
  12157. }
  12158. // Patterns are only checked at the empty path at the moment
  12159. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  12160. for (const element of this.elements) {
  12161. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12162. return true;
  12163. }
  12164. return false;
  12165. }
  12166. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12167. let included = false;
  12168. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  12169. for (const element of [...this.elements].reverse()) {
  12170. if (element) {
  12171. if (included && !element.included) {
  12172. element.includeNode(context);
  12173. }
  12174. included =
  12175. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  12176. }
  12177. }
  12178. if (!this.included && included) {
  12179. this.includeNode(context);
  12180. }
  12181. return this.included;
  12182. }
  12183. render(code, options) {
  12184. let removedStart = this.start + 1;
  12185. for (const element of this.elements) {
  12186. if (!element)
  12187. continue;
  12188. if (element.included) {
  12189. element.render(code, options);
  12190. removedStart = element.end;
  12191. }
  12192. else {
  12193. code.remove(removedStart, this.end - 1);
  12194. break;
  12195. }
  12196. }
  12197. }
  12198. markDeclarationReached() {
  12199. for (const element of this.elements) {
  12200. element?.markDeclarationReached();
  12201. }
  12202. }
  12203. }
  12204. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  12205. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  12206. ? destructuredInitPath
  12207. : [...destructuredInitPath, UnknownInteger];
  12208. class ArrowFunctionExpression extends FunctionBase {
  12209. constructor() {
  12210. super(...arguments);
  12211. this.objectEntity = null;
  12212. }
  12213. get expression() {
  12214. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  12215. }
  12216. set expression(value) {
  12217. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  12218. }
  12219. createScope(parentScope) {
  12220. this.scope = new ReturnValueScope(parentScope, false);
  12221. }
  12222. hasEffects() {
  12223. return false;
  12224. }
  12225. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12226. if (this.annotationNoSideEffects &&
  12227. path.length === 0 &&
  12228. interaction.type === INTERACTION_CALLED) {
  12229. return false;
  12230. }
  12231. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  12232. return true;
  12233. }
  12234. if (interaction.type === INTERACTION_CALLED) {
  12235. const { ignore, brokenFlow } = context;
  12236. context.ignore = {
  12237. breaks: false,
  12238. continues: false,
  12239. labels: new Set(),
  12240. returnYield: true,
  12241. this: false
  12242. };
  12243. if (this.body.hasEffects(context))
  12244. return true;
  12245. context.ignore = ignore;
  12246. context.brokenFlow = brokenFlow;
  12247. }
  12248. return false;
  12249. }
  12250. onlyFunctionCallUsed() {
  12251. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  12252. this.parent.callee === this;
  12253. return isIIFE || super.onlyFunctionCallUsed();
  12254. }
  12255. include(context, includeChildrenRecursively) {
  12256. super.include(context, includeChildrenRecursively);
  12257. for (const parameter of this.params) {
  12258. if (!(parameter instanceof Identifier)) {
  12259. parameter.include(context, includeChildrenRecursively);
  12260. }
  12261. }
  12262. }
  12263. includeNode(context) {
  12264. this.included = true;
  12265. this.body.includePath(UNKNOWN_PATH, context);
  12266. for (const parameter of this.params) {
  12267. if (!(parameter instanceof Identifier)) {
  12268. parameter.includePath(UNKNOWN_PATH, context);
  12269. }
  12270. }
  12271. }
  12272. getObjectEntity() {
  12273. if (this.objectEntity !== null) {
  12274. return this.objectEntity;
  12275. }
  12276. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  12277. }
  12278. }
  12279. class ObjectPattern extends NodeBase {
  12280. addExportedVariables(variables, exportNamesByVariable) {
  12281. for (const property of this.properties) {
  12282. if (property.type === parseAst_js.Property) {
  12283. property.value.addExportedVariables(variables, exportNamesByVariable);
  12284. }
  12285. else {
  12286. property.argument.addExportedVariables(variables, exportNamesByVariable);
  12287. }
  12288. }
  12289. }
  12290. declare(kind, destructuredInitPath, init) {
  12291. const variables = [];
  12292. for (const property of this.properties) {
  12293. variables.push(...property.declare(kind, destructuredInitPath, init));
  12294. }
  12295. return variables;
  12296. }
  12297. deoptimizeAssignment(destructuredInitPath, init) {
  12298. for (const property of this.properties) {
  12299. property.deoptimizeAssignment(destructuredInitPath, init);
  12300. }
  12301. }
  12302. deoptimizePath(path) {
  12303. if (path.length === 0) {
  12304. for (const property of this.properties) {
  12305. property.deoptimizePath(path);
  12306. }
  12307. }
  12308. }
  12309. hasEffectsOnInteractionAtPath(
  12310. // At the moment, this is only triggered for assignment left-hand sides,
  12311. // where the path is empty
  12312. _path, interaction, context) {
  12313. for (const property of this.properties) {
  12314. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12315. return true;
  12316. }
  12317. return false;
  12318. }
  12319. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12320. for (const property of this.properties) {
  12321. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  12322. return true;
  12323. }
  12324. return false;
  12325. }
  12326. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12327. if (!this.properties.length)
  12328. return this.included;
  12329. const lastProperty = this.properties.at(-1);
  12330. let included = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12331. const lastPropertyIsRestElement = lastProperty.type === parseAst_js.RestElement;
  12332. for (const property of this.properties.slice(0, -1)) {
  12333. if (lastPropertyIsRestElement && included && !property.included) {
  12334. property.includeNode(context);
  12335. }
  12336. included =
  12337. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  12338. }
  12339. if (!this.included && included) {
  12340. this.includeNode(context);
  12341. }
  12342. return this.included;
  12343. }
  12344. markDeclarationReached() {
  12345. for (const property of this.properties) {
  12346. property.markDeclarationReached();
  12347. }
  12348. }
  12349. render(code, options) {
  12350. if (this.properties.length > 0) {
  12351. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  12352. let lastSeparatorPos = null;
  12353. for (const { node, separator, start, end } of separatedNodes) {
  12354. if (!node.included) {
  12355. treeshakeNode(node, code, start, end);
  12356. continue;
  12357. }
  12358. lastSeparatorPos = separator;
  12359. node.render(code, options);
  12360. }
  12361. if (lastSeparatorPos) {
  12362. code.remove(lastSeparatorPos, this.end - 1);
  12363. }
  12364. }
  12365. }
  12366. }
  12367. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12368. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  12369. class AssignmentExpression extends NodeBase {
  12370. constructor() {
  12371. super(...arguments);
  12372. this.isConstReassignment = false;
  12373. }
  12374. hasEffects(context) {
  12375. const { deoptimized, isConstReassignment, left, operator, right } = this;
  12376. if (!deoptimized)
  12377. this.applyDeoptimizations();
  12378. // MemberExpressions do not access the property before assignments if the
  12379. // operator is '='.
  12380. return (isConstReassignment ||
  12381. right.hasEffects(context) ||
  12382. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  12383. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  12384. }
  12385. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12386. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  12387. }
  12388. include(context, includeChildrenRecursively) {
  12389. const { deoptimized, isConstReassignment, left, right, operator } = this;
  12390. if (!deoptimized)
  12391. this.applyDeoptimizations();
  12392. if (!this.included)
  12393. this.includeNode(context);
  12394. const hasEffectsContext = createHasEffectsContext();
  12395. if (includeChildrenRecursively ||
  12396. isConstReassignment ||
  12397. operator !== '=' ||
  12398. left.included ||
  12399. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  12400. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  12401. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  12402. }
  12403. right.include(context, includeChildrenRecursively);
  12404. }
  12405. includeNode(context) {
  12406. this.included = true;
  12407. if (!this.deoptimized)
  12408. this.applyDeoptimizations();
  12409. this.right.includePath(UNKNOWN_PATH, context);
  12410. }
  12411. initialise() {
  12412. super.initialise();
  12413. if (this.left instanceof Identifier) {
  12414. const variable = this.scope.variables.get(this.left.name);
  12415. if (variable?.kind === 'const') {
  12416. this.isConstReassignment = true;
  12417. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logConstVariableReassignError(), this.left.start);
  12418. }
  12419. }
  12420. this.left.setAssignedValue(this.right);
  12421. }
  12422. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12423. const { left, right, start, end, parent } = this;
  12424. if (left.included) {
  12425. left.render(code, options);
  12426. right.render(code, options);
  12427. }
  12428. else {
  12429. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  12430. code.remove(start, inclusionStart);
  12431. if (preventASI) {
  12432. removeLineBreaks(code, inclusionStart, right.start);
  12433. }
  12434. right.render(code, options, {
  12435. renderedParentType: renderedParentType || parent.type,
  12436. renderedSurroundingElement: renderedSurroundingElement || parent.type
  12437. });
  12438. }
  12439. if (options.format === 'system') {
  12440. if (left instanceof Identifier) {
  12441. const variable = left.variable;
  12442. const exportNames = options.exportNamesByVariable.get(variable);
  12443. if (exportNames) {
  12444. if (exportNames.length === 1) {
  12445. renderSystemExportExpression(variable, start, end, code, options);
  12446. }
  12447. else {
  12448. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== parseAst_js.ExpressionStatement, code, options);
  12449. }
  12450. return;
  12451. }
  12452. }
  12453. else {
  12454. const systemPatternExports = [];
  12455. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  12456. if (systemPatternExports.length > 0) {
  12457. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === parseAst_js.ExpressionStatement, code, options);
  12458. return;
  12459. }
  12460. }
  12461. }
  12462. if (left.included &&
  12463. left instanceof ObjectPattern &&
  12464. (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  12465. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression)) {
  12466. code.appendRight(start, '(');
  12467. code.prependLeft(end, ')');
  12468. }
  12469. }
  12470. applyDeoptimizations() {
  12471. this.deoptimized = true;
  12472. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  12473. this.scope.context.requestTreeshakingPass();
  12474. }
  12475. }
  12476. class AssignmentPattern extends NodeBase {
  12477. addExportedVariables(variables, exportNamesByVariable) {
  12478. this.left.addExportedVariables(variables, exportNamesByVariable);
  12479. }
  12480. declare(kind, destructuredInitPath, init) {
  12481. return this.left.declare(kind, destructuredInitPath, init);
  12482. }
  12483. deoptimizeAssignment(destructuredInitPath, init) {
  12484. this.left.deoptimizeAssignment(destructuredInitPath, init);
  12485. }
  12486. deoptimizePath(path) {
  12487. if (path.length === 0) {
  12488. this.left.deoptimizePath(path);
  12489. }
  12490. }
  12491. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12492. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  12493. }
  12494. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12495. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  12496. }
  12497. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12498. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  12499. this.included;
  12500. if ((included ||= this.right.shouldBeIncluded(context))) {
  12501. this.right.include(context, false);
  12502. if (!this.left.included) {
  12503. this.left.includeNode(context);
  12504. // Unfortunately, we need to include the left side again now, so that
  12505. // any declared variables are properly included.
  12506. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12507. }
  12508. }
  12509. if (!this.included && included) {
  12510. this.includeNode(context);
  12511. }
  12512. return this.included;
  12513. }
  12514. includeNode(context) {
  12515. this.included = true;
  12516. if (!this.deoptimized)
  12517. this.applyDeoptimizations();
  12518. this.right.includePath(UNKNOWN_PATH, context);
  12519. }
  12520. markDeclarationReached() {
  12521. this.left.markDeclarationReached();
  12522. }
  12523. render(code, options, { isShorthandProperty } = parseAst_js.BLANK) {
  12524. this.left.render(code, options, { isShorthandProperty });
  12525. this.right.render(code, options);
  12526. }
  12527. applyDeoptimizations() {
  12528. this.deoptimized = true;
  12529. this.left.deoptimizePath(EMPTY_PATH);
  12530. this.right.deoptimizePath(UNKNOWN_PATH);
  12531. this.scope.context.requestTreeshakingPass();
  12532. }
  12533. }
  12534. class AwaitExpression extends NodeBase {
  12535. hasEffects() {
  12536. if (!this.deoptimized)
  12537. this.applyDeoptimizations();
  12538. return true;
  12539. }
  12540. initialise() {
  12541. super.initialise();
  12542. let parent = this.parent;
  12543. do {
  12544. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  12545. return;
  12546. } while ((parent = parent.parent));
  12547. this.scope.context.usesTopLevelAwait = true;
  12548. }
  12549. include(context, includeChildrenRecursively) {
  12550. if (!this.included)
  12551. this.includeNode(context);
  12552. this.argument.include(context, includeChildrenRecursively);
  12553. }
  12554. includeNode(context) {
  12555. this.included = true;
  12556. if (!this.deoptimized)
  12557. this.applyDeoptimizations();
  12558. // Thenables need to be included
  12559. this.argument.includePath(THEN_PATH, context);
  12560. }
  12561. includePath(path, context) {
  12562. if (!this.deoptimized)
  12563. this.applyDeoptimizations();
  12564. if (!this.included)
  12565. this.includeNode(context);
  12566. this.argument.includePath(path, context);
  12567. }
  12568. }
  12569. const THEN_PATH = ['then'];
  12570. function getRenderedLiteralValue(value) {
  12571. if (value === undefined) {
  12572. return 'void 0';
  12573. }
  12574. if (typeof value === 'boolean') {
  12575. return String(value);
  12576. }
  12577. if (typeof value === 'string') {
  12578. return JSON.stringify(value);
  12579. }
  12580. if (typeof value === 'number') {
  12581. return getSimplifiedNumber(value);
  12582. }
  12583. return UnknownValue;
  12584. }
  12585. function getSimplifiedNumber(value) {
  12586. if (Object.is(-0, value)) {
  12587. return '-0';
  12588. }
  12589. const exp = value.toExponential();
  12590. const [base, exponent] = exp.split('e');
  12591. const floatLength = base.split('.')[1]?.length || 0;
  12592. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  12593. const stringifiedValue = String(value).replace('+', '');
  12594. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  12595. }
  12596. const binaryOperators = {
  12597. '!=': (left, right) => left != right,
  12598. '!==': (left, right) => left !== right,
  12599. '%': (left, right) => left % right,
  12600. '&': (left, right) => left & right,
  12601. '*': (left, right) => left * right,
  12602. // At the moment, "**" will be transpiled to Math.pow
  12603. '**': (left, right) => left ** right,
  12604. '+': (left, right) => left + right,
  12605. '-': (left, right) => left - right,
  12606. '/': (left, right) => left / right,
  12607. '<': (left, right) => left < right,
  12608. '<<': (left, right) => left << right,
  12609. '<=': (left, right) => left <= right,
  12610. '==': (left, right) => left == right,
  12611. '===': (left, right) => left === right,
  12612. '>': (left, right) => left > right,
  12613. '>=': (left, right) => left >= right,
  12614. '>>': (left, right) => left >> right,
  12615. '>>>': (left, right) => left >>> right,
  12616. '^': (left, right) => left ^ right,
  12617. '|': (left, right) => left | right
  12618. // We use the fallback for cases where we return something unknown
  12619. // in: () => UnknownValue,
  12620. // instanceof: () => UnknownValue,
  12621. };
  12622. const UNASSIGNED$1 = Symbol('Unassigned');
  12623. class BinaryExpression extends NodeBase {
  12624. constructor() {
  12625. super(...arguments);
  12626. this.renderedLiteralValue = UNASSIGNED$1;
  12627. }
  12628. deoptimizeCache() {
  12629. this.renderedLiteralValue = UnknownValue;
  12630. }
  12631. getLiteralValueAtPath(path, recursionTracker, origin) {
  12632. if (path.length > 0)
  12633. return UnknownValue;
  12634. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12635. if (typeof leftValue === 'symbol')
  12636. return UnknownValue;
  12637. // Optimize `'export' in namespace`
  12638. if (this.operator === 'in' && this.right.variable instanceof NamespaceVariable) {
  12639. const [variable] = this.right.variable.context.traceExport(String(leftValue));
  12640. if (variable instanceof ExternalVariable)
  12641. return UnknownValue;
  12642. if (variable instanceof SyntheticNamedExportVariable)
  12643. return UnknownValue;
  12644. return !!variable;
  12645. }
  12646. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12647. if (typeof rightValue === 'symbol')
  12648. return UnknownValue;
  12649. const operatorFunction = binaryOperators[this.operator];
  12650. if (!operatorFunction)
  12651. return UnknownValue;
  12652. return operatorFunction(leftValue, rightValue);
  12653. }
  12654. getRenderedLiteralValue() {
  12655. // Only optimize `'export' in ns`
  12656. if (this.operator !== 'in' || !(this.right.variable instanceof NamespaceVariable)) {
  12657. return UnknownValue;
  12658. }
  12659. if (this.renderedLiteralValue !== UNASSIGNED$1)
  12660. return this.renderedLiteralValue;
  12661. return (this.renderedLiteralValue = getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  12662. }
  12663. hasEffects(context) {
  12664. // support some implicit type coercion runtime errors
  12665. if (this.operator === '+' &&
  12666. this.parent instanceof ExpressionStatement &&
  12667. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  12668. return true;
  12669. }
  12670. return super.hasEffects(context);
  12671. }
  12672. hasEffectsOnInteractionAtPath(path, { type }) {
  12673. return type !== INTERACTION_ACCESSED || path.length > 1;
  12674. }
  12675. include(context, includeChildrenRecursively, options) {
  12676. if (!this.included)
  12677. this.includeNode(context);
  12678. if (typeof this.getRenderedLiteralValue() === 'symbol') {
  12679. this.left.include(context, includeChildrenRecursively, options);
  12680. this.right.include(context, includeChildrenRecursively, options);
  12681. }
  12682. }
  12683. includeNode(context) {
  12684. this.included = true;
  12685. if (this.operator === 'in' && typeof this.getRenderedLiteralValue() === 'symbol') {
  12686. this.right.includePath(UNKNOWN_PATH, context);
  12687. }
  12688. }
  12689. removeAnnotations(code) {
  12690. this.left.removeAnnotations(code);
  12691. }
  12692. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12693. const renderedLiteralValue = this.getRenderedLiteralValue();
  12694. if (typeof renderedLiteralValue !== 'symbol') {
  12695. code.overwrite(this.start, this.end, renderedLiteralValue);
  12696. }
  12697. else {
  12698. this.left.render(code, options, { renderedSurroundingElement });
  12699. this.right.render(code, options);
  12700. }
  12701. }
  12702. }
  12703. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12704. class BreakStatement extends NodeBase {
  12705. hasEffects(context) {
  12706. if (this.label) {
  12707. if (!context.ignore.labels.has(this.label.name))
  12708. return true;
  12709. context.includedLabels.add(this.label.name);
  12710. }
  12711. else {
  12712. if (!context.ignore.breaks)
  12713. return true;
  12714. context.hasBreak = true;
  12715. }
  12716. context.brokenFlow = true;
  12717. return false;
  12718. }
  12719. include(context, includeChildrenRecursively) {
  12720. this.included = true;
  12721. if (this.label) {
  12722. this.label.include(context, includeChildrenRecursively);
  12723. context.includedLabels.add(this.label.name);
  12724. }
  12725. else {
  12726. context.hasBreak = true;
  12727. }
  12728. context.brokenFlow = true;
  12729. }
  12730. }
  12731. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12732. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12733. function renderCallArguments(code, options, node) {
  12734. if (node.arguments.length > 0) {
  12735. if (node.arguments[node.arguments.length - 1].included) {
  12736. for (const argument of node.arguments) {
  12737. argument.render(code, options);
  12738. }
  12739. }
  12740. else {
  12741. let lastIncludedIndex = node.arguments.length - 2;
  12742. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  12743. lastIncludedIndex--;
  12744. }
  12745. if (lastIncludedIndex >= 0) {
  12746. for (let index = 0; index <= lastIncludedIndex; index++) {
  12747. node.arguments[index].render(code, options);
  12748. }
  12749. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  12750. }
  12751. else {
  12752. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  12753. }
  12754. }
  12755. }
  12756. }
  12757. class CallExpressionBase extends NodeBase {
  12758. constructor() {
  12759. super(...arguments);
  12760. this.returnExpression = null;
  12761. this.deoptimizableDependentExpressions = [];
  12762. this.expressionsToBeDeoptimized = new Set();
  12763. }
  12764. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12765. const { args } = interaction;
  12766. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  12767. if (isPure)
  12768. return;
  12769. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  12770. if (deoptimizedExpressions.length === 0)
  12771. return;
  12772. if (returnExpression === UNKNOWN_EXPRESSION) {
  12773. for (const expression of deoptimizedExpressions) {
  12774. expression.deoptimizePath(UNKNOWN_PATH);
  12775. }
  12776. }
  12777. else {
  12778. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12779. for (const expression of deoptimizedExpressions) {
  12780. this.expressionsToBeDeoptimized.add(expression);
  12781. }
  12782. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12783. }, null);
  12784. }
  12785. }
  12786. deoptimizeCache() {
  12787. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  12788. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12789. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  12790. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_SET;
  12791. this.deoptimizableDependentExpressions = parseAst_js.EMPTY_ARRAY;
  12792. for (const expression of deoptimizableDependentExpressions) {
  12793. expression.deoptimizeCache();
  12794. }
  12795. for (const expression of expressionsToBeDeoptimized) {
  12796. expression.deoptimizePath(UNKNOWN_PATH);
  12797. }
  12798. }
  12799. }
  12800. deoptimizePath(path) {
  12801. if (path.length === 0 ||
  12802. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  12803. return;
  12804. }
  12805. const [returnExpression] = this.getReturnExpression();
  12806. if (returnExpression !== UNKNOWN_EXPRESSION) {
  12807. returnExpression.deoptimizePath(path);
  12808. }
  12809. }
  12810. getLiteralValueAtPath(path, recursionTracker, origin) {
  12811. const [returnExpression] = this.getReturnExpression(recursionTracker);
  12812. if (returnExpression === UNKNOWN_EXPRESSION) {
  12813. return UnknownValue;
  12814. }
  12815. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12816. this.deoptimizableDependentExpressions.push(origin);
  12817. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  12818. }, UnknownValue);
  12819. }
  12820. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12821. const returnExpression = this.getReturnExpression(recursionTracker);
  12822. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  12823. return returnExpression;
  12824. }
  12825. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12826. this.deoptimizableDependentExpressions.push(origin);
  12827. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12828. return [expression, isPure || returnExpression[1]];
  12829. }, UNKNOWN_RETURN_EXPRESSION);
  12830. }
  12831. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12832. const { type } = interaction;
  12833. if (type === INTERACTION_CALLED) {
  12834. const { args, withNew } = interaction;
  12835. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  12836. return false;
  12837. }
  12838. }
  12839. else if ((type === INTERACTION_ASSIGNED
  12840. ? context.assigned
  12841. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  12842. return false;
  12843. }
  12844. const [returnExpression, isPure] = this.getReturnExpression();
  12845. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  12846. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  12847. }
  12848. }
  12849. class CallExpression extends CallExpressionBase {
  12850. get hasCheckedForWarnings() {
  12851. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  12852. }
  12853. set hasCheckedForWarnings(value) {
  12854. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  12855. }
  12856. get optional() {
  12857. return isFlagSet(this.flags, 128 /* Flag.optional */);
  12858. }
  12859. set optional(value) {
  12860. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  12861. }
  12862. bind() {
  12863. super.bind();
  12864. this.interaction = {
  12865. args: [
  12866. this.callee instanceof MemberExpression && !this.callee.variable
  12867. ? this.callee.object
  12868. : null,
  12869. ...this.arguments
  12870. ],
  12871. type: INTERACTION_CALLED,
  12872. withNew: false
  12873. };
  12874. }
  12875. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  12876. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  12877. }
  12878. hasEffects(context) {
  12879. if (!this.deoptimized)
  12880. this.applyDeoptimizations();
  12881. for (const argument of this.arguments) {
  12882. if (argument.hasEffects(context))
  12883. return true;
  12884. }
  12885. if (this.annotationPure) {
  12886. return false;
  12887. }
  12888. return (this.callee.hasEffects(context) ||
  12889. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12890. }
  12891. hasEffectsAsChainElement(context) {
  12892. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  12893. ? this.callee.hasEffectsAsChainElement(context)
  12894. : this.callee.hasEffects(context);
  12895. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  12896. return IS_SKIPPED_CHAIN;
  12897. if (this.optional &&
  12898. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  12899. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  12900. }
  12901. // We only apply deoptimizations lazily once we know we are not skipping
  12902. if (!this.deoptimized)
  12903. this.applyDeoptimizations();
  12904. for (const argument of this.arguments) {
  12905. if (argument.hasEffects(context))
  12906. return true;
  12907. }
  12908. return (!this.annotationPure &&
  12909. (calleeHasEffects ||
  12910. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  12911. }
  12912. include(context, includeChildrenRecursively) {
  12913. if (!this.included)
  12914. this.includeNode(context);
  12915. if (includeChildrenRecursively) {
  12916. super.include(context, true);
  12917. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  12918. this.callee instanceof Identifier &&
  12919. this.callee.variable) {
  12920. this.callee.variable.markCalledFromTryStatement();
  12921. }
  12922. }
  12923. else {
  12924. this.callee.include(context, false);
  12925. this.callee.includeCallArguments(this.interaction, context);
  12926. }
  12927. }
  12928. includeNode(context) {
  12929. this.included = true;
  12930. if (!this.deoptimized)
  12931. this.applyDeoptimizations();
  12932. this.callee.includePath(UNKNOWN_PATH, context);
  12933. }
  12934. initialise() {
  12935. super.initialise();
  12936. if (this.annotations &&
  12937. this.scope.context.options.treeshake.annotations) {
  12938. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  12939. }
  12940. }
  12941. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12942. this.callee.render(code, options, {
  12943. isCalleeOfRenderedParent: true,
  12944. renderedSurroundingElement
  12945. });
  12946. renderCallArguments(code, options, this);
  12947. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  12948. this.hasCheckedForWarnings = true;
  12949. const variable = this.scope.findVariable(this.callee.name);
  12950. if (variable.isNamespace) {
  12951. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(this.callee.name), this.start);
  12952. }
  12953. if (this.callee.name === 'eval') {
  12954. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEval(this.scope.context.module.id), this.start);
  12955. }
  12956. }
  12957. }
  12958. applyDeoptimizations() {
  12959. this.deoptimized = true;
  12960. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12961. this.scope.context.requestTreeshakingPass();
  12962. }
  12963. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  12964. if (this.returnExpression === null) {
  12965. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12966. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  12967. }
  12968. return this.returnExpression;
  12969. }
  12970. }
  12971. class CatchClause extends NodeBase {
  12972. createScope(parentScope) {
  12973. this.scope = new ParameterScope(parentScope, true);
  12974. }
  12975. parseNode(esTreeNode) {
  12976. const { body, param, type } = esTreeNode;
  12977. this.type = type;
  12978. if (param) {
  12979. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  12980. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  12981. }
  12982. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  12983. return super.parseNode(esTreeNode);
  12984. }
  12985. }
  12986. CatchClause.prototype.preventChildBlockScope = true;
  12987. CatchClause.prototype.includeNode = onlyIncludeSelf;
  12988. class ChainExpression extends NodeBase {
  12989. // deoptimizations are not relevant as we are not caching values
  12990. deoptimizeCache() { }
  12991. getLiteralValueAtPath(path, recursionTracker, origin) {
  12992. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  12993. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  12994. }
  12995. hasEffects(context) {
  12996. return this.expression.hasEffectsAsChainElement(context) === true;
  12997. }
  12998. includePath(path, context) {
  12999. this.included = true;
  13000. this.expression.includePath(path, context);
  13001. }
  13002. removeAnnotations(code) {
  13003. this.expression.removeAnnotations(code);
  13004. }
  13005. }
  13006. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13007. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13008. class ClassBodyScope extends ChildScope {
  13009. constructor(parent, classNode) {
  13010. const { context } = parent;
  13011. super(parent, context);
  13012. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  13013. this.instanceScope = new ChildScope(this, context);
  13014. this.instanceScope.variables.set('this', new ThisVariable(context));
  13015. }
  13016. findLexicalBoundary() {
  13017. return this;
  13018. }
  13019. }
  13020. class ClassBody extends NodeBase {
  13021. createScope(parentScope) {
  13022. this.scope = new ClassBodyScope(parentScope, this.parent);
  13023. }
  13024. include(context, includeChildrenRecursively) {
  13025. this.included = true;
  13026. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  13027. for (const definition of this.body) {
  13028. definition.include(context, includeChildrenRecursively);
  13029. }
  13030. }
  13031. parseNode(esTreeNode) {
  13032. const body = (this.body = new Array(esTreeNode.body.length));
  13033. let index = 0;
  13034. for (const definition of esTreeNode.body) {
  13035. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  13036. }
  13037. return super.parseNode(esTreeNode);
  13038. }
  13039. }
  13040. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13041. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  13042. class ClassExpression extends ClassNode {
  13043. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13044. super.render(code, options);
  13045. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13046. code.appendRight(this.start, '(');
  13047. code.prependLeft(this.end, ')');
  13048. }
  13049. }
  13050. }
  13051. function tryCastLiteralValueToBoolean(literalValue) {
  13052. if (typeof literalValue === 'symbol') {
  13053. if (literalValue === UnknownFalsyValue) {
  13054. return false;
  13055. }
  13056. if (literalValue === UnknownTruthyValue) {
  13057. return true;
  13058. }
  13059. return UnknownValue;
  13060. }
  13061. return !!literalValue;
  13062. }
  13063. class MultiExpression extends ExpressionEntity {
  13064. constructor(expressions) {
  13065. super();
  13066. this.expressions = expressions;
  13067. }
  13068. deoptimizePath(path) {
  13069. for (const expression of this.expressions) {
  13070. expression.deoptimizePath(path);
  13071. }
  13072. }
  13073. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13074. return [
  13075. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  13076. false
  13077. ];
  13078. }
  13079. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13080. for (const expression of this.expressions) {
  13081. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  13082. return true;
  13083. }
  13084. return false;
  13085. }
  13086. }
  13087. class ConditionalExpression extends NodeBase {
  13088. constructor() {
  13089. super(...arguments);
  13090. this.expressionsToBeDeoptimized = [];
  13091. this.usedBranch = null;
  13092. }
  13093. get isBranchResolutionAnalysed() {
  13094. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13095. }
  13096. set isBranchResolutionAnalysed(value) {
  13097. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13098. }
  13099. get hasDeoptimizedCache() {
  13100. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13101. }
  13102. set hasDeoptimizedCache(value) {
  13103. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13104. }
  13105. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13106. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13107. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13108. }
  13109. deoptimizeCache() {
  13110. if (this.hasDeoptimizedCache)
  13111. return;
  13112. this.hasDeoptimizedCache = true;
  13113. if (this.usedBranch !== null) {
  13114. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  13115. this.usedBranch = null;
  13116. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13117. if (this.included) {
  13118. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13119. }
  13120. const { expressionsToBeDeoptimized } = this;
  13121. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  13122. for (const expression of expressionsToBeDeoptimized) {
  13123. expression.deoptimizeCache();
  13124. }
  13125. }
  13126. }
  13127. deoptimizePath(path) {
  13128. const usedBranch = this.getUsedBranch();
  13129. if (usedBranch) {
  13130. usedBranch.deoptimizePath(path);
  13131. }
  13132. else {
  13133. this.consequent.deoptimizePath(path);
  13134. this.alternate.deoptimizePath(path);
  13135. }
  13136. }
  13137. getLiteralValueAtPath(path, recursionTracker, origin) {
  13138. const usedBranch = this.getUsedBranch();
  13139. if (!usedBranch) {
  13140. if (this.hasDeoptimizedCache) {
  13141. return UnknownValue;
  13142. }
  13143. const consequentValue = this.consequent.getLiteralValueAtPath(path, recursionTracker, origin);
  13144. const castedConsequentValue = tryCastLiteralValueToBoolean(consequentValue);
  13145. if (castedConsequentValue === UnknownValue)
  13146. return UnknownValue;
  13147. const alternateValue = this.alternate.getLiteralValueAtPath(path, recursionTracker, origin);
  13148. const castedAlternateValue = tryCastLiteralValueToBoolean(alternateValue);
  13149. if (castedConsequentValue !== castedAlternateValue)
  13150. return UnknownValue;
  13151. this.expressionsToBeDeoptimized.push(origin);
  13152. if (consequentValue !== alternateValue)
  13153. return castedConsequentValue ? UnknownTruthyValue : UnknownFalsyValue;
  13154. return consequentValue;
  13155. }
  13156. this.expressionsToBeDeoptimized.push(origin);
  13157. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13158. }
  13159. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13160. const usedBranch = this.getUsedBranch();
  13161. if (!usedBranch)
  13162. return [
  13163. new MultiExpression([
  13164. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13165. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13166. ]),
  13167. false
  13168. ];
  13169. this.expressionsToBeDeoptimized.push(origin);
  13170. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13171. }
  13172. hasEffects(context) {
  13173. if (this.test.hasEffects(context))
  13174. return true;
  13175. const usedBranch = this.getUsedBranch();
  13176. if (!usedBranch) {
  13177. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  13178. }
  13179. return usedBranch.hasEffects(context);
  13180. }
  13181. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13182. const usedBranch = this.getUsedBranch();
  13183. if (!usedBranch) {
  13184. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13185. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  13186. }
  13187. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13188. }
  13189. include(context, includeChildrenRecursively) {
  13190. this.included = true;
  13191. const usedBranch = this.getUsedBranch();
  13192. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  13193. this.test.include(context, includeChildrenRecursively);
  13194. this.consequent.include(context, includeChildrenRecursively);
  13195. this.alternate.include(context, includeChildrenRecursively);
  13196. }
  13197. else {
  13198. usedBranch.include(context, includeChildrenRecursively);
  13199. }
  13200. }
  13201. includePath(path, context) {
  13202. this.included = true;
  13203. const usedBranch = this.getUsedBranch();
  13204. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  13205. this.consequent.includePath(path, context);
  13206. this.alternate.includePath(path, context);
  13207. }
  13208. else {
  13209. usedBranch.includePath(path, context);
  13210. }
  13211. }
  13212. includeCallArguments(interaction, context) {
  13213. const usedBranch = this.getUsedBranch();
  13214. if (usedBranch) {
  13215. usedBranch.includeCallArguments(interaction, context);
  13216. }
  13217. else {
  13218. this.consequent.includeCallArguments(interaction, context);
  13219. this.alternate.includeCallArguments(interaction, context);
  13220. }
  13221. }
  13222. removeAnnotations(code) {
  13223. this.test.removeAnnotations(code);
  13224. }
  13225. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  13226. if (this.test.included) {
  13227. this.test.render(code, options, { renderedSurroundingElement });
  13228. this.consequent.render(code, options);
  13229. this.alternate.render(code, options);
  13230. }
  13231. else {
  13232. const usedBranch = this.getUsedBranch();
  13233. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  13234. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  13235. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  13236. : colonPos) + 1);
  13237. if (preventASI) {
  13238. removeLineBreaks(code, inclusionStart, usedBranch.start);
  13239. }
  13240. code.remove(this.start, inclusionStart);
  13241. if (this.consequent.included) {
  13242. code.remove(colonPos, this.end);
  13243. }
  13244. this.test.removeAnnotations(code);
  13245. usedBranch.render(code, options, {
  13246. isCalleeOfRenderedParent,
  13247. preventASI: true,
  13248. renderedParentType: renderedParentType || this.parent.type,
  13249. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13250. });
  13251. }
  13252. }
  13253. getUsedBranch() {
  13254. if (this.isBranchResolutionAnalysed) {
  13255. return this.usedBranch;
  13256. }
  13257. this.isBranchResolutionAnalysed = true;
  13258. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  13259. return typeof testValue === 'symbol'
  13260. ? null
  13261. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  13262. }
  13263. }
  13264. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13265. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13266. class ContinueStatement extends NodeBase {
  13267. hasEffects(context) {
  13268. if (this.label) {
  13269. if (!context.ignore.labels.has(this.label.name))
  13270. return true;
  13271. context.includedLabels.add(this.label.name);
  13272. }
  13273. else {
  13274. if (!context.ignore.continues)
  13275. return true;
  13276. context.hasContinue = true;
  13277. }
  13278. context.brokenFlow = true;
  13279. return false;
  13280. }
  13281. include(context, includeChildrenRecursively) {
  13282. this.included = true;
  13283. if (this.label) {
  13284. this.label.include(context, includeChildrenRecursively);
  13285. context.includedLabels.add(this.label.name);
  13286. }
  13287. else {
  13288. context.hasContinue = true;
  13289. }
  13290. context.brokenFlow = true;
  13291. }
  13292. }
  13293. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13294. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13295. class DebuggerStatement extends NodeBase {
  13296. hasEffects() {
  13297. return true;
  13298. }
  13299. }
  13300. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  13301. class Decorator extends NodeBase {
  13302. hasEffects(context) {
  13303. return (this.expression.hasEffects(context) ||
  13304. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  13305. }
  13306. }
  13307. Decorator.prototype.includeNode = onlyIncludeSelf;
  13308. function hasLoopBodyEffects(context, body) {
  13309. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  13310. const { breaks, continues } = ignore;
  13311. ignore.breaks = true;
  13312. ignore.continues = true;
  13313. context.hasBreak = false;
  13314. context.hasContinue = false;
  13315. if (body.hasEffects(context))
  13316. return true;
  13317. ignore.breaks = breaks;
  13318. ignore.continues = continues;
  13319. context.hasBreak = hasBreak;
  13320. context.hasContinue = hasContinue;
  13321. context.brokenFlow = brokenFlow;
  13322. return false;
  13323. }
  13324. function includeLoopBody(context, body, includeChildrenRecursively) {
  13325. const { brokenFlow, hasBreak, hasContinue } = context;
  13326. context.hasBreak = false;
  13327. context.hasContinue = false;
  13328. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  13329. context.hasBreak = hasBreak;
  13330. context.hasContinue = hasContinue;
  13331. context.brokenFlow = brokenFlow;
  13332. }
  13333. class DoWhileStatement extends NodeBase {
  13334. hasEffects(context) {
  13335. if (this.test.hasEffects(context))
  13336. return true;
  13337. return hasLoopBodyEffects(context, this.body);
  13338. }
  13339. include(context, includeChildrenRecursively) {
  13340. this.included = true;
  13341. this.test.include(context, includeChildrenRecursively);
  13342. includeLoopBody(context, this.body, includeChildrenRecursively);
  13343. }
  13344. }
  13345. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13346. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13347. class EmptyStatement extends NodeBase {
  13348. hasEffects() {
  13349. return false;
  13350. }
  13351. }
  13352. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  13353. class ExportAllDeclaration extends NodeBase {
  13354. hasEffects() {
  13355. return false;
  13356. }
  13357. initialise() {
  13358. super.initialise();
  13359. this.scope.context.addExport(this);
  13360. }
  13361. render(code, _options, nodeRenderOptions) {
  13362. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13363. }
  13364. }
  13365. ExportAllDeclaration.prototype.needsBoundaries = true;
  13366. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13367. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13368. class ExportNamedDeclaration extends NodeBase {
  13369. bind() {
  13370. // Do not bind specifiers
  13371. this.declaration?.bind();
  13372. }
  13373. hasEffects(context) {
  13374. return !!this.declaration?.hasEffects(context);
  13375. }
  13376. initialise() {
  13377. super.initialise();
  13378. this.scope.context.addExport(this);
  13379. }
  13380. removeAnnotations(code) {
  13381. this.declaration?.removeAnnotations(code);
  13382. }
  13383. render(code, options, nodeRenderOptions) {
  13384. const { start, end } = nodeRenderOptions;
  13385. if (this.declaration === null) {
  13386. code.remove(start, end);
  13387. }
  13388. else {
  13389. let endBoundary = this.declaration.start;
  13390. // the start of the decorator may be before the start of the class declaration
  13391. if (this.declaration instanceof ClassDeclaration) {
  13392. const decorators = this.declaration.decorators;
  13393. for (const decorator of decorators) {
  13394. endBoundary = Math.min(endBoundary, decorator.start);
  13395. }
  13396. if (endBoundary <= this.start) {
  13397. endBoundary = this.declaration.start;
  13398. }
  13399. }
  13400. code.remove(this.start, endBoundary);
  13401. this.declaration.render(code, options, { end, start });
  13402. }
  13403. }
  13404. }
  13405. ExportNamedDeclaration.prototype.needsBoundaries = true;
  13406. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13407. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13408. class ExportSpecifier extends NodeBase {
  13409. }
  13410. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13411. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13412. class ForInStatement extends NodeBase {
  13413. createScope(parentScope) {
  13414. this.scope = new BlockScope(parentScope);
  13415. }
  13416. hasEffects(context) {
  13417. const { body, deoptimized, left, right } = this;
  13418. if (!deoptimized)
  13419. this.applyDeoptimizations();
  13420. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  13421. return true;
  13422. return hasLoopBodyEffects(context, body);
  13423. }
  13424. include(context, includeChildrenRecursively) {
  13425. const { body, deoptimized, left, right } = this;
  13426. if (!deoptimized)
  13427. this.applyDeoptimizations();
  13428. if (!this.included)
  13429. this.includeNode(context);
  13430. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13431. right.include(context, includeChildrenRecursively);
  13432. includeLoopBody(context, body, includeChildrenRecursively);
  13433. }
  13434. includeNode(context) {
  13435. this.included = true;
  13436. if (!this.deoptimized)
  13437. this.applyDeoptimizations();
  13438. this.right.includePath(UNKNOWN_PATH, context);
  13439. }
  13440. initialise() {
  13441. super.initialise();
  13442. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13443. }
  13444. render(code, options) {
  13445. this.left.render(code, options, NO_SEMICOLON);
  13446. this.right.render(code, options, NO_SEMICOLON);
  13447. // handle no space between "in" and the right side
  13448. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  13449. code.prependLeft(this.right.start, ' ');
  13450. }
  13451. this.body.render(code, options);
  13452. }
  13453. applyDeoptimizations() {
  13454. this.deoptimized = true;
  13455. this.left.deoptimizePath(EMPTY_PATH);
  13456. this.scope.context.requestTreeshakingPass();
  13457. }
  13458. }
  13459. class ForOfStatement extends NodeBase {
  13460. get await() {
  13461. return isFlagSet(this.flags, 131072 /* Flag.await */);
  13462. }
  13463. set await(value) {
  13464. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  13465. }
  13466. createScope(parentScope) {
  13467. this.scope = new BlockScope(parentScope);
  13468. }
  13469. hasEffects() {
  13470. if (!this.deoptimized)
  13471. this.applyDeoptimizations();
  13472. // Placeholder until proper Symbol.Iterator support
  13473. return true;
  13474. }
  13475. include(context, includeChildrenRecursively) {
  13476. const { body, deoptimized, left, right } = this;
  13477. if (!deoptimized)
  13478. this.applyDeoptimizations();
  13479. if (!this.included)
  13480. this.includeNode(context);
  13481. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13482. right.include(context, includeChildrenRecursively);
  13483. includeLoopBody(context, body, includeChildrenRecursively);
  13484. }
  13485. includeNode(context) {
  13486. this.included = true;
  13487. if (!this.deoptimized)
  13488. this.applyDeoptimizations();
  13489. this.right.includePath(UNKNOWN_PATH, context);
  13490. }
  13491. initialise() {
  13492. super.initialise();
  13493. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13494. }
  13495. render(code, options) {
  13496. this.left.render(code, options, NO_SEMICOLON);
  13497. this.right.render(code, options, NO_SEMICOLON);
  13498. // handle no space between "of" and the right side
  13499. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  13500. code.prependLeft(this.right.start, ' ');
  13501. }
  13502. this.body.render(code, options);
  13503. }
  13504. applyDeoptimizations() {
  13505. this.deoptimized = true;
  13506. this.left.deoptimizePath(EMPTY_PATH);
  13507. this.right.deoptimizePath(UNKNOWN_PATH);
  13508. this.scope.context.requestTreeshakingPass();
  13509. }
  13510. }
  13511. class ForStatement extends NodeBase {
  13512. createScope(parentScope) {
  13513. this.scope = new BlockScope(parentScope);
  13514. }
  13515. hasEffects(context) {
  13516. if (this.init?.hasEffects(context) ||
  13517. this.test?.hasEffects(context) ||
  13518. this.update?.hasEffects(context)) {
  13519. return true;
  13520. }
  13521. return hasLoopBodyEffects(context, this.body);
  13522. }
  13523. include(context, includeChildrenRecursively) {
  13524. this.included = true;
  13525. this.init?.include(context, includeChildrenRecursively, {
  13526. asSingleStatement: true
  13527. });
  13528. this.test?.include(context, includeChildrenRecursively);
  13529. this.update?.include(context, includeChildrenRecursively);
  13530. includeLoopBody(context, this.body, includeChildrenRecursively);
  13531. }
  13532. render(code, options) {
  13533. this.init?.render(code, options, NO_SEMICOLON);
  13534. this.test?.render(code, options, NO_SEMICOLON);
  13535. this.update?.render(code, options, NO_SEMICOLON);
  13536. this.body.render(code, options);
  13537. }
  13538. }
  13539. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13540. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13541. class FunctionExpression extends FunctionNode {
  13542. createScope(parentScope) {
  13543. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  13544. }
  13545. parseNode(esTreeNode) {
  13546. if (esTreeNode.id !== null) {
  13547. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  13548. }
  13549. return super.parseNode(esTreeNode);
  13550. }
  13551. onlyFunctionCallUsed() {
  13552. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  13553. this.parent.callee === this &&
  13554. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  13555. return isIIFE || super.onlyFunctionCallUsed();
  13556. }
  13557. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13558. super.render(code, options);
  13559. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13560. code.appendRight(this.start, '(');
  13561. code.prependLeft(this.end, ')');
  13562. }
  13563. }
  13564. }
  13565. class TrackingScope extends BlockScope {
  13566. constructor() {
  13567. super(...arguments);
  13568. this.hoistedDeclarations = [];
  13569. }
  13570. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13571. this.hoistedDeclarations.push(identifier);
  13572. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13573. }
  13574. }
  13575. const unset = Symbol('unset');
  13576. class IfStatement extends NodeBase {
  13577. constructor() {
  13578. super(...arguments);
  13579. this.testValue = unset;
  13580. }
  13581. deoptimizeCache() {
  13582. this.testValue = UnknownValue;
  13583. }
  13584. hasEffects(context) {
  13585. if (this.test.hasEffects(context)) {
  13586. return true;
  13587. }
  13588. const testValue = this.getTestValue();
  13589. if (typeof testValue === 'symbol') {
  13590. const { brokenFlow } = context;
  13591. if (this.consequent.hasEffects(context))
  13592. return true;
  13593. const consequentBrokenFlow = context.brokenFlow;
  13594. context.brokenFlow = brokenFlow;
  13595. if (this.alternate === null)
  13596. return false;
  13597. if (this.alternate.hasEffects(context))
  13598. return true;
  13599. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13600. return false;
  13601. }
  13602. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  13603. }
  13604. include(context, includeChildrenRecursively) {
  13605. this.included = true;
  13606. if (includeChildrenRecursively) {
  13607. this.includeRecursively(includeChildrenRecursively, context);
  13608. }
  13609. else {
  13610. const testValue = this.getTestValue();
  13611. if (typeof testValue === 'symbol') {
  13612. this.includeUnknownTest(context);
  13613. }
  13614. else {
  13615. this.includeKnownTest(context, testValue);
  13616. }
  13617. }
  13618. }
  13619. parseNode(esTreeNode) {
  13620. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  13621. if (esTreeNode.alternate) {
  13622. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  13623. }
  13624. return super.parseNode(esTreeNode);
  13625. }
  13626. render(code, options) {
  13627. const { snippets: { getPropertyAccess } } = options;
  13628. // Note that unknown test values are always included
  13629. const testValue = this.getTestValue();
  13630. const hoistedDeclarations = [];
  13631. const includesIfElse = this.test.included;
  13632. const noTreeshake = !this.scope.context.options.treeshake;
  13633. if (includesIfElse) {
  13634. this.test.render(code, options);
  13635. }
  13636. else {
  13637. code.remove(this.start, this.consequent.start);
  13638. }
  13639. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  13640. this.consequent.render(code, options);
  13641. }
  13642. else {
  13643. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  13644. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  13645. }
  13646. if (this.alternate) {
  13647. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  13648. if (includesIfElse) {
  13649. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  13650. code.prependLeft(this.alternate.start, ' ');
  13651. }
  13652. }
  13653. else {
  13654. code.remove(this.consequent.end, this.alternate.start);
  13655. }
  13656. this.alternate.render(code, options);
  13657. }
  13658. else {
  13659. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  13660. code.overwrite(this.alternate.start, this.end, ';');
  13661. }
  13662. else {
  13663. code.remove(this.consequent.end, this.end);
  13664. }
  13665. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  13666. }
  13667. }
  13668. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  13669. }
  13670. getTestValue() {
  13671. if (this.testValue === unset) {
  13672. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  13673. }
  13674. return this.testValue;
  13675. }
  13676. includeKnownTest(context, testValue) {
  13677. if (this.test.shouldBeIncluded(context)) {
  13678. this.test.include(context, false);
  13679. }
  13680. if (testValue && this.consequent.shouldBeIncluded(context)) {
  13681. this.consequent.include(context, false, { asSingleStatement: true });
  13682. }
  13683. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  13684. this.alternate.include(context, false, { asSingleStatement: true });
  13685. }
  13686. }
  13687. includeRecursively(includeChildrenRecursively, context) {
  13688. this.test.include(context, includeChildrenRecursively);
  13689. this.consequent.include(context, includeChildrenRecursively);
  13690. this.alternate?.include(context, includeChildrenRecursively);
  13691. }
  13692. includeUnknownTest(context) {
  13693. this.test.include(context, false);
  13694. const { brokenFlow } = context;
  13695. let consequentBrokenFlow = false;
  13696. if (this.consequent.shouldBeIncluded(context)) {
  13697. this.consequent.include(context, false, { asSingleStatement: true });
  13698. consequentBrokenFlow = context.brokenFlow;
  13699. context.brokenFlow = brokenFlow;
  13700. }
  13701. if (this.alternate?.shouldBeIncluded(context)) {
  13702. this.alternate.include(context, false, { asSingleStatement: true });
  13703. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13704. }
  13705. }
  13706. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  13707. const hoistedVariables = [
  13708. ...new Set(hoistedDeclarations.map(identifier => {
  13709. const variable = identifier.variable;
  13710. return variable.included ? variable.getName(getPropertyAccess) : '';
  13711. }))
  13712. ]
  13713. .filter(Boolean)
  13714. .join(', ');
  13715. if (hoistedVariables) {
  13716. const parentType = this.parent.type;
  13717. const needsBraces = parentType !== parseAst_js.Program && parentType !== parseAst_js.BlockStatement;
  13718. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  13719. if (needsBraces) {
  13720. code.appendLeft(this.end, ` }`);
  13721. }
  13722. }
  13723. }
  13724. shouldKeepAlternateBranch() {
  13725. let currentParent = this.parent;
  13726. do {
  13727. if (currentParent instanceof IfStatement && currentParent.alternate) {
  13728. return true;
  13729. }
  13730. if (currentParent instanceof BlockStatement) {
  13731. return false;
  13732. }
  13733. currentParent = currentParent.parent;
  13734. } while (currentParent);
  13735. return false;
  13736. }
  13737. }
  13738. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13739. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13740. class ImportAttribute extends NodeBase {
  13741. }
  13742. class ImportDeclaration extends NodeBase {
  13743. // Do not bind specifiers or attributes
  13744. bind() { }
  13745. hasEffects() {
  13746. return false;
  13747. }
  13748. initialise() {
  13749. super.initialise();
  13750. this.scope.context.addImport(this);
  13751. }
  13752. render(code, _options, nodeRenderOptions) {
  13753. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13754. }
  13755. }
  13756. ImportDeclaration.prototype.needsBoundaries = true;
  13757. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13758. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13759. class ImportDefaultSpecifier extends NodeBase {
  13760. }
  13761. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13762. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13763. function isReassignedExportsMember(variable, exportNamesByVariable) {
  13764. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  13765. }
  13766. class VariableDeclarator extends NodeBase {
  13767. declareDeclarator(kind, isUsingDeclaration) {
  13768. this.isUsingDeclaration = isUsingDeclaration;
  13769. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  13770. }
  13771. deoptimizePath(path) {
  13772. this.id.deoptimizePath(path);
  13773. }
  13774. hasEffects(context) {
  13775. const initEffect = this.init?.hasEffects(context);
  13776. this.id.markDeclarationReached();
  13777. return (initEffect ||
  13778. this.isUsingDeclaration ||
  13779. this.id.hasEffects(context) ||
  13780. (this.scope.context.options.treeshake
  13781. .propertyReadSideEffects &&
  13782. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  13783. }
  13784. include(context, includeChildrenRecursively) {
  13785. const { id, init } = this;
  13786. if (!this.included)
  13787. this.includeNode();
  13788. init?.include(context, includeChildrenRecursively);
  13789. id.markDeclarationReached();
  13790. if (includeChildrenRecursively) {
  13791. id.include(context, includeChildrenRecursively);
  13792. }
  13793. else {
  13794. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  13795. }
  13796. }
  13797. removeAnnotations(code) {
  13798. this.init?.removeAnnotations(code);
  13799. }
  13800. render(code, options) {
  13801. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  13802. const { end, id, init, start } = this;
  13803. const renderId = id.included || this.isUsingDeclaration;
  13804. if (renderId) {
  13805. id.render(code, options);
  13806. }
  13807. else {
  13808. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  13809. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  13810. }
  13811. if (init) {
  13812. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13813. const renderedVariable = id.variable.getName(getPropertyAccess);
  13814. if (renderedVariable !== id.name) {
  13815. code.appendLeft(init.start + 5, ` ${id.name}`);
  13816. }
  13817. }
  13818. init.render(code, options, renderId ? parseAst_js.BLANK : { renderedSurroundingElement: parseAst_js.ExpressionStatement });
  13819. }
  13820. else if (id instanceof Identifier &&
  13821. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  13822. code.appendLeft(end, `${_}=${_}void 0`);
  13823. }
  13824. }
  13825. includeNode() {
  13826. this.included = true;
  13827. const { id, init } = this;
  13828. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13829. const { name, variable } = id;
  13830. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  13831. if (accessedVariable !== variable) {
  13832. accessedVariable.forbidName(name);
  13833. }
  13834. }
  13835. }
  13836. }
  13837. }
  13838. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  13839. function getChunkInfoWithPath(chunk) {
  13840. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  13841. }
  13842. class ImportExpression extends NodeBase {
  13843. constructor() {
  13844. super(...arguments);
  13845. this.inlineNamespace = null;
  13846. this.hasUnknownAccessedKey = false;
  13847. this.accessedPropKey = new Set();
  13848. this.attributes = null;
  13849. this.mechanism = null;
  13850. this.namespaceExportName = undefined;
  13851. this.resolution = null;
  13852. this.resolutionString = null;
  13853. }
  13854. get shouldIncludeDynamicAttributes() {
  13855. return isFlagSet(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */);
  13856. }
  13857. set shouldIncludeDynamicAttributes(value) {
  13858. this.flags = setFlag(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */, value);
  13859. }
  13860. bind() {
  13861. this.source.bind();
  13862. this.options?.bind();
  13863. }
  13864. /**
  13865. * Get imported variables for deterministic usage, valid cases are:
  13866. *
  13867. * 1. `const { foo } = await import('bar')`.
  13868. * 2. `(await import('bar')).foo`
  13869. * 3. `import('bar').then(({ foo }) => {})`
  13870. *
  13871. * Returns empty array if it's side-effect only import.
  13872. * Returns undefined if it's not fully deterministic.
  13873. */
  13874. getDeterministicImportedNames() {
  13875. const parent1 = this.parent;
  13876. // Side-effect only: import('bar')
  13877. if (parent1 instanceof ExpressionStatement) {
  13878. return parseAst_js.EMPTY_ARRAY;
  13879. }
  13880. if (parent1 instanceof AwaitExpression) {
  13881. const parent2 = parent1.parent;
  13882. // Side effect only: await import('bar')
  13883. if (parent2 instanceof ExpressionStatement) {
  13884. return parseAst_js.EMPTY_ARRAY;
  13885. }
  13886. // Case 1: const { foo } / module = await import('bar')
  13887. if (parent2 instanceof VariableDeclarator) {
  13888. const declaration = parent2.id;
  13889. if (declaration instanceof Identifier) {
  13890. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  13891. }
  13892. if (declaration instanceof ObjectPattern) {
  13893. return getDeterministicObjectDestructure(declaration);
  13894. }
  13895. }
  13896. // Case 2: (await import('bar')).foo
  13897. if (parent2 instanceof MemberExpression) {
  13898. const id = parent2.property;
  13899. if (!parent2.computed && id instanceof Identifier) {
  13900. return [id.name];
  13901. }
  13902. }
  13903. return;
  13904. }
  13905. if (parent1 instanceof MemberExpression) {
  13906. const callExpression = parent1.parent;
  13907. const property = parent1.property;
  13908. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  13909. return;
  13910. }
  13911. const memberName = property.name;
  13912. // side-effect only, when only chaining .catch or .finally
  13913. if (callExpression.parent instanceof ExpressionStatement &&
  13914. ['catch', 'finally'].includes(memberName)) {
  13915. return parseAst_js.EMPTY_ARRAY;
  13916. }
  13917. if (memberName !== 'then')
  13918. return;
  13919. // Side-effect only: import('bar').then()
  13920. if (callExpression.arguments.length === 0) {
  13921. return parseAst_js.EMPTY_ARRAY;
  13922. }
  13923. const thenCallback = callExpression.arguments[0];
  13924. if (callExpression.arguments.length !== 1 ||
  13925. !(thenCallback instanceof ArrowFunctionExpression ||
  13926. thenCallback instanceof FunctionExpression)) {
  13927. return;
  13928. }
  13929. // Side-effect only: import('bar').then(() => {})
  13930. if (thenCallback.params.length === 0) {
  13931. return parseAst_js.EMPTY_ARRAY;
  13932. }
  13933. const declaration = thenCallback.params[0];
  13934. if (thenCallback.params.length === 1 && declaration instanceof ObjectPattern) {
  13935. return getDeterministicObjectDestructure(declaration);
  13936. }
  13937. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  13938. }
  13939. }
  13940. hasEffects() {
  13941. return true;
  13942. }
  13943. include(context, includeChildrenRecursively) {
  13944. if (!this.included)
  13945. this.includeNode(context);
  13946. this.source.include(context, includeChildrenRecursively);
  13947. if (this.shouldIncludeDynamicAttributes)
  13948. this.options?.include(context, includeChildrenRecursively);
  13949. }
  13950. includeNode(context) {
  13951. this.included = true;
  13952. if (this.shouldIncludeDynamicAttributes)
  13953. this.options?.includePath(UNKNOWN_PATH, context);
  13954. this.scope.context.includeDynamicImport(this);
  13955. this.scope.addAccessedDynamicImport(this);
  13956. }
  13957. includePath(path, context) {
  13958. if (!this.included)
  13959. this.includeNode(context);
  13960. // Technically, this is not correct as dynamic imports return a Promise.
  13961. if (this.hasUnknownAccessedKey)
  13962. return;
  13963. if (path[0] === UnknownKey) {
  13964. this.hasUnknownAccessedKey = true;
  13965. }
  13966. else if (typeof path[0] === 'string') {
  13967. this.accessedPropKey.add(path[0]);
  13968. }
  13969. // Update included paths
  13970. this.scope.context.includeDynamicImport(this);
  13971. }
  13972. initialise() {
  13973. super.initialise();
  13974. this.scope.context.addDynamicImport(this);
  13975. }
  13976. parseNode(esTreeNode) {
  13977. this.sourceAstNode = esTreeNode.source;
  13978. return super.parseNode(esTreeNode);
  13979. }
  13980. render(code, options) {
  13981. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  13982. if (this.inlineNamespace) {
  13983. const [left, right] = getDirectReturnFunction([], {
  13984. functionReturn: true,
  13985. lineBreakIndent: null,
  13986. name: null
  13987. });
  13988. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  13989. return;
  13990. }
  13991. if (this.mechanism) {
  13992. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  13993. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  13994. }
  13995. if (this.resolutionString) {
  13996. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  13997. if (this.namespaceExportName) {
  13998. const [left, right] = getDirectReturnFunction(['n'], {
  13999. functionReturn: true,
  14000. lineBreakIndent: null,
  14001. name: null
  14002. });
  14003. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  14004. }
  14005. }
  14006. else {
  14007. this.source.render(code, options);
  14008. }
  14009. if (this.attributes !== true) {
  14010. if (this.options) {
  14011. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  14012. }
  14013. if (this.attributes) {
  14014. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  14015. lineBreakIndent: null
  14016. })}`);
  14017. }
  14018. }
  14019. }
  14020. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  14021. const { format } = options;
  14022. this.inlineNamespace = null;
  14023. this.resolution = resolution;
  14024. this.resolutionString = resolutionString;
  14025. this.namespaceExportName = namespaceExportName;
  14026. this.attributes = attributes;
  14027. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  14028. let helper;
  14029. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  14030. if (helper) {
  14031. accessedGlobals.push(helper);
  14032. }
  14033. if (accessedGlobals.length > 0) {
  14034. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  14035. }
  14036. }
  14037. setInternalResolution(inlineNamespace) {
  14038. this.inlineNamespace = inlineNamespace;
  14039. }
  14040. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  14041. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  14042. {
  14043. chunk: getChunkInfoWithPath(ownChunk),
  14044. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  14045. format,
  14046. getTargetChunkImports() {
  14047. if (targetChunk === null)
  14048. return null;
  14049. const chunkInfos = [];
  14050. const importerPath = ownChunk.getFileName();
  14051. for (const dep of targetChunk.dependencies) {
  14052. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  14053. if (dep instanceof ExternalChunk) {
  14054. chunkInfos.push({
  14055. fileName: dep.getFileName(),
  14056. resolvedImportPath,
  14057. type: 'external'
  14058. });
  14059. }
  14060. else {
  14061. chunkInfos.push({
  14062. chunk: dep.getPreRenderedChunkInfo(),
  14063. fileName: dep.getFileName(),
  14064. resolvedImportPath,
  14065. type: 'internal'
  14066. });
  14067. }
  14068. }
  14069. return chunkInfos;
  14070. },
  14071. moduleId: this.scope.context.module.id,
  14072. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  14073. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  14074. }
  14075. ]);
  14076. if (mechanism) {
  14077. return { helper: null, mechanism };
  14078. }
  14079. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  14080. switch (format) {
  14081. case 'cjs': {
  14082. if (dynamicImportInCjs &&
  14083. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  14084. return { helper: null, mechanism: null };
  14085. }
  14086. const helper = getInteropHelper(resolution, exportMode, interop);
  14087. let left = `require(`;
  14088. let right = `)`;
  14089. if (helper) {
  14090. left = `/*#__PURE__*/${helper}(${left}`;
  14091. right += ')';
  14092. }
  14093. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  14094. functionReturn: true,
  14095. lineBreakIndent: null,
  14096. name: null
  14097. });
  14098. left = `Promise.resolve().then(${functionLeft}${left}`;
  14099. right += `${functionRight})`;
  14100. if (!arrowFunctions && hasDynamicTarget) {
  14101. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  14102. needsArrowReturnParens: false,
  14103. needsWrappedFunction: true
  14104. });
  14105. right = ')';
  14106. }
  14107. return {
  14108. helper,
  14109. mechanism: { left, right }
  14110. };
  14111. }
  14112. case 'amd': {
  14113. const resolve = compact ? 'c' : 'resolve';
  14114. const reject = compact ? 'e' : 'reject';
  14115. const helper = getInteropHelper(resolution, exportMode, interop);
  14116. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  14117. functionReturn: false,
  14118. lineBreakIndent: null,
  14119. name: null
  14120. });
  14121. const resolveNamespace = helper
  14122. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  14123. : resolve;
  14124. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  14125. functionReturn: false,
  14126. lineBreakIndent: null,
  14127. name: null
  14128. });
  14129. let left = `new Promise(${handlerLeft}require([`;
  14130. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  14131. if (!arrowFunctions && hasDynamicTarget) {
  14132. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  14133. needsArrowReturnParens: false,
  14134. needsWrappedFunction: true
  14135. });
  14136. right = ')';
  14137. }
  14138. return {
  14139. helper,
  14140. mechanism: { left, right }
  14141. };
  14142. }
  14143. case 'system': {
  14144. return {
  14145. helper: null,
  14146. mechanism: {
  14147. left: 'module.import(',
  14148. right: ')'
  14149. }
  14150. };
  14151. }
  14152. }
  14153. return { helper: null, mechanism: null };
  14154. }
  14155. }
  14156. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14157. function getInteropHelper(resolution, exportMode, interop) {
  14158. return exportMode === 'external'
  14159. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  14160. : exportMode === 'default'
  14161. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  14162. : null;
  14163. }
  14164. const accessedImportGlobals = {
  14165. amd: ['require'],
  14166. cjs: ['require'],
  14167. system: ['module']
  14168. };
  14169. function getDeterministicObjectDestructure(objectPattern) {
  14170. const variables = [];
  14171. for (const property of objectPattern.properties) {
  14172. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  14173. return;
  14174. variables.push(property.key.name);
  14175. }
  14176. return variables;
  14177. }
  14178. class ImportNamespaceSpecifier extends NodeBase {
  14179. }
  14180. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14181. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14182. class ImportSpecifier extends NodeBase {
  14183. }
  14184. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14185. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  14186. class JSXIdentifier extends IdentifierBase {
  14187. constructor() {
  14188. super(...arguments);
  14189. this.isNativeElement = false;
  14190. }
  14191. bind() {
  14192. const type = this.getType();
  14193. if (type === 0 /* IdentifierType.Reference */) {
  14194. this.variable = this.scope.findVariable(this.name);
  14195. this.variable.addReference(this);
  14196. }
  14197. else if (type === 1 /* IdentifierType.NativeElementName */) {
  14198. this.isNativeElement = true;
  14199. }
  14200. }
  14201. include(context) {
  14202. if (!this.included)
  14203. this.includeNode(context);
  14204. }
  14205. includeNode(context) {
  14206. this.included = true;
  14207. if (!this.deoptimized)
  14208. this.applyDeoptimizations();
  14209. if (this.variable !== null) {
  14210. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14211. }
  14212. }
  14213. includePath(path, context) {
  14214. if (!this.included) {
  14215. this.included = true;
  14216. if (this.variable !== null) {
  14217. this.scope.context.includeVariableInModule(this.variable, path, context);
  14218. }
  14219. }
  14220. else if (path.length > 0) {
  14221. this.variable?.includePath(path, context);
  14222. }
  14223. }
  14224. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  14225. if (this.variable) {
  14226. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  14227. if (name !== this.name) {
  14228. code.overwrite(this.start, this.end, name, {
  14229. contentOnly: true,
  14230. storeName: true
  14231. });
  14232. }
  14233. }
  14234. else if (this.isNativeElement &&
  14235. this.scope.context.options.jsx.mode !== 'preserve') {
  14236. code.update(this.start, this.end, JSON.stringify(this.name));
  14237. }
  14238. }
  14239. getType() {
  14240. switch (this.parent.type) {
  14241. case 'JSXOpeningElement':
  14242. case 'JSXClosingElement': {
  14243. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  14244. ? 0 /* IdentifierType.Reference */
  14245. : 1 /* IdentifierType.NativeElementName */;
  14246. }
  14247. case 'JSXMemberExpression': {
  14248. return this.parent.object === this
  14249. ? 0 /* IdentifierType.Reference */
  14250. : 2 /* IdentifierType.Other */;
  14251. }
  14252. case 'JSXAttribute':
  14253. case 'JSXNamespacedName': {
  14254. return 2 /* IdentifierType.Other */;
  14255. }
  14256. default: {
  14257. /* istanbul ignore next */
  14258. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  14259. }
  14260. }
  14261. }
  14262. }
  14263. class JSXAttribute extends NodeBase {
  14264. render(code, options, { jsxMode } = parseAst_js.BLANK) {
  14265. super.render(code, options);
  14266. if (['classic', 'automatic'].includes(jsxMode)) {
  14267. const { name, value } = this;
  14268. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  14269. if (!(jsxMode === 'automatic' && key === 'key')) {
  14270. const safeKey = stringifyObjectKeyIfNeeded(key);
  14271. if (key !== safeKey) {
  14272. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  14273. }
  14274. if (value) {
  14275. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  14276. // foo="aa \n aa"
  14277. if (value instanceof Literal &&
  14278. typeof value.value === 'string' &&
  14279. value.value.includes('\n')) {
  14280. code.overwrite(value.start, value.end, JSON.stringify(value.value), {
  14281. contentOnly: true
  14282. });
  14283. }
  14284. }
  14285. else {
  14286. code.appendLeft(name.end, ': true');
  14287. }
  14288. }
  14289. }
  14290. }
  14291. }
  14292. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  14293. class JSXClosingBase extends NodeBase {
  14294. render(code, options) {
  14295. const { mode } = this.scope.context.options.jsx;
  14296. if (mode !== 'preserve') {
  14297. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  14298. }
  14299. else {
  14300. super.render(code, options);
  14301. }
  14302. }
  14303. }
  14304. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  14305. class JSXClosingElement extends JSXClosingBase {
  14306. }
  14307. class JSXClosingFragment extends JSXClosingBase {
  14308. }
  14309. class JSXSpreadAttribute extends NodeBase {
  14310. render(code, options) {
  14311. this.argument.render(code, options);
  14312. const { mode } = this.scope.context.options.jsx;
  14313. if (mode !== 'preserve') {
  14314. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  14315. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  14316. }
  14317. }
  14318. }
  14319. class JSXEmptyExpression extends NodeBase {
  14320. }
  14321. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  14322. class JSXExpressionContainer extends NodeBase {
  14323. includeNode(context) {
  14324. this.included = true;
  14325. if (!this.deoptimized)
  14326. this.applyDeoptimizations();
  14327. this.expression.includePath(UNKNOWN_PATH, context);
  14328. }
  14329. render(code, options) {
  14330. const { mode } = this.scope.context.options.jsx;
  14331. if (mode !== 'preserve') {
  14332. code.remove(this.start, this.expression.start);
  14333. code.remove(this.expression.end, this.end);
  14334. }
  14335. this.expression.render(code, options);
  14336. }
  14337. }
  14338. const RE_WHITESPACE_TRIM = /^[ \t]*\r?\n[ \t\r\n]*|[ \t]*\r?\n[ \t\r\n]*$/g;
  14339. const RE_WHITESPACE_MERGE = /[ \t]*\r?\n[ \t\r\n]*/g;
  14340. class JSXText extends NodeBase {
  14341. shouldRender() {
  14342. return !!this.getRenderedText();
  14343. }
  14344. render(code) {
  14345. const { mode } = this.scope.context.options.jsx;
  14346. if (mode !== 'preserve') {
  14347. code.overwrite(this.start, this.end, JSON.stringify(this.getRenderedText()), {
  14348. contentOnly: true
  14349. });
  14350. }
  14351. }
  14352. getRenderedText() {
  14353. if (this.renderedText === undefined)
  14354. this.renderedText = this.value
  14355. .replace(RE_WHITESPACE_TRIM, '')
  14356. .replace(RE_WHITESPACE_MERGE, ' ');
  14357. return this.renderedText;
  14358. }
  14359. }
  14360. JSXText.prototype.includeNode = onlyIncludeSelf;
  14361. function getRenderedJsxChildren(children) {
  14362. let renderedChildren = 0;
  14363. for (const child of children) {
  14364. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression) &&
  14365. (!(child instanceof JSXText) || child.shouldRender())) {
  14366. renderedChildren++;
  14367. }
  14368. }
  14369. return renderedChildren;
  14370. }
  14371. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  14372. const [baseName, nestedName] = factory.split('.');
  14373. let factoryVariable;
  14374. if (importSource) {
  14375. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  14376. if (preserve) {
  14377. // This pretends we are accessing an included global variable of the same name
  14378. const globalVariable = node.scope.findGlobal(baseName);
  14379. globalVariable.includePath(UNKNOWN_PATH, context);
  14380. // This excludes this variable from renaming
  14381. factoryVariable.globalName = baseName;
  14382. }
  14383. }
  14384. else {
  14385. factoryVariable = node.scope.findGlobal(baseName);
  14386. }
  14387. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  14388. if (factoryVariable instanceof LocalVariable) {
  14389. factoryVariable.consolidateInitializers();
  14390. factoryVariable.addUsedPlace(node);
  14391. node.scope.context.requestTreeshakingPass();
  14392. }
  14393. return factoryVariable;
  14394. }
  14395. class JSXElementBase extends NodeBase {
  14396. constructor() {
  14397. super(...arguments);
  14398. this.factoryVariable = null;
  14399. this.factory = null;
  14400. }
  14401. initialise() {
  14402. super.initialise();
  14403. const { importSource } = (this.jsxMode = this.getRenderingMode());
  14404. if (importSource) {
  14405. this.scope.context.addImportSource(importSource);
  14406. }
  14407. }
  14408. include(context, includeChildrenRecursively) {
  14409. if (!this.included)
  14410. this.includeNode(context);
  14411. for (const child of this.children) {
  14412. child.include(context, includeChildrenRecursively);
  14413. }
  14414. }
  14415. includeNode(context) {
  14416. this.included = true;
  14417. const { factory, importSource, mode } = this.jsxMode;
  14418. if (factory) {
  14419. this.factory = factory;
  14420. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  14421. }
  14422. }
  14423. getRenderingMode() {
  14424. const jsx = this.scope.context.options.jsx;
  14425. const { mode, factory, importSource } = jsx;
  14426. if (mode === 'automatic') {
  14427. return {
  14428. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  14429. importSource: jsx.jsxImportSource,
  14430. mode
  14431. };
  14432. }
  14433. return { factory, importSource, mode };
  14434. }
  14435. renderChildren(code, options, openingEnd) {
  14436. const { children } = this;
  14437. let hasMultipleChildren = false;
  14438. let childrenEnd = openingEnd;
  14439. let firstChild = null;
  14440. for (const child of children) {
  14441. if ((child instanceof JSXExpressionContainer &&
  14442. child.expression instanceof JSXEmptyExpression) ||
  14443. (child instanceof JSXText && !child.shouldRender())) {
  14444. code.remove(childrenEnd, child.end);
  14445. }
  14446. else {
  14447. code.appendLeft(childrenEnd, ', ');
  14448. child.render(code, options);
  14449. if (firstChild) {
  14450. hasMultipleChildren = true;
  14451. }
  14452. else {
  14453. firstChild = child;
  14454. }
  14455. }
  14456. childrenEnd = child.end;
  14457. }
  14458. return { childrenEnd, firstChild, hasMultipleChildren };
  14459. }
  14460. }
  14461. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  14462. class JSXElement extends JSXElementBase {
  14463. include(context, includeChildrenRecursively) {
  14464. super.include(context, includeChildrenRecursively);
  14465. this.openingElement.include(context, includeChildrenRecursively);
  14466. this.closingElement?.include(context, includeChildrenRecursively);
  14467. }
  14468. render(code, options) {
  14469. switch (this.jsxMode.mode) {
  14470. case 'classic': {
  14471. this.renderClassicMode(code, options);
  14472. break;
  14473. }
  14474. case 'automatic': {
  14475. this.renderAutomaticMode(code, options);
  14476. break;
  14477. }
  14478. default: {
  14479. super.render(code, options);
  14480. }
  14481. }
  14482. }
  14483. getRenderingMode() {
  14484. const jsx = this.scope.context.options.jsx;
  14485. const { mode, factory, importSource } = jsx;
  14486. if (mode === 'automatic') {
  14487. // In the case there is a key after a spread attribute, we fall back to
  14488. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  14489. // for reasoning.
  14490. let hasSpread = false;
  14491. for (const attribute of this.openingElement.attributes) {
  14492. if (attribute instanceof JSXSpreadAttribute) {
  14493. hasSpread = true;
  14494. }
  14495. else if (hasSpread && attribute.name.name === 'key') {
  14496. return { factory, importSource, mode: 'classic' };
  14497. }
  14498. }
  14499. }
  14500. return super.getRenderingMode();
  14501. }
  14502. renderClassicMode(code, options) {
  14503. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14504. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  14505. const [, ...nestedName] = factory.split('.');
  14506. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  14507. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  14508. this.renderChildren(code, options, openingEnd);
  14509. if (selfClosing) {
  14510. code.appendLeft(end, ')');
  14511. }
  14512. else {
  14513. closingElement.render(code, options);
  14514. }
  14515. }
  14516. renderAutomaticMode(code, options) {
  14517. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14518. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  14519. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  14520. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  14521. if (firstChild) {
  14522. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  14523. if (!inObject) {
  14524. code.prependRight(firstChild.start, '{ ');
  14525. inObject = true;
  14526. }
  14527. previousEnd = closingElement.start;
  14528. if (hasMultipleChildren) {
  14529. code.appendLeft(previousEnd, ']');
  14530. }
  14531. }
  14532. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  14533. if (keyAttribute) {
  14534. const { value } = keyAttribute;
  14535. // This will appear to the left of the moved code...
  14536. code.appendLeft(childrenEnd, ', ');
  14537. if (value) {
  14538. code.move(value.start, value.end, childrenEnd);
  14539. }
  14540. else {
  14541. code.appendLeft(childrenEnd, 'true');
  14542. }
  14543. }
  14544. if (selfClosing) {
  14545. // Moving the key attribute will also move the parenthesis to the right position
  14546. code.appendLeft(keyAttribute?.value?.end || end, ')');
  14547. }
  14548. else {
  14549. closingElement.render(code, options);
  14550. }
  14551. }
  14552. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  14553. const { jsxMode: { mode }, openingElement } = this;
  14554. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  14555. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  14556. openingElement.render(code, options, { jsxMode: mode });
  14557. let keyAttribute = null;
  14558. let hasSpread = false;
  14559. let inObject = false;
  14560. let previousEnd = nameEnd;
  14561. let hasAttributes = false;
  14562. let firstAttribute = null;
  14563. for (const attribute of attributes) {
  14564. if (attribute instanceof JSXAttribute) {
  14565. if (extractKeyAttribute && attribute.name.name === 'key') {
  14566. keyAttribute = attribute;
  14567. code.remove(previousEnd, attribute.value?.start || attribute.end);
  14568. continue;
  14569. }
  14570. code.appendLeft(previousEnd, ',');
  14571. if (!inObject) {
  14572. code.prependRight(attribute.start, '{ ');
  14573. inObject = true;
  14574. }
  14575. hasAttributes = true;
  14576. }
  14577. else {
  14578. if (inObject) {
  14579. if (hasAttributes) {
  14580. code.appendLeft(previousEnd, ' ');
  14581. }
  14582. code.appendLeft(previousEnd, '},');
  14583. inObject = false;
  14584. }
  14585. else {
  14586. code.appendLeft(previousEnd, ',');
  14587. }
  14588. hasSpread = true;
  14589. }
  14590. previousEnd = attribute.end;
  14591. if (!firstAttribute) {
  14592. firstAttribute = attribute;
  14593. }
  14594. }
  14595. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  14596. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  14597. }
  14598. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  14599. if (inObject) {
  14600. code.appendLeft(attributesEnd, ' }');
  14601. }
  14602. if (hasSpread) {
  14603. if (hasAttributes) {
  14604. const { start } = firstAttribute;
  14605. if (firstAttribute instanceof JSXSpreadAttribute) {
  14606. code.prependRight(start, '{}, ');
  14607. }
  14608. code.prependRight(start, 'Object.assign(');
  14609. code.appendLeft(attributesEnd, ')');
  14610. }
  14611. }
  14612. else if (!hasAttributes) {
  14613. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  14614. }
  14615. }
  14616. }
  14617. class JSXFragment extends JSXElementBase {
  14618. include(context, includeChildrenRecursively) {
  14619. super.include(context, includeChildrenRecursively);
  14620. this.openingFragment.include(context, includeChildrenRecursively);
  14621. this.closingFragment.include(context, includeChildrenRecursively);
  14622. }
  14623. render(code, options) {
  14624. switch (this.jsxMode.mode) {
  14625. case 'classic': {
  14626. this.renderClassicMode(code, options);
  14627. break;
  14628. }
  14629. case 'automatic': {
  14630. this.renderAutomaticMode(code, options);
  14631. break;
  14632. }
  14633. default: {
  14634. super.render(code, options);
  14635. }
  14636. }
  14637. }
  14638. renderClassicMode(code, options) {
  14639. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14640. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  14641. const [, ...nestedName] = factory.split('.');
  14642. openingFragment.render(code, options);
  14643. code.prependRight(start, `/*#__PURE__*/${[
  14644. factoryVariable.getName(getPropertyAccess, useOriginalName),
  14645. ...nestedName
  14646. ].join('.')}(`);
  14647. code.appendLeft(openingFragment.end, ', null');
  14648. this.renderChildren(code, options, openingFragment.end);
  14649. closingFragment.render(code, options);
  14650. }
  14651. renderAutomaticMode(code, options) {
  14652. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14653. const { closingFragment, factoryVariable, openingFragment, start } = this;
  14654. openingFragment.render(code, options);
  14655. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  14656. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  14657. if (firstChild) {
  14658. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  14659. if (hasMultipleChildren) {
  14660. code.appendLeft(closingFragment.start, ']');
  14661. }
  14662. code.appendLeft(childrenEnd, ' }');
  14663. }
  14664. else {
  14665. code.appendLeft(openingFragment.end, ', {}');
  14666. }
  14667. closingFragment.render(code, options);
  14668. }
  14669. }
  14670. class JSXMemberExpression extends NodeBase {
  14671. includeNode(context) {
  14672. this.included = true;
  14673. if (!this.deoptimized)
  14674. this.applyDeoptimizations();
  14675. this.object.includePath([this.property.name], context);
  14676. }
  14677. includePath(path, context) {
  14678. if (!this.included)
  14679. this.includeNode(context);
  14680. this.object.includePath([this.property.name, ...path], context);
  14681. }
  14682. }
  14683. class JSXNamespacedName extends NodeBase {
  14684. }
  14685. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  14686. class JSXOpeningElement extends NodeBase {
  14687. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  14688. this.name.render(code, options);
  14689. for (const attribute of this.attributes) {
  14690. attribute.render(code, options, { jsxMode });
  14691. }
  14692. }
  14693. }
  14694. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  14695. class JSXOpeningFragment extends NodeBase {
  14696. constructor() {
  14697. super(...arguments);
  14698. this.fragment = null;
  14699. this.fragmentVariable = null;
  14700. }
  14701. includeNode(context) {
  14702. this.included = true;
  14703. if (!this.deoptimized)
  14704. this.applyDeoptimizations();
  14705. const jsx = this.scope.context.options.jsx;
  14706. if (jsx.mode === 'automatic') {
  14707. this.fragment = 'Fragment';
  14708. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  14709. }
  14710. else {
  14711. const { fragment, importSource, mode } = jsx;
  14712. if (fragment != null) {
  14713. this.fragment = fragment;
  14714. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  14715. }
  14716. }
  14717. }
  14718. render(code, options) {
  14719. const { mode } = this.scope.context.options.jsx;
  14720. if (mode !== 'preserve') {
  14721. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14722. const [, ...nestedFragment] = this.fragment.split('.');
  14723. const fragment = [
  14724. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  14725. ...nestedFragment
  14726. ].join('.');
  14727. code.update(this.start, this.end, fragment);
  14728. }
  14729. }
  14730. }
  14731. class JSXSpreadChild extends NodeBase {
  14732. render(code, options) {
  14733. super.render(code, options);
  14734. const { mode } = this.scope.context.options.jsx;
  14735. if (mode !== 'preserve') {
  14736. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  14737. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  14738. }
  14739. }
  14740. }
  14741. class LabeledStatement extends NodeBase {
  14742. hasEffects(context) {
  14743. const { brokenFlow, includedLabels } = context;
  14744. context.ignore.labels.add(this.label.name);
  14745. context.includedLabels = new Set();
  14746. let bodyHasEffects = false;
  14747. if (this.body.hasEffects(context)) {
  14748. bodyHasEffects = true;
  14749. }
  14750. else {
  14751. context.ignore.labels.delete(this.label.name);
  14752. if (context.includedLabels.has(this.label.name)) {
  14753. context.includedLabels.delete(this.label.name);
  14754. context.brokenFlow = brokenFlow;
  14755. }
  14756. }
  14757. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14758. return bodyHasEffects;
  14759. }
  14760. include(context, includeChildrenRecursively) {
  14761. if (!this.included)
  14762. this.includeNode(context);
  14763. const { brokenFlow, includedLabels } = context;
  14764. context.includedLabels = new Set();
  14765. this.body.include(context, includeChildrenRecursively);
  14766. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  14767. this.label.include(context, includeChildrenRecursively);
  14768. context.includedLabels.delete(this.label.name);
  14769. context.brokenFlow = brokenFlow;
  14770. }
  14771. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14772. }
  14773. includeNode(context) {
  14774. this.included = true;
  14775. this.body.includePath(UNKNOWN_PATH, context);
  14776. }
  14777. render(code, options) {
  14778. if (this.label.included) {
  14779. this.label.render(code, options);
  14780. }
  14781. else {
  14782. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  14783. }
  14784. this.body.render(code, options);
  14785. }
  14786. }
  14787. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14788. class LogicalExpression extends NodeBase {
  14789. constructor() {
  14790. super(...arguments);
  14791. // We collect deoptimization information if usedBranch !== null
  14792. this.expressionsToBeDeoptimized = [];
  14793. this.usedBranch = null;
  14794. }
  14795. //private isBranchResolutionAnalysed = false;
  14796. get isBranchResolutionAnalysed() {
  14797. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  14798. }
  14799. set isBranchResolutionAnalysed(value) {
  14800. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  14801. }
  14802. get hasDeoptimizedCache() {
  14803. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  14804. }
  14805. set hasDeoptimizedCache(value) {
  14806. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  14807. }
  14808. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14809. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14810. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14811. }
  14812. deoptimizeCache() {
  14813. if (this.hasDeoptimizedCache)
  14814. return;
  14815. this.hasDeoptimizedCache = true;
  14816. if (this.usedBranch) {
  14817. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  14818. this.usedBranch = null;
  14819. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  14820. if (this.included) {
  14821. // As we are not tracking inclusions, we just include everything
  14822. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  14823. }
  14824. }
  14825. const { scope: { context }, expressionsToBeDeoptimized } = this;
  14826. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  14827. for (const expression of expressionsToBeDeoptimized) {
  14828. expression.deoptimizeCache();
  14829. }
  14830. // Request another pass because we need to ensure "include" runs again if
  14831. // it is rendered
  14832. context.requestTreeshakingPass();
  14833. }
  14834. deoptimizePath(path) {
  14835. const usedBranch = this.getUsedBranch();
  14836. if (usedBranch) {
  14837. usedBranch.deoptimizePath(path);
  14838. }
  14839. else {
  14840. this.left.deoptimizePath(path);
  14841. this.right.deoptimizePath(path);
  14842. }
  14843. }
  14844. getLiteralValueAtPath(path, recursionTracker, origin) {
  14845. if (origin === this)
  14846. return UnknownValue;
  14847. const usedBranch = this.getUsedBranch();
  14848. if (usedBranch) {
  14849. this.expressionsToBeDeoptimized.push(origin);
  14850. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  14851. }
  14852. else if (!this.hasDeoptimizedCache && !path.length) {
  14853. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  14854. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  14855. if (typeof booleanOrUnknown !== 'symbol') {
  14856. if (!booleanOrUnknown && this.operator === '&&') {
  14857. this.expressionsToBeDeoptimized.push(origin);
  14858. return UnknownFalsyValue;
  14859. }
  14860. if (booleanOrUnknown && this.operator === '||') {
  14861. this.expressionsToBeDeoptimized.push(origin);
  14862. return UnknownTruthyValue;
  14863. }
  14864. }
  14865. }
  14866. return UnknownValue;
  14867. }
  14868. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14869. const usedBranch = this.getUsedBranch();
  14870. if (usedBranch) {
  14871. this.expressionsToBeDeoptimized.push(origin);
  14872. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  14873. }
  14874. return [
  14875. new MultiExpression([
  14876. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  14877. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  14878. ]),
  14879. false
  14880. ];
  14881. }
  14882. hasEffects(context) {
  14883. if (this.left.hasEffects(context)) {
  14884. return true;
  14885. }
  14886. if (this.getUsedBranch() !== this.left) {
  14887. return this.right.hasEffects(context);
  14888. }
  14889. return false;
  14890. }
  14891. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14892. const usedBranch = this.getUsedBranch();
  14893. if (usedBranch) {
  14894. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  14895. }
  14896. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  14897. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  14898. }
  14899. include(context, includeChildrenRecursively) {
  14900. this.included = true;
  14901. const usedBranch = this.getUsedBranch();
  14902. if (includeChildrenRecursively ||
  14903. !usedBranch ||
  14904. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14905. this.left.include(context, includeChildrenRecursively);
  14906. this.right.include(context, includeChildrenRecursively);
  14907. }
  14908. else {
  14909. usedBranch.include(context, includeChildrenRecursively);
  14910. }
  14911. }
  14912. includePath(path, context) {
  14913. this.included = true;
  14914. const usedBranch = this.getUsedBranch();
  14915. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14916. this.left.includePath(path, context);
  14917. this.right.includePath(path, context);
  14918. }
  14919. else {
  14920. usedBranch.includePath(path, context);
  14921. }
  14922. }
  14923. removeAnnotations(code) {
  14924. this.left.removeAnnotations(code);
  14925. }
  14926. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  14927. if (!this.left.included || !this.right.included) {
  14928. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  14929. if (this.right.included) {
  14930. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  14931. code.remove(this.start, removePos);
  14932. if (preventASI) {
  14933. removeLineBreaks(code, removePos, this.right.start);
  14934. }
  14935. this.left.removeAnnotations(code);
  14936. }
  14937. else {
  14938. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  14939. }
  14940. this.getUsedBranch().render(code, options, {
  14941. isCalleeOfRenderedParent,
  14942. preventASI,
  14943. renderedParentType: renderedParentType || this.parent.type,
  14944. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  14945. });
  14946. }
  14947. else {
  14948. this.left.render(code, options, {
  14949. preventASI,
  14950. renderedSurroundingElement
  14951. });
  14952. this.right.render(code, options);
  14953. }
  14954. }
  14955. getUsedBranch() {
  14956. if (!this.isBranchResolutionAnalysed) {
  14957. this.isBranchResolutionAnalysed = true;
  14958. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  14959. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  14960. if (typeof booleanOrUnknown === 'symbol' ||
  14961. (this.operator === '??' && typeof leftValue === 'symbol')) {
  14962. return null;
  14963. }
  14964. else {
  14965. this.usedBranch =
  14966. (this.operator === '||' && booleanOrUnknown) ||
  14967. (this.operator === '&&' && !booleanOrUnknown) ||
  14968. (this.operator === '??' && leftValue != null)
  14969. ? this.left
  14970. : this.right;
  14971. }
  14972. }
  14973. return this.usedBranch;
  14974. }
  14975. }
  14976. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14977. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14978. class NewExpression extends NodeBase {
  14979. hasEffects(context) {
  14980. if (!this.deoptimized)
  14981. this.applyDeoptimizations();
  14982. for (const argument of this.arguments) {
  14983. if (argument.hasEffects(context))
  14984. return true;
  14985. }
  14986. if (this.annotationPure) {
  14987. return false;
  14988. }
  14989. return (this.callee.hasEffects(context) ||
  14990. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14991. }
  14992. hasEffectsOnInteractionAtPath(path, { type }) {
  14993. return path.length > 0 || type !== INTERACTION_ACCESSED;
  14994. }
  14995. include(context, includeChildrenRecursively) {
  14996. if (!this.included)
  14997. this.includeNode(context);
  14998. if (includeChildrenRecursively) {
  14999. super.include(context, true);
  15000. }
  15001. else {
  15002. this.callee.include(context, false);
  15003. this.callee.includeCallArguments(this.interaction, context);
  15004. }
  15005. }
  15006. includeNode(context) {
  15007. this.included = true;
  15008. if (!this.deoptimized)
  15009. this.applyDeoptimizations();
  15010. this.callee.includePath(UNKNOWN_PATH, context);
  15011. }
  15012. initialise() {
  15013. super.initialise();
  15014. this.interaction = {
  15015. args: [null, ...this.arguments],
  15016. type: INTERACTION_CALLED,
  15017. withNew: true
  15018. };
  15019. if (this.annotations &&
  15020. this.scope.context.options.treeshake.annotations) {
  15021. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  15022. }
  15023. }
  15024. render(code, options) {
  15025. this.callee.render(code, options);
  15026. renderCallArguments(code, options, this);
  15027. }
  15028. applyDeoptimizations() {
  15029. this.deoptimized = true;
  15030. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15031. this.scope.context.requestTreeshakingPass();
  15032. }
  15033. }
  15034. class ObjectExpression extends NodeBase {
  15035. constructor() {
  15036. super(...arguments);
  15037. this.objectEntity = null;
  15038. this.protoProp = null;
  15039. }
  15040. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15041. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15042. }
  15043. deoptimizeCache() {
  15044. this.getObjectEntity().deoptimizeAllProperties();
  15045. }
  15046. deoptimizePath(path) {
  15047. this.getObjectEntity().deoptimizePath(path);
  15048. }
  15049. getLiteralValueAtPath(path, recursionTracker, origin) {
  15050. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  15051. }
  15052. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15053. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  15054. }
  15055. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15056. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  15057. }
  15058. include(context, includeChildrenRecursively) {
  15059. if (!this.included)
  15060. this.includeNode(context);
  15061. this.getObjectEntity().include(context, includeChildrenRecursively);
  15062. this.protoProp?.include(context, includeChildrenRecursively);
  15063. }
  15064. includeNode(context) {
  15065. this.included = true;
  15066. this.protoProp?.includePath(UNKNOWN_PATH, context);
  15067. }
  15068. includePath(path, context) {
  15069. if (!this.included)
  15070. this.includeNode(context);
  15071. this.getObjectEntity().includePath(path, context);
  15072. }
  15073. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  15074. if (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  15075. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression) {
  15076. code.appendRight(this.start, '(');
  15077. code.prependLeft(this.end, ')');
  15078. }
  15079. if (this.properties.length > 0) {
  15080. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  15081. let lastSeparatorPos = null;
  15082. for (const { node, separator, start, end } of separatedNodes) {
  15083. if (!node.included) {
  15084. treeshakeNode(node, code, start, end);
  15085. continue;
  15086. }
  15087. lastSeparatorPos = separator;
  15088. node.render(code, options);
  15089. }
  15090. if (lastSeparatorPos) {
  15091. code.remove(lastSeparatorPos, this.end - 1);
  15092. }
  15093. }
  15094. }
  15095. getObjectEntity() {
  15096. if (this.objectEntity !== null) {
  15097. return this.objectEntity;
  15098. }
  15099. let prototype = OBJECT_PROTOTYPE;
  15100. const properties = [];
  15101. for (const property of this.properties) {
  15102. if (property instanceof SpreadElement) {
  15103. properties.push({ key: UnknownKey, kind: 'init', property });
  15104. continue;
  15105. }
  15106. let key;
  15107. if (property.computed) {
  15108. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  15109. if (typeof keyValue === 'symbol') {
  15110. properties.push({ key: UnknownKey, kind: property.kind, property });
  15111. continue;
  15112. }
  15113. else {
  15114. key = String(keyValue);
  15115. }
  15116. }
  15117. else {
  15118. key =
  15119. property.key instanceof Identifier
  15120. ? property.key.name
  15121. : String(property.key.value);
  15122. if (key === '__proto__' && property.kind === 'init') {
  15123. this.protoProp = property;
  15124. prototype =
  15125. property.value instanceof Literal && property.value.value === null
  15126. ? null
  15127. : property.value;
  15128. continue;
  15129. }
  15130. }
  15131. properties.push({ key, kind: property.kind, property });
  15132. }
  15133. return (this.objectEntity = new ObjectEntity(properties, prototype));
  15134. }
  15135. }
  15136. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15137. class PanicError extends NodeBase {
  15138. initialise() {
  15139. const id = this.scope.context.module.id;
  15140. // This simulates the current nested error structure. We could also just
  15141. // replace it with a flat error.
  15142. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message));
  15143. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  15144. return parseAst_js.error(moduleParseError);
  15145. }
  15146. }
  15147. class ParseError extends NodeBase {
  15148. initialise() {
  15149. const pos = this.start;
  15150. const id = this.scope.context.module.id;
  15151. // This simulates the current nested error structure. We could also just
  15152. // replace it with a flat error.
  15153. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message, pos));
  15154. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  15155. this.scope.context.error(moduleParseError, pos);
  15156. }
  15157. }
  15158. class PrivateIdentifier extends NodeBase {
  15159. }
  15160. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  15161. class Program extends NodeBase {
  15162. constructor() {
  15163. super(...arguments);
  15164. this.hasCachedEffect = null;
  15165. this.hasLoggedEffect = false;
  15166. }
  15167. hasCachedEffects() {
  15168. if (!this.included) {
  15169. return false;
  15170. }
  15171. return this.hasCachedEffect === null
  15172. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  15173. : this.hasCachedEffect;
  15174. }
  15175. hasEffects(context) {
  15176. for (const node of this.body) {
  15177. if (node.hasEffects(context)) {
  15178. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  15179. this.hasLoggedEffect = true;
  15180. const { code, log, module } = this.scope.context;
  15181. log(parseAst_js.LOGLEVEL_INFO, parseAst_js.logFirstSideEffect(code, module.id, parseAst_js.locate(code, node.start, { offsetLine: 1 })), node.start);
  15182. }
  15183. return (this.hasCachedEffect = true);
  15184. }
  15185. }
  15186. return false;
  15187. }
  15188. include(context, includeChildrenRecursively) {
  15189. this.included = true;
  15190. for (const node of this.body) {
  15191. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  15192. node.include(context, includeChildrenRecursively);
  15193. }
  15194. }
  15195. }
  15196. initialise() {
  15197. super.initialise();
  15198. if (this.invalidAnnotations)
  15199. for (const { start, end, type } of this.invalidAnnotations) {
  15200. this.scope.context.magicString.remove(start, end);
  15201. if (type === 'pure' || type === 'noSideEffects') {
  15202. 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);
  15203. }
  15204. }
  15205. }
  15206. render(code, options) {
  15207. let start = this.start;
  15208. if (code.original.startsWith('#!')) {
  15209. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  15210. code.remove(0, start);
  15211. }
  15212. if (this.body.length > 0) {
  15213. // Keep all consecutive lines that start with a comment
  15214. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  15215. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  15216. if (firstLineBreak[0] === -1) {
  15217. break;
  15218. }
  15219. start += firstLineBreak[1];
  15220. }
  15221. renderStatementList(this.body, code, start, this.end, options);
  15222. }
  15223. else {
  15224. super.render(code, options);
  15225. }
  15226. }
  15227. }
  15228. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15229. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  15230. class Property extends MethodBase {
  15231. //declare method: boolean;
  15232. get method() {
  15233. return isFlagSet(this.flags, 262144 /* Flag.method */);
  15234. }
  15235. set method(value) {
  15236. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  15237. }
  15238. //declare shorthand: boolean;
  15239. get shorthand() {
  15240. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  15241. }
  15242. set shorthand(value) {
  15243. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  15244. }
  15245. declare(kind, destructuredInitPath, init) {
  15246. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  15247. }
  15248. deoptimizeAssignment(destructuredInitPath, init) {
  15249. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  15250. }
  15251. hasEffects(context) {
  15252. return this.key.hasEffects(context) || this.value.hasEffects(context);
  15253. }
  15254. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  15255. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  15256. }
  15257. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  15258. const path = this.getPathInProperty(destructuredInitPath);
  15259. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  15260. this.included;
  15261. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  15262. this.key.include(context, false);
  15263. if (!this.value.included) {
  15264. this.value.includeNode(context);
  15265. // Unfortunately, we need to include the value again now, so that any
  15266. // declared variables are properly included.
  15267. this.value.includeDestructuredIfNecessary(context, path, init);
  15268. }
  15269. }
  15270. if (!this.included && included) {
  15271. this.includeNode(context);
  15272. }
  15273. return this.included;
  15274. }
  15275. include(context, includeChildrenRecursively) {
  15276. this.included = true;
  15277. this.key.include(context, includeChildrenRecursively);
  15278. this.value.include(context, includeChildrenRecursively);
  15279. }
  15280. includePath(path, context) {
  15281. this.included = true;
  15282. this.value.includePath(path, context);
  15283. }
  15284. markDeclarationReached() {
  15285. this.value.markDeclarationReached();
  15286. }
  15287. render(code, options) {
  15288. if (!this.shorthand) {
  15289. this.key.render(code, options);
  15290. }
  15291. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  15292. }
  15293. getPathInProperty(destructuredInitPath) {
  15294. return destructuredInitPath.at(-1) === UnknownKey
  15295. ? destructuredInitPath
  15296. : // For now, we only consider static paths as we do not know how to
  15297. // deoptimize the path in the dynamic case.
  15298. this.computed
  15299. ? [...destructuredInitPath, UnknownKey]
  15300. : this.key instanceof Identifier
  15301. ? [...destructuredInitPath, this.key.name]
  15302. : [...destructuredInitPath, String(this.key.value)];
  15303. }
  15304. }
  15305. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15306. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  15307. class PropertyDefinition extends NodeBase {
  15308. get computed() {
  15309. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  15310. }
  15311. set computed(value) {
  15312. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  15313. }
  15314. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15315. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15316. }
  15317. deoptimizePath(path) {
  15318. this.value?.deoptimizePath(path);
  15319. }
  15320. getLiteralValueAtPath(path, recursionTracker, origin) {
  15321. return this.value
  15322. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  15323. : UnknownValue;
  15324. }
  15325. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  15326. return this.value
  15327. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  15328. : UNKNOWN_RETURN_EXPRESSION;
  15329. }
  15330. hasEffects(context) {
  15331. return (this.key.hasEffects(context) ||
  15332. (this.static && !!this.value?.hasEffects(context)) ||
  15333. checkEffectForNodes(this.decorators, context));
  15334. }
  15335. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15336. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  15337. }
  15338. includeNode(context) {
  15339. this.included = true;
  15340. this.value?.includePath(UNKNOWN_PATH, context);
  15341. for (const decorator of this.decorators) {
  15342. decorator.includePath(UNKNOWN_PATH, context);
  15343. }
  15344. }
  15345. }
  15346. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  15347. class ReturnStatement extends NodeBase {
  15348. hasEffects(context) {
  15349. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  15350. return true;
  15351. context.brokenFlow = true;
  15352. return false;
  15353. }
  15354. include(context, includeChildrenRecursively) {
  15355. if (!this.included)
  15356. this.includeNode(context);
  15357. this.argument?.include(context, includeChildrenRecursively);
  15358. context.brokenFlow = true;
  15359. }
  15360. includeNode(context) {
  15361. this.included = true;
  15362. this.argument?.includePath(UNKNOWN_PATH, context);
  15363. }
  15364. initialise() {
  15365. super.initialise();
  15366. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  15367. }
  15368. render(code, options) {
  15369. if (this.argument) {
  15370. this.argument.render(code, options, { preventASI: true });
  15371. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  15372. code.prependLeft(this.start + 6, ' ');
  15373. }
  15374. }
  15375. }
  15376. }
  15377. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15378. class SequenceExpression extends NodeBase {
  15379. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15380. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15381. }
  15382. deoptimizePath(path) {
  15383. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  15384. }
  15385. getLiteralValueAtPath(path, recursionTracker, origin) {
  15386. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  15387. }
  15388. hasEffects(context) {
  15389. for (const expression of this.expressions) {
  15390. if (expression.hasEffects(context))
  15391. return true;
  15392. }
  15393. return false;
  15394. }
  15395. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15396. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  15397. }
  15398. include(context, includeChildrenRecursively) {
  15399. this.included = true;
  15400. const lastExpression = this.expressions[this.expressions.length - 1];
  15401. for (const expression of this.expressions) {
  15402. if (includeChildrenRecursively ||
  15403. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  15404. expression.shouldBeIncluded(context)) {
  15405. expression.include(context, includeChildrenRecursively);
  15406. }
  15407. }
  15408. }
  15409. includePath(path, context) {
  15410. this.included = true;
  15411. this.expressions[this.expressions.length - 1].includePath(path, context);
  15412. }
  15413. removeAnnotations(code) {
  15414. this.expressions[0].removeAnnotations(code);
  15415. }
  15416. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = parseAst_js.BLANK) {
  15417. let includedNodes = 0;
  15418. let lastSeparatorPos = null;
  15419. const lastNode = this.expressions[this.expressions.length - 1];
  15420. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  15421. if (!node.included) {
  15422. treeshakeNode(node, code, start, end);
  15423. continue;
  15424. }
  15425. includedNodes++;
  15426. lastSeparatorPos = separator;
  15427. if (includedNodes === 1 && preventASI) {
  15428. removeLineBreaks(code, start, node.start);
  15429. }
  15430. if (includedNodes === 1) {
  15431. const parentType = renderedParentType || this.parent.type;
  15432. node.render(code, options, {
  15433. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  15434. renderedParentType: parentType,
  15435. renderedSurroundingElement: parentType
  15436. });
  15437. }
  15438. else {
  15439. node.render(code, options);
  15440. }
  15441. }
  15442. if (lastSeparatorPos) {
  15443. code.remove(lastSeparatorPos, this.end);
  15444. }
  15445. }
  15446. }
  15447. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15448. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  15449. class Super extends NodeBase {
  15450. bind() {
  15451. this.variable = this.scope.findVariable('this');
  15452. }
  15453. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15454. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15455. }
  15456. deoptimizePath(path) {
  15457. this.variable.deoptimizePath(path);
  15458. }
  15459. include(context) {
  15460. if (!this.included)
  15461. this.includeNode(context);
  15462. }
  15463. includeNode(context) {
  15464. this.included = true;
  15465. if (!this.deoptimized)
  15466. this.applyDeoptimizations();
  15467. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15468. }
  15469. }
  15470. class SwitchCase extends NodeBase {
  15471. hasEffects(context) {
  15472. if (this.test?.hasEffects(context))
  15473. return true;
  15474. for (const node of this.consequent) {
  15475. if (context.brokenFlow)
  15476. break;
  15477. if (node.hasEffects(context))
  15478. return true;
  15479. }
  15480. return false;
  15481. }
  15482. include(context, includeChildrenRecursively) {
  15483. this.included = true;
  15484. this.test?.include(context, includeChildrenRecursively);
  15485. for (const node of this.consequent) {
  15486. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  15487. node.include(context, includeChildrenRecursively);
  15488. }
  15489. }
  15490. render(code, options, nodeRenderOptions) {
  15491. if (this.test) {
  15492. this.test.render(code, options);
  15493. if (this.test.start === this.start + 4) {
  15494. code.prependLeft(this.test.start, ' ');
  15495. }
  15496. }
  15497. if (this.consequent.length > 0) {
  15498. const testEnd = this.test
  15499. ? this.test.end
  15500. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  15501. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  15502. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  15503. }
  15504. }
  15505. }
  15506. SwitchCase.prototype.needsBoundaries = true;
  15507. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15508. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  15509. class SwitchStatement extends NodeBase {
  15510. createScope(parentScope) {
  15511. this.parentScope = parentScope;
  15512. this.scope = new BlockScope(parentScope);
  15513. }
  15514. hasEffects(context) {
  15515. if (this.discriminant.hasEffects(context))
  15516. return true;
  15517. const { brokenFlow, hasBreak, ignore } = context;
  15518. const { breaks } = ignore;
  15519. ignore.breaks = true;
  15520. context.hasBreak = false;
  15521. let onlyHasBrokenFlow = true;
  15522. for (const switchCase of this.cases) {
  15523. if (switchCase.hasEffects(context))
  15524. return true;
  15525. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15526. context.hasBreak = false;
  15527. context.brokenFlow = brokenFlow;
  15528. }
  15529. if (this.defaultCase !== null) {
  15530. context.brokenFlow = onlyHasBrokenFlow;
  15531. }
  15532. ignore.breaks = breaks;
  15533. context.hasBreak = hasBreak;
  15534. return false;
  15535. }
  15536. include(context, includeChildrenRecursively) {
  15537. this.included = true;
  15538. this.discriminant.include(context, includeChildrenRecursively);
  15539. const { brokenFlow, hasBreak } = context;
  15540. context.hasBreak = false;
  15541. let onlyHasBrokenFlow = true;
  15542. let isCaseIncluded = includeChildrenRecursively ||
  15543. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  15544. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  15545. const switchCase = this.cases[caseIndex];
  15546. if (switchCase.included) {
  15547. isCaseIncluded = true;
  15548. }
  15549. if (!isCaseIncluded) {
  15550. const hasEffectsContext = createHasEffectsContext();
  15551. hasEffectsContext.ignore.breaks = true;
  15552. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  15553. }
  15554. if (isCaseIncluded) {
  15555. switchCase.include(context, includeChildrenRecursively);
  15556. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15557. context.hasBreak = false;
  15558. context.brokenFlow = brokenFlow;
  15559. }
  15560. else {
  15561. onlyHasBrokenFlow = brokenFlow;
  15562. }
  15563. }
  15564. if (isCaseIncluded && this.defaultCase !== null) {
  15565. context.brokenFlow = onlyHasBrokenFlow;
  15566. }
  15567. context.hasBreak = hasBreak;
  15568. }
  15569. initialise() {
  15570. super.initialise();
  15571. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  15572. if (this.cases[caseIndex].test === null) {
  15573. this.defaultCase = caseIndex;
  15574. return;
  15575. }
  15576. }
  15577. this.defaultCase = null;
  15578. }
  15579. parseNode(esTreeNode) {
  15580. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  15581. return super.parseNode(esTreeNode);
  15582. }
  15583. render(code, options) {
  15584. this.discriminant.render(code, options);
  15585. if (this.cases.length > 0) {
  15586. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  15587. }
  15588. }
  15589. }
  15590. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15591. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15592. class TaggedTemplateExpression extends CallExpressionBase {
  15593. get hasCheckedForWarnings() {
  15594. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  15595. }
  15596. set hasCheckedForWarnings(value) {
  15597. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  15598. }
  15599. bind() {
  15600. super.bind();
  15601. }
  15602. hasEffects(context) {
  15603. if (!this.deoptimized)
  15604. this.applyDeoptimizations();
  15605. for (const argument of this.quasi.expressions) {
  15606. if (argument.hasEffects(context))
  15607. return true;
  15608. }
  15609. return (this.tag.hasEffects(context) ||
  15610. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  15611. }
  15612. include(context, includeChildrenRecursively) {
  15613. if (!this.included)
  15614. this.includeNode(context);
  15615. if (includeChildrenRecursively) {
  15616. super.include(context, true);
  15617. }
  15618. else {
  15619. this.quasi.include(context, false);
  15620. this.tag.include(context, false);
  15621. this.tag.includeCallArguments(this.interaction, context);
  15622. }
  15623. }
  15624. initialise() {
  15625. super.initialise();
  15626. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  15627. this.interaction = {
  15628. args: [
  15629. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  15630. ...this.args
  15631. ],
  15632. type: INTERACTION_CALLED,
  15633. withNew: false
  15634. };
  15635. }
  15636. render(code, options) {
  15637. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  15638. this.quasi.render(code, options);
  15639. if (!this.hasCheckedForWarnings && this.tag.type === parseAst_js.Identifier) {
  15640. this.hasCheckedForWarnings = true;
  15641. const name = this.tag.name;
  15642. const variable = this.scope.findVariable(name);
  15643. if (variable.isNamespace) {
  15644. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
  15645. }
  15646. }
  15647. }
  15648. applyDeoptimizations() {
  15649. this.deoptimized = true;
  15650. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15651. this.scope.context.requestTreeshakingPass();
  15652. }
  15653. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  15654. if (this.returnExpression === null) {
  15655. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  15656. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  15657. }
  15658. return this.returnExpression;
  15659. }
  15660. }
  15661. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  15662. class TemplateElement extends NodeBase {
  15663. get tail() {
  15664. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  15665. }
  15666. set tail(value) {
  15667. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  15668. }
  15669. // Do not try to bind value
  15670. bind() { }
  15671. hasEffects() {
  15672. return false;
  15673. }
  15674. parseNode(esTreeNode) {
  15675. this.value = esTreeNode.value;
  15676. return super.parseNode(esTreeNode);
  15677. }
  15678. render() { }
  15679. }
  15680. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  15681. class TemplateLiteral extends NodeBase {
  15682. deoptimizeArgumentsOnInteractionAtPath() { }
  15683. getLiteralValueAtPath(path) {
  15684. if (path.length > 0 || this.quasis.length !== 1) {
  15685. return UnknownValue;
  15686. }
  15687. return this.quasis[0].value.cooked;
  15688. }
  15689. getReturnExpressionWhenCalledAtPath(path) {
  15690. if (path.length !== 1) {
  15691. return UNKNOWN_RETURN_EXPRESSION;
  15692. }
  15693. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  15694. }
  15695. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15696. if (interaction.type === INTERACTION_ACCESSED) {
  15697. return path.length > 1;
  15698. }
  15699. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  15700. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  15701. }
  15702. return true;
  15703. }
  15704. includeNode(context) {
  15705. this.included = true;
  15706. if (!this.deoptimized)
  15707. this.applyDeoptimizations();
  15708. for (const node of this.expressions) {
  15709. node.includePath(UNKNOWN_PATH, context);
  15710. }
  15711. }
  15712. render(code, options) {
  15713. code.indentExclusionRanges.push([this.start, this.end]);
  15714. super.render(code, options);
  15715. }
  15716. }
  15717. class ModuleScope extends ChildScope {
  15718. constructor(parent, context) {
  15719. super(parent, context);
  15720. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  15721. }
  15722. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  15723. if (this.context.module.importDescriptions.has(identifier.name)) {
  15724. context.error(parseAst_js.logRedeclarationError(identifier.name), identifier.start);
  15725. }
  15726. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  15727. }
  15728. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  15729. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  15730. this.variables.set('default', variable);
  15731. return variable;
  15732. }
  15733. addNamespaceMemberAccess() { }
  15734. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  15735. // all module level variables are already deconflicted when deconflicting the chunk
  15736. for (const scope of this.children)
  15737. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15738. }
  15739. findLexicalBoundary() {
  15740. return this;
  15741. }
  15742. findVariable(name) {
  15743. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  15744. if (knownVariable) {
  15745. return knownVariable;
  15746. }
  15747. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  15748. if (variable instanceof GlobalVariable) {
  15749. this.accessedOutsideVariables.set(name, variable);
  15750. }
  15751. return variable;
  15752. }
  15753. }
  15754. class ThisExpression extends NodeBase {
  15755. bind() {
  15756. this.variable = this.scope.findVariable('this');
  15757. }
  15758. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15759. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15760. }
  15761. deoptimizePath(path) {
  15762. this.variable.deoptimizePath(path);
  15763. }
  15764. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15765. if (path.length === 0) {
  15766. return interaction.type !== INTERACTION_ACCESSED;
  15767. }
  15768. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  15769. }
  15770. include(context) {
  15771. if (!this.included)
  15772. this.includeNode(context);
  15773. }
  15774. includeNode(context) {
  15775. this.included = true;
  15776. if (!this.deoptimized)
  15777. this.applyDeoptimizations();
  15778. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15779. }
  15780. includePath(path, context) {
  15781. if (!this.included) {
  15782. this.included = true;
  15783. this.scope.context.includeVariableInModule(this.variable, path, context);
  15784. }
  15785. else if (path.length > 0) {
  15786. this.variable.includePath(path, context);
  15787. }
  15788. const functionScope = findFunctionScope(this.scope, this.variable);
  15789. if (functionScope &&
  15790. functionScope.functionNode.parent instanceof Property &&
  15791. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  15792. functionScope.functionNode.parent.parent.includePath(path, context);
  15793. }
  15794. }
  15795. initialise() {
  15796. super.initialise();
  15797. this.alias =
  15798. this.scope.findLexicalBoundary() instanceof ModuleScope
  15799. ? this.scope.context.moduleContext
  15800. : null;
  15801. if (this.alias === 'undefined') {
  15802. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logThisIsUndefined(), this.start);
  15803. }
  15804. }
  15805. render(code) {
  15806. if (this.alias !== null) {
  15807. code.overwrite(this.start, this.end, this.alias, {
  15808. contentOnly: false,
  15809. storeName: true
  15810. });
  15811. }
  15812. }
  15813. }
  15814. function findFunctionScope(scope, thisVariable) {
  15815. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  15816. if (!(scope instanceof ChildScope)) {
  15817. return null;
  15818. }
  15819. scope = scope.parent;
  15820. }
  15821. return scope;
  15822. }
  15823. class ThrowStatement extends NodeBase {
  15824. hasEffects() {
  15825. return true;
  15826. }
  15827. include(context, includeChildrenRecursively) {
  15828. if (!this.included)
  15829. this.includeNode(context);
  15830. this.argument.include(context, includeChildrenRecursively);
  15831. context.brokenFlow = true;
  15832. }
  15833. includeNode(context) {
  15834. if (!this.included) {
  15835. this.included = true;
  15836. this.argument.includePath(UNKNOWN_PATH, context);
  15837. }
  15838. }
  15839. render(code, options) {
  15840. this.argument.render(code, options, { preventASI: true });
  15841. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  15842. code.prependLeft(this.start + 5, ' ');
  15843. }
  15844. }
  15845. }
  15846. class TryStatement extends NodeBase {
  15847. constructor() {
  15848. super(...arguments);
  15849. this.directlyIncluded = false;
  15850. this.includedLabelsAfterBlock = null;
  15851. }
  15852. hasEffects(context) {
  15853. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  15854. ? this.block.body.length > 0
  15855. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  15856. }
  15857. include(context, includeChildrenRecursively) {
  15858. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  15859. const { brokenFlow, includedLabels } = context;
  15860. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  15861. this.included = true;
  15862. this.directlyIncluded = true;
  15863. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  15864. if (includedLabels.size > 0) {
  15865. this.includedLabelsAfterBlock = [...includedLabels];
  15866. }
  15867. context.brokenFlow = brokenFlow;
  15868. }
  15869. else if (this.includedLabelsAfterBlock) {
  15870. for (const label of this.includedLabelsAfterBlock) {
  15871. includedLabels.add(label);
  15872. }
  15873. }
  15874. if (this.handler !== null) {
  15875. this.handler.include(context, includeChildrenRecursively);
  15876. context.brokenFlow = brokenFlow;
  15877. }
  15878. this.finalizer?.include(context, includeChildrenRecursively);
  15879. }
  15880. }
  15881. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15882. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15883. const unaryOperators = {
  15884. '!': value => !value,
  15885. '+': value => +value,
  15886. '-': value => -value,
  15887. delete: () => UnknownValue,
  15888. typeof: value => typeof value,
  15889. void: () => undefined,
  15890. '~': value => ~value
  15891. };
  15892. const UNASSIGNED = Symbol('Unassigned');
  15893. class UnaryExpression extends NodeBase {
  15894. constructor() {
  15895. super(...arguments);
  15896. this.renderedLiteralValue = UNASSIGNED;
  15897. }
  15898. get prefix() {
  15899. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  15900. }
  15901. set prefix(value) {
  15902. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  15903. }
  15904. deoptimizeCache() {
  15905. this.renderedLiteralValue = UnknownValue;
  15906. }
  15907. getLiteralValueAtPath(path, recursionTracker, origin) {
  15908. if (path.length > 0)
  15909. return UnknownValue;
  15910. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  15911. if (typeof argumentValue === 'symbol') {
  15912. if (this.operator === 'void')
  15913. return undefined;
  15914. if (this.operator === '!') {
  15915. if (argumentValue === UnknownFalsyValue)
  15916. return true;
  15917. if (argumentValue === UnknownTruthyValue)
  15918. return false;
  15919. }
  15920. return UnknownValue;
  15921. }
  15922. return unaryOperators[this.operator](argumentValue);
  15923. }
  15924. hasEffects(context) {
  15925. if (!this.deoptimized)
  15926. this.applyDeoptimizations();
  15927. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  15928. return false;
  15929. return (this.argument.hasEffects(context) ||
  15930. (this.operator === 'delete' &&
  15931. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  15932. }
  15933. hasEffectsOnInteractionAtPath(path, { type }) {
  15934. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  15935. }
  15936. applyDeoptimizations() {
  15937. this.deoptimized = true;
  15938. if (this.operator === 'delete') {
  15939. this.argument.deoptimizePath(EMPTY_PATH);
  15940. this.scope.context.requestTreeshakingPass();
  15941. }
  15942. }
  15943. getRenderedLiteralValue(includeChildrenRecursively) {
  15944. if (this.renderedLiteralValue !== UNASSIGNED)
  15945. return this.renderedLiteralValue;
  15946. return (this.renderedLiteralValue = includeChildrenRecursively
  15947. ? UnknownValue
  15948. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  15949. }
  15950. include(context, includeChildrenRecursively, _options) {
  15951. if (!this.deoptimized)
  15952. this.applyDeoptimizations();
  15953. this.included = true;
  15954. // Check if the argument is an identifier that should be preserved as a reference for readability
  15955. const shouldPreserveArgument = this.argument instanceof Identifier && this.argument.variable?.included;
  15956. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  15957. this.argument.shouldBeIncluded(context) ||
  15958. shouldPreserveArgument) {
  15959. this.argument.include(context, includeChildrenRecursively);
  15960. this.renderedLiteralValue = UnknownValue;
  15961. }
  15962. }
  15963. render(code, options) {
  15964. if (typeof this.renderedLiteralValue === 'symbol') {
  15965. super.render(code, options);
  15966. }
  15967. else {
  15968. let value = this.renderedLiteralValue;
  15969. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  15970. value = ` ${value}`;
  15971. }
  15972. code.overwrite(this.start, this.end, value);
  15973. }
  15974. }
  15975. }
  15976. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  15977. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  15978. class UpdateExpression extends NodeBase {
  15979. hasEffects(context) {
  15980. if (!this.deoptimized)
  15981. this.applyDeoptimizations();
  15982. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  15983. }
  15984. hasEffectsOnInteractionAtPath(path, { type }) {
  15985. return path.length > 1 || type !== INTERACTION_ACCESSED;
  15986. }
  15987. include(context, includeChildrenRecursively) {
  15988. if (!this.included)
  15989. this.includeNode(context);
  15990. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  15991. }
  15992. initialise() {
  15993. super.initialise();
  15994. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  15995. }
  15996. render(code, options) {
  15997. const { exportNamesByVariable, format, snippets: { _ } } = options;
  15998. this.argument.render(code, options);
  15999. if (format === 'system') {
  16000. const variable = this.argument.variable;
  16001. const exportNames = exportNamesByVariable.get(variable);
  16002. if (exportNames) {
  16003. if (this.prefix) {
  16004. if (exportNames.length === 1) {
  16005. renderSystemExportExpression(variable, this.start, this.end, code, options);
  16006. }
  16007. else {
  16008. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options);
  16009. }
  16010. }
  16011. else {
  16012. const operator = this.operator[0];
  16013. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options, `${_}${operator}${_}1`);
  16014. }
  16015. }
  16016. }
  16017. }
  16018. applyDeoptimizations() {
  16019. this.deoptimized = true;
  16020. this.argument.deoptimizePath(EMPTY_PATH);
  16021. if (this.argument instanceof Identifier) {
  16022. const variable = this.scope.findVariable(this.argument.name);
  16023. variable.markReassigned();
  16024. }
  16025. this.scope.context.requestTreeshakingPass();
  16026. }
  16027. }
  16028. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  16029. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  16030. for (const declarator of declarations) {
  16031. if (!declarator.id.included)
  16032. return false;
  16033. if (declarator.id.type === parseAst_js.Identifier) {
  16034. if (exportNamesByVariable.has(declarator.id.variable))
  16035. return false;
  16036. }
  16037. else {
  16038. const exportedVariables = [];
  16039. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  16040. if (exportedVariables.length > 0)
  16041. return false;
  16042. }
  16043. }
  16044. return true;
  16045. }
  16046. class VariableDeclaration extends NodeBase {
  16047. deoptimizePath() {
  16048. for (const declarator of this.declarations) {
  16049. declarator.deoptimizePath(EMPTY_PATH);
  16050. }
  16051. }
  16052. hasEffectsOnInteractionAtPath() {
  16053. return false;
  16054. }
  16055. include(context, includeChildrenRecursively, { asSingleStatement } = parseAst_js.BLANK) {
  16056. this.included = true;
  16057. for (const declarator of this.declarations) {
  16058. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  16059. declarator.include(context, includeChildrenRecursively);
  16060. }
  16061. const { id, init } = declarator;
  16062. if (asSingleStatement) {
  16063. id.include(context, includeChildrenRecursively);
  16064. }
  16065. if (init &&
  16066. id.included &&
  16067. !init.included &&
  16068. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  16069. init.include(context, includeChildrenRecursively);
  16070. }
  16071. }
  16072. }
  16073. initialise() {
  16074. super.initialise();
  16075. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  16076. for (const declarator of this.declarations) {
  16077. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  16078. }
  16079. }
  16080. removeAnnotations(code) {
  16081. this.declarations[0].removeAnnotations(code);
  16082. }
  16083. render(code, options, nodeRenderOptions = parseAst_js.BLANK) {
  16084. if (this.isUsingDeclaration ||
  16085. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  16086. for (const declarator of this.declarations) {
  16087. declarator.render(code, options);
  16088. }
  16089. if (!nodeRenderOptions.isNoStatement &&
  16090. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  16091. code.appendLeft(this.end, ';');
  16092. }
  16093. }
  16094. else {
  16095. this.renderReplacedDeclarations(code, options);
  16096. }
  16097. }
  16098. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  16099. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  16100. code.remove(this.end - 1, this.end);
  16101. }
  16102. separatorString += ';';
  16103. if (lastSeparatorPos === null) {
  16104. code.appendLeft(renderedContentEnd, separatorString);
  16105. }
  16106. else {
  16107. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  16108. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  16109. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  16110. actualContentEnd--;
  16111. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  16112. actualContentEnd--;
  16113. }
  16114. }
  16115. if (actualContentEnd === lastSeparatorPos + 1) {
  16116. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  16117. }
  16118. else {
  16119. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  16120. code.remove(actualContentEnd, renderedContentEnd);
  16121. }
  16122. }
  16123. if (systemPatternExports.length > 0) {
  16124. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  16125. }
  16126. }
  16127. renderReplacedDeclarations(code, options) {
  16128. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  16129. let actualContentEnd, renderedContentEnd;
  16130. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  16131. let lastSeparatorPos = renderedContentEnd - 1;
  16132. code.remove(this.start, lastSeparatorPos);
  16133. let isInDeclaration = false;
  16134. let hasRenderedContent = false;
  16135. let separatorString = '', leadingString, nextSeparatorString;
  16136. const aggregatedSystemExports = [];
  16137. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  16138. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  16139. if (!node.included) {
  16140. treeshakeNode(node, code, start, end);
  16141. continue;
  16142. }
  16143. node.render(code, options);
  16144. leadingString = '';
  16145. nextSeparatorString = '';
  16146. if (!node.id.included ||
  16147. (node.id instanceof Identifier &&
  16148. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  16149. if (hasRenderedContent) {
  16150. separatorString += ';';
  16151. }
  16152. isInDeclaration = false;
  16153. }
  16154. else {
  16155. if (singleSystemExport && singleSystemExport === node.id.variable) {
  16156. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  16157. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  16158. }
  16159. if (isInDeclaration) {
  16160. separatorString += ',';
  16161. }
  16162. else {
  16163. if (hasRenderedContent) {
  16164. separatorString += ';';
  16165. }
  16166. leadingString += `${this.kind} `;
  16167. isInDeclaration = true;
  16168. }
  16169. }
  16170. if (renderedContentEnd === lastSeparatorPos + 1) {
  16171. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  16172. }
  16173. else {
  16174. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  16175. code.appendLeft(renderedContentEnd, leadingString);
  16176. }
  16177. actualContentEnd = contentEnd;
  16178. renderedContentEnd = end;
  16179. hasRenderedContent = true;
  16180. lastSeparatorPos = separator;
  16181. separatorString = nextSeparatorString;
  16182. }
  16183. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  16184. }
  16185. }
  16186. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  16187. let singleSystemExport = null;
  16188. if (options.format === 'system') {
  16189. for (const { node } of separatedNodes) {
  16190. if (node.id instanceof Identifier &&
  16191. node.init &&
  16192. aggregatedSystemExports.length === 0 &&
  16193. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  16194. singleSystemExport = node.id.variable;
  16195. aggregatedSystemExports.push(singleSystemExport);
  16196. }
  16197. else {
  16198. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  16199. }
  16200. }
  16201. if (aggregatedSystemExports.length > 1) {
  16202. singleSystemExport = null;
  16203. }
  16204. else if (singleSystemExport) {
  16205. aggregatedSystemExports.length = 0;
  16206. }
  16207. }
  16208. return singleSystemExport;
  16209. }
  16210. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16211. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  16212. class WhileStatement extends NodeBase {
  16213. hasEffects(context) {
  16214. if (this.test.hasEffects(context))
  16215. return true;
  16216. return hasLoopBodyEffects(context, this.body);
  16217. }
  16218. include(context, includeChildrenRecursively) {
  16219. this.included = true;
  16220. this.test.include(context, includeChildrenRecursively);
  16221. includeLoopBody(context, this.body, includeChildrenRecursively);
  16222. }
  16223. }
  16224. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  16225. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  16226. class YieldExpression extends NodeBase {
  16227. applyDeoptimizations() {
  16228. this.deoptimized = true;
  16229. this.argument?.deoptimizePath(UNKNOWN_PATH);
  16230. }
  16231. hasEffects(context) {
  16232. if (!this.deoptimized)
  16233. this.applyDeoptimizations();
  16234. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  16235. }
  16236. includeNode(context) {
  16237. this.included = true;
  16238. if (!this.deoptimized)
  16239. this.applyDeoptimizations();
  16240. this.argument?.includePath(UNKNOWN_PATH, context);
  16241. }
  16242. render(code, options) {
  16243. if (this.argument) {
  16244. this.argument.render(code, options, { preventASI: true });
  16245. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  16246. code.prependLeft(this.start + 5, ' ');
  16247. }
  16248. }
  16249. }
  16250. }
  16251. // This file is generated by scripts/generate-buffer-parsers.js.
  16252. // Do not edit this file directly.
  16253. function convertProgram(buffer, parent, parentScope) {
  16254. return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
  16255. }
  16256. const nodeTypeStrings = [
  16257. 'PanicError',
  16258. 'ParseError',
  16259. 'ArrayExpression',
  16260. 'ArrayPattern',
  16261. 'ArrowFunctionExpression',
  16262. 'AssignmentExpression',
  16263. 'AssignmentPattern',
  16264. 'AwaitExpression',
  16265. 'BinaryExpression',
  16266. 'BlockStatement',
  16267. 'BreakStatement',
  16268. 'CallExpression',
  16269. 'CatchClause',
  16270. 'ChainExpression',
  16271. 'ClassBody',
  16272. 'ClassDeclaration',
  16273. 'ClassExpression',
  16274. 'ConditionalExpression',
  16275. 'ContinueStatement',
  16276. 'DebuggerStatement',
  16277. 'Decorator',
  16278. 'ExpressionStatement',
  16279. 'DoWhileStatement',
  16280. 'EmptyStatement',
  16281. 'ExportAllDeclaration',
  16282. 'ExportDefaultDeclaration',
  16283. 'ExportNamedDeclaration',
  16284. 'ExportSpecifier',
  16285. 'ExpressionStatement',
  16286. 'ForInStatement',
  16287. 'ForOfStatement',
  16288. 'ForStatement',
  16289. 'FunctionDeclaration',
  16290. 'FunctionExpression',
  16291. 'Identifier',
  16292. 'IfStatement',
  16293. 'ImportAttribute',
  16294. 'ImportDeclaration',
  16295. 'ImportDefaultSpecifier',
  16296. 'ImportExpression',
  16297. 'ImportNamespaceSpecifier',
  16298. 'ImportSpecifier',
  16299. 'JSXAttribute',
  16300. 'JSXClosingElement',
  16301. 'JSXClosingFragment',
  16302. 'JSXElement',
  16303. 'JSXEmptyExpression',
  16304. 'JSXExpressionContainer',
  16305. 'JSXFragment',
  16306. 'JSXIdentifier',
  16307. 'JSXMemberExpression',
  16308. 'JSXNamespacedName',
  16309. 'JSXOpeningElement',
  16310. 'JSXOpeningFragment',
  16311. 'JSXSpreadAttribute',
  16312. 'JSXSpreadChild',
  16313. 'JSXText',
  16314. 'LabeledStatement',
  16315. 'Literal',
  16316. 'Literal',
  16317. 'Literal',
  16318. 'Literal',
  16319. 'Literal',
  16320. 'Literal',
  16321. 'LogicalExpression',
  16322. 'MemberExpression',
  16323. 'MetaProperty',
  16324. 'MethodDefinition',
  16325. 'NewExpression',
  16326. 'ObjectExpression',
  16327. 'ObjectPattern',
  16328. 'PrivateIdentifier',
  16329. 'Program',
  16330. 'Property',
  16331. 'PropertyDefinition',
  16332. 'RestElement',
  16333. 'ReturnStatement',
  16334. 'SequenceExpression',
  16335. 'SpreadElement',
  16336. 'StaticBlock',
  16337. 'Super',
  16338. 'SwitchCase',
  16339. 'SwitchStatement',
  16340. 'TaggedTemplateExpression',
  16341. 'TemplateElement',
  16342. 'TemplateLiteral',
  16343. 'ThisExpression',
  16344. 'ThrowStatement',
  16345. 'TryStatement',
  16346. 'UnaryExpression',
  16347. 'UpdateExpression',
  16348. 'VariableDeclaration',
  16349. 'VariableDeclarator',
  16350. 'WhileStatement',
  16351. 'YieldExpression'
  16352. ];
  16353. const nodeConstructors$1 = [
  16354. PanicError,
  16355. ParseError,
  16356. ArrayExpression,
  16357. ArrayPattern,
  16358. ArrowFunctionExpression,
  16359. AssignmentExpression,
  16360. AssignmentPattern,
  16361. AwaitExpression,
  16362. BinaryExpression,
  16363. BlockStatement,
  16364. BreakStatement,
  16365. CallExpression,
  16366. CatchClause,
  16367. ChainExpression,
  16368. ClassBody,
  16369. ClassDeclaration,
  16370. ClassExpression,
  16371. ConditionalExpression,
  16372. ContinueStatement,
  16373. DebuggerStatement,
  16374. Decorator,
  16375. ExpressionStatement,
  16376. DoWhileStatement,
  16377. EmptyStatement,
  16378. ExportAllDeclaration,
  16379. ExportDefaultDeclaration,
  16380. ExportNamedDeclaration,
  16381. ExportSpecifier,
  16382. ExpressionStatement,
  16383. ForInStatement,
  16384. ForOfStatement,
  16385. ForStatement,
  16386. FunctionDeclaration,
  16387. FunctionExpression,
  16388. Identifier,
  16389. IfStatement,
  16390. ImportAttribute,
  16391. ImportDeclaration,
  16392. ImportDefaultSpecifier,
  16393. ImportExpression,
  16394. ImportNamespaceSpecifier,
  16395. ImportSpecifier,
  16396. JSXAttribute,
  16397. JSXClosingElement,
  16398. JSXClosingFragment,
  16399. JSXElement,
  16400. JSXEmptyExpression,
  16401. JSXExpressionContainer,
  16402. JSXFragment,
  16403. JSXIdentifier,
  16404. JSXMemberExpression,
  16405. JSXNamespacedName,
  16406. JSXOpeningElement,
  16407. JSXOpeningFragment,
  16408. JSXSpreadAttribute,
  16409. JSXSpreadChild,
  16410. JSXText,
  16411. LabeledStatement,
  16412. Literal,
  16413. Literal,
  16414. Literal,
  16415. Literal,
  16416. Literal,
  16417. Literal,
  16418. LogicalExpression,
  16419. MemberExpression,
  16420. MetaProperty,
  16421. MethodDefinition,
  16422. NewExpression,
  16423. ObjectExpression,
  16424. ObjectPattern,
  16425. PrivateIdentifier,
  16426. Program,
  16427. Property,
  16428. PropertyDefinition,
  16429. RestElement,
  16430. ReturnStatement,
  16431. SequenceExpression,
  16432. SpreadElement,
  16433. StaticBlock,
  16434. Super,
  16435. SwitchCase,
  16436. SwitchStatement,
  16437. TaggedTemplateExpression,
  16438. TemplateElement,
  16439. TemplateLiteral,
  16440. ThisExpression,
  16441. ThrowStatement,
  16442. TryStatement,
  16443. UnaryExpression,
  16444. UpdateExpression,
  16445. VariableDeclaration,
  16446. VariableDeclarator,
  16447. WhileStatement,
  16448. YieldExpression
  16449. ];
  16450. const bufferParsers = [
  16451. function panicError(node, position, buffer) {
  16452. node.message = buffer.convertString(buffer[position]);
  16453. },
  16454. function parseError(node, position, buffer) {
  16455. node.message = buffer.convertString(buffer[position]);
  16456. },
  16457. function arrayExpression(node, position, buffer) {
  16458. const { scope } = node;
  16459. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16460. },
  16461. function arrayPattern(node, position, buffer) {
  16462. const { scope } = node;
  16463. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16464. },
  16465. function arrowFunctionExpression(node, position, buffer) {
  16466. const { scope } = node;
  16467. const flags = buffer[position];
  16468. node.async = (flags & 1) === 1;
  16469. node.expression = (flags & 2) === 2;
  16470. node.generator = (flags & 4) === 4;
  16471. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16472. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16473. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  16474. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16475. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  16476. },
  16477. function assignmentExpression(node, position, buffer) {
  16478. const { scope } = node;
  16479. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16480. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16481. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16482. },
  16483. function assignmentPattern(node, position, buffer) {
  16484. const { scope } = node;
  16485. node.left = convertNode(node, scope, buffer[position], buffer);
  16486. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16487. },
  16488. function awaitExpression(node, position, buffer) {
  16489. const { scope } = node;
  16490. node.argument = convertNode(node, scope, buffer[position], buffer);
  16491. },
  16492. function binaryExpression(node, position, buffer) {
  16493. const { scope } = node;
  16494. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16495. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16496. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16497. },
  16498. function blockStatement(node, position, buffer) {
  16499. const { scope } = node;
  16500. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16501. },
  16502. function breakStatement(node, position, buffer) {
  16503. const { scope } = node;
  16504. const labelPosition = buffer[position];
  16505. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16506. },
  16507. function callExpression(node, position, buffer) {
  16508. const { scope } = node;
  16509. const flags = buffer[position];
  16510. node.optional = (flags & 1) === 1;
  16511. node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16512. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  16513. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  16514. },
  16515. function catchClause(node, position, buffer) {
  16516. const { scope } = node;
  16517. const parameterPosition = buffer[position];
  16518. const parameter = (node.param =
  16519. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  16520. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  16521. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  16522. },
  16523. function chainExpression(node, position, buffer) {
  16524. const { scope } = node;
  16525. node.expression = convertNode(node, scope, buffer[position], buffer);
  16526. },
  16527. function classBody(node, position, buffer) {
  16528. const { scope } = node;
  16529. const bodyPosition = buffer[position];
  16530. if (bodyPosition) {
  16531. const length = buffer[bodyPosition];
  16532. const body = (node.body = new Array(length));
  16533. for (let index = 0; index < length; index++) {
  16534. const nodePosition = buffer[bodyPosition + 1 + index];
  16535. body[index] = convertNode(node, buffer[nodePosition] !== 79 &&
  16536. (buffer[nodePosition + 3] & /* the static flag is always first */ 1) === 0
  16537. ? scope.instanceScope
  16538. : scope, nodePosition, buffer);
  16539. }
  16540. }
  16541. else {
  16542. node.body = [];
  16543. }
  16544. },
  16545. function classDeclaration(node, position, buffer) {
  16546. const { scope } = node;
  16547. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16548. const idPosition = buffer[position + 1];
  16549. node.id =
  16550. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16551. const superClassPosition = buffer[position + 2];
  16552. node.superClass =
  16553. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16554. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16555. },
  16556. function classExpression(node, position, buffer) {
  16557. const { scope } = node;
  16558. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16559. const idPosition = buffer[position + 1];
  16560. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  16561. const superClassPosition = buffer[position + 2];
  16562. node.superClass =
  16563. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16564. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16565. },
  16566. function conditionalExpression(node, position, buffer) {
  16567. const { scope } = node;
  16568. node.test = convertNode(node, scope, buffer[position], buffer);
  16569. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  16570. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  16571. },
  16572. function continueStatement(node, position, buffer) {
  16573. const { scope } = node;
  16574. const labelPosition = buffer[position];
  16575. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16576. },
  16577. function debuggerStatement() { },
  16578. function decorator(node, position, buffer) {
  16579. const { scope } = node;
  16580. node.expression = convertNode(node, scope, buffer[position], buffer);
  16581. },
  16582. function directive(node, position, buffer) {
  16583. const { scope } = node;
  16584. node.directive = buffer.convertString(buffer[position]);
  16585. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  16586. },
  16587. function doWhileStatement(node, position, buffer) {
  16588. const { scope } = node;
  16589. node.body = convertNode(node, scope, buffer[position], buffer);
  16590. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  16591. },
  16592. function emptyStatement() { },
  16593. function exportAllDeclaration(node, position, buffer) {
  16594. const { scope } = node;
  16595. const exportedPosition = buffer[position];
  16596. node.exported =
  16597. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  16598. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16599. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16600. },
  16601. function exportDefaultDeclaration(node, position, buffer) {
  16602. const { scope } = node;
  16603. node.declaration = convertNode(node, scope, buffer[position], buffer);
  16604. },
  16605. function exportNamedDeclaration(node, position, buffer) {
  16606. const { scope } = node;
  16607. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16608. const sourcePosition = buffer[position + 1];
  16609. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  16610. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16611. const declarationPosition = buffer[position + 3];
  16612. node.declaration =
  16613. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  16614. },
  16615. function exportSpecifier(node, position, buffer) {
  16616. const { scope } = node;
  16617. node.local = convertNode(node, scope, buffer[position], buffer);
  16618. const exportedPosition = buffer[position + 1];
  16619. node.exported =
  16620. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  16621. },
  16622. function expressionStatement(node, position, buffer) {
  16623. const { scope } = node;
  16624. node.expression = convertNode(node, scope, buffer[position], buffer);
  16625. },
  16626. function forInStatement(node, position, buffer) {
  16627. const { scope } = node;
  16628. node.left = convertNode(node, scope, buffer[position], buffer);
  16629. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16630. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  16631. },
  16632. function forOfStatement(node, position, buffer) {
  16633. const { scope } = node;
  16634. const flags = buffer[position];
  16635. node.await = (flags & 1) === 1;
  16636. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16637. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16638. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16639. },
  16640. function forStatement(node, position, buffer) {
  16641. const { scope } = node;
  16642. const initPosition = buffer[position];
  16643. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16644. const testPosition = buffer[position + 1];
  16645. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16646. const updatePosition = buffer[position + 2];
  16647. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  16648. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16649. },
  16650. function functionDeclaration(node, position, buffer) {
  16651. const { scope } = node;
  16652. const flags = buffer[position];
  16653. node.async = (flags & 1) === 1;
  16654. node.generator = (flags & 2) === 2;
  16655. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16656. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16657. const idPosition = buffer[position + 2];
  16658. node.id =
  16659. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16660. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16661. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16662. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16663. },
  16664. function functionExpression(node, position, buffer) {
  16665. const { scope } = node;
  16666. const flags = buffer[position];
  16667. node.async = (flags & 1) === 1;
  16668. node.generator = (flags & 2) === 2;
  16669. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16670. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16671. const idPosition = buffer[position + 2];
  16672. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  16673. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16674. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16675. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16676. },
  16677. function identifier(node, position, buffer) {
  16678. node.name = buffer.convertString(buffer[position]);
  16679. },
  16680. function ifStatement(node, position, buffer) {
  16681. const { scope } = node;
  16682. node.test = convertNode(node, scope, buffer[position], buffer);
  16683. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  16684. const alternatePosition = buffer[position + 2];
  16685. node.alternate =
  16686. alternatePosition === 0
  16687. ? null
  16688. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  16689. },
  16690. function importAttribute(node, position, buffer) {
  16691. const { scope } = node;
  16692. node.key = convertNode(node, scope, buffer[position], buffer);
  16693. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  16694. },
  16695. function importDeclaration(node, position, buffer) {
  16696. const { scope } = node;
  16697. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16698. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16699. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16700. },
  16701. function importDefaultSpecifier(node, position, buffer) {
  16702. const { scope } = node;
  16703. node.local = convertNode(node, scope, buffer[position], buffer);
  16704. },
  16705. function importExpression(node, position, buffer) {
  16706. const { scope } = node;
  16707. node.source = convertNode(node, scope, buffer[position], buffer);
  16708. node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
  16709. const optionsPosition = buffer[position + 1];
  16710. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  16711. },
  16712. function importNamespaceSpecifier(node, position, buffer) {
  16713. const { scope } = node;
  16714. node.local = convertNode(node, scope, buffer[position], buffer);
  16715. },
  16716. function importSpecifier(node, position, buffer) {
  16717. const { scope } = node;
  16718. const importedPosition = buffer[position];
  16719. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  16720. node.imported =
  16721. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  16722. },
  16723. function jsxAttribute(node, position, buffer) {
  16724. const { scope } = node;
  16725. node.name = convertNode(node, scope, buffer[position], buffer);
  16726. const valuePosition = buffer[position + 1];
  16727. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16728. },
  16729. function jsxClosingElement(node, position, buffer) {
  16730. const { scope } = node;
  16731. node.name = convertNode(node, scope, buffer[position], buffer);
  16732. },
  16733. function jsxClosingFragment() { },
  16734. function jsxElement(node, position, buffer) {
  16735. const { scope } = node;
  16736. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  16737. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16738. const closingElementPosition = buffer[position + 2];
  16739. node.closingElement =
  16740. closingElementPosition === 0
  16741. ? null
  16742. : convertNode(node, scope, closingElementPosition, buffer);
  16743. },
  16744. function jsxEmptyExpression() { },
  16745. function jsxExpressionContainer(node, position, buffer) {
  16746. const { scope } = node;
  16747. node.expression = convertNode(node, scope, buffer[position], buffer);
  16748. },
  16749. function jsxFragment(node, position, buffer) {
  16750. const { scope } = node;
  16751. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  16752. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16753. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  16754. },
  16755. function jsxIdentifier(node, position, buffer) {
  16756. node.name = buffer.convertString(buffer[position]);
  16757. },
  16758. function jsxMemberExpression(node, position, buffer) {
  16759. const { scope } = node;
  16760. node.object = convertNode(node, scope, buffer[position], buffer);
  16761. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16762. },
  16763. function jsxNamespacedName(node, position, buffer) {
  16764. const { scope } = node;
  16765. node.namespace = convertNode(node, scope, buffer[position], buffer);
  16766. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16767. },
  16768. function jsxOpeningElement(node, position, buffer) {
  16769. const { scope } = node;
  16770. const flags = buffer[position];
  16771. node.selfClosing = (flags & 1) === 1;
  16772. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16773. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16774. },
  16775. function jsxOpeningFragment(node) {
  16776. node.attributes = [];
  16777. node.selfClosing = false;
  16778. },
  16779. function jsxSpreadAttribute(node, position, buffer) {
  16780. const { scope } = node;
  16781. node.argument = convertNode(node, scope, buffer[position], buffer);
  16782. },
  16783. function jsxSpreadChild(node, position, buffer) {
  16784. const { scope } = node;
  16785. node.expression = convertNode(node, scope, buffer[position], buffer);
  16786. },
  16787. function jsxText(node, position, buffer) {
  16788. node.value = buffer.convertString(buffer[position]);
  16789. node.raw = buffer.convertString(buffer[position + 1]);
  16790. },
  16791. function labeledStatement(node, position, buffer) {
  16792. const { scope } = node;
  16793. node.label = convertNode(node, scope, buffer[position], buffer);
  16794. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16795. },
  16796. function literalBigInt(node, position, buffer) {
  16797. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  16798. node.raw = buffer.convertString(buffer[position + 1]);
  16799. node.value = BigInt(bigint);
  16800. },
  16801. function literalBoolean(node, position, buffer) {
  16802. const flags = buffer[position];
  16803. const value = (node.value = (flags & 1) === 1);
  16804. node.raw = value ? 'true' : 'false';
  16805. },
  16806. function literalNull(node) {
  16807. node.value = null;
  16808. },
  16809. function literalNumber(node, position, buffer) {
  16810. const rawPosition = buffer[position];
  16811. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16812. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  16813. },
  16814. function literalRegExp(node, position, buffer) {
  16815. const flags = buffer.convertString(buffer[position]);
  16816. const pattern = buffer.convertString(buffer[position + 1]);
  16817. node.raw = `/${pattern}/${flags}`;
  16818. node.regex = { flags, pattern };
  16819. node.value = new RegExp(pattern, flags);
  16820. },
  16821. function literalString(node, position, buffer) {
  16822. node.value = buffer.convertString(buffer[position]);
  16823. const rawPosition = buffer[position + 1];
  16824. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16825. },
  16826. function logicalExpression(node, position, buffer) {
  16827. const { scope } = node;
  16828. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16829. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16830. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16831. },
  16832. function memberExpression(node, position, buffer) {
  16833. const { scope } = node;
  16834. const flags = buffer[position];
  16835. node.computed = (flags & 1) === 1;
  16836. node.optional = (flags & 2) === 2;
  16837. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  16838. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  16839. },
  16840. function metaProperty(node, position, buffer) {
  16841. const { scope } = node;
  16842. node.meta = convertNode(node, scope, buffer[position], buffer);
  16843. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16844. },
  16845. function methodDefinition(node, position, buffer) {
  16846. const { scope } = node;
  16847. const flags = buffer[position];
  16848. node.static = (flags & 1) === 1;
  16849. node.computed = (flags & 2) === 2;
  16850. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16851. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16852. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  16853. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 4]];
  16854. },
  16855. function newExpression(node, position, buffer) {
  16856. const { scope } = node;
  16857. node.annotations = parseAst_js.convertAnnotations(buffer[position], buffer);
  16858. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  16859. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  16860. },
  16861. function objectExpression(node, position, buffer) {
  16862. const { scope } = node;
  16863. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16864. },
  16865. function objectPattern(node, position, buffer) {
  16866. const { scope } = node;
  16867. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16868. },
  16869. function privateIdentifier(node, position, buffer) {
  16870. node.name = buffer.convertString(buffer[position]);
  16871. },
  16872. function program(node, position, buffer) {
  16873. const { scope } = node;
  16874. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16875. node.invalidAnnotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16876. },
  16877. function property(node, position, buffer) {
  16878. const { scope } = node;
  16879. const flags = buffer[position];
  16880. node.method = (flags & 1) === 1;
  16881. node.shorthand = (flags & 2) === 2;
  16882. node.computed = (flags & 4) === 4;
  16883. const keyPosition = buffer[position + 1];
  16884. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  16885. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 3]];
  16886. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  16887. },
  16888. function propertyDefinition(node, position, buffer) {
  16889. const { scope } = node;
  16890. const flags = buffer[position];
  16891. node.static = (flags & 1) === 1;
  16892. node.computed = (flags & 2) === 2;
  16893. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16894. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16895. const valuePosition = buffer[position + 3];
  16896. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16897. },
  16898. function restElement(node, position, buffer) {
  16899. const { scope } = node;
  16900. node.argument = convertNode(node, scope, buffer[position], buffer);
  16901. },
  16902. function returnStatement(node, position, buffer) {
  16903. const { scope } = node;
  16904. const argumentPosition = buffer[position];
  16905. node.argument =
  16906. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16907. },
  16908. function sequenceExpression(node, position, buffer) {
  16909. const { scope } = node;
  16910. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  16911. },
  16912. function spreadElement(node, position, buffer) {
  16913. const { scope } = node;
  16914. node.argument = convertNode(node, scope, buffer[position], buffer);
  16915. },
  16916. function staticBlock(node, position, buffer) {
  16917. const { scope } = node;
  16918. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16919. },
  16920. function superElement() { },
  16921. function switchCase(node, position, buffer) {
  16922. const { scope } = node;
  16923. const testPosition = buffer[position];
  16924. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16925. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  16926. },
  16927. function switchStatement(node, position, buffer) {
  16928. const { scope } = node;
  16929. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  16930. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  16931. },
  16932. function taggedTemplateExpression(node, position, buffer) {
  16933. const { scope } = node;
  16934. node.tag = convertNode(node, scope, buffer[position], buffer);
  16935. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  16936. },
  16937. function templateElement(node, position, buffer) {
  16938. const flags = buffer[position];
  16939. node.tail = (flags & 1) === 1;
  16940. const cookedPosition = buffer[position + 1];
  16941. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  16942. const raw = buffer.convertString(buffer[position + 2]);
  16943. node.value = { cooked, raw };
  16944. },
  16945. function templateLiteral(node, position, buffer) {
  16946. const { scope } = node;
  16947. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  16948. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  16949. },
  16950. function thisExpression() { },
  16951. function throwStatement(node, position, buffer) {
  16952. const { scope } = node;
  16953. node.argument = convertNode(node, scope, buffer[position], buffer);
  16954. },
  16955. function tryStatement(node, position, buffer) {
  16956. const { scope } = node;
  16957. node.block = convertNode(node, scope, buffer[position], buffer);
  16958. const handlerPosition = buffer[position + 1];
  16959. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  16960. const finalizerPosition = buffer[position + 2];
  16961. node.finalizer =
  16962. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  16963. },
  16964. function unaryExpression(node, position, buffer) {
  16965. const { scope } = node;
  16966. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16967. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  16968. },
  16969. function updateExpression(node, position, buffer) {
  16970. const { scope } = node;
  16971. const flags = buffer[position];
  16972. node.prefix = (flags & 1) === 1;
  16973. node.operator = parseAst_js.FIXED_STRINGS[buffer[position + 1]];
  16974. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  16975. },
  16976. function variableDeclaration(node, position, buffer) {
  16977. const { scope } = node;
  16978. node.kind = parseAst_js.FIXED_STRINGS[buffer[position]];
  16979. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  16980. },
  16981. function variableDeclarator(node, position, buffer) {
  16982. const { scope } = node;
  16983. node.id = convertNode(node, scope, buffer[position], buffer);
  16984. const initPosition = buffer[position + 1];
  16985. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16986. },
  16987. function whileStatement(node, position, buffer) {
  16988. const { scope } = node;
  16989. node.test = convertNode(node, scope, buffer[position], buffer);
  16990. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16991. },
  16992. function yieldExpression(node, position, buffer) {
  16993. const { scope } = node;
  16994. const flags = buffer[position];
  16995. node.delegate = (flags & 1) === 1;
  16996. const argumentPosition = buffer[position + 1];
  16997. node.argument =
  16998. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16999. }
  17000. ];
  17001. function convertNode(parent, parentScope, position, buffer) {
  17002. const nodeType = buffer[position];
  17003. const NodeConstructor = nodeConstructors$1[nodeType];
  17004. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  17005. if (!NodeConstructor) {
  17006. console.trace();
  17007. throw new Error(`Unknown node type: ${nodeType}`);
  17008. }
  17009. const node = new NodeConstructor(parent, parentScope);
  17010. node.type = nodeTypeStrings[nodeType];
  17011. node.start = buffer[position + 1];
  17012. node.end = buffer[position + 2];
  17013. bufferParsers[nodeType](node, position + 3, buffer);
  17014. node.initialise();
  17015. return node;
  17016. }
  17017. function convertNodeList(parent, parentScope, position, buffer) {
  17018. if (position === 0)
  17019. return parseAst_js.EMPTY_ARRAY;
  17020. const length = buffer[position++];
  17021. const list = new Array(length);
  17022. for (let index = 0; index < length; index++) {
  17023. const nodePosition = buffer[position++];
  17024. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  17025. }
  17026. return list;
  17027. }
  17028. class UnknownNode extends NodeBase {
  17029. hasEffects() {
  17030. return true;
  17031. }
  17032. include(context) {
  17033. super.include(context, true);
  17034. }
  17035. }
  17036. // This file is generated by scripts/generate-node-index.js.
  17037. // Do not edit this file directly.
  17038. const nodeConstructors = {
  17039. ArrayExpression,
  17040. ArrayPattern,
  17041. ArrowFunctionExpression,
  17042. AssignmentExpression,
  17043. AssignmentPattern,
  17044. AwaitExpression,
  17045. BinaryExpression,
  17046. BlockStatement,
  17047. BreakStatement,
  17048. CallExpression,
  17049. CatchClause,
  17050. ChainExpression,
  17051. ClassBody,
  17052. ClassDeclaration,
  17053. ClassExpression,
  17054. ConditionalExpression,
  17055. ContinueStatement,
  17056. DebuggerStatement,
  17057. Decorator,
  17058. DoWhileStatement,
  17059. EmptyStatement,
  17060. ExportAllDeclaration,
  17061. ExportDefaultDeclaration,
  17062. ExportNamedDeclaration,
  17063. ExportSpecifier,
  17064. ExpressionStatement,
  17065. ForInStatement,
  17066. ForOfStatement,
  17067. ForStatement,
  17068. FunctionDeclaration,
  17069. FunctionExpression,
  17070. Identifier,
  17071. IfStatement,
  17072. ImportAttribute,
  17073. ImportDeclaration,
  17074. ImportDefaultSpecifier,
  17075. ImportExpression,
  17076. ImportNamespaceSpecifier,
  17077. ImportSpecifier,
  17078. JSXAttribute,
  17079. JSXClosingElement,
  17080. JSXClosingFragment,
  17081. JSXElement,
  17082. JSXEmptyExpression,
  17083. JSXExpressionContainer,
  17084. JSXFragment,
  17085. JSXIdentifier,
  17086. JSXMemberExpression,
  17087. JSXNamespacedName,
  17088. JSXOpeningElement,
  17089. JSXOpeningFragment,
  17090. JSXSpreadAttribute,
  17091. JSXSpreadChild,
  17092. JSXText,
  17093. LabeledStatement,
  17094. Literal,
  17095. LogicalExpression,
  17096. MemberExpression,
  17097. MetaProperty,
  17098. MethodDefinition,
  17099. NewExpression,
  17100. ObjectExpression,
  17101. ObjectPattern,
  17102. PanicError,
  17103. ParseError,
  17104. PrivateIdentifier,
  17105. Program,
  17106. Property,
  17107. PropertyDefinition,
  17108. RestElement,
  17109. ReturnStatement,
  17110. SequenceExpression,
  17111. SpreadElement,
  17112. StaticBlock,
  17113. Super,
  17114. SwitchCase,
  17115. SwitchStatement,
  17116. TaggedTemplateExpression,
  17117. TemplateElement,
  17118. TemplateLiteral,
  17119. ThisExpression,
  17120. ThrowStatement,
  17121. TryStatement,
  17122. UnaryExpression,
  17123. UnknownNode,
  17124. UpdateExpression,
  17125. VariableDeclaration,
  17126. VariableDeclarator,
  17127. WhileStatement,
  17128. YieldExpression
  17129. };
  17130. class ExportShimVariable extends Variable {
  17131. constructor(module) {
  17132. super(MISSING_EXPORT_SHIM_VARIABLE);
  17133. this.module = module;
  17134. }
  17135. includePath(path, context) {
  17136. super.includePath(path, context);
  17137. this.module.needsExportShim = true;
  17138. }
  17139. }
  17140. const sourceMapCache = new WeakMap();
  17141. /**
  17142. * This clears the decoded array and falls back to the encoded string form.
  17143. * Sourcemap mappings arrays can be very large and holding on to them for longer
  17144. * than is necessary leads to poor heap utilization.
  17145. */
  17146. function resetCacheToEncoded(cache) {
  17147. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  17148. cache.encodedMappings = encode(cache.decodedMappings);
  17149. }
  17150. cache.decodedMappings = undefined;
  17151. }
  17152. function resetSourcemapCache(map, sourcemapChain) {
  17153. if (map) {
  17154. const cache = sourceMapCache.get(map);
  17155. if (cache) {
  17156. resetCacheToEncoded(cache);
  17157. }
  17158. }
  17159. if (!sourcemapChain) {
  17160. return;
  17161. }
  17162. for (const map of sourcemapChain) {
  17163. if (map.missing)
  17164. continue;
  17165. resetSourcemapCache(map);
  17166. }
  17167. }
  17168. function decodedSourcemap(map) {
  17169. if (!map)
  17170. return null;
  17171. if (typeof map === 'string') {
  17172. map = JSON.parse(map);
  17173. }
  17174. if (!map.mappings) {
  17175. return {
  17176. mappings: [],
  17177. names: [],
  17178. sources: [],
  17179. version: 3
  17180. };
  17181. }
  17182. const originalMappings = map.mappings;
  17183. const isAlreadyDecoded = Array.isArray(originalMappings);
  17184. const cache = {
  17185. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  17186. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  17187. };
  17188. const decodedMap = {
  17189. ...map,
  17190. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  17191. // where the mappings field is never actually accessed. This appears to greatly reduce
  17192. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  17193. get mappings() {
  17194. if (cache.decodedMappings) {
  17195. return cache.decodedMappings;
  17196. }
  17197. // If decodedMappings doesn't exist then encodedMappings should.
  17198. // The only scenario where cache.encodedMappings should be undefined is if the map
  17199. // this was constructed from was already decoded, or if mappings was set to a new
  17200. // decoded string. In either case, this line shouldn't get hit.
  17201. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  17202. cache.encodedMappings = undefined;
  17203. return cache.decodedMappings;
  17204. }
  17205. };
  17206. sourceMapCache.set(decodedMap, cache);
  17207. return decodedMap;
  17208. }
  17209. function getId(m) {
  17210. return m.id;
  17211. }
  17212. function getOriginalLocation(sourcemapChain, location) {
  17213. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  17214. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  17215. const sourcemap = filteredSourcemapChain.pop();
  17216. const line = sourcemap.mappings[location.line - 1];
  17217. if (line) {
  17218. const filteredLine = line.filter((segment) => segment.length > 1);
  17219. const lastSegment = filteredLine[filteredLine.length - 1];
  17220. let previousSegment = filteredLine[0];
  17221. for (let segment of filteredLine) {
  17222. if (segment[0] >= location.column || segment === lastSegment) {
  17223. const notMatched = segment[0] !== location.column;
  17224. segment = notMatched ? previousSegment : segment;
  17225. location = {
  17226. column: segment[3],
  17227. line: segment[2] + 1
  17228. };
  17229. continue traceSourcemap;
  17230. }
  17231. previousSegment = segment;
  17232. }
  17233. }
  17234. throw new Error("Can't resolve original location of error.");
  17235. }
  17236. return location;
  17237. }
  17238. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  17239. function getAttributesFromImportExpression(node) {
  17240. const { scope: { context }, options, start } = node;
  17241. if (!(options instanceof ObjectExpression)) {
  17242. if (options) {
  17243. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), start);
  17244. }
  17245. return parseAst_js.EMPTY_OBJECT;
  17246. }
  17247. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  17248. if (!assertProperty) {
  17249. return parseAst_js.EMPTY_OBJECT;
  17250. }
  17251. if (!(assertProperty instanceof ObjectExpression)) {
  17252. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportOptionsAreInvalid(context.module.id), start);
  17253. return parseAst_js.EMPTY_OBJECT;
  17254. }
  17255. const assertFields = assertProperty.properties
  17256. .map(property => {
  17257. const key = getPropertyKey(property);
  17258. if (typeof key === 'string' &&
  17259. typeof property.value.value === 'string') {
  17260. return [key, property.value.value];
  17261. }
  17262. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), property.start);
  17263. return null;
  17264. })
  17265. .filter((property) => !!property);
  17266. if (assertFields.length > 0) {
  17267. return Object.fromEntries(assertFields);
  17268. }
  17269. return parseAst_js.EMPTY_OBJECT;
  17270. }
  17271. const getPropertyKey = (property) => {
  17272. const key = property.key;
  17273. return (key &&
  17274. !property.computed &&
  17275. (key.name || key.value));
  17276. };
  17277. function getAttributesFromImportExportDeclaration(attributes) {
  17278. return attributes?.length
  17279. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  17280. : parseAst_js.EMPTY_OBJECT;
  17281. }
  17282. function doAttributesDiffer(assertionA, assertionB) {
  17283. const keysA = Object.keys(assertionA);
  17284. return (keysA.length !== Object.keys(assertionB).length ||
  17285. keysA.some(key => assertionA[key] !== assertionB[key]));
  17286. }
  17287. let timers = new Map();
  17288. function getPersistedLabel(label, level) {
  17289. switch (level) {
  17290. case 1: {
  17291. return `# ${label}`;
  17292. }
  17293. case 2: {
  17294. return `## ${label}`;
  17295. }
  17296. case 3: {
  17297. return label;
  17298. }
  17299. default: {
  17300. return `- ${label}`;
  17301. }
  17302. }
  17303. }
  17304. function timeStartImpl(label, level = 3) {
  17305. label = getPersistedLabel(label, level);
  17306. const startMemory = process$1.memoryUsage().heapUsed;
  17307. const startTime = node_perf_hooks.performance.now();
  17308. const timer = timers.get(label);
  17309. if (timer === undefined) {
  17310. timers.set(label, {
  17311. memory: 0,
  17312. startMemory,
  17313. startTime,
  17314. time: 0,
  17315. totalMemory: 0
  17316. });
  17317. }
  17318. else {
  17319. timer.startMemory = startMemory;
  17320. timer.startTime = startTime;
  17321. }
  17322. }
  17323. function timeEndImpl(label, level = 3) {
  17324. label = getPersistedLabel(label, level);
  17325. const timer = timers.get(label);
  17326. if (timer !== undefined) {
  17327. const currentMemory = process$1.memoryUsage().heapUsed;
  17328. timer.memory += currentMemory - timer.startMemory;
  17329. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  17330. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  17331. }
  17332. }
  17333. function getTimings() {
  17334. const newTimings = {};
  17335. for (const [label, { memory, time, totalMemory }] of timers) {
  17336. newTimings[label] = [time, memory, totalMemory];
  17337. }
  17338. return newTimings;
  17339. }
  17340. let timeStart = doNothing;
  17341. let timeEnd = doNothing;
  17342. const TIMED_PLUGIN_HOOKS = [
  17343. 'augmentChunkHash',
  17344. 'buildEnd',
  17345. 'buildStart',
  17346. 'generateBundle',
  17347. 'load',
  17348. 'moduleParsed',
  17349. 'options',
  17350. 'outputOptions',
  17351. 'renderChunk',
  17352. 'renderDynamicImport',
  17353. 'renderStart',
  17354. 'resolveDynamicImport',
  17355. 'resolveFileUrl',
  17356. 'resolveId',
  17357. 'resolveImportMeta',
  17358. 'shouldTransformCachedModule',
  17359. 'transform',
  17360. 'writeBundle'
  17361. ];
  17362. function getPluginWithTimers(plugin, index) {
  17363. if (plugin._hasTimer)
  17364. return plugin;
  17365. plugin._hasTimer = true;
  17366. for (const hook of TIMED_PLUGIN_HOOKS) {
  17367. if (hook in plugin) {
  17368. let timerLabel = `plugin ${index}`;
  17369. if (plugin.name) {
  17370. timerLabel += ` (${plugin.name})`;
  17371. }
  17372. timerLabel += ` - ${hook}`;
  17373. const handler = function (...parameters) {
  17374. timeStart(timerLabel, 4);
  17375. const result = hookFunction.apply(this, parameters);
  17376. timeEnd(timerLabel, 4);
  17377. return result;
  17378. };
  17379. let hookFunction;
  17380. if (typeof plugin[hook].handler === 'function') {
  17381. hookFunction = plugin[hook].handler;
  17382. plugin[hook].handler = handler;
  17383. }
  17384. else {
  17385. hookFunction = plugin[hook];
  17386. plugin[hook] = handler;
  17387. }
  17388. }
  17389. }
  17390. return plugin;
  17391. }
  17392. function initialiseTimers(inputOptions) {
  17393. if (inputOptions.perf) {
  17394. timers = new Map();
  17395. timeStart = timeStartImpl;
  17396. timeEnd = timeEndImpl;
  17397. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  17398. }
  17399. else {
  17400. timeStart = doNothing;
  17401. timeEnd = doNothing;
  17402. }
  17403. }
  17404. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  17405. identifier: null,
  17406. localName: MISSING_EXPORT_SHIM_VARIABLE
  17407. };
  17408. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  17409. const searchedModules = searchedNamesAndModules.get(name);
  17410. if (searchedModules) {
  17411. if (searchedModules.has(target)) {
  17412. return isExportAllSearch ? [null] : parseAst_js.error(parseAst_js.logCircularReexport(name, target.id));
  17413. }
  17414. searchedModules.add(target);
  17415. }
  17416. else {
  17417. searchedNamesAndModules.set(name, new Set([target]));
  17418. }
  17419. return target.getVariableForExportName(name, {
  17420. importerForSideEffects,
  17421. isExportAllSearch,
  17422. searchedNamesAndModules
  17423. });
  17424. }
  17425. function getAndExtendSideEffectModules(variable, module) {
  17426. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  17427. let currentVariable = variable;
  17428. const referencedVariables = new Set([currentVariable]);
  17429. while (true) {
  17430. const importingModule = currentVariable.module;
  17431. currentVariable =
  17432. currentVariable instanceof ExportDefaultVariable
  17433. ? currentVariable.getDirectOriginalVariable()
  17434. : currentVariable instanceof SyntheticNamedExportVariable
  17435. ? currentVariable.syntheticNamespace
  17436. : null;
  17437. if (!currentVariable || referencedVariables.has(currentVariable)) {
  17438. break;
  17439. }
  17440. referencedVariables.add(currentVariable);
  17441. sideEffectModules.add(importingModule);
  17442. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  17443. if (originalSideEffects) {
  17444. for (const module of originalSideEffects) {
  17445. sideEffectModules.add(module);
  17446. }
  17447. }
  17448. }
  17449. return sideEffectModules;
  17450. }
  17451. class Module {
  17452. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  17453. this.graph = graph;
  17454. this.id = id;
  17455. this.options = options;
  17456. this.alternativeReexportModules = new Map();
  17457. this.chunkFileNames = new Set();
  17458. this.chunkNames = [];
  17459. this.cycles = new Set();
  17460. this.dependencies = new Set();
  17461. this.dynamicDependencies = new Set();
  17462. this.dynamicImporters = [];
  17463. this.dynamicImports = [];
  17464. this.execIndex = Infinity;
  17465. this.hasTreeShakingPassStarted = false;
  17466. this.implicitlyLoadedAfter = new Set();
  17467. this.implicitlyLoadedBefore = new Set();
  17468. this.importDescriptions = new Map();
  17469. this.importMetas = [];
  17470. this.importedFromNotTreeshaken = false;
  17471. this.importers = [];
  17472. this.includedDynamicImporters = [];
  17473. this.includedTopLevelAwaitingDynamicImporters = new Set();
  17474. this.includedImports = new Set();
  17475. this.isExecuted = false;
  17476. this.isUserDefinedEntryPoint = false;
  17477. this.needsExportShim = false;
  17478. this.sideEffectDependenciesByVariable = new Map();
  17479. this.sourcesWithAttributes = new Map();
  17480. this.allExportNames = null;
  17481. this.allExportsIncluded = false;
  17482. this.ast = null;
  17483. this.exportAllModules = [];
  17484. this.exportAllSources = new Set();
  17485. this.exportNamesByVariable = null;
  17486. this.exportShimVariable = new ExportShimVariable(this);
  17487. this.exports = new Map();
  17488. this.namespaceReexportsByName = new Map();
  17489. this.reexportDescriptions = new Map();
  17490. this.relevantDependencies = null;
  17491. this.syntheticExports = new Map();
  17492. this.syntheticNamespace = null;
  17493. this.transformDependencies = [];
  17494. this.transitiveReexports = null;
  17495. this.excludeFromSourcemap = /\0/.test(id);
  17496. this.context = options.moduleContext(id);
  17497. this.preserveSignature = this.options.preserveEntrySignatures;
  17498. // eslint-disable-next-line @typescript-eslint/no-this-alias
  17499. const module = this;
  17500. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  17501. this.info = {
  17502. ast: null,
  17503. attributes,
  17504. code: null,
  17505. get dynamicallyImportedIdResolutions() {
  17506. return dynamicImports
  17507. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  17508. .filter(Boolean);
  17509. },
  17510. get dynamicallyImportedIds() {
  17511. // We cannot use this.dynamicDependencies because this is needed before
  17512. // dynamicDependencies are populated
  17513. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  17514. },
  17515. get dynamicImporters() {
  17516. return dynamicImporters.sort();
  17517. },
  17518. get exportedBindings() {
  17519. const exportBindings = { '.': [...exports.keys()] };
  17520. for (const [name, { source }] of reexportDescriptions) {
  17521. (exportBindings[source] ??= []).push(name);
  17522. }
  17523. for (const source of exportAllSources) {
  17524. (exportBindings[source] ??= []).push('*');
  17525. }
  17526. return exportBindings;
  17527. },
  17528. get exports() {
  17529. return [
  17530. ...exports.keys(),
  17531. ...reexportDescriptions.keys(),
  17532. ...[...exportAllSources].map(() => '*')
  17533. ];
  17534. },
  17535. get hasDefaultExport() {
  17536. // This information is only valid after parsing
  17537. if (!module.ast) {
  17538. return null;
  17539. }
  17540. return module.exports.has('default') || reexportDescriptions.has('default');
  17541. },
  17542. id,
  17543. get implicitlyLoadedAfterOneOf() {
  17544. return Array.from(implicitlyLoadedAfter, getId).sort();
  17545. },
  17546. get implicitlyLoadedBefore() {
  17547. return Array.from(implicitlyLoadedBefore, getId).sort();
  17548. },
  17549. get importedIdResolutions() {
  17550. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  17551. },
  17552. get importedIds() {
  17553. // We cannot use this.dependencies because this is needed before
  17554. // dependencies are populated
  17555. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  17556. },
  17557. get importers() {
  17558. return importers.sort();
  17559. },
  17560. isEntry,
  17561. isExternal: false,
  17562. get isIncluded() {
  17563. if (graph.phase !== BuildPhase.GENERATE) {
  17564. return null;
  17565. }
  17566. return module.isIncluded();
  17567. },
  17568. meta: { ...meta },
  17569. moduleSideEffects,
  17570. syntheticNamedExports
  17571. };
  17572. }
  17573. basename() {
  17574. const base = path.basename(this.id);
  17575. const extension = path.extname(this.id);
  17576. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  17577. }
  17578. bindReferences() {
  17579. this.ast.bind();
  17580. }
  17581. cacheInfoGetters() {
  17582. cacheObjectGetters(this.info, [
  17583. 'dynamicallyImportedIdResolutions',
  17584. 'dynamicallyImportedIds',
  17585. 'dynamicImporters',
  17586. 'exportedBindings',
  17587. 'exports',
  17588. 'hasDefaultExport',
  17589. 'implicitlyLoadedAfterOneOf',
  17590. 'implicitlyLoadedBefore',
  17591. 'importedIdResolutions',
  17592. 'importedIds',
  17593. 'importers'
  17594. ]);
  17595. }
  17596. error(properties, pos) {
  17597. if (pos !== undefined) {
  17598. this.addLocationToLogProps(properties, pos);
  17599. }
  17600. return parseAst_js.error(properties);
  17601. }
  17602. // sum up the length of all ast nodes that are included
  17603. estimateSize() {
  17604. let size = 0;
  17605. for (const node of this.ast.body) {
  17606. if (node.included) {
  17607. size += node.end - node.start;
  17608. }
  17609. }
  17610. return size;
  17611. }
  17612. getAllExportNames() {
  17613. if (this.allExportNames) {
  17614. return this.allExportNames;
  17615. }
  17616. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  17617. for (const module of this.exportAllModules) {
  17618. if (module instanceof ExternalModule) {
  17619. this.allExportNames.add(`*${module.id}`);
  17620. continue;
  17621. }
  17622. for (const name of module.getAllExportNames()) {
  17623. if (name !== 'default')
  17624. this.allExportNames.add(name);
  17625. }
  17626. }
  17627. // We do not count the synthetic namespace as a regular export to hide it
  17628. // from entry signatures and namespace objects
  17629. if (typeof this.info.syntheticNamedExports === 'string') {
  17630. this.allExportNames.delete(this.info.syntheticNamedExports);
  17631. }
  17632. return this.allExportNames;
  17633. }
  17634. getDependenciesToBeIncluded() {
  17635. if (this.relevantDependencies)
  17636. return this.relevantDependencies;
  17637. this.relevantDependencies = new Set();
  17638. const necessaryDependencies = new Set();
  17639. const alwaysCheckedDependencies = new Set();
  17640. const dependencyVariables = new Set(this.includedImports);
  17641. if (this.info.isEntry ||
  17642. this.includedDynamicImporters.length > 0 ||
  17643. this.namespace.included ||
  17644. this.implicitlyLoadedAfter.size > 0) {
  17645. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  17646. const [exportedVariable] = this.getVariableForExportName(exportName);
  17647. if (exportedVariable?.included) {
  17648. dependencyVariables.add(exportedVariable);
  17649. }
  17650. }
  17651. }
  17652. for (let variable of dependencyVariables) {
  17653. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  17654. if (sideEffectDependencies) {
  17655. for (const module of sideEffectDependencies) {
  17656. alwaysCheckedDependencies.add(module);
  17657. }
  17658. }
  17659. if (variable instanceof SyntheticNamedExportVariable) {
  17660. variable = variable.getBaseVariable();
  17661. }
  17662. else if (variable instanceof ExportDefaultVariable) {
  17663. variable = variable.getOriginalVariable();
  17664. }
  17665. necessaryDependencies.add(variable.module);
  17666. }
  17667. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  17668. for (const dependency of this.dependencies) {
  17669. this.relevantDependencies.add(dependency);
  17670. }
  17671. }
  17672. else {
  17673. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  17674. }
  17675. for (const dependency of necessaryDependencies) {
  17676. this.relevantDependencies.add(dependency);
  17677. }
  17678. return this.relevantDependencies;
  17679. }
  17680. getExportNamesByVariable() {
  17681. if (this.exportNamesByVariable) {
  17682. return this.exportNamesByVariable;
  17683. }
  17684. const exportNamesByVariable = new Map();
  17685. for (const exportName of this.getAllExportNames()) {
  17686. let [tracedVariable] = this.getVariableForExportName(exportName);
  17687. if (tracedVariable instanceof ExportDefaultVariable) {
  17688. tracedVariable = tracedVariable.getOriginalVariable();
  17689. }
  17690. if (!tracedVariable ||
  17691. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  17692. continue;
  17693. }
  17694. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  17695. if (existingExportNames) {
  17696. existingExportNames.push(exportName);
  17697. }
  17698. else {
  17699. exportNamesByVariable.set(tracedVariable, [exportName]);
  17700. }
  17701. }
  17702. return (this.exportNamesByVariable = exportNamesByVariable);
  17703. }
  17704. getExports() {
  17705. return [...this.exports.keys()];
  17706. }
  17707. getReexports() {
  17708. if (this.transitiveReexports) {
  17709. return this.transitiveReexports;
  17710. }
  17711. // to avoid infinite recursion when using circular `export * from X`
  17712. this.transitiveReexports = [];
  17713. const reexports = new Set(this.reexportDescriptions.keys());
  17714. for (const module of this.exportAllModules) {
  17715. if (module instanceof ExternalModule) {
  17716. reexports.add(`*${module.id}`);
  17717. }
  17718. else {
  17719. for (const name of [...module.getReexports(), ...module.getExports()]) {
  17720. if (name !== 'default')
  17721. reexports.add(name);
  17722. }
  17723. }
  17724. }
  17725. return (this.transitiveReexports = [...reexports]);
  17726. }
  17727. getRenderedExports() {
  17728. // only direct exports are counted here, not reexports at all
  17729. const renderedExports = [];
  17730. const removedExports = [];
  17731. for (const exportName of this.exports.keys()) {
  17732. const [variable] = this.getVariableForExportName(exportName);
  17733. (variable?.included ? renderedExports : removedExports).push(exportName);
  17734. }
  17735. return { removedExports, renderedExports };
  17736. }
  17737. getSyntheticNamespace() {
  17738. if (this.syntheticNamespace === null) {
  17739. this.syntheticNamespace = undefined;
  17740. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  17741. ? this.info.syntheticNamedExports
  17742. : 'default', { onlyExplicit: true });
  17743. }
  17744. if (!this.syntheticNamespace) {
  17745. return parseAst_js.error(parseAst_js.logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  17746. }
  17747. return this.syntheticNamespace;
  17748. }
  17749. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  17750. if (name[0] === '*') {
  17751. if (name.length === 1) {
  17752. // export * from './other'
  17753. return [this.namespace];
  17754. }
  17755. // export * from 'external'
  17756. const module = this.graph.modulesById.get(name.slice(1));
  17757. return module.getVariableForExportName('*');
  17758. }
  17759. // export { foo } from './other'
  17760. const reexportDeclaration = this.reexportDescriptions.get(name);
  17761. if (reexportDeclaration) {
  17762. const [variable, options] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  17763. if (!variable) {
  17764. return this.error(parseAst_js.logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id, !!options?.missingButExportExists), reexportDeclaration.start);
  17765. }
  17766. if (importerForSideEffects) {
  17767. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17768. if (this.info.moduleSideEffects) {
  17769. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17770. }
  17771. }
  17772. return [variable];
  17773. }
  17774. const exportDeclaration = this.exports.get(name);
  17775. if (exportDeclaration) {
  17776. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  17777. return [this.exportShimVariable];
  17778. }
  17779. const name = exportDeclaration.localName;
  17780. const variable = this.traceVariable(name, {
  17781. importerForSideEffects,
  17782. searchedNamesAndModules
  17783. });
  17784. if (!variable) {
  17785. return [null, { missingButExportExists: true }];
  17786. }
  17787. if (importerForSideEffects) {
  17788. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17789. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17790. }
  17791. return [variable];
  17792. }
  17793. if (onlyExplicit) {
  17794. return [null];
  17795. }
  17796. if (name !== 'default') {
  17797. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  17798. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  17799. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  17800. if (foundNamespaceReexport[0]) {
  17801. return foundNamespaceReexport;
  17802. }
  17803. }
  17804. if (this.info.syntheticNamedExports) {
  17805. return [
  17806. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  17807. ];
  17808. }
  17809. // we don't want to create shims when we are just
  17810. // probing export * modules for exports
  17811. if (!isExportAllSearch && this.options.shimMissingExports) {
  17812. this.shimMissingExport(name);
  17813. return [this.exportShimVariable];
  17814. }
  17815. return [null];
  17816. }
  17817. hasEffects() {
  17818. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  17819. }
  17820. include() {
  17821. const context = createInclusionContext();
  17822. if (this.ast.shouldBeIncluded(context))
  17823. this.ast.include(context, false);
  17824. }
  17825. includeAllExports(includeNamespaceMembers) {
  17826. if (includeNamespaceMembers) {
  17827. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17828. }
  17829. if (this.allExportsIncluded)
  17830. return;
  17831. this.allExportsIncluded = true;
  17832. if (!this.isExecuted) {
  17833. markModuleAndImpureDependenciesAsExecuted(this);
  17834. this.graph.needsTreeshakingPass = true;
  17835. }
  17836. const inclusionContext = createInclusionContext();
  17837. for (const exportName of this.exports.keys()) {
  17838. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  17839. const variable = this.getVariableForExportName(exportName)[0];
  17840. if (!variable) {
  17841. return parseAst_js.error(parseAst_js.logMissingEntryExport(exportName, this.id));
  17842. }
  17843. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17844. variable.deoptimizePath(UNKNOWN_PATH);
  17845. }
  17846. }
  17847. for (const name of this.getReexports()) {
  17848. const [variable] = this.getVariableForExportName(name);
  17849. if (variable) {
  17850. variable.deoptimizePath(UNKNOWN_PATH);
  17851. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17852. if (variable instanceof ExternalVariable) {
  17853. variable.module.reexported = true;
  17854. }
  17855. }
  17856. }
  17857. }
  17858. includeAllInBundle() {
  17859. this.ast.include(createInclusionContext(), true);
  17860. this.includeAllExports(false);
  17861. }
  17862. includeExportsByNames(names) {
  17863. if (!this.isExecuted) {
  17864. markModuleAndImpureDependenciesAsExecuted(this);
  17865. this.graph.needsTreeshakingPass = true;
  17866. }
  17867. let includeNamespaceMembers = false;
  17868. const inclusionContext = createInclusionContext();
  17869. for (const name of names) {
  17870. const variable = this.getVariableForExportName(name)[0];
  17871. if (variable) {
  17872. variable.deoptimizePath(UNKNOWN_PATH);
  17873. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17874. }
  17875. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  17876. includeNamespaceMembers = true;
  17877. }
  17878. }
  17879. if (includeNamespaceMembers) {
  17880. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17881. }
  17882. }
  17883. isIncluded() {
  17884. // Modules where this.ast is missing have been loaded via this.load and are
  17885. // not yet fully processed, hence they cannot be included.
  17886. return (this.ast &&
  17887. (this.ast.included ||
  17888. this.namespace.included ||
  17889. this.importedFromNotTreeshaken ||
  17890. this.exportShimVariable.included));
  17891. }
  17892. linkImports() {
  17893. this.addModulesToImportDescriptions(this.importDescriptions);
  17894. this.addModulesToImportDescriptions(this.reexportDescriptions);
  17895. const externalExportAllModules = [];
  17896. for (const source of this.exportAllSources) {
  17897. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  17898. if (module instanceof ExternalModule) {
  17899. externalExportAllModules.push(module);
  17900. continue;
  17901. }
  17902. this.exportAllModules.push(module);
  17903. }
  17904. this.exportAllModules.push(...externalExportAllModules);
  17905. }
  17906. log(level, properties, pos) {
  17907. this.addLocationToLogProps(properties, pos);
  17908. this.options.onLog(level, properties);
  17909. }
  17910. render(options) {
  17911. const source = this.magicString.clone();
  17912. this.ast.render(source, options);
  17913. source.trim();
  17914. const { usesTopLevelAwait } = this.astContext;
  17915. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  17916. return parseAst_js.error(parseAst_js.logInvalidFormatForTopLevelAwait(this.id, options.format));
  17917. }
  17918. return { source, usesTopLevelAwait };
  17919. }
  17920. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  17921. timeStart('generate ast', 3);
  17922. if (code.startsWith('#!')) {
  17923. const shebangEndPosition = code.indexOf('\n');
  17924. this.shebang = code.slice(2, shebangEndPosition);
  17925. }
  17926. this.info.code = code;
  17927. this.originalCode = originalCode;
  17928. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  17929. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  17930. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  17931. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  17932. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  17933. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  17934. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  17935. if (transformFiles) {
  17936. this.transformFiles = transformFiles;
  17937. }
  17938. this.transformDependencies = transformDependencies;
  17939. this.customTransformCache = customTransformCache;
  17940. this.updateOptions(moduleOptions);
  17941. this.resolvedIds = resolvedIds ?? Object.create(null);
  17942. // By default, `id` is the file name. Custom resolvers and loaders
  17943. // can change that, but it makes sense to use it for the source file name
  17944. const fileName = this.id;
  17945. this.magicString = new MagicString(code, {
  17946. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  17947. indentExclusionRanges: []
  17948. });
  17949. this.astContext = {
  17950. addDynamicImport: this.addDynamicImport.bind(this),
  17951. addExport: this.addExport.bind(this),
  17952. addImport: this.addImport.bind(this),
  17953. addImportMeta: this.addImportMeta.bind(this),
  17954. addImportSource: this.addImportSource.bind(this),
  17955. code, // Only needed for debugging
  17956. deoptimizationTracker: this.graph.deoptimizationTracker,
  17957. error: this.error.bind(this),
  17958. fileName, // Needed for warnings
  17959. getExports: this.getExports.bind(this),
  17960. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  17961. getModuleExecIndex: () => this.execIndex,
  17962. getModuleName: this.basename.bind(this),
  17963. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  17964. getReexports: this.getReexports.bind(this),
  17965. importDescriptions: this.importDescriptions,
  17966. includeAllExports: () => this.includeAllExports(true),
  17967. includeDynamicImport: this.includeDynamicImport.bind(this),
  17968. includeVariableInModule: this.includeVariableInModule.bind(this),
  17969. log: this.log.bind(this),
  17970. magicString: this.magicString,
  17971. manualPureFunctions: this.graph.pureFunctions,
  17972. module: this,
  17973. moduleContext: this.context,
  17974. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  17975. options: this.options,
  17976. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  17977. traceExport: (name) => this.getVariableForExportName(name),
  17978. traceVariable: this.traceVariable.bind(this),
  17979. usesTopLevelAwait: false
  17980. };
  17981. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  17982. this.namespace = new NamespaceVariable(this.astContext);
  17983. const programParent = { context: this.astContext, type: 'Module' };
  17984. if (ast) {
  17985. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  17986. this.info.ast = ast;
  17987. }
  17988. else {
  17989. // Measuring asynchronous code does not provide reasonable results
  17990. timeEnd('generate ast', 3);
  17991. const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
  17992. timeStart('generate ast', 3);
  17993. this.ast = convertProgram(astBuffer, programParent, this.scope);
  17994. // Make lazy and apply LRU cache to not hog the memory
  17995. Object.defineProperty(this.info, 'ast', {
  17996. get: () => {
  17997. if (this.graph.astLru.has(fileName)) {
  17998. return this.graph.astLru.get(fileName);
  17999. }
  18000. else {
  18001. const parsedAst = this.tryParse();
  18002. // If the cache is not disabled, we need to keep the AST in memory
  18003. // until the end when the cache is generated
  18004. if (this.options.cache !== false) {
  18005. Object.defineProperty(this.info, 'ast', {
  18006. value: parsedAst
  18007. });
  18008. return parsedAst;
  18009. }
  18010. // Otherwise, we keep it in a small LRU cache to not hog too much
  18011. // memory but allow the same AST to be requested several times.
  18012. this.graph.astLru.set(fileName, parsedAst);
  18013. return parsedAst;
  18014. }
  18015. }
  18016. });
  18017. }
  18018. timeEnd('generate ast', 3);
  18019. }
  18020. toJSON() {
  18021. return {
  18022. ast: this.info.ast,
  18023. attributes: this.info.attributes,
  18024. code: this.info.code,
  18025. customTransformCache: this.customTransformCache,
  18026. dependencies: Array.from(this.dependencies, getId),
  18027. id: this.id,
  18028. meta: this.info.meta,
  18029. moduleSideEffects: this.info.moduleSideEffects,
  18030. originalCode: this.originalCode,
  18031. originalSourcemap: this.originalSourcemap,
  18032. resolvedIds: this.resolvedIds,
  18033. sourcemapChain: this.sourcemapChain,
  18034. syntheticNamedExports: this.info.syntheticNamedExports,
  18035. transformDependencies: this.transformDependencies,
  18036. transformFiles: this.transformFiles
  18037. };
  18038. }
  18039. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  18040. const localVariable = this.scope.variables.get(name);
  18041. if (localVariable) {
  18042. return localVariable;
  18043. }
  18044. const importDescription = this.importDescriptions.get(name);
  18045. if (importDescription) {
  18046. const otherModule = importDescription.module;
  18047. if (otherModule instanceof Module && importDescription.name === '*') {
  18048. return otherModule.namespace;
  18049. }
  18050. const [declaration, options] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  18051. if (!declaration) {
  18052. return this.error(parseAst_js.logMissingExport(importDescription.name, this.id, otherModule.id, !!options?.missingButExportExists), importDescription.start);
  18053. }
  18054. return declaration;
  18055. }
  18056. return null;
  18057. }
  18058. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  18059. if (moduleSideEffects != null) {
  18060. this.info.moduleSideEffects = moduleSideEffects;
  18061. }
  18062. if (syntheticNamedExports != null) {
  18063. this.info.syntheticNamedExports = syntheticNamedExports;
  18064. }
  18065. if (meta != null) {
  18066. Object.assign(this.info.meta, meta);
  18067. }
  18068. }
  18069. addDynamicImport(node) {
  18070. let argument = node.sourceAstNode;
  18071. if (argument.type === parseAst_js.TemplateLiteral) {
  18072. if (argument.quasis.length === 1 &&
  18073. typeof argument.quasis[0].value.cooked === 'string') {
  18074. argument = argument.quasis[0].value.cooked;
  18075. }
  18076. }
  18077. else if (argument.type === parseAst_js.Literal &&
  18078. typeof argument.value === 'string') {
  18079. argument = argument.value;
  18080. }
  18081. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  18082. }
  18083. assertUniqueExportName(name, nodeStart) {
  18084. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  18085. this.error(parseAst_js.logDuplicateExportError(name), nodeStart);
  18086. }
  18087. }
  18088. addExport(node) {
  18089. if (node instanceof ExportDefaultDeclaration) {
  18090. // export default foo;
  18091. this.assertUniqueExportName('default', node.start);
  18092. this.exports.set('default', {
  18093. identifier: node.variable.getAssignedVariableName(),
  18094. localName: 'default'
  18095. });
  18096. }
  18097. else if (node instanceof ExportAllDeclaration) {
  18098. const source = node.source.value;
  18099. this.addSource(source, node);
  18100. if (node.exported) {
  18101. // export * as name from './other'
  18102. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  18103. this.assertUniqueExportName(name, node.exported.start);
  18104. this.reexportDescriptions.set(name, {
  18105. localName: '*',
  18106. module: null, // filled in later,
  18107. source,
  18108. start: node.start
  18109. });
  18110. }
  18111. else {
  18112. // export * from './other'
  18113. this.exportAllSources.add(source);
  18114. }
  18115. }
  18116. else if (node.source instanceof Literal) {
  18117. // export { name } from './other'
  18118. const source = node.source.value;
  18119. this.addSource(source, node);
  18120. for (const { exported, local, start } of node.specifiers) {
  18121. const name = exported instanceof Literal ? exported.value : exported.name;
  18122. this.assertUniqueExportName(name, start);
  18123. this.reexportDescriptions.set(name, {
  18124. localName: local instanceof Literal ? local.value : local.name,
  18125. module: null, // filled in later,
  18126. source,
  18127. start
  18128. });
  18129. }
  18130. }
  18131. else if (node.declaration) {
  18132. const declaration = node.declaration;
  18133. if (declaration instanceof VariableDeclaration) {
  18134. // export var { foo, bar } = ...
  18135. // export var foo = 1, bar = 2;
  18136. for (const declarator of declaration.declarations) {
  18137. for (const localName of extractAssignedNames(declarator.id)) {
  18138. this.assertUniqueExportName(localName, declarator.id.start);
  18139. this.exports.set(localName, { identifier: null, localName });
  18140. }
  18141. }
  18142. }
  18143. else {
  18144. // export function foo () {}
  18145. const localName = declaration.id.name;
  18146. this.assertUniqueExportName(localName, declaration.id.start);
  18147. this.exports.set(localName, { identifier: null, localName });
  18148. }
  18149. }
  18150. else {
  18151. // export { foo, bar, baz }
  18152. for (const { local, exported } of node.specifiers) {
  18153. // except for reexports, local must be an Identifier
  18154. const localName = local.name;
  18155. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  18156. this.assertUniqueExportName(exportedName, exported.start);
  18157. this.exports.set(exportedName, { identifier: null, localName });
  18158. }
  18159. }
  18160. }
  18161. addImport(node) {
  18162. const source = node.source.value;
  18163. this.addSource(source, node);
  18164. for (const specifier of node.specifiers) {
  18165. const localName = specifier.local.name;
  18166. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  18167. this.error(parseAst_js.logRedeclarationError(localName), specifier.local.start);
  18168. }
  18169. const name = specifier instanceof ImportDefaultSpecifier
  18170. ? 'default'
  18171. : specifier instanceof ImportNamespaceSpecifier
  18172. ? '*'
  18173. : specifier.imported instanceof Identifier
  18174. ? specifier.imported.name
  18175. : specifier.imported.value;
  18176. this.importDescriptions.set(localName, {
  18177. module: null, // filled in later
  18178. name,
  18179. source,
  18180. start: specifier.start
  18181. });
  18182. }
  18183. }
  18184. addImportSource(importSource) {
  18185. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  18186. this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
  18187. }
  18188. }
  18189. addImportMeta(node) {
  18190. this.importMetas.push(node);
  18191. }
  18192. addLocationToLogProps(properties, pos) {
  18193. properties.id = this.id;
  18194. properties.pos = pos;
  18195. let code = this.info.code;
  18196. const location = parseAst_js.locate(code, pos, { offsetLine: 1 });
  18197. if (location) {
  18198. let { column, line } = location;
  18199. try {
  18200. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  18201. code = this.originalCode;
  18202. }
  18203. catch (error_) {
  18204. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidSourcemapForError(error_, this.id, column, line, pos));
  18205. }
  18206. parseAst_js.augmentCodeLocation(properties, { column, line }, code, this.id);
  18207. }
  18208. }
  18209. addModulesToImportDescriptions(importDescription) {
  18210. for (const specifier of importDescription.values()) {
  18211. const { id } = this.resolvedIds[specifier.source];
  18212. specifier.module = this.graph.modulesById.get(id);
  18213. }
  18214. }
  18215. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  18216. const handledDependencies = new Set();
  18217. const addSideEffectDependencies = (possibleDependencies) => {
  18218. for (const dependency of possibleDependencies) {
  18219. if (handledDependencies.has(dependency)) {
  18220. continue;
  18221. }
  18222. handledDependencies.add(dependency);
  18223. if (necessaryDependencies.has(dependency)) {
  18224. relevantDependencies.add(dependency);
  18225. continue;
  18226. }
  18227. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  18228. continue;
  18229. }
  18230. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  18231. relevantDependencies.add(dependency);
  18232. continue;
  18233. }
  18234. addSideEffectDependencies(dependency.dependencies);
  18235. }
  18236. };
  18237. addSideEffectDependencies(this.dependencies);
  18238. addSideEffectDependencies(alwaysCheckedDependencies);
  18239. }
  18240. addSource(source, declaration) {
  18241. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  18242. const existingAttributes = this.sourcesWithAttributes.get(source);
  18243. if (existingAttributes) {
  18244. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  18245. this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  18246. }
  18247. }
  18248. else {
  18249. this.sourcesWithAttributes.set(source, parsedAttributes);
  18250. }
  18251. }
  18252. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  18253. const { id } = this.resolvedIds[importSource];
  18254. const module = this.graph.modulesById.get(id);
  18255. const [variable] = module.getVariableForExportName(baseName);
  18256. if (!variable) {
  18257. return this.error(parseAst_js.logMissingJsxExport(baseName, id, this.id), nodeStart);
  18258. }
  18259. return variable;
  18260. }
  18261. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  18262. let foundSyntheticDeclaration = null;
  18263. const foundInternalDeclarations = new Map();
  18264. const foundExternalDeclarations = new Set();
  18265. for (const module of this.exportAllModules) {
  18266. // Synthetic namespaces should not hide "regular" exports of the same name
  18267. if (module.info.syntheticNamedExports === name) {
  18268. continue;
  18269. }
  18270. const [variable, options] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  18271. // We are creating a copy to handle the case where the same binding is
  18272. // imported through different namespace reexports gracefully
  18273. copyNameToModulesMap(searchedNamesAndModules));
  18274. if (module instanceof ExternalModule || options?.indirectExternal) {
  18275. foundExternalDeclarations.add(variable);
  18276. }
  18277. else if (variable instanceof SyntheticNamedExportVariable) {
  18278. if (!foundSyntheticDeclaration) {
  18279. foundSyntheticDeclaration = variable;
  18280. }
  18281. }
  18282. else if (variable) {
  18283. foundInternalDeclarations.set(variable, module);
  18284. }
  18285. }
  18286. if (foundInternalDeclarations.size > 0) {
  18287. const foundDeclarationList = [...foundInternalDeclarations];
  18288. const usedDeclaration = foundDeclarationList[0][0];
  18289. if (foundDeclarationList.length === 1) {
  18290. return [usedDeclaration];
  18291. }
  18292. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  18293. // TODO we are pretending it was not found while it should behave like "undefined"
  18294. return [null];
  18295. }
  18296. if (foundExternalDeclarations.size > 0) {
  18297. const foundDeclarationList = [...foundExternalDeclarations];
  18298. const usedDeclaration = foundDeclarationList[0];
  18299. if (foundDeclarationList.length > 1) {
  18300. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  18301. }
  18302. return [usedDeclaration, { indirectExternal: true }];
  18303. }
  18304. if (foundSyntheticDeclaration) {
  18305. return [foundSyntheticDeclaration];
  18306. }
  18307. return [null];
  18308. }
  18309. includeAndGetAdditionalMergedNamespaces() {
  18310. const externalNamespaces = new Set();
  18311. const syntheticNamespaces = new Set();
  18312. for (const module of [this, ...this.exportAllModules]) {
  18313. if (module instanceof ExternalModule) {
  18314. const [externalVariable] = module.getVariableForExportName('*');
  18315. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  18316. this.includedImports.add(externalVariable);
  18317. externalNamespaces.add(externalVariable);
  18318. }
  18319. else if (module.info.syntheticNamedExports) {
  18320. const syntheticNamespace = module.getSyntheticNamespace();
  18321. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  18322. this.includedImports.add(syntheticNamespace);
  18323. syntheticNamespaces.add(syntheticNamespace);
  18324. }
  18325. }
  18326. return [...syntheticNamespaces, ...externalNamespaces];
  18327. }
  18328. includeDynamicImport(node) {
  18329. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  18330. if (resolution instanceof Module) {
  18331. if (!resolution.includedDynamicImporters.includes(this)) {
  18332. resolution.includedDynamicImporters.push(this);
  18333. // If a module has a top-level await, removing this entry can create
  18334. // deadlocks.
  18335. if (this.astContext.usesTopLevelAwait) {
  18336. resolution.includedTopLevelAwaitingDynamicImporters.add(this);
  18337. }
  18338. }
  18339. const importedNames = this.options.treeshake
  18340. ? node.getDeterministicImportedNames()
  18341. : undefined;
  18342. if (importedNames) {
  18343. resolution.includeExportsByNames(importedNames);
  18344. }
  18345. else {
  18346. resolution.includeAllExports(true);
  18347. }
  18348. }
  18349. }
  18350. includeVariable(variable, path, context) {
  18351. const { included, module: variableModule } = variable;
  18352. variable.includePath(path, context);
  18353. if (included) {
  18354. if (variableModule instanceof Module && variableModule !== this) {
  18355. getAndExtendSideEffectModules(variable, this);
  18356. }
  18357. }
  18358. else {
  18359. this.graph.needsTreeshakingPass = true;
  18360. if (variableModule instanceof Module) {
  18361. if (!variableModule.isExecuted) {
  18362. markModuleAndImpureDependenciesAsExecuted(variableModule);
  18363. }
  18364. if (variableModule !== this) {
  18365. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  18366. for (const module of sideEffectModules) {
  18367. if (!module.isExecuted) {
  18368. markModuleAndImpureDependenciesAsExecuted(module);
  18369. }
  18370. }
  18371. }
  18372. }
  18373. }
  18374. }
  18375. includeVariableInModule(variable, path, context) {
  18376. this.includeVariable(variable, path, context);
  18377. const variableModule = variable.module;
  18378. if (variableModule && variableModule !== this) {
  18379. this.includedImports.add(variable);
  18380. }
  18381. }
  18382. shimMissingExport(name) {
  18383. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
  18384. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  18385. }
  18386. tryParse() {
  18387. try {
  18388. return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
  18389. }
  18390. catch (error_) {
  18391. return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
  18392. }
  18393. }
  18394. }
  18395. // if there is a cyclic import in the reexport chain, we should not
  18396. // import from the original module but from the cyclic module to not
  18397. // mess up execution order.
  18398. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  18399. if (variable.module instanceof Module && variable.module !== reexporter) {
  18400. const exporterCycles = variable.module.cycles;
  18401. if (exporterCycles.size > 0) {
  18402. const importerCycles = reexporter.cycles;
  18403. for (const cycleSymbol of importerCycles) {
  18404. if (exporterCycles.has(cycleSymbol)) {
  18405. importer.alternativeReexportModules.set(variable, reexporter);
  18406. break;
  18407. }
  18408. }
  18409. }
  18410. }
  18411. }
  18412. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  18413. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  18414. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  18415. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  18416. async function createAddons(options, outputPluginDriver, chunk) {
  18417. try {
  18418. let [banner, footer, intro, outro] = await Promise.all([
  18419. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  18420. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  18421. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  18422. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  18423. ]);
  18424. if (intro)
  18425. intro += '\n\n';
  18426. if (outro)
  18427. outro = `\n\n${outro}`;
  18428. if (banner)
  18429. banner += '\n';
  18430. if (footer)
  18431. footer = '\n' + footer;
  18432. return { banner, footer, intro, outro };
  18433. }
  18434. catch (error_) {
  18435. return parseAst_js.error(parseAst_js.logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  18436. }
  18437. }
  18438. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  18439. amd: deconflictImportsOther,
  18440. cjs: deconflictImportsOther,
  18441. es: deconflictImportsEsmOrSystem,
  18442. iife: deconflictImportsOther,
  18443. system: deconflictImportsEsmOrSystem,
  18444. umd: deconflictImportsOther
  18445. };
  18446. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  18447. const reversedModules = [...modules].reverse();
  18448. for (const module of reversedModules) {
  18449. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  18450. }
  18451. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  18452. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  18453. for (const module of reversedModules) {
  18454. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  18455. }
  18456. }
  18457. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  18458. // This is needed for namespace reexports
  18459. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  18460. if (preserveModules || dependency instanceof ExternalChunk) {
  18461. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  18462. }
  18463. }
  18464. for (const variable of imports) {
  18465. const module = variable.module;
  18466. const name = variable.name;
  18467. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  18468. variable.setRenderNames(null, (module instanceof ExternalModule
  18469. ? externalChunkByModule.get(module)
  18470. : chunkByModule.get(module)).variableName);
  18471. }
  18472. else if (module instanceof ExternalModule && name === 'default') {
  18473. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  18474. ? module.suggestedVariableName + '__default'
  18475. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  18476. }
  18477. else {
  18478. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  18479. }
  18480. }
  18481. for (const variable of syntheticExports) {
  18482. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18483. }
  18484. }
  18485. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  18486. for (const chunk of dependencies) {
  18487. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  18488. }
  18489. for (const chunk of deconflictedNamespace) {
  18490. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  18491. }
  18492. for (const externalModule of deconflictedDefault) {
  18493. externalModule.defaultVariableName =
  18494. deconflictedNamespace.has(externalModule) &&
  18495. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  18496. ? externalModule.namespaceVariableName
  18497. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  18498. }
  18499. for (const variable of imports) {
  18500. const module = variable.module;
  18501. if (module instanceof ExternalModule) {
  18502. const chunk = externalChunkByModule.get(module);
  18503. const name = variable.name;
  18504. if (name === 'default') {
  18505. const moduleInterop = interop(module.id);
  18506. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  18507. ? chunk.defaultVariableName
  18508. : chunk.variableName;
  18509. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  18510. variable.setRenderNames(variableName, 'default');
  18511. }
  18512. else {
  18513. variable.setRenderNames(null, variableName);
  18514. }
  18515. }
  18516. else if (name === '*') {
  18517. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  18518. ? chunk.namespaceVariableName
  18519. : chunk.variableName);
  18520. }
  18521. else {
  18522. // if the second parameter is `null`, it uses its "name" for the property name
  18523. variable.setRenderNames(chunk.variableName, null);
  18524. }
  18525. }
  18526. else {
  18527. const chunk = chunkByModule.get(module);
  18528. if (preserveModules && variable.isNamespace) {
  18529. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  18530. }
  18531. else if (chunk.exportMode === 'default') {
  18532. variable.setRenderNames(null, chunk.variableName);
  18533. }
  18534. else {
  18535. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  18536. }
  18537. }
  18538. }
  18539. }
  18540. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  18541. for (const module of modules) {
  18542. for (const variable of module.scope.variables.values()) {
  18543. if (variable.included &&
  18544. // this will only happen for exports in some formats
  18545. !(variable.renderBaseName ||
  18546. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  18547. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18548. }
  18549. }
  18550. if (includedNamespaces.has(module)) {
  18551. const namespace = module.namespace;
  18552. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  18553. }
  18554. }
  18555. }
  18556. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  18557. let nameIndex = 0;
  18558. for (const variable of exports) {
  18559. let [exportName] = variable.name;
  18560. if (exportsByName.has(exportName)) {
  18561. do {
  18562. exportName = toBase64(++nameIndex);
  18563. // skip past leading number identifiers
  18564. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  18565. nameIndex += 9 * 64 ** (exportName.length - 1);
  18566. exportName = toBase64(nameIndex);
  18567. }
  18568. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  18569. }
  18570. exportsByName.set(exportName, variable);
  18571. exportNamesByVariable.set(variable, [exportName]);
  18572. }
  18573. }
  18574. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  18575. for (const variable of exports) {
  18576. let nameIndex = 0;
  18577. let exportName = variable.name;
  18578. while (exportsByName.has(exportName)) {
  18579. exportName = variable.name + '$' + ++nameIndex;
  18580. }
  18581. exportsByName.set(exportName, variable);
  18582. exportNamesByVariable.set(variable, [exportName]);
  18583. }
  18584. }
  18585. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  18586. const exportKeys = chunk.getExportNames();
  18587. if (exportMode === 'default') {
  18588. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  18589. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  18590. }
  18591. }
  18592. else if (exportMode === 'none' && exportKeys.length > 0) {
  18593. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  18594. }
  18595. if (exportMode === 'auto') {
  18596. if (exportKeys.length === 0) {
  18597. exportMode = 'none';
  18598. }
  18599. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  18600. exportMode = 'default';
  18601. }
  18602. else {
  18603. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  18604. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMixedExport(facadeModuleId, name));
  18605. }
  18606. exportMode = 'named';
  18607. }
  18608. }
  18609. return exportMode;
  18610. }
  18611. function guessIndentString(code) {
  18612. const lines = code.split('\n');
  18613. const tabbed = lines.filter(line => /^\t+/.test(line));
  18614. const spaced = lines.filter(line => /^ {2,}/.test(line));
  18615. if (tabbed.length === 0 && spaced.length === 0) {
  18616. return null;
  18617. }
  18618. // More lines tabbed than spaced? Assume tabs, and
  18619. // default to tabs in the case of a tie (or nothing
  18620. // to go on)
  18621. if (tabbed.length >= spaced.length) {
  18622. return '\t';
  18623. }
  18624. // Otherwise, we need to guess the multiple
  18625. const min = spaced.reduce((previous, current) => {
  18626. const numberSpaces = /^ +/.exec(current)[0].length;
  18627. return Math.min(numberSpaces, previous);
  18628. }, Infinity);
  18629. return ' '.repeat(min);
  18630. }
  18631. function getIndentString(modules, options) {
  18632. if (options.indent !== true)
  18633. return options.indent;
  18634. for (const module of modules) {
  18635. const indent = guessIndentString(module.originalCode);
  18636. if (indent !== null)
  18637. return indent;
  18638. }
  18639. return '\t';
  18640. }
  18641. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  18642. const staticDependencyBlocks = [];
  18643. const handledDependencies = new Set();
  18644. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  18645. const module = orderedModules[modulePos];
  18646. if (!handledDependencies.has(module)) {
  18647. const staticDependencies = [];
  18648. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  18649. staticDependencyBlocks.unshift(staticDependencies);
  18650. }
  18651. }
  18652. const dependencies = new Set();
  18653. for (const block of staticDependencyBlocks) {
  18654. for (const dependency of block) {
  18655. dependencies.add(dependency);
  18656. }
  18657. }
  18658. return dependencies;
  18659. }
  18660. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  18661. const dependencies = module.getDependenciesToBeIncluded();
  18662. for (const dependency of dependencies) {
  18663. if (dependency instanceof ExternalModule) {
  18664. staticDependencies.push(externalChunkByModule.get(dependency));
  18665. continue;
  18666. }
  18667. const dependencyChunk = chunkByModule.get(dependency);
  18668. if (dependencyChunk !== chunk) {
  18669. staticDependencies.push(dependencyChunk);
  18670. continue;
  18671. }
  18672. if (!handledModules.has(dependency)) {
  18673. handledModules.add(dependency);
  18674. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  18675. }
  18676. }
  18677. }
  18678. const NON_ASSET_EXTENSIONS = new Set([
  18679. '.js',
  18680. '.jsx',
  18681. '.ts',
  18682. '.tsx',
  18683. '.mjs',
  18684. '.mts',
  18685. '.cjs',
  18686. '.cts'
  18687. ]);
  18688. function getGlobalName(chunk, globals, hasExports, log) {
  18689. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  18690. if (globalName) {
  18691. return globalName;
  18692. }
  18693. if (hasExports) {
  18694. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingGlobalName(chunk.id, chunk.variableName));
  18695. return chunk.variableName;
  18696. }
  18697. }
  18698. class Chunk {
  18699. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  18700. this.orderedModules = orderedModules;
  18701. this.inputOptions = inputOptions;
  18702. this.outputOptions = outputOptions;
  18703. this.unsetOptions = unsetOptions;
  18704. this.pluginDriver = pluginDriver;
  18705. this.modulesById = modulesById;
  18706. this.chunkByModule = chunkByModule;
  18707. this.externalChunkByModule = externalChunkByModule;
  18708. this.facadeChunkByModule = facadeChunkByModule;
  18709. this.includedNamespaces = includedNamespaces;
  18710. this.manualChunkAlias = manualChunkAlias;
  18711. this.getPlaceholder = getPlaceholder;
  18712. this.bundle = bundle;
  18713. this.inputBase = inputBase;
  18714. this.snippets = snippets;
  18715. this.dependencies = new Set();
  18716. this.entryModules = [];
  18717. this.exportMode = 'named';
  18718. this.facadeModule = null;
  18719. this.namespaceVariableName = '';
  18720. this.variableName = '';
  18721. this.accessedGlobalsByScope = new Map();
  18722. this.dynamicEntryModules = [];
  18723. this.dynamicName = null;
  18724. this.exportNamesByVariable = new Map();
  18725. this.exports = new Set();
  18726. this.exportsByName = new Map();
  18727. this.fileName = null;
  18728. this.implicitEntryModules = [];
  18729. this.implicitlyLoadedBefore = new Set();
  18730. this.imports = new Set();
  18731. this.includedDynamicImports = null;
  18732. this.includedReexportsByModule = new Map();
  18733. // This may be updated in the constructor
  18734. this.isEmpty = true;
  18735. this.name = null;
  18736. this.needsExportsShim = false;
  18737. this.preRenderedChunkInfo = null;
  18738. this.preliminaryFileName = null;
  18739. this.preliminarySourcemapFileName = null;
  18740. this.renderedChunkInfo = null;
  18741. this.renderedDependencies = null;
  18742. this.renderedModules = Object.create(null);
  18743. this.sortedExportNames = null;
  18744. this.strictFacade = false;
  18745. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  18746. this.allowExtensionModules = new Set();
  18747. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  18748. const chunkModules = new Set(orderedModules);
  18749. for (const module of orderedModules) {
  18750. chunkByModule.set(module, this);
  18751. if (module.namespace.included && !outputOptions.preserveModules) {
  18752. includedNamespaces.add(module);
  18753. }
  18754. if (this.isEmpty && module.isIncluded()) {
  18755. this.isEmpty = false;
  18756. }
  18757. if (module.info.isEntry || outputOptions.preserveModules) {
  18758. this.entryModules.push(module);
  18759. }
  18760. for (const importer of module.includedDynamicImporters) {
  18761. if (!chunkModules.has(importer)) {
  18762. this.dynamicEntryModules.push(module);
  18763. // Modules with synthetic exports need an artificial namespace for dynamic imports
  18764. if (module.info.syntheticNamedExports) {
  18765. includedNamespaces.add(module);
  18766. this.exports.add(module.namespace);
  18767. }
  18768. }
  18769. }
  18770. if (module.implicitlyLoadedAfter.size > 0) {
  18771. this.implicitEntryModules.push(module);
  18772. }
  18773. }
  18774. this.suggestedVariableName = makeLegal(this.generateVariableName());
  18775. }
  18776. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  18777. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  18778. chunk.assignFacadeName(facadeName, facadedModule);
  18779. if (!facadeChunkByModule.has(facadedModule)) {
  18780. facadeChunkByModule.set(facadedModule, chunk);
  18781. }
  18782. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  18783. chunk.dependencies.add(dependency instanceof Module
  18784. ? chunkByModule.get(dependency)
  18785. : externalChunkByModule.get(dependency));
  18786. }
  18787. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  18788. facadedModule.info.moduleSideEffects &&
  18789. facadedModule.hasEffects()) {
  18790. chunk.dependencies.add(chunkByModule.get(facadedModule));
  18791. }
  18792. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  18793. chunk.facadeModule = facadedModule;
  18794. chunk.strictFacade = true;
  18795. return chunk;
  18796. }
  18797. canModuleBeFacade(module, exposedVariables) {
  18798. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  18799. // All exports of this chunk need to be exposed by the candidate module
  18800. for (const exposedVariable of this.exports) {
  18801. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  18802. return false;
  18803. }
  18804. }
  18805. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  18806. for (const exposedVariable of exposedVariables) {
  18807. if (!(exposedVariable.module === module ||
  18808. moduleExportNamesByVariable.has(exposedVariable) ||
  18809. (exposedVariable instanceof SyntheticNamedExportVariable &&
  18810. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  18811. return false;
  18812. }
  18813. }
  18814. return true;
  18815. }
  18816. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  18817. const renderedChunkInfo = this.getRenderedChunkInfo();
  18818. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  18819. const preliminaryFileName = renderedChunkInfo.fileName;
  18820. const fileName = (this.fileName = finalize(preliminaryFileName));
  18821. return {
  18822. ...renderedChunkInfo,
  18823. code,
  18824. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  18825. fileName,
  18826. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  18827. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  18828. finalize(fileName),
  18829. bindings
  18830. ])),
  18831. imports: renderedChunkInfo.imports.map(finalize),
  18832. map,
  18833. preliminaryFileName,
  18834. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  18835. sourcemapFileName
  18836. };
  18837. }
  18838. generateExports() {
  18839. this.sortedExportNames = null;
  18840. const remainingExports = new Set(this.exports);
  18841. if (this.facadeModule !== null &&
  18842. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  18843. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  18844. for (const [variable, exportNames] of exportNamesByVariable) {
  18845. this.exportNamesByVariable.set(variable, [...exportNames]);
  18846. for (const exportName of exportNames) {
  18847. this.exportsByName.set(exportName, variable);
  18848. }
  18849. remainingExports.delete(variable);
  18850. }
  18851. }
  18852. for (const module of this.allowExtensionModules) {
  18853. const exportNamesByVariable = module.getExportNamesByVariable();
  18854. for (const [variable, exportNames] of exportNamesByVariable) {
  18855. this.exportNamesByVariable.set(variable, [...exportNames]);
  18856. for (const exportName of exportNames) {
  18857. this.exportsByName.set(exportName, variable);
  18858. }
  18859. remainingExports.delete(variable);
  18860. }
  18861. }
  18862. if (this.outputOptions.minifyInternalExports) {
  18863. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18864. }
  18865. else {
  18866. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18867. }
  18868. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  18869. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  18870. }
  18871. generateFacades() {
  18872. const facades = [];
  18873. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  18874. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  18875. for (const module of entryModules) {
  18876. if (module.preserveSignature === 'allow-extension') {
  18877. const canPreserveExports = this.canPreserveModuleExports(module);
  18878. if (canPreserveExports &&
  18879. !module.chunkFileNames.size &&
  18880. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  18881. this.allowExtensionModules.add(module);
  18882. if (!this.facadeModule) {
  18883. this.facadeModule = module;
  18884. this.strictFacade = false;
  18885. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  18886. }
  18887. this.facadeChunkByModule.set(module, this);
  18888. continue;
  18889. }
  18890. }
  18891. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  18892. // mapping must run after Set 'name' dedupe
  18893. name => ({
  18894. name
  18895. }));
  18896. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  18897. requiredFacades.push({});
  18898. }
  18899. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  18900. if (requiredFacades.length === 0) {
  18901. requiredFacades.push({});
  18902. }
  18903. if (!this.facadeModule) {
  18904. const needsStrictFacade = !this.outputOptions.preserveModules &&
  18905. (module.preserveSignature === 'strict' ||
  18906. (module.preserveSignature === 'exports-only' &&
  18907. module.getExportNamesByVariable().size > 0));
  18908. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  18909. this.facadeModule = module;
  18910. this.facadeChunkByModule.set(module, this);
  18911. if (module.preserveSignature) {
  18912. this.strictFacade = needsStrictFacade;
  18913. }
  18914. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  18915. }
  18916. }
  18917. for (const facadeName of requiredFacades) {
  18918. 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));
  18919. }
  18920. }
  18921. for (const module of this.dynamicEntryModules) {
  18922. if (module.info.syntheticNamedExports)
  18923. continue;
  18924. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  18925. this.facadeModule = module;
  18926. this.facadeChunkByModule.set(module, this);
  18927. this.strictFacade = true;
  18928. this.dynamicName = getChunkNameFromModule(module);
  18929. }
  18930. else if (this.facadeModule === module &&
  18931. !this.strictFacade &&
  18932. this.canModuleBeFacade(module, exposedVariables)) {
  18933. this.strictFacade = true;
  18934. }
  18935. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  18936. this.includedNamespaces.add(module);
  18937. this.exports.add(module.namespace);
  18938. }
  18939. }
  18940. if (!this.outputOptions.preserveModules) {
  18941. this.addNecessaryImportsForFacades();
  18942. }
  18943. return facades;
  18944. }
  18945. canPreserveModuleExports(module) {
  18946. const exportNamesByVariable = module.getExportNamesByVariable();
  18947. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  18948. for (const [variable, exportNames] of exportNamesByVariable) {
  18949. for (const exportName of exportNames) {
  18950. const existingVariable = this.exportsByName.get(exportName);
  18951. // It's ok if the same export name in two modules references the exact same variable
  18952. if (existingVariable && existingVariable !== variable) {
  18953. return false;
  18954. }
  18955. }
  18956. }
  18957. // No actual conflicts found, add export names for future conflict checks
  18958. for (const [variable, exportNames] of exportNamesByVariable) {
  18959. for (const exportName of exportNames) {
  18960. this.exportsByName.set(exportName, variable);
  18961. }
  18962. }
  18963. return true;
  18964. }
  18965. getChunkName() {
  18966. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  18967. }
  18968. getExportNames() {
  18969. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  18970. }
  18971. getFileName() {
  18972. return this.fileName || this.getPreliminaryFileName().fileName;
  18973. }
  18974. getImportPath(importer) {
  18975. return escapeId(parseAst_js.getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  18976. }
  18977. getPreliminaryFileName() {
  18978. if (this.preliminaryFileName) {
  18979. return this.preliminaryFileName;
  18980. }
  18981. let fileName;
  18982. let hashPlaceholder = null;
  18983. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  18984. if (file) {
  18985. fileName = path.basename(file);
  18986. }
  18987. else if (this.fileName === null) {
  18988. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  18989. ? [entryFileNames, 'output.entryFileNames']
  18990. : [chunkFileNames, 'output.chunkFileNames'];
  18991. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  18992. format: () => format,
  18993. hash: size => hashPlaceholder ||
  18994. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  18995. name: () => this.getChunkName()
  18996. });
  18997. if (!hashPlaceholder) {
  18998. fileName = makeUnique(fileName, this.bundle);
  18999. }
  19000. }
  19001. else {
  19002. fileName = this.fileName;
  19003. }
  19004. if (!hashPlaceholder) {
  19005. this.bundle[fileName] = FILE_PLACEHOLDER;
  19006. }
  19007. // Caching is essential to not conflict with the file name reservation above
  19008. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  19009. }
  19010. getPreliminarySourcemapFileName() {
  19011. if (this.preliminarySourcemapFileName) {
  19012. return this.preliminarySourcemapFileName;
  19013. }
  19014. let sourcemapFileName = null;
  19015. let hashPlaceholder = null;
  19016. const { sourcemapFileNames, format } = this.outputOptions;
  19017. if (sourcemapFileNames) {
  19018. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  19019. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  19020. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  19021. format: () => format,
  19022. hash: size => hashPlaceholder ||
  19023. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  19024. name: () => this.getChunkName()
  19025. });
  19026. if (!hashPlaceholder) {
  19027. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  19028. }
  19029. }
  19030. else {
  19031. return null;
  19032. }
  19033. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  19034. }
  19035. getRenderedChunkInfo() {
  19036. if (this.renderedChunkInfo) {
  19037. return this.renderedChunkInfo;
  19038. }
  19039. return (this.renderedChunkInfo = {
  19040. ...this.getPreRenderedChunkInfo(),
  19041. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  19042. fileName: this.getFileName(),
  19043. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  19044. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  19045. imports: Array.from(this.dependencies, resolveFileName),
  19046. modules: this.renderedModules,
  19047. referencedFiles: this.getReferencedFiles()
  19048. });
  19049. }
  19050. getVariableExportName(variable) {
  19051. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  19052. return '*';
  19053. }
  19054. return this.exportNamesByVariable.get(variable)[0];
  19055. }
  19056. link() {
  19057. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  19058. for (const module of this.orderedModules) {
  19059. this.addImplicitlyLoadedBeforeFromModule(module);
  19060. this.setUpChunkImportsAndExportsForModule(module);
  19061. }
  19062. }
  19063. inlineTransitiveImports() {
  19064. const { facadeModule, dependencies, outputOptions } = this;
  19065. const { hoistTransitiveImports, preserveModules } = outputOptions;
  19066. // for static and dynamic entry points, add transitive dependencies to this
  19067. // chunk's dependencies to avoid loading latency
  19068. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  19069. for (const dep of dependencies) {
  19070. if (dep instanceof Chunk)
  19071. this.inlineChunkDependencies(dep);
  19072. }
  19073. }
  19074. }
  19075. async render() {
  19076. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  19077. const { format, preserveModules } = outputOptions;
  19078. const preliminaryFileName = this.getPreliminaryFileName();
  19079. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  19080. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  19081. const renderedDependencies = [...this.getRenderedDependencies().values()];
  19082. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  19083. let hasExports = renderedExports.length > 0;
  19084. let hasDefaultExport = false;
  19085. for (const renderedDependency of renderedDependencies) {
  19086. const { reexports } = renderedDependency;
  19087. if (reexports?.length) {
  19088. hasExports = true;
  19089. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  19090. hasDefaultExport = true;
  19091. }
  19092. if (format === 'es') {
  19093. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  19094. }
  19095. }
  19096. }
  19097. if (!hasDefaultExport) {
  19098. for (const { exported } of renderedExports) {
  19099. if (exported === 'default') {
  19100. hasDefaultExport = true;
  19101. break;
  19102. }
  19103. }
  19104. }
  19105. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  19106. finalisers[format](renderedSource, {
  19107. accessedGlobals,
  19108. dependencies: renderedDependencies,
  19109. exports: renderedExports,
  19110. hasDefaultExport,
  19111. hasExports,
  19112. id: preliminaryFileName.fileName,
  19113. indent,
  19114. intro,
  19115. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  19116. isModuleFacade: facadeModule !== null,
  19117. log: onLog,
  19118. namedExportsMode: exportMode !== 'default',
  19119. outro,
  19120. snippets,
  19121. usesTopLevelAwait
  19122. }, outputOptions);
  19123. if (banner)
  19124. magicString.prepend(banner);
  19125. if (format === 'es' || format === 'cjs') {
  19126. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  19127. if (shebang) {
  19128. magicString.prepend(`#!${shebang}\n`);
  19129. }
  19130. }
  19131. if (footer)
  19132. magicString.append(footer);
  19133. return {
  19134. chunk: this,
  19135. magicString,
  19136. preliminaryFileName,
  19137. preliminarySourcemapFileName,
  19138. usedModules
  19139. };
  19140. }
  19141. addImplicitlyLoadedBeforeFromModule(baseModule) {
  19142. const { chunkByModule, implicitlyLoadedBefore } = this;
  19143. for (const module of baseModule.implicitlyLoadedBefore) {
  19144. const chunk = chunkByModule.get(module);
  19145. if (chunk && chunk !== this) {
  19146. implicitlyLoadedBefore.add(chunk);
  19147. }
  19148. }
  19149. }
  19150. addNecessaryImportsForFacades() {
  19151. for (const [module, variables] of this.includedReexportsByModule) {
  19152. if (this.includedNamespaces.has(module)) {
  19153. for (const variable of variables) {
  19154. this.imports.add(variable);
  19155. }
  19156. }
  19157. }
  19158. }
  19159. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  19160. if (fileName) {
  19161. this.fileName = fileName;
  19162. }
  19163. else {
  19164. this.name = this.outputOptions.sanitizeFileName(name ||
  19165. (preservePath
  19166. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  19167. : getChunkNameFromModule(facadedModule)));
  19168. }
  19169. }
  19170. checkCircularDependencyImport(variable, importingModule) {
  19171. const variableModule = variable.module;
  19172. if (variableModule instanceof Module) {
  19173. const exportChunk = this.chunkByModule.get(variableModule);
  19174. let alternativeReexportModule;
  19175. do {
  19176. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  19177. if (alternativeReexportModule) {
  19178. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  19179. if (exportingChunk !== exportChunk) {
  19180. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCyclicCrossChunkReexport(
  19181. // Namespaces do not have an export name
  19182. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  19183. }
  19184. importingModule = alternativeReexportModule;
  19185. }
  19186. } while (alternativeReexportModule);
  19187. }
  19188. }
  19189. ensureReexportsAreAvailableForModule(module) {
  19190. const includedReexports = [];
  19191. const map = module.getExportNamesByVariable();
  19192. for (const exportedVariable of map.keys()) {
  19193. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  19194. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  19195. this.checkCircularDependencyImport(importedVariable, module);
  19196. // When preserving modules, we do not create namespace objects but directly
  19197. // use the actual namespaces, which would be broken by this logic.
  19198. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19199. const exportingModule = importedVariable.module;
  19200. if (exportingModule instanceof Module) {
  19201. const chunk = this.chunkByModule.get(exportingModule);
  19202. if (chunk && chunk !== this) {
  19203. chunk.exports.add(importedVariable);
  19204. includedReexports.push(importedVariable);
  19205. if (isSynthetic) {
  19206. this.imports.add(importedVariable);
  19207. }
  19208. }
  19209. }
  19210. }
  19211. }
  19212. if (includedReexports.length > 0) {
  19213. this.includedReexportsByModule.set(module, includedReexports);
  19214. }
  19215. }
  19216. generateVariableName() {
  19217. if (this.manualChunkAlias) {
  19218. return this.manualChunkAlias;
  19219. }
  19220. const moduleForNaming = this.entryModules[0] ||
  19221. this.implicitEntryModules[0] ||
  19222. this.dynamicEntryModules[0] ||
  19223. this.orderedModules[this.orderedModules.length - 1];
  19224. if (moduleForNaming) {
  19225. return getChunkNameFromModule(moduleForNaming);
  19226. }
  19227. return 'chunk';
  19228. }
  19229. getChunkExportDeclarations(format) {
  19230. const exports = [];
  19231. for (const exportName of this.getExportNames()) {
  19232. if (exportName[0] === '*')
  19233. continue;
  19234. const variable = this.exportsByName.get(exportName);
  19235. if (!(variable instanceof SyntheticNamedExportVariable)) {
  19236. const module = variable.module;
  19237. if (module) {
  19238. const chunk = this.chunkByModule.get(module);
  19239. if (chunk !== this) {
  19240. if (!chunk || format !== 'es') {
  19241. continue;
  19242. }
  19243. const chunkDep = this.renderedDependencies.get(chunk);
  19244. if (!chunkDep) {
  19245. continue;
  19246. }
  19247. const { imports, reexports } = chunkDep;
  19248. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  19249. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  19250. if (!isImported) {
  19251. continue;
  19252. }
  19253. }
  19254. }
  19255. }
  19256. let expression = null;
  19257. let hoisted = false;
  19258. let local = variable.getName(this.snippets.getPropertyAccess);
  19259. if (variable instanceof LocalVariable) {
  19260. for (const declaration of variable.declarations) {
  19261. if (declaration.parent instanceof FunctionDeclaration ||
  19262. (declaration instanceof ExportDefaultDeclaration &&
  19263. declaration.declaration instanceof FunctionDeclaration)) {
  19264. hoisted = true;
  19265. break;
  19266. }
  19267. }
  19268. }
  19269. else if (variable instanceof SyntheticNamedExportVariable) {
  19270. expression = local;
  19271. if (format === 'es') {
  19272. local = variable.renderName;
  19273. }
  19274. }
  19275. exports.push({
  19276. exported: exportName,
  19277. expression,
  19278. hoisted,
  19279. local
  19280. });
  19281. }
  19282. return exports;
  19283. }
  19284. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  19285. const dependencies = new Set();
  19286. const deconflictedDefault = new Set();
  19287. const deconflictedNamespace = new Set();
  19288. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  19289. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  19290. const module = variable.module;
  19291. if (module instanceof ExternalModule) {
  19292. const chunk = this.externalChunkByModule.get(module);
  19293. dependencies.add(chunk);
  19294. if (addNonNamespacesAndInteropHelpers) {
  19295. if (variable.name === 'default') {
  19296. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  19297. deconflictedDefault.add(chunk);
  19298. }
  19299. }
  19300. else if (variable.isNamespace &&
  19301. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  19302. (this.imports.has(variable) ||
  19303. !this.exportNamesByVariable.get(variable)?.every(name => name[0] === '*'))) {
  19304. // We only need to deconflict it if the namespace is actually
  19305. // created as a variable, i.e. because it is used internally or
  19306. // because it is reexported as an object
  19307. deconflictedNamespace.add(chunk);
  19308. }
  19309. }
  19310. }
  19311. else {
  19312. const chunk = this.chunkByModule.get(module);
  19313. if (chunk !== this) {
  19314. dependencies.add(chunk);
  19315. if (addNonNamespacesAndInteropHelpers &&
  19316. chunk.exportMode === 'default' &&
  19317. variable.isNamespace) {
  19318. deconflictedNamespace.add(chunk);
  19319. }
  19320. }
  19321. }
  19322. }
  19323. }
  19324. if (addDependenciesWithoutBindings) {
  19325. for (const dependency of this.dependencies) {
  19326. dependencies.add(dependency);
  19327. }
  19328. }
  19329. return { deconflictedDefault, deconflictedNamespace, dependencies };
  19330. }
  19331. getDynamicDependencies() {
  19332. return this.getIncludedDynamicImports()
  19333. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  19334. resolvedDynamicImport.chunk ||
  19335. resolvedDynamicImport.externalChunk ||
  19336. resolvedDynamicImport.resolution)
  19337. .filter((resolution) => resolution !== this &&
  19338. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  19339. }
  19340. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  19341. const { externalImportAttributes } = this.outputOptions;
  19342. const keepExternalImportAttributes = ['es', 'cjs'].includes(this.outputOptions.format) && externalImportAttributes;
  19343. if (resolution instanceof ExternalModule) {
  19344. const chunk = this.externalChunkByModule.get(resolution);
  19345. const dynamicAttributes = chunk.getImportAttributes(this.snippets);
  19346. return [
  19347. `'${chunk.getImportPath(fileName)}'`,
  19348. dynamicAttributes || (keepExternalImportAttributes ? true : null)
  19349. ];
  19350. }
  19351. let attributes = null;
  19352. if (keepExternalImportAttributes) {
  19353. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  19354. attributes =
  19355. attributesFromImportAttributes === parseAst_js.EMPTY_OBJECT
  19356. ? true
  19357. : formatAttributes(attributesFromImportAttributes, this.snippets);
  19358. }
  19359. return [resolution || '', attributes];
  19360. }
  19361. getFallbackChunkName() {
  19362. if (this.manualChunkAlias) {
  19363. return this.manualChunkAlias;
  19364. }
  19365. if (this.dynamicName) {
  19366. return this.dynamicName;
  19367. }
  19368. if (this.fileName) {
  19369. return parseAst_js.getAliasName(this.fileName);
  19370. }
  19371. return parseAst_js.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  19372. }
  19373. getImportSpecifiers() {
  19374. const { interop } = this.outputOptions;
  19375. const importsByDependency = new Map();
  19376. for (const variable of this.imports) {
  19377. const module = variable.module;
  19378. let dependency;
  19379. let imported;
  19380. if (module instanceof ExternalModule) {
  19381. dependency = this.externalChunkByModule.get(module);
  19382. imported = variable.name;
  19383. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  19384. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, false));
  19385. }
  19386. }
  19387. else {
  19388. dependency = this.chunkByModule.get(module);
  19389. imported = dependency.getVariableExportName(variable);
  19390. }
  19391. getOrCreate(importsByDependency, dependency, getNewArray).push({
  19392. imported,
  19393. local: variable.getName(this.snippets.getPropertyAccess)
  19394. });
  19395. }
  19396. return importsByDependency;
  19397. }
  19398. getIncludedDynamicImports() {
  19399. if (this.includedDynamicImports) {
  19400. return this.includedDynamicImports;
  19401. }
  19402. const includedDynamicImports = [];
  19403. for (const module of this.orderedModules) {
  19404. for (const { node, resolution } of module.dynamicImports) {
  19405. if (!node.included) {
  19406. continue;
  19407. }
  19408. includedDynamicImports.push(resolution instanceof Module
  19409. ? {
  19410. chunk: this.chunkByModule.get(resolution),
  19411. externalChunk: null,
  19412. facadeChunk: this.facadeChunkByModule.get(resolution),
  19413. node,
  19414. resolution
  19415. }
  19416. : resolution instanceof ExternalModule
  19417. ? {
  19418. chunk: null,
  19419. externalChunk: this.externalChunkByModule.get(resolution),
  19420. facadeChunk: null,
  19421. node,
  19422. resolution
  19423. }
  19424. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  19425. }
  19426. }
  19427. return (this.includedDynamicImports = includedDynamicImports);
  19428. }
  19429. getPreRenderedChunkInfo() {
  19430. if (this.preRenderedChunkInfo) {
  19431. return this.preRenderedChunkInfo;
  19432. }
  19433. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  19434. return (this.preRenderedChunkInfo = {
  19435. exports: this.getExportNames(),
  19436. facadeModuleId: facadeModule && facadeModule.id,
  19437. isDynamicEntry: dynamicEntryModules.length > 0,
  19438. isEntry: !!facadeModule?.info.isEntry,
  19439. isImplicitEntry: implicitEntryModules.length > 0,
  19440. moduleIds: orderedModules.map(({ id }) => id),
  19441. name: this.getChunkName(),
  19442. type: 'chunk'
  19443. });
  19444. }
  19445. getPreserveModulesChunkNameFromModule(module) {
  19446. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  19447. if (predefinedChunkName)
  19448. return predefinedChunkName;
  19449. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  19450. const sanitizedId = sanitizeFileName(parseAst_js.normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  19451. const extensionName = path.extname(sanitizedId);
  19452. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  19453. ? sanitizedId.slice(0, -extensionName.length)
  19454. : sanitizedId;
  19455. if (parseAst_js.isAbsolute(idWithoutExtension)) {
  19456. if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
  19457. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  19458. }
  19459. else {
  19460. // handle edge case in Windows
  19461. if (this.inputBase === '/' && idWithoutExtension[0] !== '/') {
  19462. return parseAst_js.relative(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  19463. }
  19464. return parseAst_js.relative(this.inputBase, idWithoutExtension);
  19465. }
  19466. }
  19467. else {
  19468. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
  19469. }
  19470. }
  19471. getReexportSpecifiers() {
  19472. const { externalLiveBindings, interop } = this.outputOptions;
  19473. const reexportSpecifiers = new Map();
  19474. for (let exportName of this.getExportNames()) {
  19475. let dependency;
  19476. let imported;
  19477. let needsLiveBinding = false;
  19478. if (exportName[0] === '*') {
  19479. const id = exportName.slice(1);
  19480. if (interop(id) === 'defaultOnly') {
  19481. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnexpectedNamespaceReexport(id));
  19482. }
  19483. needsLiveBinding = externalLiveBindings;
  19484. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  19485. imported = exportName = '*';
  19486. }
  19487. else {
  19488. const variable = this.exportsByName.get(exportName);
  19489. if (variable instanceof SyntheticNamedExportVariable)
  19490. continue;
  19491. const module = variable.module;
  19492. if (module instanceof Module) {
  19493. dependency = this.chunkByModule.get(module);
  19494. if (dependency === this)
  19495. continue;
  19496. imported = dependency.getVariableExportName(variable);
  19497. needsLiveBinding = variable.isReassigned;
  19498. }
  19499. else {
  19500. dependency = this.externalChunkByModule.get(module);
  19501. imported = variable.name;
  19502. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  19503. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, true));
  19504. }
  19505. needsLiveBinding =
  19506. externalLiveBindings &&
  19507. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  19508. }
  19509. }
  19510. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  19511. imported,
  19512. needsLiveBinding,
  19513. reexported: exportName
  19514. });
  19515. }
  19516. return reexportSpecifiers;
  19517. }
  19518. getReferencedFiles() {
  19519. const referencedFiles = new Set();
  19520. for (const module of this.orderedModules) {
  19521. for (const meta of module.importMetas) {
  19522. const fileName = meta.getReferencedFileName(this.pluginDriver);
  19523. if (fileName) {
  19524. referencedFiles.add(fileName);
  19525. }
  19526. }
  19527. }
  19528. return [...referencedFiles];
  19529. }
  19530. getRenderedDependencies() {
  19531. if (this.renderedDependencies) {
  19532. return this.renderedDependencies;
  19533. }
  19534. const importSpecifiers = this.getImportSpecifiers();
  19535. const reexportSpecifiers = this.getReexportSpecifiers();
  19536. const renderedDependencies = new Map();
  19537. const fileName = this.getFileName();
  19538. for (const dependency of this.dependencies) {
  19539. const imports = importSpecifiers.get(dependency) || null;
  19540. const reexports = reexportSpecifiers.get(dependency) || null;
  19541. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  19542. const importPath = dependency.getImportPath(fileName);
  19543. renderedDependencies.set(dependency, {
  19544. attributes: dependency instanceof ExternalChunk
  19545. ? dependency.getImportAttributes(this.snippets)
  19546. : null,
  19547. defaultVariableName: dependency.defaultVariableName,
  19548. globalName: dependency instanceof ExternalChunk &&
  19549. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  19550. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  19551. importPath,
  19552. imports,
  19553. isChunk: dependency instanceof Chunk,
  19554. name: dependency.variableName,
  19555. namedExportsMode,
  19556. namespaceVariableName: dependency.namespaceVariableName,
  19557. reexports
  19558. });
  19559. }
  19560. return (this.renderedDependencies = renderedDependencies);
  19561. }
  19562. inlineChunkDependencies(chunk) {
  19563. for (const dep of chunk.dependencies) {
  19564. if (this.dependencies.has(dep))
  19565. continue;
  19566. this.dependencies.add(dep);
  19567. if (dep instanceof Chunk) {
  19568. this.inlineChunkDependencies(dep);
  19569. }
  19570. }
  19571. }
  19572. // This method changes properties on the AST before rendering and must not be async
  19573. renderModules(fileName) {
  19574. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  19575. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  19576. const { _, cnst, n } = snippets;
  19577. this.setDynamicImportResolutions(fileName);
  19578. this.setImportMetaResolutions(fileName);
  19579. this.setIdentifierRenderResolutions();
  19580. const magicString = new Bundle$1({ separator: `${n}${n}` });
  19581. const indent = getIndentString(orderedModules, outputOptions);
  19582. const usedModules = [];
  19583. let hoistedSource = '';
  19584. const accessedGlobals = new Set();
  19585. const renderedModuleSources = new Map();
  19586. const renderOptions = {
  19587. accessedDocumentCurrentScript: false,
  19588. exportNamesByVariable,
  19589. format,
  19590. freeze,
  19591. importAttributesKey,
  19592. indent,
  19593. pluginDriver,
  19594. snippets,
  19595. symbols,
  19596. useOriginalName: null
  19597. };
  19598. let usesTopLevelAwait = false;
  19599. for (const module of orderedModules) {
  19600. let renderedLength = 0;
  19601. let source;
  19602. if (module.isIncluded() || includedNamespaces.has(module)) {
  19603. const rendered = module.render(renderOptions);
  19604. if (!renderOptions.accessedDocumentCurrentScript &&
  19605. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  19606. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  19607. }
  19608. renderOptions.accessedDocumentCurrentScript = false;
  19609. ({ source } = rendered);
  19610. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  19611. renderedLength = source.length();
  19612. if (renderedLength) {
  19613. if (compact && source.lastLine().includes('//'))
  19614. source.append('\n');
  19615. renderedModuleSources.set(module, source);
  19616. magicString.addSource(source);
  19617. usedModules.push(module);
  19618. }
  19619. const namespace = module.namespace;
  19620. if (includedNamespaces.has(module)) {
  19621. const rendered = namespace.renderBlock(renderOptions);
  19622. if (namespace.renderFirst())
  19623. hoistedSource += n + rendered;
  19624. else
  19625. magicString.addSource(new MagicString(rendered));
  19626. }
  19627. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  19628. if (accessedGlobalVariables) {
  19629. for (const name of accessedGlobalVariables) {
  19630. accessedGlobals.add(name);
  19631. }
  19632. }
  19633. }
  19634. const { renderedExports, removedExports } = module.getRenderedExports();
  19635. renderedModules[module.id] = {
  19636. get code() {
  19637. return source?.toString() ?? null;
  19638. },
  19639. originalLength: module.originalCode.length,
  19640. removedExports,
  19641. renderedExports,
  19642. renderedLength
  19643. };
  19644. }
  19645. if (hoistedSource)
  19646. magicString.prepend(hoistedSource + n + n);
  19647. if (this.needsExportsShim) {
  19648. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  19649. }
  19650. const renderedSource = compact ? magicString : magicString.trim();
  19651. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  19652. onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyChunk(this.getChunkName()));
  19653. }
  19654. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  19655. }
  19656. setDynamicImportResolutions(fileName) {
  19657. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  19658. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  19659. if (resolvedDynamicImport.chunk) {
  19660. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  19661. if (chunk === this) {
  19662. node.setInternalResolution(resolution.namespace);
  19663. }
  19664. else {
  19665. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  19666. }
  19667. }
  19668. else {
  19669. const { node, resolution } = resolvedDynamicImport;
  19670. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  19671. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  19672. }
  19673. }
  19674. }
  19675. setIdentifierRenderResolutions() {
  19676. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  19677. const syntheticExports = new Set();
  19678. for (const exportName of this.getExportNames()) {
  19679. const exportVariable = this.exportsByName.get(exportName);
  19680. if (format !== 'es' &&
  19681. format !== 'system' &&
  19682. exportVariable.isReassigned &&
  19683. !exportVariable.isId) {
  19684. exportVariable.setRenderNames('exports', exportName);
  19685. }
  19686. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  19687. syntheticExports.add(exportVariable);
  19688. }
  19689. else {
  19690. exportVariable.setRenderNames(null, null);
  19691. }
  19692. }
  19693. for (const module of this.orderedModules) {
  19694. if (module.needsExportShim) {
  19695. this.needsExportsShim = true;
  19696. break;
  19697. }
  19698. }
  19699. const usedNames = new Set(['Object', 'Promise']);
  19700. if (this.needsExportsShim) {
  19701. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  19702. }
  19703. if (symbols) {
  19704. usedNames.add('Symbol');
  19705. }
  19706. switch (format) {
  19707. case 'system': {
  19708. usedNames.add('module').add('exports');
  19709. break;
  19710. }
  19711. case 'es': {
  19712. break;
  19713. }
  19714. case 'cjs': {
  19715. usedNames.add('module').add('require').add('__filename').add('__dirname');
  19716. }
  19717. // fallthrough
  19718. default: {
  19719. usedNames.add('exports');
  19720. for (const helper of HELPER_NAMES) {
  19721. usedNames.add(helper);
  19722. }
  19723. }
  19724. }
  19725. 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);
  19726. }
  19727. setImportMetaResolutions(fileName) {
  19728. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  19729. for (const module of orderedModules) {
  19730. for (const importMeta of module.importMetas) {
  19731. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  19732. }
  19733. if (includedNamespaces.has(module)) {
  19734. module.namespace.prepare(accessedGlobalsByScope);
  19735. }
  19736. }
  19737. }
  19738. setUpChunkImportsAndExportsForModule(module) {
  19739. const moduleImports = new Set(module.includedImports);
  19740. // when we are not preserving modules, we need to make all namespace variables available for
  19741. // rendering the namespace object
  19742. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  19743. const memberVariables = module.namespace.getMemberVariables();
  19744. for (const variable of Object.values(memberVariables)) {
  19745. if (variable.included) {
  19746. moduleImports.add(variable);
  19747. }
  19748. }
  19749. }
  19750. for (let variable of moduleImports) {
  19751. if (variable instanceof ExportDefaultVariable) {
  19752. variable = variable.getOriginalVariable();
  19753. }
  19754. if (variable instanceof SyntheticNamedExportVariable) {
  19755. variable = variable.getBaseVariable();
  19756. }
  19757. const chunk = this.chunkByModule.get(variable.module);
  19758. if (chunk !== this) {
  19759. this.imports.add(variable);
  19760. if (variable.module instanceof Module) {
  19761. this.checkCircularDependencyImport(variable, module);
  19762. // When preserving modules, we do not create namespace objects but directly
  19763. // use the actual namespaces, which would be broken by this logic.
  19764. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19765. chunk.exports.add(variable);
  19766. }
  19767. }
  19768. }
  19769. }
  19770. if (this.includedNamespaces.has(module) ||
  19771. (module.info.isEntry && module.preserveSignature !== false) ||
  19772. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  19773. this.ensureReexportsAreAvailableForModule(module);
  19774. }
  19775. for (const { node, resolution } of module.dynamicImports) {
  19776. if (node.included &&
  19777. resolution instanceof Module &&
  19778. this.chunkByModule.get(resolution) === this &&
  19779. !this.includedNamespaces.has(resolution)) {
  19780. this.includedNamespaces.add(resolution);
  19781. this.ensureReexportsAreAvailableForModule(resolution);
  19782. }
  19783. }
  19784. }
  19785. }
  19786. function getChunkNameFromModule(module) {
  19787. return getPredefinedChunkNameFromModule(module) ?? parseAst_js.getAliasName(module.id);
  19788. }
  19789. function getPredefinedChunkNameFromModule(module) {
  19790. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  19791. }
  19792. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  19793. const importedBindingsPerDependency = {};
  19794. for (const [dependency, declaration] of renderedDependencies) {
  19795. const specifiers = new Set();
  19796. if (declaration.imports) {
  19797. for (const { imported } of declaration.imports) {
  19798. specifiers.add(imported);
  19799. }
  19800. }
  19801. if (declaration.reexports) {
  19802. for (const { imported } of declaration.reexports) {
  19803. specifiers.add(imported);
  19804. }
  19805. }
  19806. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  19807. }
  19808. return importedBindingsPerDependency;
  19809. }
  19810. const QUERY_HASH_REGEX = /[#?]/;
  19811. const resolveFileName = (dependency) => dependency.getFileName();
  19812. /**
  19813. * Concatenate a number of iterables to a new iterable without fully evaluating
  19814. * their iterators. Useful when e.g. working with large sets or lists and when
  19815. * there is a chance that the iterators will not be fully exhausted.
  19816. */
  19817. function* concatLazy(iterables) {
  19818. for (const iterable of iterables) {
  19819. yield* iterable;
  19820. }
  19821. }
  19822. /**
  19823. * At its core, the algorithm first starts from each static or dynamic entry
  19824. * point and then assigns that entry point to all modules than can be reached
  19825. * via static imports. We call this the *dependent entry points* of that
  19826. * module.
  19827. *
  19828. * Then we group all modules with the same dependent entry points into chunks
  19829. * as those modules will always be loaded together.
  19830. *
  19831. * One non-trivial optimization we can apply is that dynamic entries are
  19832. * different from static entries in so far as when a dynamic import occurs,
  19833. * some modules are already in memory. If some of these modules are also
  19834. * dependencies of the dynamic entry, then it does not make sense to create a
  19835. * separate chunk for them. Instead, the dynamic import target can load them
  19836. * from the importing chunk.
  19837. *
  19838. * With regard to chunking, if B is implicitly loaded after A, then this can be
  19839. * handled the same way as if there was a dynamic import A => B.
  19840. *
  19841. * Example:
  19842. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  19843. * Then the initial algorithm would assign A into the A chunk, C into the C
  19844. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  19845. * points A and C.
  19846. * However we know that C can only be loaded from A, so A and its dependency B
  19847. * must already be in memory when C is loaded. So it is enough to create only
  19848. * two chunks A containing [AB] and C containing [C].
  19849. *
  19850. * So we do not assign the dynamic entry C as dependent entry point to modules
  19851. * that are already loaded.
  19852. *
  19853. * In a more complex example, let us assume that we have entry points X and Y.
  19854. * Further, let us assume
  19855. * X -> A, X -> B, X -> C,
  19856. * Y -> A, Y -> B,
  19857. * A => D,
  19858. * D -> B, D -> C
  19859. * So without dynamic import optimization, the dependent entry points are
  19860. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  19861. * chunks.
  19862. *
  19863. * Now D is loaded only after A is loaded. But A is loaded if either X is
  19864. * loaded or Y is loaded. So the modules that are already in memory when D is
  19865. * loaded are the intersection of all modules that X depends on with all
  19866. * modules that Y depends on, which in this case are the modules A and B.
  19867. * We could also say they are all modules that have both X and Y as dependent
  19868. * entry points.
  19869. *
  19870. * So we can remove D as dependent entry point from A and B, which means they
  19871. * both now have only XY as dependent entry points and can be merged into the
  19872. * same chunk.
  19873. *
  19874. * Now let us extend this to the most general case where we have several
  19875. * dynamic importers for one dynamic entry point.
  19876. *
  19877. * In the most general form, it works like this:
  19878. * For each dynamic entry point, we have a number of dynamic importers, which
  19879. * are the modules importing it. Using the previous ideas, we can determine
  19880. * the modules already in memory for each dynamic importer by looking for all
  19881. * modules that have all the dependent entry points of the dynamic importer as
  19882. * dependent entry points.
  19883. * So the modules that are guaranteed to be in memory when the dynamic entry
  19884. * point is loaded are the intersection of the modules already in memory for
  19885. * each dynamic importer.
  19886. *
  19887. * Assuming that A => D and B => D and A has dependent entry points XY and B
  19888. * has dependent entry points YZ, then the modules guaranteed to be in memory
  19889. * are all modules that have at least XYZ as dependent entry points.
  19890. * We call XYZ the *dynamically dependent entry points* of D.
  19891. *
  19892. * Now there is one last case to consider: If one of the dynamically dependent
  19893. * entries is itself a dynamic entry, then any module is in memory that either
  19894. * is a dependency of that dynamic entry or again has the dynamic dependent
  19895. * entries of that dynamic entry as dependent entry points.
  19896. *
  19897. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  19898. * complexity with regard to dynamic entries that blew up for very large
  19899. * projects.
  19900. *
  19901. * If we have an efficient way to do Set operations, an alternative approach
  19902. * would be to instead collect already loaded modules per dynamic entry. And as
  19903. * all chunks from the initial grouping would behave the same, we can instead
  19904. * collect already loaded chunks for a performance improvement.
  19905. *
  19906. * To do that efficiently, need
  19907. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  19908. * imports that can be triggered by a dynamic entry
  19909. * - a Map of static dependencies per entry
  19910. * - a Map of already loaded chunks per entry that we initially populate with
  19911. * empty Sets for static entries and Sets containing all entries for dynamic
  19912. * entries
  19913. *
  19914. * For efficient operations, we assign each entry a numerical index and
  19915. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  19916. * bit index. Then the last two maps can be represented as arrays of BigInt
  19917. * values.
  19918. *
  19919. * Then we iterate through each dynamic entry. We set the already loaded modules
  19920. * to the intersection of the previously already loaded modules with the union
  19921. * of the already loaded modules of that chunk with its static dependencies.
  19922. *
  19923. * If the already loaded modules changed, then we use the Map of dynamic imports
  19924. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  19925. * them back into the iteration. As an additional optimization, we note for
  19926. * each dynamic entry which dynamic dependent entries have changed and only
  19927. * intersect those entries again on subsequent interations.
  19928. *
  19929. * Then we remove the dynamic entries from the list of dependent entries for
  19930. * those chunks that are already loaded for that dynamic entry and create
  19931. * another round of chunks.
  19932. */
  19933. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  19934. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks);
  19935. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  19936. // Each chunk is identified by its position in this array
  19937. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  19938. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  19939. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19940. // If we no longer want this, we should make a copy here.
  19941. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  19942. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  19943. // This mutates the dependentEntries in chunkAtoms
  19944. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  19945. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  19946. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  19947. alias: null,
  19948. modules
  19949. })));
  19950. return chunkDefinitions;
  19951. }
  19952. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  19953. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  19954. const manualChunkModulesByAlias = Object.create(null);
  19955. for (const [entry, alias] of manualChunkAliasByEntry) {
  19956. if (isManualChunksFunctionForm && onlyExplicitManualChunks) {
  19957. (manualChunkModulesByAlias[alias] ||= []).push(entry);
  19958. }
  19959. else {
  19960. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  19961. }
  19962. }
  19963. const manualChunks = Object.entries(manualChunkModulesByAlias);
  19964. const chunkDefinitions = new Array(manualChunks.length);
  19965. let index = 0;
  19966. for (const [alias, modules] of manualChunks) {
  19967. chunkDefinitions[index++] = { alias, modules };
  19968. }
  19969. return { chunkDefinitions, modulesInManualChunks };
  19970. }
  19971. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  19972. const modulesToHandle = new Set([entry]);
  19973. for (const module of modulesToHandle) {
  19974. modulesInManualChunks.add(module);
  19975. manualChunkModules.push(module);
  19976. for (const dependency of module.dependencies) {
  19977. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  19978. modulesToHandle.add(dependency);
  19979. }
  19980. }
  19981. }
  19982. }
  19983. function analyzeModuleGraph(entries) {
  19984. const dynamicEntryModules = new Set();
  19985. const awaitedDynamicEntryModules = new Set();
  19986. const dependentEntriesByModule = new Map();
  19987. const allEntriesSet = new Set(entries);
  19988. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  19989. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  19990. let entryIndex = 0;
  19991. for (const currentEntry of allEntriesSet) {
  19992. const dynamicImportsForCurrentEntry = new Set();
  19993. const awaitedDynamicImportsForCurrentEntry = new Set();
  19994. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  19995. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  19996. const staticDependencies = new Set([currentEntry]);
  19997. for (const module of staticDependencies) {
  19998. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  19999. for (const dependency of module.getDependenciesToBeIncluded()) {
  20000. if (!(dependency instanceof ExternalModule)) {
  20001. staticDependencies.add(dependency);
  20002. }
  20003. }
  20004. for (const { resolution } of module.dynamicImports) {
  20005. if (resolution instanceof Module &&
  20006. resolution.includedDynamicImporters.length > 0 &&
  20007. !allEntriesSet.has(resolution)) {
  20008. dynamicEntryModules.add(resolution);
  20009. allEntriesSet.add(resolution);
  20010. dynamicImportsForCurrentEntry.add(resolution);
  20011. for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
  20012. if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
  20013. awaitedDynamicEntryModules.add(resolution);
  20014. awaitedDynamicImportsForCurrentEntry.add(resolution);
  20015. break;
  20016. }
  20017. }
  20018. }
  20019. }
  20020. for (const dependency of module.implicitlyLoadedBefore) {
  20021. if (!allEntriesSet.has(dependency)) {
  20022. dynamicEntryModules.add(dependency);
  20023. allEntriesSet.add(dependency);
  20024. }
  20025. }
  20026. }
  20027. entryIndex++;
  20028. }
  20029. const allEntries = [...allEntriesSet];
  20030. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  20031. return {
  20032. allEntries,
  20033. awaitedDynamicImportsByEntry,
  20034. dependentEntriesByModule,
  20035. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
  20036. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  20037. dynamicImportsByEntry
  20038. };
  20039. }
  20040. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  20041. const entryIndexByModule = new Map();
  20042. const dynamicEntries = new Set();
  20043. const awaitedDynamicEntries = new Set();
  20044. for (const [entryIndex, entry] of allEntries.entries()) {
  20045. entryIndexByModule.set(entry, entryIndex);
  20046. if (dynamicEntryModules.has(entry)) {
  20047. dynamicEntries.add(entryIndex);
  20048. }
  20049. if (awaitedDynamicEntryModules.has(entry)) {
  20050. awaitedDynamicEntries.add(entryIndex);
  20051. }
  20052. }
  20053. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  20054. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  20055. return {
  20056. awaitedDynamicEntries,
  20057. awaitedDynamicImportsByEntry,
  20058. dynamicEntries,
  20059. dynamicImportsByEntry
  20060. };
  20061. }
  20062. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  20063. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  20064. let index = 0;
  20065. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  20066. const dynamicImports = new Set();
  20067. for (const dynamicEntry of dynamicImportModules) {
  20068. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  20069. }
  20070. dynamicImportsByEntry[index++] = dynamicImports;
  20071. }
  20072. return dynamicImportsByEntry;
  20073. }
  20074. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  20075. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  20076. for (const dynamicEntryIndex of dynamicEntries) {
  20077. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  20078. const dynamicEntry = allEntries[dynamicEntryIndex];
  20079. for (const importer of concatLazy([
  20080. getDynamicImporters(dynamicEntry),
  20081. dynamicEntry.implicitlyLoadedAfter
  20082. ])) {
  20083. for (const entry of dependentEntriesByModule.get(importer)) {
  20084. dynamicallyDependentEntries.add(entry);
  20085. }
  20086. }
  20087. }
  20088. return dynamicallyDependentEntriesByDynamicEntry;
  20089. }
  20090. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  20091. const chunkModules = Object.create(null);
  20092. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  20093. let chunkSignature = 0n;
  20094. for (const entryIndex of dependentEntries) {
  20095. chunkSignature |= 1n << BigInt(entryIndex);
  20096. }
  20097. (chunkModules[String(chunkSignature)] ||= {
  20098. dependentEntries: new Set(dependentEntries),
  20099. modules: []
  20100. }).modules.push(...modules);
  20101. }
  20102. return Object.values(chunkModules);
  20103. }
  20104. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  20105. for (const [module, dependentEntries] of dependentEntriesByModule) {
  20106. if (!modulesInManualChunks.has(module)) {
  20107. yield { dependentEntries, modules: [module] };
  20108. }
  20109. }
  20110. }
  20111. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  20112. // The indices correspond to the indices in allEntries. The atoms correspond
  20113. // to bits in the bigint values where chunk 0 is the lowest bit.
  20114. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  20115. // This toggles the bits for each atom that is a dependency of an entry
  20116. let atomMask = 1n;
  20117. for (const { dependentEntries } of chunkAtoms) {
  20118. for (const entryIndex of dependentEntries) {
  20119. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  20120. }
  20121. atomMask <<= 1n;
  20122. }
  20123. return staticDependencyAtomsByEntry;
  20124. }
  20125. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  20126. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  20127. // Dynamic entries have all atoms as already loaded initially because we then
  20128. // intersect with the static dependency atoms of all dynamic importers.
  20129. // Static entries cannot have already loaded atoms.
  20130. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  20131. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  20132. // We delete here so that they can be added again if necessary to be handled
  20133. // again by the loop
  20134. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  20135. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  20136. let updatedLoadedAtoms = knownLoadedAtoms;
  20137. for (const entryIndex of dynamicallyDependentEntries) {
  20138. updatedLoadedAtoms &=
  20139. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  20140. }
  20141. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  20142. // updated again
  20143. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  20144. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  20145. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  20146. // If this adds an entry that was deleted before, it will be handled
  20147. // again. This is the reason why we delete every entry from this map
  20148. // that we processed.
  20149. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  20150. }
  20151. }
  20152. }
  20153. return alreadyLoadedAtomsByEntry;
  20154. }
  20155. /**
  20156. * This removes all unnecessary dynamic entries from the dependentEntries in its
  20157. * first argument if a chunk is already loaded without that entry.
  20158. */
  20159. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  20160. // Remove entries from dependent entries if a chunk is already loaded without
  20161. // that entry. Do not remove already loaded atoms where some dynamic imports
  20162. // are awaited to avoid cycles in the output.
  20163. let chunkMask = 1n;
  20164. for (const { dependentEntries } of chunkAtoms) {
  20165. for (const entryIndex of dependentEntries) {
  20166. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  20167. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  20168. dependentEntries.delete(entryIndex);
  20169. }
  20170. }
  20171. chunkMask <<= 1n;
  20172. }
  20173. }
  20174. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  20175. const chunksBySignature = Object.create(null);
  20176. const chunkByModule = new Map();
  20177. const sizeByAtom = new Array(chunkAtoms.length);
  20178. let sideEffectAtoms = 0n;
  20179. let atomMask = 1n;
  20180. let index = 0;
  20181. for (const { dependentEntries, modules } of chunkAtoms) {
  20182. let chunkSignature = 0n;
  20183. let correlatedAtoms = -1n;
  20184. for (const entryIndex of dependentEntries) {
  20185. chunkSignature |= 1n << BigInt(entryIndex);
  20186. // Correlated atoms are the atoms that are guaranteed to be loaded as
  20187. // well when a given atom is loaded. It is the intersection of the already
  20188. // loaded modules of each chunk merged with its static dependencies.
  20189. correlatedAtoms &=
  20190. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  20191. }
  20192. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  20193. containedAtoms: 0n,
  20194. correlatedAtoms,
  20195. dependencies: new Set(),
  20196. dependentChunks: new Set(),
  20197. dependentEntries: new Set(dependentEntries),
  20198. modules: [],
  20199. pure: true,
  20200. size: 0
  20201. });
  20202. let atomSize = 0;
  20203. let pure = true;
  20204. for (const module of modules) {
  20205. chunkByModule.set(module, chunk);
  20206. // Unfortunately, we cannot take tree-shaking into account here because
  20207. // rendering did not happen yet, but we can detect empty modules
  20208. if (module.isIncluded()) {
  20209. pure &&= !module.hasEffects();
  20210. // we use a trivial size for the default minChunkSize to improve
  20211. // performance
  20212. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  20213. }
  20214. }
  20215. if (!pure) {
  20216. sideEffectAtoms |= atomMask;
  20217. }
  20218. sizeByAtom[index++] = atomSize;
  20219. chunk.containedAtoms |= atomMask;
  20220. chunk.modules.push(...modules);
  20221. chunk.pure &&= pure;
  20222. chunk.size += atomSize;
  20223. atomMask <<= 1n;
  20224. }
  20225. const chunks = Object.values(chunksBySignature);
  20226. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  20227. return { chunks, sideEffectAtoms, sizeByAtom };
  20228. }
  20229. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  20230. const signatureByExternalModule = new Map();
  20231. let externalSideEffectAtoms = 0n;
  20232. for (const chunk of chunks) {
  20233. const { dependencies, modules } = chunk;
  20234. for (const module of modules) {
  20235. for (const dependency of module.getDependenciesToBeIncluded()) {
  20236. if (dependency instanceof ExternalModule) {
  20237. if (dependency.info.moduleSideEffects) {
  20238. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  20239. const signature = nextAvailableAtomMask;
  20240. nextAvailableAtomMask <<= 1n;
  20241. externalSideEffectAtoms |= signature;
  20242. return signature;
  20243. });
  20244. chunk.containedAtoms |= signature;
  20245. chunk.correlatedAtoms |= signature;
  20246. }
  20247. }
  20248. else {
  20249. const dependencyChunk = chunkByModule.get(dependency);
  20250. if (dependencyChunk && dependencyChunk !== chunk) {
  20251. dependencies.add(dependencyChunk);
  20252. dependencyChunk.dependentChunks.add(chunk);
  20253. }
  20254. }
  20255. }
  20256. }
  20257. }
  20258. return externalSideEffectAtoms;
  20259. }
  20260. /**
  20261. * This function tries to get rid of small chunks by merging them with other
  20262. * chunks.
  20263. *
  20264. * We can only merge chunks safely if after the merge, loading any entry point
  20265. * in any allowed order will not trigger side effects that should not have been
  20266. * triggered. While side effects are usually things like global function calls,
  20267. * global variable mutations or potentially thrown errors, details do not
  20268. * matter here, and we just discern chunks without side effects (pure chunks)
  20269. * from other chunks.
  20270. *
  20271. * As a first step, we assign each pre-generated chunk with side effects a
  20272. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  20273. *
  20274. * Now to determine the side effects of loading a chunk, one also has to take
  20275. * the side effects of its dependencies into account. So if A depends on B
  20276. * (A -> B) and both have side effects, loading A triggers effects AB.
  20277. *
  20278. * Now from the previous step we know that each chunk is uniquely determine by
  20279. * the entry points that depend on it and cause it to load, which we will call
  20280. * its dependent entry points.
  20281. *
  20282. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  20283. * Starting from that idea, we can determine a set of chunks—and thus a set
  20284. * of side effects—that must have been triggered if a certain chunk has been
  20285. * loaded. Basically, it is the intersection of all chunks loaded by the
  20286. * dependent entry points of a given chunk. We call the corresponding side
  20287. * effects the correlated side effects of that chunk.
  20288. *
  20289. * Example:
  20290. * X -> ABC, Y -> ADE, A-> F, B -> D
  20291. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  20292. * The intersection is ADF. So we know that when A is loaded, D and F must also
  20293. * be in memory even though neither D nor A is a dependency of the other.
  20294. * If all have side effects, we call ADF the correlated side effects of A. The
  20295. * correlated side effects need to remain constant when merging chunks.
  20296. *
  20297. * In contrast, we have the dependency side effects of A, which represents
  20298. * the side effects we trigger if we directly load A. In this example, the
  20299. * dependency side effects are AF.
  20300. * For entry chunks, dependency and correlated side effects are the same.
  20301. *
  20302. * With these concepts, merging chunks is allowed if the correlated side
  20303. * effects of each entry do not change. Thus, we are allowed to merge two
  20304. * chunks if
  20305. *
  20306. * a) the dependency side effects of each chunk are a subset of the correlated
  20307. * side effects of the other chunk, so no additional side effects are
  20308. * triggered for any entry, or
  20309. * b) The dependent entry points of chunk A are a subset of the dependent entry
  20310. * points of chunk B while the dependency side effects of A are a subset of
  20311. * the correlated side effects of B. Because in that scenario, whenever A is
  20312. * loaded, B is loaded as well. But there are cases when B is loaded where A
  20313. * is not loaded. So if we merge the chunks, all dependency side effects of
  20314. * A will be added to the correlated side effects of B, and as the latter is
  20315. * not allowed to change, the former need to be a subset of the latter.
  20316. *
  20317. * Another consideration when merging small chunks into other chunks is to
  20318. * avoid
  20319. * that too much additional code is loaded. This is achieved when the dependent
  20320. * entries of the small chunk are a subset of the dependent entries of the
  20321. * other
  20322. * chunk. Because then when the small chunk is loaded, the other chunk was
  20323. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  20324. * additional size of the small chunk is loaded unnecessarily.
  20325. *
  20326. * So the algorithm performs merges in two passes:
  20327. *
  20328. * 1. First we try to merge small chunks A only into other chunks B if the
  20329. * dependent entries of A are a subset of the dependent entries of B and the
  20330. * dependency side effects of A are a subset of the correlated side effects
  20331. * of B.
  20332. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  20333. * following the rule (a), starting with the smallest chunks to look for
  20334. * possible merge targets.
  20335. */
  20336. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  20337. timeStart('optimize chunks', 3);
  20338. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  20339. if (!chunkPartition) {
  20340. timeEnd('optimize chunks', 3);
  20341. return chunks; // the actual modules
  20342. }
  20343. if (minChunkSize > 1) {
  20344. log('info', parseAst_js.logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  20345. }
  20346. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  20347. if (minChunkSize > 1) {
  20348. log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  20349. }
  20350. timeEnd('optimize chunks', 3);
  20351. return [...chunkPartition.small, ...chunkPartition.big];
  20352. }
  20353. function getPartitionedChunks(chunks, minChunkSize) {
  20354. const smallChunks = [];
  20355. const bigChunks = [];
  20356. for (const chunk of chunks) {
  20357. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  20358. }
  20359. if (smallChunks.length === 0) {
  20360. return null;
  20361. }
  20362. smallChunks.sort(compareChunkSize);
  20363. bigChunks.sort(compareChunkSize);
  20364. return {
  20365. big: new Set(bigChunks),
  20366. small: new Set(smallChunks)
  20367. };
  20368. }
  20369. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  20370. return sizeA - sizeB;
  20371. }
  20372. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  20373. const { small } = chunkPartition;
  20374. for (const mergedChunk of small) {
  20375. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  20376. // In the default case, we do not accept size increases
  20377. minChunkSize <= 1 ? 1 : Infinity);
  20378. if (bestTargetChunk) {
  20379. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  20380. small.delete(mergedChunk);
  20381. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  20382. bestTargetChunk.modules.push(...modules);
  20383. bestTargetChunk.size += size;
  20384. bestTargetChunk.pure &&= pure;
  20385. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  20386. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  20387. bestTargetChunk.containedAtoms |= containedAtoms;
  20388. for (const entry of mergedChunk.dependentEntries) {
  20389. dependentEntries.add(entry);
  20390. }
  20391. for (const dependency of mergedChunk.dependencies) {
  20392. dependencies.add(dependency);
  20393. dependency.dependentChunks.delete(mergedChunk);
  20394. dependency.dependentChunks.add(bestTargetChunk);
  20395. }
  20396. for (const dependentChunk of mergedChunk.dependentChunks) {
  20397. dependentChunks.add(dependentChunk);
  20398. dependentChunk.dependencies.delete(mergedChunk);
  20399. dependentChunk.dependencies.add(bestTargetChunk);
  20400. }
  20401. dependencies.delete(bestTargetChunk);
  20402. dependentChunks.delete(bestTargetChunk);
  20403. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  20404. }
  20405. }
  20406. }
  20407. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  20408. let bestTargetChunk = null;
  20409. // In the default case, we do not accept size increases
  20410. for (const targetChunk of concatLazy([small, big])) {
  20411. if (mergedChunk === targetChunk)
  20412. continue;
  20413. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  20414. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  20415. bestTargetChunk = targetChunk;
  20416. if (additionalSizeAfterMerge === 0)
  20417. break;
  20418. smallestAdditionalSize = additionalSizeAfterMerge;
  20419. }
  20420. }
  20421. return bestTargetChunk;
  20422. }
  20423. /**
  20424. * Determine the additional unused code size that would be added by merging the
  20425. * two chunks. This is not an exact measurement but rather an upper bound. If
  20426. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  20427. * is returned.
  20428. * Merging will not produce cycles if none of the direct non-merged
  20429. * dependencies of a chunk have the other chunk as a transitive dependency.
  20430. */
  20431. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  20432. // The maximum additional unused code size allowed to be added by the merge,
  20433. // taking dependencies into account, needs to be below this number
  20434. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20435. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  20436. return firstSize < currentAdditionalSize
  20437. ? firstSize +
  20438. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  20439. : Infinity;
  20440. }
  20441. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  20442. const { correlatedAtoms } = dependencyChunk;
  20443. let dependencyAtoms = dependentChunk.containedAtoms;
  20444. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  20445. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  20446. return Infinity;
  20447. }
  20448. const chunksToCheck = new Set(dependentChunk.dependencies);
  20449. for (const { dependencies, containedAtoms } of chunksToCheck) {
  20450. dependencyAtoms |= containedAtoms;
  20451. const containedSideEffects = containedAtoms & sideEffectAtoms;
  20452. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  20453. return Infinity;
  20454. }
  20455. for (const dependency of dependencies) {
  20456. if (dependency === dependencyChunk) {
  20457. return Infinity;
  20458. }
  20459. chunksToCheck.add(dependency);
  20460. }
  20461. }
  20462. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  20463. }
  20464. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  20465. let size = 0;
  20466. let atomIndex = 0;
  20467. let atomSignature = 1n;
  20468. const { length } = sizeByAtom;
  20469. for (; atomIndex < length; atomIndex++) {
  20470. if ((atoms & atomSignature) === atomSignature) {
  20471. size += sizeByAtom[atomIndex];
  20472. }
  20473. atomSignature <<= 1n;
  20474. if (size >= currentAdditionalSize) {
  20475. return Infinity;
  20476. }
  20477. }
  20478. return size;
  20479. }
  20480. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  20481. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  20482. }
  20483. // ported from https://github.com/substack/node-commondir
  20484. function commondir(files) {
  20485. if (files.length === 0)
  20486. return '/';
  20487. if (files.length === 1)
  20488. return path.dirname(files[0]);
  20489. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  20490. const pathSegments = file.split(/\/+|\\+/);
  20491. let index;
  20492. for (index = 0; commonSegments[index] === pathSegments[index] &&
  20493. index < Math.min(commonSegments.length, pathSegments.length); index++)
  20494. ;
  20495. return commonSegments.slice(0, index);
  20496. }, files[0].split(/\/+|\\+/));
  20497. // Windows correctly handles paths with forward-slashes
  20498. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  20499. }
  20500. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  20501. function sortByExecutionOrder(units) {
  20502. units.sort(compareExecIndex);
  20503. }
  20504. // This process is currently faulty in so far as it only takes the first entry
  20505. // module into account and assumes that dynamic imports are imported in a
  20506. // certain order.
  20507. // A better algorithm would follow every possible execution path and mark which
  20508. // modules are executed before or after which other modules. THen the chunking
  20509. // would need to take care that in each chunk, all modules are always executed
  20510. // in the same sequence.
  20511. function analyseModuleExecution(entryModules) {
  20512. let nextExecIndex = 0;
  20513. const cyclePaths = [];
  20514. const analysedModules = new Set();
  20515. const dynamicImports = new Set();
  20516. const parents = new Map();
  20517. const orderedModules = [];
  20518. const handleSyncLoadedModule = (module, parent) => {
  20519. if (parents.has(module)) {
  20520. if (!analysedModules.has(module)) {
  20521. cyclePaths.push(getCyclePath(module, parent, parents));
  20522. }
  20523. return;
  20524. }
  20525. parents.set(module, parent);
  20526. analyseModule(module);
  20527. };
  20528. const analyseModule = (module) => {
  20529. if (module instanceof Module) {
  20530. for (const dependency of module.dependencies) {
  20531. handleSyncLoadedModule(dependency, module);
  20532. }
  20533. for (const dependency of module.implicitlyLoadedBefore) {
  20534. dynamicImports.add(dependency);
  20535. }
  20536. for (const { resolution, node } of module.dynamicImports) {
  20537. if (resolution instanceof Module) {
  20538. if (node.scope.context.usesTopLevelAwait) {
  20539. handleSyncLoadedModule(resolution, module);
  20540. }
  20541. else {
  20542. dynamicImports.add(resolution);
  20543. }
  20544. }
  20545. }
  20546. orderedModules.push(module);
  20547. }
  20548. module.execIndex = nextExecIndex++;
  20549. analysedModules.add(module);
  20550. };
  20551. for (const currentEntry of entryModules) {
  20552. if (!parents.has(currentEntry)) {
  20553. parents.set(currentEntry, null);
  20554. analyseModule(currentEntry);
  20555. }
  20556. }
  20557. for (const currentEntry of dynamicImports) {
  20558. if (!parents.has(currentEntry)) {
  20559. parents.set(currentEntry, null);
  20560. analyseModule(currentEntry);
  20561. }
  20562. }
  20563. return { cyclePaths, orderedModules };
  20564. }
  20565. function getCyclePath(module, parent, parents) {
  20566. const cycleSymbol = Symbol(module.id);
  20567. const path = [module.id];
  20568. let nextModule = parent;
  20569. module.cycles.add(cycleSymbol);
  20570. while (nextModule !== module) {
  20571. nextModule.cycles.add(cycleSymbol);
  20572. path.push(nextModule.id);
  20573. nextModule = parents.get(nextModule);
  20574. }
  20575. path.push(path[0]);
  20576. path.reverse();
  20577. return path;
  20578. }
  20579. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  20580. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  20581. const cnst = constBindings ? 'const' : 'var';
  20582. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  20583. const getFunctionIntro = arrowFunctions
  20584. ? (parameters, { isAsync, name }) => {
  20585. const singleParameter = parameters.length === 1;
  20586. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  20587. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  20588. }
  20589. : getNonArrowFunctionIntro;
  20590. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  20591. `${getFunctionIntro(parameters, {
  20592. isAsync: false,
  20593. name
  20594. })}${arrowFunctions
  20595. ? lineBreakIndent
  20596. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  20597. : ''
  20598. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  20599. arrowFunctions
  20600. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  20601. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  20602. ];
  20603. const isValidPropertyName = reservedNamesAsProps
  20604. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  20605. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  20606. return {
  20607. _,
  20608. cnst,
  20609. getDirectReturnFunction,
  20610. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  20611. const [left, right] = getDirectReturnFunction(parameters, {
  20612. functionReturn: true,
  20613. lineBreakIndent: null,
  20614. name: null
  20615. });
  20616. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  20617. },
  20618. getFunctionIntro,
  20619. getNonArrowFunctionIntro,
  20620. getObject(fields, { lineBreakIndent }) {
  20621. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  20622. return `{${fields
  20623. .map(([key, value]) => {
  20624. if (key === null)
  20625. return `${prefix}${value}`;
  20626. const keyInObject = stringifyObjectKeyIfNeeded(key);
  20627. return key === value && objectShorthand && key === keyInObject
  20628. ? prefix + key
  20629. : `${prefix}${keyInObject}:${_}${value}`;
  20630. })
  20631. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  20632. },
  20633. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  20634. n,
  20635. s
  20636. };
  20637. }
  20638. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  20639. class Source {
  20640. constructor(filename, content) {
  20641. this.isOriginal = true;
  20642. this.filename = filename;
  20643. this.content = content;
  20644. }
  20645. traceSegment(line, column, name) {
  20646. return { column, line, name, source: this };
  20647. }
  20648. }
  20649. class Link {
  20650. constructor(map, sources) {
  20651. this.sources = sources;
  20652. this.names = map.names;
  20653. this.mappings = map.mappings;
  20654. }
  20655. traceMappings() {
  20656. const sources = [];
  20657. const sourceIndexMap = new Map();
  20658. const sourcesContent = [];
  20659. const names = [];
  20660. const nameIndexMap = new Map();
  20661. const mappings = [];
  20662. for (const line of this.mappings) {
  20663. const tracedLine = [];
  20664. for (const segment of line) {
  20665. if (segment.length === 1)
  20666. continue;
  20667. const source = this.sources[segment[1]];
  20668. if (!source)
  20669. continue;
  20670. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  20671. if (traced) {
  20672. const { column, line, name, source: { content, filename } } = traced;
  20673. let sourceIndex = sourceIndexMap.get(filename);
  20674. if (sourceIndex === undefined) {
  20675. sourceIndex = sources.length;
  20676. sources.push(filename);
  20677. sourceIndexMap.set(filename, sourceIndex);
  20678. sourcesContent[sourceIndex] = content;
  20679. }
  20680. else if (sourcesContent[sourceIndex] == null) {
  20681. sourcesContent[sourceIndex] = content;
  20682. }
  20683. else if (content != null && sourcesContent[sourceIndex] !== content) {
  20684. return parseAst_js.error(parseAst_js.logConflictingSourcemapSources(filename));
  20685. }
  20686. const tracedSegment = [segment[0], sourceIndex, line, column];
  20687. if (name) {
  20688. let nameIndex = nameIndexMap.get(name);
  20689. if (nameIndex === undefined) {
  20690. nameIndex = names.length;
  20691. names.push(name);
  20692. nameIndexMap.set(name, nameIndex);
  20693. }
  20694. tracedSegment[4] = nameIndex;
  20695. }
  20696. tracedLine.push(tracedSegment);
  20697. }
  20698. }
  20699. mappings.push(tracedLine);
  20700. }
  20701. return { mappings, names, sources, sourcesContent };
  20702. }
  20703. traceSegment(line, column, name) {
  20704. const segments = this.mappings[line];
  20705. if (!segments)
  20706. return null;
  20707. // binary search through segments for the given column
  20708. let searchStart = 0;
  20709. const lastSegmentIndex = segments.length - 1;
  20710. let searchEnd = lastSegmentIndex;
  20711. while (searchStart <= searchEnd) {
  20712. const m = (searchStart + searchEnd) >> 1;
  20713. let segment = segments[m];
  20714. // If a sourcemap does not have sufficient resolution to contain a
  20715. // necessary mapping, e.g. because it only contains line information or
  20716. // 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),
  20717. // we approximate by finding the closest segment whose segment[0] is less than the given column
  20718. if (segment[0] !== column && searchStart === searchEnd) {
  20719. const approximatedSegmentIndex = segments[searchStart][0] > column ? Math.max(0, searchStart - 1) : searchStart;
  20720. segment = segments[approximatedSegmentIndex];
  20721. }
  20722. if (segment[0] === column || searchStart === searchEnd) {
  20723. if (segment.length == 1)
  20724. return null;
  20725. const source = this.sources[segment[1]];
  20726. if (!source)
  20727. return null;
  20728. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  20729. }
  20730. if (segment[0] > column) {
  20731. searchEnd = m - 1;
  20732. }
  20733. else {
  20734. searchStart = m + 1;
  20735. }
  20736. }
  20737. return null;
  20738. }
  20739. }
  20740. function getLinkMap(log) {
  20741. return function linkMap(source, map) {
  20742. if (!map.missing) {
  20743. return new Link(map, [source]);
  20744. }
  20745. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logSourcemapBroken(map.plugin));
  20746. return new Link({
  20747. mappings: [],
  20748. names: []
  20749. }, [source]);
  20750. };
  20751. }
  20752. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  20753. let source;
  20754. if (originalSourcemap) {
  20755. const sources = originalSourcemap.sources;
  20756. const sourcesContent = originalSourcemap.sourcesContent || [];
  20757. const directory = path.dirname(id) || '.';
  20758. const sourceRoot = originalSourcemap.sourceRoot || '.';
  20759. const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  20760. source = new Link(originalSourcemap, baseSources);
  20761. }
  20762. else {
  20763. source = new Source(id, originalCode);
  20764. }
  20765. return sourcemapChain.reduce(linkMap, source);
  20766. }
  20767. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  20768. const linkMap = getLinkMap(log);
  20769. const moduleSources = modules
  20770. .filter(module => !module.excludeFromSourcemap)
  20771. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  20772. const link = new Link(map, moduleSources);
  20773. const source = bundleSourcemapChain.reduce(linkMap, link);
  20774. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  20775. if (file) {
  20776. const directory = path.dirname(file);
  20777. sources = sources.map((source) => path.relative(directory, source));
  20778. file = path.basename(file);
  20779. }
  20780. sourcesContent = (excludeContent ? null : sourcesContent);
  20781. for (const module of modules) {
  20782. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  20783. }
  20784. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  20785. }
  20786. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  20787. if (sourcemapChain.length === 0) {
  20788. return originalSourcemap;
  20789. }
  20790. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  20791. const map = source.traceMappings();
  20792. return decodedSourcemap({ version: 3, ...map });
  20793. }
  20794. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  20795. // this for an actual sourceMappingURL
  20796. let SOURCEMAPPING_URL = 'sourceMa';
  20797. SOURCEMAPPING_URL += 'ppingURL';
  20798. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  20799. timeStart('render chunks', 2);
  20800. reserveEntryChunksInBundle(chunks);
  20801. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  20802. timeEnd('render chunks', 2);
  20803. timeStart('transform chunks', 2);
  20804. const getHash = hasherByType[outputOptions.hashCharacters];
  20805. const chunkGraph = getChunkGraph(chunks);
  20806. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  20807. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  20808. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  20809. timeEnd('transform chunks', 2);
  20810. }
  20811. function reserveEntryChunksInBundle(chunks) {
  20812. for (const chunk of chunks) {
  20813. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  20814. // reserves name in bundle as side effect if it does not contain a hash
  20815. chunk.getPreliminaryFileName();
  20816. }
  20817. }
  20818. }
  20819. function getChunkGraph(chunks) {
  20820. return Object.fromEntries(chunks.map(chunk => {
  20821. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  20822. return [renderedChunkInfo.fileName, renderedChunkInfo];
  20823. }));
  20824. }
  20825. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  20826. let map = null;
  20827. const sourcemapChain = [];
  20828. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  20829. if (result == null)
  20830. return code;
  20831. if (typeof result === 'string')
  20832. result = {
  20833. code: result,
  20834. map: undefined
  20835. };
  20836. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  20837. if (result.map !== null) {
  20838. const map = decodedSourcemap(result.map);
  20839. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  20840. }
  20841. return result.code;
  20842. });
  20843. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  20844. if (!compact && code[code.length - 1] !== '\n')
  20845. code += '\n';
  20846. if (sourcemap) {
  20847. timeStart('sourcemaps', 3);
  20848. let resultingFile;
  20849. if (file)
  20850. resultingFile = path.resolve(sourcemapFile || file);
  20851. else if (dir)
  20852. resultingFile = path.resolve(dir, fileName);
  20853. else
  20854. resultingFile = path.resolve(fileName);
  20855. const decodedMap = magicString.generateDecodedMap({});
  20856. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  20857. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  20858. let sourcePath = map.sources[sourcesIndex];
  20859. const sourcemapPath = `${resultingFile}.map`;
  20860. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  20861. if (typeof ignoreList !== 'boolean') {
  20862. parseAst_js.error(parseAst_js.logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  20863. }
  20864. if (ignoreList) {
  20865. if (map.x_google_ignoreList === undefined) {
  20866. map.x_google_ignoreList = [];
  20867. }
  20868. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  20869. map.x_google_ignoreList.push(sourcesIndex);
  20870. }
  20871. }
  20872. if (sourcemapPathTransform) {
  20873. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  20874. if (typeof sourcePath !== 'string') {
  20875. parseAst_js.error(parseAst_js.logFailedValidation(`sourcemapPathTransform function must return a string.`));
  20876. }
  20877. }
  20878. map.sources[sourcesIndex] = parseAst_js.normalize(sourcePath);
  20879. }
  20880. timeEnd('sourcemaps', 3);
  20881. }
  20882. return {
  20883. code,
  20884. map
  20885. };
  20886. }
  20887. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  20888. const nonHashedChunksWithPlaceholders = [];
  20889. const renderedChunksByPlaceholder = new Map();
  20890. const hashDependenciesByPlaceholder = new Map();
  20891. const initialHashesByPlaceholder = new Map();
  20892. const placeholders = new Set();
  20893. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  20894. if (hashPlaceholder)
  20895. placeholders.add(hashPlaceholder);
  20896. }
  20897. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  20898. const transformedChunk = {
  20899. chunk,
  20900. fileName,
  20901. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  20902. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  20903. };
  20904. const { code, map } = transformedChunk;
  20905. if (hashPlaceholder) {
  20906. // To create a reproducible content-only hash, all placeholders are
  20907. // replaced with the same value before hashing
  20908. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  20909. let contentToHash = transformedCode;
  20910. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  20911. if (pluginHash) {
  20912. augmentation += pluginHash;
  20913. }
  20914. return augmentation;
  20915. });
  20916. if (hashAugmentation) {
  20917. contentToHash += hashAugmentation;
  20918. }
  20919. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  20920. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  20921. containedPlaceholders,
  20922. contentHash: getHash(contentToHash)
  20923. });
  20924. }
  20925. else {
  20926. nonHashedChunksWithPlaceholders.push(transformedChunk);
  20927. }
  20928. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  20929. if (map && sourcemapHashPlaceholder) {
  20930. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  20931. }
  20932. }));
  20933. return {
  20934. hashDependenciesByPlaceholder,
  20935. initialHashesByPlaceholder,
  20936. nonHashedChunksWithPlaceholders,
  20937. placeholders,
  20938. renderedChunksByPlaceholder
  20939. };
  20940. }
  20941. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  20942. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  20943. for (const placeholder of placeholders) {
  20944. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  20945. let contentToHash = '';
  20946. const hashDependencyPlaceholders = new Set([placeholder]);
  20947. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  20948. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  20949. contentToHash += contentHash;
  20950. for (const containedPlaceholder of containedPlaceholders) {
  20951. // When looping over a map, setting an entry only causes a new iteration if the key is new
  20952. hashDependencyPlaceholders.add(containedPlaceholder);
  20953. }
  20954. }
  20955. let finalFileName;
  20956. let finalHash;
  20957. do {
  20958. // In case of a hash collision, create a hash of the hash
  20959. if (finalHash) {
  20960. contentToHash = finalHash;
  20961. }
  20962. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  20963. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  20964. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  20965. bundle[finalFileName] = FILE_PLACEHOLDER;
  20966. hashesByPlaceholder.set(placeholder, finalHash);
  20967. }
  20968. return hashesByPlaceholder;
  20969. }
  20970. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  20971. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  20972. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  20973. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  20974. let finalSourcemapFileName = null;
  20975. if (map) {
  20976. if (options.sourcemapDebugIds) {
  20977. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20978. }
  20979. finalSourcemapFileName = sourcemapFileName
  20980. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20981. : `${finalFileName}.map`;
  20982. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  20983. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20984. }
  20985. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  20986. }
  20987. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  20988. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  20989. let finalSourcemapFileName = null;
  20990. if (map) {
  20991. if (options.sourcemapDebugIds) {
  20992. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20993. }
  20994. finalSourcemapFileName = sourcemapFileName
  20995. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20996. : `${fileName}.map`;
  20997. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20998. }
  20999. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  21000. }
  21001. }
  21002. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  21003. let url;
  21004. if (sourcemap === 'inline') {
  21005. url = map.toUrl();
  21006. }
  21007. else {
  21008. const sourcemapFileName = path.basename(fileName);
  21009. url = sourcemapBaseUrl
  21010. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  21011. : sourcemapFileName;
  21012. pluginDriver.emitFile({
  21013. fileName,
  21014. originalFileName: null,
  21015. source: map.toString(),
  21016. type: 'asset'
  21017. });
  21018. }
  21019. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  21020. }
  21021. function calculateDebugIdAndGetComment(code, map) {
  21022. const hash = hasherByType.hex(code);
  21023. const debugId = [
  21024. hash.slice(0, 8),
  21025. hash.slice(8, 12),
  21026. '4' + hash.slice(12, 15),
  21027. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  21028. hash.slice(20, 32)
  21029. ].join('-');
  21030. map.debugId = debugId;
  21031. return '//# debugId=' + debugId + '\n';
  21032. }
  21033. class Bundle {
  21034. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  21035. this.outputOptions = outputOptions;
  21036. this.unsetOptions = unsetOptions;
  21037. this.inputOptions = inputOptions;
  21038. this.pluginDriver = pluginDriver;
  21039. this.graph = graph;
  21040. this.facadeChunkByModule = new Map();
  21041. this.includedNamespaces = new Set();
  21042. }
  21043. async generate(isWrite) {
  21044. timeStart('GENERATE', 1);
  21045. const outputBundleBase = Object.create(null);
  21046. const outputBundle = getOutputBundle(outputBundleBase);
  21047. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  21048. try {
  21049. timeStart('initialize render', 2);
  21050. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  21051. timeEnd('initialize render', 2);
  21052. timeStart('generate chunks', 2);
  21053. const getHashPlaceholder = getHashPlaceholderGenerator();
  21054. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  21055. if (chunks.length > 1) {
  21056. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  21057. }
  21058. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  21059. for (const chunk of chunks) {
  21060. chunk.generateExports();
  21061. chunk.inlineTransitiveImports();
  21062. }
  21063. timeEnd('generate chunks', 2);
  21064. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  21065. }
  21066. catch (error_) {
  21067. await this.pluginDriver.hookParallel('renderError', [error_]);
  21068. throw error_;
  21069. }
  21070. removeUnreferencedAssets(outputBundle);
  21071. timeStart('generate bundle', 2);
  21072. await this.pluginDriver.hookSeq('generateBundle', [
  21073. this.outputOptions,
  21074. outputBundle,
  21075. isWrite
  21076. ]);
  21077. this.finaliseAssets(outputBundle);
  21078. timeEnd('generate bundle', 2);
  21079. timeEnd('GENERATE', 1);
  21080. return outputBundleBase;
  21081. }
  21082. async addManualChunks(manualChunks) {
  21083. const manualChunkAliasByEntry = new Map();
  21084. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  21085. alias,
  21086. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  21087. })));
  21088. for (const { alias, entries } of chunkEntries) {
  21089. for (const entry of entries) {
  21090. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  21091. }
  21092. }
  21093. return manualChunkAliasByEntry;
  21094. }
  21095. assignManualChunks(getManualChunk) {
  21096. const manualChunkAliasesWithEntry = [];
  21097. const manualChunksApi = {
  21098. getModuleIds: () => this.graph.modulesById.keys(),
  21099. getModuleInfo: this.graph.getModuleInfo
  21100. };
  21101. for (const module of this.graph.modulesById.values()) {
  21102. if (module instanceof Module) {
  21103. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  21104. if (typeof manualChunkAlias === 'string') {
  21105. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  21106. }
  21107. }
  21108. }
  21109. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  21110. const manualChunkAliasByEntry = new Map();
  21111. for (const [alias, module] of manualChunkAliasesWithEntry) {
  21112. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  21113. }
  21114. return manualChunkAliasByEntry;
  21115. }
  21116. finaliseAssets(bundle) {
  21117. if (this.outputOptions.validate) {
  21118. for (const file of Object.values(bundle)) {
  21119. if ('code' in file) {
  21120. try {
  21121. parseAst_js.parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  21122. }
  21123. catch (error_) {
  21124. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logChunkInvalid(file, error_));
  21125. }
  21126. }
  21127. }
  21128. }
  21129. this.pluginDriver.finaliseAssets();
  21130. }
  21131. async generateChunks(bundle, getHashPlaceholder) {
  21132. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules, onlyExplicitManualChunks } = this.outputOptions;
  21133. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  21134. ? await this.addManualChunks(manualChunks)
  21135. : this.assignManualChunks(manualChunks);
  21136. const snippets = getGenerateCodeSnippets(this.outputOptions);
  21137. const includedModules = getIncludedModules(this.graph.modulesById);
  21138. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  21139. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  21140. const executableModule = inlineDynamicImports
  21141. ? [{ alias: null, modules: includedModules }]
  21142. : preserveModules
  21143. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  21144. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, typeof manualChunks === 'function', onlyExplicitManualChunks);
  21145. const chunks = new Array(executableModule.length);
  21146. const chunkByModule = new Map();
  21147. let index = 0;
  21148. for (const { alias, modules } of executableModule) {
  21149. sortByExecutionOrder(modules);
  21150. 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);
  21151. chunks[index++] = chunk;
  21152. }
  21153. for (const chunk of chunks) {
  21154. chunk.link();
  21155. }
  21156. const facades = [];
  21157. for (const chunk of chunks) {
  21158. facades.push(...chunk.generateFacades());
  21159. }
  21160. return [...chunks, ...facades];
  21161. }
  21162. }
  21163. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  21164. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  21165. 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));
  21166. if (typeof outputOptions.file === 'string')
  21167. 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'));
  21168. if (outputOptions.sourcemapFile)
  21169. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapFile', parseAst_js.URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  21170. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  21171. 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'));
  21172. }
  21173. function getIncludedModules(modulesById) {
  21174. const includedModules = [];
  21175. for (const module of modulesById.values()) {
  21176. if (module instanceof Module &&
  21177. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  21178. includedModules.push(module);
  21179. }
  21180. }
  21181. return includedModules;
  21182. }
  21183. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  21184. const absoluteEntryModulePaths = [];
  21185. for (const module of includedModules) {
  21186. if ((module.info.isEntry || preserveModules) && parseAst_js.isAbsolute(module.id)) {
  21187. absoluteEntryModulePaths.push(module.id);
  21188. }
  21189. }
  21190. return absoluteEntryModulePaths;
  21191. }
  21192. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  21193. const externalChunkByModule = new Map();
  21194. for (const module of modulesById.values()) {
  21195. if (module instanceof ExternalModule) {
  21196. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  21197. }
  21198. }
  21199. return externalChunkByModule;
  21200. }
  21201. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  21202. const existingAlias = manualChunkAliasByEntry.get(module);
  21203. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  21204. return parseAst_js.error(parseAst_js.logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  21205. }
  21206. manualChunkAliasByEntry.set(module, alias);
  21207. }
  21208. function flru (max) {
  21209. var num, curr, prev;
  21210. var limit = max;
  21211. function keep(key, value) {
  21212. if (++num > limit) {
  21213. prev = curr;
  21214. reset(1);
  21215. ++num;
  21216. }
  21217. curr[key] = value;
  21218. }
  21219. function reset(isPartial) {
  21220. num = 0;
  21221. curr = Object.create(null);
  21222. isPartial || (prev=Object.create(null));
  21223. }
  21224. reset();
  21225. return {
  21226. clear: reset,
  21227. has: function (key) {
  21228. return curr[key] !== void 0 || prev[key] !== void 0;
  21229. },
  21230. get: function (key) {
  21231. var val = curr[key];
  21232. if (val !== void 0) return val;
  21233. if ((val=prev[key]) !== void 0) {
  21234. keep(key, val);
  21235. return val;
  21236. }
  21237. },
  21238. set: function (key, value) {
  21239. if (curr[key] !== void 0) {
  21240. curr[key] = value;
  21241. } else {
  21242. keep(key, value);
  21243. }
  21244. }
  21245. };
  21246. }
  21247. class GlobalScope extends Scope {
  21248. constructor() {
  21249. super();
  21250. this.parent = null;
  21251. this.variables.set('undefined', new UndefinedVariable());
  21252. }
  21253. findVariable(name) {
  21254. let variable = this.variables.get(name);
  21255. if (!variable) {
  21256. variable = new GlobalVariable(name);
  21257. this.variables.set(name, variable);
  21258. }
  21259. return variable;
  21260. }
  21261. }
  21262. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  21263. let skipped = null;
  21264. let replaceContext = null;
  21265. if (skip) {
  21266. skipped = new Set();
  21267. for (const skippedCall of skip) {
  21268. if (source === skippedCall.source && importer === skippedCall.importer) {
  21269. skipped.add(skippedCall.plugin);
  21270. }
  21271. }
  21272. replaceContext = (pluginContext, plugin) => ({
  21273. ...pluginContext,
  21274. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) => {
  21275. skipSelf ??= true;
  21276. if (skipSelf &&
  21277. skip.findIndex(skippedCall => {
  21278. return (skippedCall.plugin === plugin &&
  21279. skippedCall.source === source &&
  21280. skippedCall.importer === importer);
  21281. }) !== -1) {
  21282. // This means that the plugin recursively called itself
  21283. // Thus returning Promise.resolve(null) in purpose of fallback to default behavior of `resolveId` plugin hook.
  21284. return Promise.resolve(null);
  21285. }
  21286. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  21287. }
  21288. });
  21289. }
  21290. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  21291. }
  21292. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, fs) {
  21293. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  21294. if (pluginResult != null) {
  21295. const [resolveIdResult, plugin] = pluginResult;
  21296. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  21297. return {
  21298. ...resolveIdResult,
  21299. resolvedBy: plugin.name
  21300. };
  21301. }
  21302. if (typeof resolveIdResult === 'string') {
  21303. return {
  21304. id: resolveIdResult,
  21305. resolvedBy: plugin.name
  21306. };
  21307. }
  21308. return resolveIdResult;
  21309. }
  21310. // external modules (non-entry modules that start with neither '.' or '/')
  21311. // are skipped at this stage.
  21312. if (importer !== undefined && !parseAst_js.isAbsolute(source) && source[0] !== '.')
  21313. return null;
  21314. // `resolve` processes paths from right to left, prepending them until an
  21315. // absolute path is created. Absolute importees therefore shortcircuit the
  21316. // resolve call and require no special handing on our part.
  21317. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  21318. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks, fs);
  21319. }
  21320. async function addJsExtensionIfNecessary(file, preserveSymlinks, fs) {
  21321. return ((await findFile(file, preserveSymlinks, fs)) ??
  21322. (await findFile(file + '.mjs', preserveSymlinks, fs)) ??
  21323. (await findFile(file + '.js', preserveSymlinks, fs)));
  21324. }
  21325. async function findFile(file, preserveSymlinks, fs) {
  21326. try {
  21327. const stats = await fs.lstat(file);
  21328. if (!preserveSymlinks && stats.isSymbolicLink())
  21329. return await findFile(await fs.realpath(file), preserveSymlinks, fs);
  21330. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  21331. // check case
  21332. const name = path.basename(file);
  21333. const files = await fs.readdir(path.dirname(file));
  21334. if (files.includes(name))
  21335. return file;
  21336. }
  21337. }
  21338. catch {
  21339. // suppress
  21340. }
  21341. }
  21342. function stripBom(content) {
  21343. if (content.charCodeAt(0) === 0xfe_ff) {
  21344. return stripBom(content.slice(1));
  21345. }
  21346. return content;
  21347. }
  21348. async function transform(source, module, pluginDriver, log) {
  21349. const id = module.id;
  21350. const sourcemapChain = [];
  21351. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  21352. const originalCode = source.code;
  21353. let ast = source.ast;
  21354. const transformDependencies = [];
  21355. const emittedFiles = [];
  21356. let customTransformCache = false;
  21357. const useCustomTransformCache = () => (customTransformCache = true);
  21358. let pluginName = '';
  21359. let currentSource = source.code;
  21360. function transformReducer(previousCode, result, plugin) {
  21361. let code;
  21362. let map;
  21363. if (typeof result === 'string') {
  21364. code = result;
  21365. }
  21366. else if (result && typeof result === 'object') {
  21367. module.updateOptions(result);
  21368. if (result.code == null) {
  21369. if (result.map || result.ast) {
  21370. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNoTransformMapOrAstWithoutCode(plugin.name));
  21371. }
  21372. return previousCode;
  21373. }
  21374. ({ code, map, ast } = result);
  21375. }
  21376. else {
  21377. return previousCode;
  21378. }
  21379. // strict null check allows 'null' maps to not be pushed to the chain,
  21380. // while 'undefined' gets the missing map warning
  21381. if (map !== null) {
  21382. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  21383. missing: true,
  21384. plugin: plugin.name
  21385. });
  21386. }
  21387. currentSource = code;
  21388. return code;
  21389. }
  21390. const getLogHandler = (handler) => (log, pos) => {
  21391. log = normalizeLog(log);
  21392. if (pos)
  21393. parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
  21394. log.id = id;
  21395. log.hook = 'transform';
  21396. handler(log);
  21397. };
  21398. let code;
  21399. try {
  21400. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  21401. pluginName = plugin.name;
  21402. return {
  21403. ...pluginContext,
  21404. addWatchFile(id) {
  21405. transformDependencies.push(id);
  21406. pluginContext.addWatchFile(id);
  21407. },
  21408. cache: customTransformCache
  21409. ? pluginContext.cache
  21410. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  21411. debug: getLogHandler(pluginContext.debug),
  21412. emitFile(emittedFile) {
  21413. emittedFiles.push(emittedFile);
  21414. return pluginDriver.emitFile(emittedFile);
  21415. },
  21416. error(error_, pos) {
  21417. if (typeof error_ === 'string')
  21418. error_ = { message: error_ };
  21419. if (pos)
  21420. parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
  21421. error_.id = id;
  21422. error_.hook = 'transform';
  21423. return pluginContext.error(error_);
  21424. },
  21425. getCombinedSourcemap() {
  21426. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  21427. if (!combinedMap) {
  21428. const magicString = new MagicString(originalCode);
  21429. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  21430. }
  21431. if (originalSourcemap !== combinedMap) {
  21432. originalSourcemap = combinedMap;
  21433. sourcemapChain.length = 0;
  21434. }
  21435. return new SourceMap({
  21436. ...combinedMap,
  21437. file: null,
  21438. sourcesContent: combinedMap.sourcesContent
  21439. });
  21440. },
  21441. info: getLogHandler(pluginContext.info),
  21442. setAssetSource() {
  21443. return this.error(parseAst_js.logInvalidSetAssetSourceCall());
  21444. },
  21445. warn: getLogHandler(pluginContext.warn)
  21446. };
  21447. });
  21448. }
  21449. catch (error_) {
  21450. return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
  21451. }
  21452. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  21453. emittedFiles.length > 0)
  21454. module.transformFiles = emittedFiles;
  21455. return {
  21456. ast,
  21457. code,
  21458. customTransformCache,
  21459. originalCode,
  21460. originalSourcemap,
  21461. sourcemapChain,
  21462. transformDependencies
  21463. };
  21464. }
  21465. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  21466. class ModuleLoader {
  21467. constructor(graph, modulesById, options, pluginDriver) {
  21468. this.graph = graph;
  21469. this.modulesById = modulesById;
  21470. this.options = options;
  21471. this.pluginDriver = pluginDriver;
  21472. this.implicitEntryModules = new Set();
  21473. this.indexedEntryModules = [];
  21474. this.latestLoadModulesPromise = Promise.resolve();
  21475. this.moduleLoadPromises = new Map();
  21476. this.modulesWithLoadedDependencies = new Set();
  21477. this.nextChunkNamePriority = 0;
  21478. this.nextEntryModuleIndex = 0;
  21479. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  21480. ? false
  21481. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, this.options.fs), importer, source), attributes);
  21482. this.hasModuleSideEffects = options.treeshake
  21483. ? options.treeshake.moduleSideEffects
  21484. : () => true;
  21485. }
  21486. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  21487. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  21488. await this.awaitLoadModulesPromise();
  21489. return result;
  21490. }
  21491. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  21492. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  21493. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  21494. const firstChunkNamePriority = this.nextChunkNamePriority;
  21495. this.nextChunkNamePriority += unresolvedEntryModules.length;
  21496. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  21497. for (const [index, entryModule] of entryModules.entries()) {
  21498. entryModule.isUserDefinedEntryPoint =
  21499. entryModule.isUserDefinedEntryPoint || isUserDefined;
  21500. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  21501. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  21502. if (existingIndexedModule) {
  21503. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  21504. }
  21505. else {
  21506. this.indexedEntryModules.push({
  21507. index: firstEntryModuleIndex + index,
  21508. module: entryModule
  21509. });
  21510. }
  21511. }
  21512. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  21513. return entryModules;
  21514. }));
  21515. await this.awaitLoadModulesPromise();
  21516. return {
  21517. entryModules: this.indexedEntryModules.map(({ module }) => module),
  21518. implicitEntryModules: [...this.implicitEntryModules],
  21519. newEntryModules
  21520. };
  21521. }
  21522. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  21523. const unresolvedModule = {
  21524. fileName: fileName || null,
  21525. id,
  21526. importer,
  21527. name: name || null
  21528. };
  21529. const module = implicitlyLoadedAfterOneOf
  21530. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  21531. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  21532. if (preserveSignature != null) {
  21533. module.preserveSignature = preserveSignature;
  21534. }
  21535. return module;
  21536. }
  21537. async preloadModule(resolvedId) {
  21538. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  21539. return module.info;
  21540. }
  21541. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  21542. const chunkNamePriority = this.nextChunkNamePriority++;
  21543. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  21544. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  21545. if (!entryModule.info.isEntry) {
  21546. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  21547. // We need to check again if this is still an entry module as these
  21548. // changes need to be performed atomically to avoid race conditions
  21549. // if the same module is re-emitted as an entry module.
  21550. // The inverse changes happen in "handleExistingModule"
  21551. if (!entryModule.info.isEntry) {
  21552. this.implicitEntryModules.add(entryModule);
  21553. for (const module of implicitlyLoadedAfterModules) {
  21554. entryModule.implicitlyLoadedAfter.add(module);
  21555. }
  21556. for (const dependant of entryModule.implicitlyLoadedAfter) {
  21557. dependant.implicitlyLoadedBefore.add(entryModule);
  21558. }
  21559. }
  21560. }
  21561. return entryModule;
  21562. }));
  21563. }
  21564. async addModuleSource(id, importer, module) {
  21565. let source;
  21566. try {
  21567. source = await this.graph.fileOperationQueue.run(async () => {
  21568. const content = await this.pluginDriver.hookFirst('load', [id]);
  21569. if (content !== null)
  21570. return content;
  21571. this.graph.watchFiles[id] = true;
  21572. return (await this.options.fs.readFile(id, { encoding: 'utf8' }));
  21573. });
  21574. }
  21575. catch (error_) {
  21576. let message = `Could not load ${id}`;
  21577. if (importer)
  21578. message += ` (imported by ${parseAst_js.relativeId(importer)})`;
  21579. message += `: ${error_.message}`;
  21580. error_.message = message;
  21581. throw error_;
  21582. }
  21583. const sourceDescription = typeof source === 'string'
  21584. ? { code: source }
  21585. : source != null && typeof source === 'object' && typeof source.code === 'string'
  21586. ? source
  21587. : parseAst_js.error(parseAst_js.logBadLoader(id));
  21588. sourceDescription.code = stripBom(sourceDescription.code);
  21589. const cachedModule = this.graph.cachedModules.get(id);
  21590. if (cachedModule &&
  21591. !cachedModule.customTransformCache &&
  21592. cachedModule.originalCode === sourceDescription.code &&
  21593. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  21594. {
  21595. ast: cachedModule.ast,
  21596. code: cachedModule.code,
  21597. id: cachedModule.id,
  21598. meta: cachedModule.meta,
  21599. moduleSideEffects: cachedModule.moduleSideEffects,
  21600. resolvedSources: cachedModule.resolvedIds,
  21601. syntheticNamedExports: cachedModule.syntheticNamedExports
  21602. }
  21603. ]))) {
  21604. if (cachedModule.transformFiles) {
  21605. for (const emittedFile of cachedModule.transformFiles)
  21606. this.pluginDriver.emitFile(emittedFile);
  21607. }
  21608. await module.setSource(cachedModule);
  21609. }
  21610. else {
  21611. module.updateOptions(sourceDescription);
  21612. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  21613. }
  21614. }
  21615. async awaitLoadModulesPromise() {
  21616. let startingPromise;
  21617. do {
  21618. startingPromise = this.latestLoadModulesPromise;
  21619. await startingPromise;
  21620. } while (startingPromise !== this.latestLoadModulesPromise);
  21621. }
  21622. extendLoadModulesPromise(loadNewModulesPromise) {
  21623. this.latestLoadModulesPromise = Promise.all([
  21624. loadNewModulesPromise,
  21625. this.latestLoadModulesPromise
  21626. ]);
  21627. this.latestLoadModulesPromise.catch(() => {
  21628. /* Avoid unhandled Promise rejections */
  21629. });
  21630. return loadNewModulesPromise;
  21631. }
  21632. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  21633. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  21634. if (resolvedId === null)
  21635. return null;
  21636. if (typeof resolvedId === 'string') {
  21637. dynamicImport.resolution = resolvedId;
  21638. return null;
  21639. }
  21640. return (dynamicImport.resolution = await this.fetchResolvedDependency(parseAst_js.relativeId(resolvedId.id), module.id, resolvedId));
  21641. })));
  21642. for (const dependency of dependencies) {
  21643. if (dependency) {
  21644. module.dynamicDependencies.add(dependency);
  21645. dependency.dynamicImporters.push(module.id);
  21646. }
  21647. }
  21648. }
  21649. // If this is a preload, then this method always waits for the dependencies of
  21650. // the module to be resolved.
  21651. // Otherwise, if the module does not exist, it waits for the module and all
  21652. // its dependencies to be loaded.
  21653. // Otherwise, it returns immediately.
  21654. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  21655. const existingModule = this.modulesById.get(id);
  21656. if (existingModule instanceof Module) {
  21657. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  21658. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  21659. }
  21660. await this.handleExistingModule(existingModule, isEntry, isPreload);
  21661. return existingModule;
  21662. }
  21663. if (existingModule instanceof ExternalModule) {
  21664. return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
  21665. }
  21666. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  21667. this.modulesById.set(id, module);
  21668. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  21669. this.getResolveStaticDependencyPromises(module),
  21670. this.getResolveDynamicImportPromises(module),
  21671. loadAndResolveDependenciesPromise
  21672. ]);
  21673. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  21674. loadAndResolveDependenciesPromise.catch(() => {
  21675. /* avoid unhandled promise rejections */
  21676. });
  21677. this.moduleLoadPromises.set(module, loadPromise);
  21678. const resolveDependencyPromises = await loadPromise;
  21679. if (!isPreload) {
  21680. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  21681. }
  21682. else if (isPreload === RESOLVE_DEPENDENCIES) {
  21683. await loadAndResolveDependenciesPromise;
  21684. }
  21685. return module;
  21686. }
  21687. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  21688. if (this.modulesWithLoadedDependencies.has(module)) {
  21689. return;
  21690. }
  21691. this.modulesWithLoadedDependencies.add(module);
  21692. await Promise.all([
  21693. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  21694. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  21695. ]);
  21696. module.linkImports();
  21697. // To handle errors when resolving dependencies or in moduleParsed
  21698. await loadAndResolveDependenciesPromise;
  21699. }
  21700. fetchResolvedDependency(source, importer, resolvedId) {
  21701. if (resolvedId.external) {
  21702. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  21703. let externalModule = this.modulesById.get(id);
  21704. if (!externalModule) {
  21705. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
  21706. this.modulesById.set(id, externalModule);
  21707. }
  21708. else if (!(externalModule instanceof ExternalModule)) {
  21709. return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
  21710. }
  21711. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  21712. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  21713. }
  21714. return Promise.resolve(externalModule);
  21715. }
  21716. return this.fetchModule(resolvedId, importer, false, false);
  21717. }
  21718. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  21719. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  21720. module.dependencies.add(dependency);
  21721. dependency.importers.push(module.id);
  21722. }
  21723. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  21724. for (const dependency of module.dependencies) {
  21725. if (dependency instanceof Module) {
  21726. dependency.importedFromNotTreeshaken = true;
  21727. }
  21728. }
  21729. }
  21730. }
  21731. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  21732. const { makeAbsoluteExternalsRelative } = this.options;
  21733. if (resolveIdResult) {
  21734. if (typeof resolveIdResult === 'object') {
  21735. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  21736. return {
  21737. ...resolveIdResult,
  21738. external: external &&
  21739. (external === 'relative' ||
  21740. !parseAst_js.isAbsolute(resolveIdResult.id) ||
  21741. (external === true &&
  21742. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  21743. 'absolute')
  21744. };
  21745. }
  21746. const external = this.options.external(resolveIdResult, importer, true);
  21747. return {
  21748. external: external &&
  21749. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  21750. 'absolute'),
  21751. id: external && makeAbsoluteExternalsRelative
  21752. ? normalizeRelativeExternalId(resolveIdResult, importer)
  21753. : resolveIdResult
  21754. };
  21755. }
  21756. const id = makeAbsoluteExternalsRelative
  21757. ? normalizeRelativeExternalId(source, importer)
  21758. : source;
  21759. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  21760. return null;
  21761. }
  21762. return {
  21763. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  21764. id
  21765. };
  21766. }
  21767. getResolveDynamicImportPromises(module) {
  21768. return module.dynamicImports.map(async (dynamicImport) => {
  21769. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  21770. if (!resolvedId || typeof resolvedId === 'string') {
  21771. dynamicImport.node.shouldIncludeDynamicAttributes = true;
  21772. }
  21773. else {
  21774. dynamicImport.node.shouldIncludeDynamicAttributes = !!resolvedId.external;
  21775. dynamicImport.id = resolvedId.id;
  21776. }
  21777. return [dynamicImport, resolvedId];
  21778. });
  21779. }
  21780. getResolveStaticDependencyPromises(module) {
  21781. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  21782. source,
  21783. (module.resolvedIds[source] =
  21784. module.resolvedIds[source] ||
  21785. this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  21786. ]);
  21787. }
  21788. getResolvedIdWithDefaults(resolvedId, attributes) {
  21789. if (!resolvedId) {
  21790. return null;
  21791. }
  21792. const external = resolvedId.external || false;
  21793. return {
  21794. attributes: resolvedId.attributes || attributes,
  21795. external,
  21796. id: resolvedId.id,
  21797. meta: resolvedId.meta || {},
  21798. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  21799. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  21800. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  21801. };
  21802. }
  21803. async handleExistingModule(module, isEntry, isPreload) {
  21804. const loadPromise = this.moduleLoadPromises.get(module);
  21805. if (isPreload) {
  21806. return isPreload === RESOLVE_DEPENDENCIES
  21807. ? waitForDependencyResolution(loadPromise)
  21808. : loadPromise;
  21809. }
  21810. if (isEntry) {
  21811. // This reverts the changes in addEntryWithImplicitDependants and needs to
  21812. // be performed atomically
  21813. module.info.isEntry = true;
  21814. this.implicitEntryModules.delete(module);
  21815. for (const dependant of module.implicitlyLoadedAfter) {
  21816. dependant.implicitlyLoadedBefore.delete(module);
  21817. }
  21818. module.implicitlyLoadedAfter.clear();
  21819. }
  21820. return this.fetchModuleDependencies(module, ...(await loadPromise));
  21821. }
  21822. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  21823. if (resolvedId === null) {
  21824. if (parseAst_js.isRelative(source)) {
  21825. return parseAst_js.error(parseAst_js.logUnresolvedImport(source, importer));
  21826. }
  21827. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnresolvedImportTreatedAsExternal(source, importer));
  21828. return {
  21829. attributes,
  21830. external: true,
  21831. id: source,
  21832. meta: {},
  21833. moduleSideEffects: this.hasModuleSideEffects(source, true),
  21834. resolvedBy: 'rollup',
  21835. syntheticNamedExports: false
  21836. };
  21837. }
  21838. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  21839. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logExternalSyntheticExports(source, importer));
  21840. }
  21841. return resolvedId;
  21842. }
  21843. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  21844. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT, this.options.fs);
  21845. if (resolveIdResult == null) {
  21846. return parseAst_js.error(implicitlyLoadedBefore === null
  21847. ? parseAst_js.logUnresolvedEntry(unresolvedId)
  21848. : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  21849. }
  21850. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  21851. if (resolveIdResult === false || isExternalModules) {
  21852. return parseAst_js.error(implicitlyLoadedBefore === null
  21853. ? isExternalModules && isLoadForManualChunks
  21854. ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  21855. : parseAst_js.logEntryCannotBeExternal(unresolvedId)
  21856. : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  21857. }
  21858. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  21859. ? resolveIdResult
  21860. : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
  21861. }
  21862. async resolveDynamicImport(module, specifier, importer, attributes) {
  21863. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  21864. specifier,
  21865. importer,
  21866. { attributes }
  21867. ]);
  21868. if (typeof specifier !== 'string') {
  21869. if (typeof resolution === 'string') {
  21870. return resolution;
  21871. }
  21872. if (!resolution) {
  21873. return null;
  21874. }
  21875. return this.getResolvedIdWithDefaults(resolution, attributes);
  21876. }
  21877. if (resolution == null) {
  21878. const existingResolution = module.resolvedIds[specifier];
  21879. if (existingResolution) {
  21880. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  21881. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  21882. }
  21883. return existingResolution;
  21884. }
  21885. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  21886. }
  21887. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  21888. }
  21889. }
  21890. function normalizeRelativeExternalId(source, importer) {
  21891. return parseAst_js.isRelative(source)
  21892. ? importer
  21893. ? path.resolve(importer, '..', source)
  21894. : path.resolve(source)
  21895. : source;
  21896. }
  21897. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  21898. if (fileName !== null) {
  21899. module.chunkFileNames.add(fileName);
  21900. }
  21901. else if (name !== null) {
  21902. // Always keep chunkNames sorted by priority
  21903. let namePosition = 0;
  21904. while (module.chunkNames[namePosition]?.priority < priority)
  21905. namePosition++;
  21906. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  21907. }
  21908. }
  21909. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  21910. return (makeAbsoluteExternalsRelative === true ||
  21911. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && parseAst_js.isRelative(source)) ||
  21912. !parseAst_js.isAbsolute(id));
  21913. }
  21914. async function waitForDependencyResolution(loadPromise) {
  21915. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  21916. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  21917. }
  21918. class Queue {
  21919. constructor(maxParallel) {
  21920. this.maxParallel = maxParallel;
  21921. this.queue = [];
  21922. this.workerCount = 0;
  21923. }
  21924. run(task) {
  21925. return new Promise((resolve, reject) => {
  21926. this.queue.push({ reject, resolve, task });
  21927. this.work();
  21928. });
  21929. }
  21930. async work() {
  21931. if (this.workerCount >= this.maxParallel)
  21932. return;
  21933. this.workerCount++;
  21934. let entry;
  21935. while ((entry = this.queue.shift())) {
  21936. const { reject, resolve, task } = entry;
  21937. try {
  21938. const result = await task();
  21939. resolve(result);
  21940. }
  21941. catch (error) {
  21942. reject(error);
  21943. }
  21944. }
  21945. this.workerCount--;
  21946. }
  21947. }
  21948. function normalizeEntryModules(entryModules) {
  21949. if (Array.isArray(entryModules)) {
  21950. return entryModules.map(id => ({
  21951. fileName: null,
  21952. id,
  21953. implicitlyLoadedAfter: [],
  21954. importer: undefined,
  21955. name: null
  21956. }));
  21957. }
  21958. return Object.entries(entryModules).map(([name, id]) => ({
  21959. fileName: null,
  21960. id,
  21961. implicitlyLoadedAfter: [],
  21962. importer: undefined,
  21963. name
  21964. }));
  21965. }
  21966. class Graph {
  21967. constructor(options, watcher) {
  21968. this.options = options;
  21969. this.astLru = flru(5);
  21970. this.cachedModules = new Map();
  21971. this.deoptimizationTracker = new EntityPathTracker();
  21972. this.entryModules = [];
  21973. this.modulesById = new Map();
  21974. this.needsTreeshakingPass = false;
  21975. this.newlyIncludedVariableInits = new Set();
  21976. this.phase = BuildPhase.LOAD_AND_PARSE;
  21977. this.scope = new GlobalScope();
  21978. this.watchFiles = Object.create(null);
  21979. this.watchMode = false;
  21980. this.externalModules = [];
  21981. this.implicitEntryModules = [];
  21982. this.modules = [];
  21983. this.getModuleInfo = (moduleId) => {
  21984. const foundModule = this.modulesById.get(moduleId);
  21985. if (!foundModule)
  21986. return null;
  21987. return foundModule.info;
  21988. };
  21989. if (options.cache !== false) {
  21990. if (options.cache?.modules) {
  21991. for (const module of options.cache.modules)
  21992. this.cachedModules.set(module.id, module);
  21993. }
  21994. this.pluginCache = options.cache?.plugins || Object.create(null);
  21995. // increment access counter
  21996. for (const name in this.pluginCache) {
  21997. const cache = this.pluginCache[name];
  21998. for (const value of Object.values(cache))
  21999. value[0]++;
  22000. }
  22001. }
  22002. if (watcher) {
  22003. this.watchMode = true;
  22004. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  22005. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  22006. watcher.onCurrentRun('change', handleChange);
  22007. watcher.onCurrentRun('close', handleClose);
  22008. }
  22009. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  22010. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  22011. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  22012. this.pureFunctions = getPureFunctions(options);
  22013. }
  22014. async build() {
  22015. timeStart('generate module graph', 2);
  22016. await this.generateModuleGraph();
  22017. timeEnd('generate module graph', 2);
  22018. timeStart('sort and bind modules', 2);
  22019. this.phase = BuildPhase.ANALYSE;
  22020. this.sortModules();
  22021. timeEnd('sort and bind modules', 2);
  22022. timeStart('mark included statements', 2);
  22023. this.includeStatements();
  22024. timeEnd('mark included statements', 2);
  22025. this.phase = BuildPhase.GENERATE;
  22026. }
  22027. getCache() {
  22028. // handle plugin cache eviction
  22029. for (const name in this.pluginCache) {
  22030. const cache = this.pluginCache[name];
  22031. let allDeleted = true;
  22032. for (const [key, value] of Object.entries(cache)) {
  22033. if (value[0] >= this.options.experimentalCacheExpiry)
  22034. delete cache[key];
  22035. else
  22036. allDeleted = false;
  22037. }
  22038. if (allDeleted)
  22039. delete this.pluginCache[name];
  22040. }
  22041. return {
  22042. modules: this.modules.map(module => module.toJSON()),
  22043. plugins: this.pluginCache
  22044. };
  22045. }
  22046. async generateModuleGraph() {
  22047. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  22048. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  22049. if (this.entryModules.length === 0) {
  22050. throw new Error('You must supply options.input to rollup');
  22051. }
  22052. for (const module of this.modulesById.values()) {
  22053. module.cacheInfoGetters();
  22054. if (module instanceof Module) {
  22055. this.modules.push(module);
  22056. }
  22057. else {
  22058. this.externalModules.push(module);
  22059. }
  22060. }
  22061. }
  22062. includeStatements() {
  22063. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  22064. for (const module of entryModules) {
  22065. markModuleAndImpureDependenciesAsExecuted(module);
  22066. }
  22067. if (this.options.treeshake) {
  22068. let treeshakingPass = 1;
  22069. this.newlyIncludedVariableInits.clear();
  22070. do {
  22071. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  22072. this.needsTreeshakingPass = false;
  22073. for (const module of this.modules) {
  22074. if (module.isExecuted) {
  22075. module.hasTreeShakingPassStarted = true;
  22076. if (module.info.moduleSideEffects === 'no-treeshake') {
  22077. module.includeAllInBundle();
  22078. }
  22079. else {
  22080. module.include();
  22081. }
  22082. for (const entity of this.newlyIncludedVariableInits) {
  22083. this.newlyIncludedVariableInits.delete(entity);
  22084. entity.include(createInclusionContext(), false);
  22085. }
  22086. }
  22087. }
  22088. if (treeshakingPass === 1) {
  22089. // We only include exports after the first pass to avoid issues with
  22090. // the TDZ detection logic
  22091. for (const module of entryModules) {
  22092. if (module.preserveSignature !== false) {
  22093. module.includeAllExports(false);
  22094. this.needsTreeshakingPass = true;
  22095. }
  22096. }
  22097. }
  22098. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  22099. } while (this.needsTreeshakingPass);
  22100. }
  22101. else {
  22102. for (const module of this.modules)
  22103. module.includeAllInBundle();
  22104. }
  22105. for (const externalModule of this.externalModules)
  22106. externalModule.warnUnusedImports();
  22107. for (const module of this.implicitEntryModules) {
  22108. for (const dependant of module.implicitlyLoadedAfter) {
  22109. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  22110. parseAst_js.error(parseAst_js.logImplicitDependantIsNotIncluded(dependant));
  22111. }
  22112. }
  22113. }
  22114. }
  22115. sortModules() {
  22116. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  22117. for (const cyclePath of cyclePaths) {
  22118. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularDependency(cyclePath));
  22119. }
  22120. this.modules = orderedModules;
  22121. for (const module of this.modules) {
  22122. module.bindReferences();
  22123. }
  22124. this.warnForMissingExports();
  22125. }
  22126. warnForMissingExports() {
  22127. for (const module of this.modules) {
  22128. for (const importDescription of module.importDescriptions.values()) {
  22129. if (importDescription.name !== '*') {
  22130. const [variable, options] = importDescription.module.getVariableForExportName(importDescription.name);
  22131. if (!variable) {
  22132. module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(importDescription.name, module.id, importDescription.module.id, !!options?.missingButExportExists), importDescription.start);
  22133. }
  22134. }
  22135. }
  22136. }
  22137. }
  22138. }
  22139. function formatAction([pluginName, hookName, parameters]) {
  22140. const action = `(${pluginName}) ${hookName}`;
  22141. const s = JSON.stringify;
  22142. switch (hookName) {
  22143. case 'resolveId': {
  22144. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  22145. }
  22146. case 'load': {
  22147. return `${action} ${s(parameters[0])}`;
  22148. }
  22149. case 'transform': {
  22150. return `${action} ${s(parameters[1])}`;
  22151. }
  22152. case 'shouldTransformCachedModule': {
  22153. return `${action} ${s(parameters[0].id)}`;
  22154. }
  22155. case 'moduleParsed': {
  22156. return `${action} ${s(parameters[0].id)}`;
  22157. }
  22158. }
  22159. return action;
  22160. }
  22161. let handleBeforeExit = null;
  22162. const rejectByPluginDriver = new Map();
  22163. async function catchUnfinishedHookActions(pluginDriver, callback) {
  22164. const emptyEventLoopPromise = new Promise((_, reject) => {
  22165. rejectByPluginDriver.set(pluginDriver, reject);
  22166. if (!handleBeforeExit) {
  22167. // We only ever create a single event listener to avoid max listener and
  22168. // other issues
  22169. handleBeforeExit = () => {
  22170. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  22171. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  22172. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  22173. [...unfulfilledActions].map(formatAction).join('\n')));
  22174. }
  22175. };
  22176. process$1.once('beforeExit', handleBeforeExit);
  22177. }
  22178. });
  22179. try {
  22180. return await Promise.race([callback(), emptyEventLoopPromise]);
  22181. }
  22182. finally {
  22183. rejectByPluginDriver.delete(pluginDriver);
  22184. if (rejectByPluginDriver.size === 0) {
  22185. process$1.off('beforeExit', handleBeforeExit);
  22186. handleBeforeExit = null;
  22187. }
  22188. }
  22189. }
  22190. async function initWasm() { }
  22191. const fs = /*#__PURE__*/_mergeNamespaces({
  22192. __proto__: null
  22193. }, [promises__namespace]);
  22194. async function normalizeInputOptions(config, watchMode) {
  22195. // These are options that may trigger special warnings or behaviour later
  22196. // if the user did not select an explicit value
  22197. const unsetOptions = new Set();
  22198. const context = config.context ?? 'undefined';
  22199. const plugins = await normalizePluginOption(config.plugins);
  22200. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  22201. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  22202. const strictDeprecations = config.strictDeprecations || false;
  22203. const maxParallelFileOps = getMaxParallelFileOps(config);
  22204. const options = {
  22205. cache: getCache(config),
  22206. context,
  22207. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  22208. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  22209. external: getIdMatcher(config.external),
  22210. fs: config.fs ?? fs,
  22211. input: getInput(config),
  22212. jsx: getJsx(config),
  22213. logLevel,
  22214. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  22215. maxParallelFileOps,
  22216. moduleContext: getModuleContext(config, context),
  22217. onLog,
  22218. perf: config.perf || false,
  22219. plugins,
  22220. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  22221. preserveSymlinks: config.preserveSymlinks || false,
  22222. shimMissingExports: config.shimMissingExports || false,
  22223. strictDeprecations,
  22224. treeshake: getTreeshake(config)
  22225. };
  22226. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  22227. return { options, unsetOptions };
  22228. }
  22229. const getCache = (config) => config.cache === true // `true` is the default
  22230. ? undefined
  22231. : config.cache?.cache || config.cache;
  22232. const getIdMatcher = (option) => {
  22233. if (option === true) {
  22234. return () => true;
  22235. }
  22236. if (typeof option === 'function') {
  22237. return (id, ...parameters) => (id[0] !== '\0' && option(id, ...parameters)) || false;
  22238. }
  22239. if (option) {
  22240. const ids = new Set();
  22241. const matchers = [];
  22242. for (const value of ensureArray$1(option)) {
  22243. if (value instanceof RegExp) {
  22244. matchers.push(value);
  22245. }
  22246. else {
  22247. ids.add(value);
  22248. }
  22249. }
  22250. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  22251. }
  22252. return () => false;
  22253. };
  22254. const getInput = (config) => {
  22255. const configInput = config.input;
  22256. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  22257. };
  22258. const getJsx = (config) => {
  22259. const configJsx = config.jsx;
  22260. if (!configJsx)
  22261. return false;
  22262. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ');
  22263. const { factory, importSource, mode } = configWithPreset;
  22264. switch (mode) {
  22265. case 'automatic': {
  22266. return {
  22267. factory: factory || 'React.createElement',
  22268. importSource: importSource || 'react',
  22269. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  22270. mode: 'automatic'
  22271. };
  22272. }
  22273. case 'preserve': {
  22274. if (importSource && !(factory || configWithPreset.fragment)) {
  22275. 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'));
  22276. }
  22277. return {
  22278. factory: factory || null,
  22279. fragment: configWithPreset.fragment || null,
  22280. importSource: importSource || null,
  22281. mode: 'preserve'
  22282. };
  22283. }
  22284. // case 'classic':
  22285. default: {
  22286. if (mode && mode !== 'classic') {
  22287. parseAst_js.error(parseAst_js.logInvalidOption('jsx.mode', parseAst_js.URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  22288. }
  22289. return {
  22290. factory: factory || 'React.createElement',
  22291. fragment: configWithPreset.fragment || 'React.Fragment',
  22292. importSource: importSource || null,
  22293. mode: 'classic'
  22294. };
  22295. }
  22296. }
  22297. };
  22298. const getMaxParallelFileOps = (config) => {
  22299. const maxParallelFileOps = config.maxParallelFileOps;
  22300. if (typeof maxParallelFileOps === 'number') {
  22301. if (maxParallelFileOps <= 0)
  22302. return Infinity;
  22303. return maxParallelFileOps;
  22304. }
  22305. return 1000;
  22306. };
  22307. const getModuleContext = (config, context) => {
  22308. const configModuleContext = config.moduleContext;
  22309. if (typeof configModuleContext === 'function') {
  22310. return id => configModuleContext(id) ?? context;
  22311. }
  22312. if (configModuleContext) {
  22313. const contextByModuleId = Object.create(null);
  22314. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  22315. contextByModuleId[path.resolve(key)] = moduleContext;
  22316. }
  22317. return id => contextByModuleId[id] ?? context;
  22318. }
  22319. return () => context;
  22320. };
  22321. const getTreeshake = (config) => {
  22322. const configTreeshake = config.treeshake;
  22323. if (configTreeshake === false) {
  22324. return false;
  22325. }
  22326. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ');
  22327. return {
  22328. annotations: configWithPreset.annotations !== false,
  22329. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  22330. manualPureFunctions: configWithPreset.manualPureFunctions ?? parseAst_js.EMPTY_ARRAY,
  22331. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  22332. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  22333. ? 'always'
  22334. : configWithPreset.propertyReadSideEffects !== false,
  22335. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  22336. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  22337. };
  22338. };
  22339. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  22340. if (typeof moduleSideEffectsOption === 'boolean') {
  22341. return () => moduleSideEffectsOption;
  22342. }
  22343. if (moduleSideEffectsOption === 'no-external') {
  22344. return (_id, external) => !external;
  22345. }
  22346. if (typeof moduleSideEffectsOption === 'function') {
  22347. return (id, external) => id[0] === '\0' ? true : moduleSideEffectsOption(id, external) !== false;
  22348. }
  22349. if (Array.isArray(moduleSideEffectsOption)) {
  22350. const ids = new Set(moduleSideEffectsOption);
  22351. return id => ids.has(id);
  22352. }
  22353. if (moduleSideEffectsOption) {
  22354. 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'));
  22355. }
  22356. return () => true;
  22357. };
  22358. // https://datatracker.ietf.org/doc/html/rfc2396
  22359. // eslint-disable-next-line no-control-regex
  22360. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  22361. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  22362. function sanitizeFileName(name) {
  22363. const match = DRIVE_LETTER_REGEX.exec(name);
  22364. const driveLetter = match ? match[0] : '';
  22365. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  22366. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  22367. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  22368. }
  22369. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  22370. // These are options that may trigger special warnings or behaviour later
  22371. // if the user did not select an explicit value
  22372. const unsetOptions = new Set(unsetInputOptions);
  22373. const compact = config.compact || false;
  22374. const format = getFormat(config);
  22375. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  22376. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  22377. const file = getFile(config, preserveModules, inputOptions);
  22378. const generatedCode = getGeneratedCode(config);
  22379. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  22380. const outputOptions = {
  22381. amd: getAmd(config),
  22382. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  22383. banner: getAddon(config, 'banner'),
  22384. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  22385. compact,
  22386. dir: getDir(config, file),
  22387. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  22388. entryFileNames: getEntryFileNames(config, unsetOptions),
  22389. esModule: config.esModule ?? 'if-default-prop',
  22390. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  22391. exports: getExports(config, unsetOptions),
  22392. extend: config.extend || false,
  22393. externalImportAssertions: externalImportAttributes,
  22394. externalImportAttributes,
  22395. externalLiveBindings: config.externalLiveBindings ?? true,
  22396. file,
  22397. footer: getAddon(config, 'footer'),
  22398. format,
  22399. freeze: config.freeze ?? true,
  22400. generatedCode,
  22401. globals: config.globals || {},
  22402. hashCharacters: config.hashCharacters ?? 'base64',
  22403. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  22404. importAttributesKey: config.importAttributesKey ?? 'assert',
  22405. indent: getIndent(config, compact),
  22406. inlineDynamicImports,
  22407. interop: getInterop(config),
  22408. intro: getAddon(config, 'intro'),
  22409. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  22410. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  22411. name: config.name,
  22412. noConflict: config.noConflict || false,
  22413. onlyExplicitManualChunks: config.onlyExplicitManualChunks || false,
  22414. outro: getAddon(config, 'outro'),
  22415. paths: config.paths || {},
  22416. plugins: await normalizePluginOption(config.plugins),
  22417. preserveModules,
  22418. preserveModulesRoot: getPreserveModulesRoot(config),
  22419. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  22420. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  22421. ? config.sanitizeFileName
  22422. : config.sanitizeFileName === false
  22423. ? id => id
  22424. : sanitizeFileName,
  22425. sourcemap: config.sourcemap || false,
  22426. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  22427. sourcemapDebugIds: config.sourcemapDebugIds || false,
  22428. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  22429. sourcemapFile: config.sourcemapFile,
  22430. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  22431. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  22432. ? config.sourcemapIgnoreList
  22433. : config.sourcemapIgnoreList === false
  22434. ? () => false
  22435. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  22436. sourcemapPathTransform: config.sourcemapPathTransform,
  22437. strict: config.strict ?? true,
  22438. systemNullSetters: config.systemNullSetters ?? true,
  22439. validate: config.validate || false,
  22440. virtualDirname: config.virtualDirname || '_virtual'
  22441. };
  22442. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  22443. return { options: outputOptions, unsetOptions };
  22444. }
  22445. const getFile = (config, preserveModules, inputOptions) => {
  22446. const { file } = config;
  22447. if (typeof file === 'string') {
  22448. if (preserveModules) {
  22449. 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'));
  22450. }
  22451. if (!Array.isArray(inputOptions.input))
  22452. 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'));
  22453. }
  22454. return file;
  22455. };
  22456. const getFormat = (config) => {
  22457. const configFormat = config.format;
  22458. switch (configFormat) {
  22459. case undefined:
  22460. case 'es':
  22461. case 'esm':
  22462. case 'module': {
  22463. return 'es';
  22464. }
  22465. case 'cjs':
  22466. case 'commonjs': {
  22467. return 'cjs';
  22468. }
  22469. case 'system':
  22470. case 'systemjs': {
  22471. return 'system';
  22472. }
  22473. case 'amd':
  22474. case 'iife':
  22475. case 'umd': {
  22476. return configFormat;
  22477. }
  22478. default: {
  22479. 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));
  22480. }
  22481. }
  22482. };
  22483. const getInlineDynamicImports = (config, inputOptions) => {
  22484. const inlineDynamicImports = config.inlineDynamicImports || false;
  22485. const { input } = inputOptions;
  22486. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22487. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22488. }
  22489. return inlineDynamicImports;
  22490. };
  22491. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22492. const preserveModules = config.preserveModules || false;
  22493. if (preserveModules) {
  22494. if (inlineDynamicImports) {
  22495. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  22496. }
  22497. if (inputOptions.preserveEntrySignatures === false) {
  22498. return parseAst_js.error(parseAst_js.logInvalidOption('preserveEntrySignatures', parseAst_js.URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  22499. }
  22500. }
  22501. return preserveModules;
  22502. };
  22503. const getPreserveModulesRoot = (config) => {
  22504. const { preserveModulesRoot } = config;
  22505. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22506. return undefined;
  22507. }
  22508. return path.resolve(preserveModulesRoot);
  22509. };
  22510. const getAmd = (config) => {
  22511. const mergedOption = {
  22512. autoId: false,
  22513. basePath: '',
  22514. define: 'define',
  22515. forceJsExtensionForImports: false,
  22516. ...config.amd
  22517. };
  22518. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22519. 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"'));
  22520. }
  22521. if (mergedOption.basePath && !mergedOption.autoId) {
  22522. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.basePath', parseAst_js.URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  22523. }
  22524. return mergedOption.autoId
  22525. ? {
  22526. autoId: true,
  22527. basePath: mergedOption.basePath,
  22528. define: mergedOption.define,
  22529. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22530. }
  22531. : {
  22532. autoId: false,
  22533. define: mergedOption.define,
  22534. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22535. id: mergedOption.id
  22536. };
  22537. };
  22538. const getAddon = (config, name) => {
  22539. const configAddon = config[name];
  22540. if (typeof configAddon === 'function') {
  22541. return configAddon;
  22542. }
  22543. return () => configAddon || '';
  22544. };
  22545. const getDir = (config, file) => {
  22546. const { dir } = config;
  22547. if (typeof dir === 'string' && typeof file === 'string') {
  22548. 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'));
  22549. }
  22550. return dir;
  22551. };
  22552. const getEntryFileNames = (config, unsetOptions) => {
  22553. const configEntryFileNames = config.entryFileNames;
  22554. if (configEntryFileNames == null) {
  22555. unsetOptions.add('entryFileNames');
  22556. }
  22557. return configEntryFileNames ?? '[name].js';
  22558. };
  22559. function getExports(config, unsetOptions) {
  22560. const configExports = config.exports;
  22561. if (configExports == null) {
  22562. unsetOptions.add('exports');
  22563. }
  22564. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22565. return parseAst_js.error(parseAst_js.logInvalidExportOptionValue(configExports));
  22566. }
  22567. return configExports || 'auto';
  22568. }
  22569. const getExternalImportAttributes = (config, inputOptions) => {
  22570. if (config.externalImportAssertions != undefined) {
  22571. parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22572. }
  22573. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22574. };
  22575. const getGeneratedCode = (config) => {
  22576. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
  22577. return {
  22578. arrowFunctions: configWithPreset.arrowFunctions === true,
  22579. constBindings: configWithPreset.constBindings === true,
  22580. objectShorthand: configWithPreset.objectShorthand === true,
  22581. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22582. symbols: configWithPreset.symbols === true
  22583. };
  22584. };
  22585. const getIndent = (config, compact) => {
  22586. if (compact) {
  22587. return '';
  22588. }
  22589. const configIndent = config.indent;
  22590. return configIndent === false ? '' : (configIndent ?? true);
  22591. };
  22592. const ALLOWED_INTEROP_TYPES = new Set([
  22593. 'compat',
  22594. 'auto',
  22595. 'esModule',
  22596. 'default',
  22597. 'defaultOnly'
  22598. ]);
  22599. const getInterop = (config) => {
  22600. const configInterop = config.interop;
  22601. if (typeof configInterop === 'function') {
  22602. const interopPerId = Object.create(null);
  22603. let defaultInterop = null;
  22604. return id => id === null
  22605. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22606. : id in interopPerId
  22607. ? interopPerId[id]
  22608. : validateInterop((interopPerId[id] = configInterop(id)));
  22609. }
  22610. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22611. };
  22612. const validateInterop = (interop) => {
  22613. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22614. 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));
  22615. }
  22616. return interop;
  22617. };
  22618. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22619. const configManualChunks = config.manualChunks;
  22620. if (configManualChunks) {
  22621. if (inlineDynamicImports) {
  22622. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22623. }
  22624. if (preserveModules) {
  22625. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22626. }
  22627. }
  22628. return configManualChunks || {};
  22629. };
  22630. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22631. const getSourcemapFileNames = (config, unsetOptions) => {
  22632. const configSourcemapFileNames = config.sourcemapFileNames;
  22633. if (configSourcemapFileNames == null) {
  22634. unsetOptions.add('sourcemapFileNames');
  22635. }
  22636. return configSourcemapFileNames;
  22637. };
  22638. const getSourcemapBaseUrl = (config) => {
  22639. const { sourcemapBaseUrl } = config;
  22640. if (sourcemapBaseUrl) {
  22641. if (parseAst_js.isValidUrl(sourcemapBaseUrl)) {
  22642. return parseAst_js.addTrailingSlashIfMissed(sourcemapBaseUrl);
  22643. }
  22644. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapBaseUrl', parseAst_js.URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22645. }
  22646. };
  22647. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22648. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22649. function rollup(rawInputOptions) {
  22650. return rollupInternal(rawInputOptions, null);
  22651. }
  22652. async function rollupInternal(rawInputOptions, watcher) {
  22653. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22654. initialiseTimers(inputOptions);
  22655. await initWasm();
  22656. const graph = new Graph(inputOptions, watcher);
  22657. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22658. const useCache = rawInputOptions.cache !== false;
  22659. if (rawInputOptions.cache) {
  22660. inputOptions.cache = undefined;
  22661. rawInputOptions.cache = undefined;
  22662. }
  22663. timeStart('BUILD', 1);
  22664. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22665. try {
  22666. timeStart('initialize', 2);
  22667. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22668. timeEnd('initialize', 2);
  22669. await graph.build();
  22670. }
  22671. catch (error_) {
  22672. const watchFiles = Object.keys(graph.watchFiles);
  22673. if (watchFiles.length > 0) {
  22674. error_.watchFiles = watchFiles;
  22675. }
  22676. try {
  22677. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22678. }
  22679. catch (buildEndError) {
  22680. // Create a compound error object to include both errors, based on the original error
  22681. const compoundError = parseAst_js.getRollupError({
  22682. ...error_,
  22683. 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}`
  22684. });
  22685. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22686. throw compoundError;
  22687. }
  22688. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22689. throw error_;
  22690. }
  22691. try {
  22692. await graph.pluginDriver.hookParallel('buildEnd', []);
  22693. }
  22694. catch (buildEndError) {
  22695. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22696. throw buildEndError;
  22697. }
  22698. });
  22699. timeEnd('BUILD', 1);
  22700. const result = {
  22701. cache: useCache ? graph.getCache() : undefined,
  22702. async close() {
  22703. if (result.closed)
  22704. return;
  22705. result.closed = true;
  22706. await graph.pluginDriver.hookParallel('closeBundle', []);
  22707. },
  22708. closed: false,
  22709. async [Symbol.asyncDispose]() {
  22710. await this.close();
  22711. },
  22712. async generate(rawOutputOptions) {
  22713. if (result.closed)
  22714. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22715. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22716. },
  22717. get watchFiles() {
  22718. return Object.keys(graph.watchFiles);
  22719. },
  22720. async write(rawOutputOptions) {
  22721. if (result.closed)
  22722. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22723. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22724. }
  22725. };
  22726. if (inputOptions.perf)
  22727. result.getTimings = getTimings;
  22728. return result;
  22729. }
  22730. async function getInputOptions(initialInputOptions, watchMode) {
  22731. if (!initialInputOptions) {
  22732. throw new Error('You must supply an options object to rollup');
  22733. }
  22734. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22735. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22736. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22737. return { options, unsetOptions };
  22738. }
  22739. async function getProcessedInputOptions(inputOptions, watchMode) {
  22740. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22741. const logLevel = inputOptions.logLevel || parseAst_js.LOGLEVEL_INFO;
  22742. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22743. for (const plugin of plugins) {
  22744. const { name, options } = plugin;
  22745. const handler = 'handler' in options ? options.handler : options;
  22746. const processedOptions = await handler.call({
  22747. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22748. error: (error_) => parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22749. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22750. meta: { rollupVersion: version, watchMode },
  22751. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22752. }, inputOptions);
  22753. if (processedOptions) {
  22754. inputOptions = processedOptions;
  22755. }
  22756. }
  22757. return inputOptions;
  22758. }
  22759. function normalizePlugins(plugins, anonymousPrefix) {
  22760. for (const [index, plugin] of plugins.entries()) {
  22761. if (!plugin.name) {
  22762. plugin.name = `${anonymousPrefix}${index + 1}`;
  22763. }
  22764. }
  22765. }
  22766. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22767. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22768. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22769. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22770. const generated = await bundle.generate(isWrite);
  22771. if (isWrite) {
  22772. timeStart('WRITE', 1);
  22773. if (!outputOptions.dir && !outputOptions.file) {
  22774. return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
  22775. }
  22776. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
  22777. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22778. timeEnd('WRITE', 1);
  22779. }
  22780. return createOutput(generated);
  22781. });
  22782. }
  22783. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22784. if (!rawOutputOptions) {
  22785. throw new Error('You must supply an options object');
  22786. }
  22787. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22788. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22789. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22790. return {
  22791. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22792. outputPluginDriver
  22793. };
  22794. }
  22795. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22796. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22797. const emitError = () => pluginContext.error(parseAst_js.logCannotEmitFromOptionsHook());
  22798. return {
  22799. ...pluginContext,
  22800. emitFile: emitError,
  22801. setAssetSource: emitError
  22802. };
  22803. }), inputOptions, unsetInputOptions);
  22804. }
  22805. function createOutput(outputBundle) {
  22806. return {
  22807. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22808. };
  22809. }
  22810. var SortingFileType;
  22811. (function (SortingFileType) {
  22812. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22813. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22814. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22815. })(SortingFileType || (SortingFileType = {}));
  22816. function getSortingFileType(file) {
  22817. if (file.type === 'asset') {
  22818. return SortingFileType.ASSET;
  22819. }
  22820. if (file.isEntry) {
  22821. return SortingFileType.ENTRY_CHUNK;
  22822. }
  22823. return SortingFileType.SECONDARY_CHUNK;
  22824. }
  22825. async function writeOutputFile(outputFile, outputOptions, { fs: { mkdir, writeFile } }) {
  22826. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  22827. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22828. await mkdir(path.dirname(fileName), { recursive: true });
  22829. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22830. }
  22831. /**
  22832. * Auxiliary function for defining rollup configuration
  22833. * Mainly to facilitate IDE code prompts, after all, export default does not
  22834. * prompt, even if you add @type annotations, it is not accurate
  22835. * @param options
  22836. */
  22837. function defineConfig(options) {
  22838. return options;
  22839. }
  22840. exports.bold = bold;
  22841. exports.commandAliases = commandAliases;
  22842. exports.createFilter = createFilter;
  22843. exports.cyan = cyan;
  22844. exports.defineConfig = defineConfig;
  22845. exports.ensureArray = ensureArray$1;
  22846. exports.getAugmentedNamespace = getAugmentedNamespace;
  22847. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  22848. exports.getNewArray = getNewArray;
  22849. exports.getOrCreate = getOrCreate;
  22850. exports.gray = gray;
  22851. exports.green = green;
  22852. exports.handleError = handleError;
  22853. exports.isWatchEnabled = isWatchEnabled;
  22854. exports.mergeOptions = mergeOptions;
  22855. exports.normalizePluginOption = normalizePluginOption;
  22856. exports.pc = pc;
  22857. exports.rollup = rollup;
  22858. exports.rollupInternal = rollupInternal;
  22859. exports.stderr = stderr;
  22860. exports.underline = underline;
  22861. exports.version = version;
  22862. exports.yellow = yellow;
  22863. //# sourceMappingURL=rollup.js.map