rollup.js 876 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221
  1. /*
  2. @license
  3. Rollup.js v4.34.8
  4. Mon, 17 Feb 2025 06:25:53 GMT - commit 8f667b7c15b176728449a4917cb29fe5ee3a1c0c
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const parseAst_js = require('./parseAst.js');
  10. const process$1 = require('node:process');
  11. const path = require('node:path');
  12. const require$$0 = require('path');
  13. const native_js = require('../native.js');
  14. const node_perf_hooks = require('node:perf_hooks');
  15. const promises = require('node:fs/promises');
  16. var version = "4.34.8";
  17. function ensureArray$1(items) {
  18. if (Array.isArray(items)) {
  19. return items.filter(Boolean);
  20. }
  21. if (items) {
  22. return [items];
  23. }
  24. return [];
  25. }
  26. var BuildPhase;
  27. (function (BuildPhase) {
  28. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  29. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  30. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  31. })(BuildPhase || (BuildPhase = {}));
  32. let textEncoder;
  33. const getHash64 = input => native_js.xxhashBase64Url(ensureBuffer(input));
  34. const getHash36 = input => native_js.xxhashBase36(ensureBuffer(input));
  35. const getHash16 = input => native_js.xxhashBase16(ensureBuffer(input));
  36. const hasherByType = {
  37. base36: getHash36,
  38. base64: getHash64,
  39. hex: getHash16
  40. };
  41. function ensureBuffer(input) {
  42. if (typeof input === 'string') {
  43. if (typeof Buffer === 'undefined') {
  44. textEncoder ??= new TextEncoder();
  45. return textEncoder.encode(input);
  46. }
  47. return Buffer.from(input);
  48. }
  49. return input;
  50. }
  51. function getOrCreate(map, key, init) {
  52. const existing = map.get(key);
  53. if (existing !== undefined) {
  54. return existing;
  55. }
  56. const value = init();
  57. map.set(key, value);
  58. return value;
  59. }
  60. function getNewSet() {
  61. return new Set();
  62. }
  63. function getNewArray() {
  64. return [];
  65. }
  66. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  67. const base = 64;
  68. function toBase64(value) {
  69. let outString = '';
  70. do {
  71. const currentDigit = value % base;
  72. value = (value / base) | 0;
  73. outString = chars$1[currentDigit] + outString;
  74. } while (value !== 0);
  75. return outString;
  76. }
  77. // Four random characters from the private use area to minimize risk of
  78. // conflicts
  79. const hashPlaceholderLeft = '!~{';
  80. const hashPlaceholderRight = '}~';
  81. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  82. // This is the size of a 128-bits xxhash with base64url encoding
  83. const MAX_HASH_SIZE = 21;
  84. const DEFAULT_HASH_SIZE = 8;
  85. const getHashPlaceholderGenerator = () => {
  86. let nextIndex = 0;
  87. return (optionName, hashSize) => {
  88. if (hashSize > MAX_HASH_SIZE) {
  89. return parseAst_js.error(parseAst_js.logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  90. }
  91. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  92. if (placeholder.length > hashSize) {
  93. return parseAst_js.error(parseAst_js.logFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`));
  94. }
  95. return placeholder;
  96. };
  97. };
  98. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  99. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  100. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  101. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  102. const containedPlaceholders = new Set();
  103. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  104. if (placeholders.has(placeholder)) {
  105. containedPlaceholders.add(placeholder);
  106. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  107. }
  108. return placeholder;
  109. });
  110. return { containedPlaceholders, transformedCode };
  111. };
  112. const lowercaseBundleKeys = Symbol('bundleKeys');
  113. const FILE_PLACEHOLDER = {
  114. type: 'placeholder'
  115. };
  116. const getOutputBundle = (outputBundleBase) => {
  117. const reservedLowercaseBundleKeys = new Set();
  118. return new Proxy(outputBundleBase, {
  119. deleteProperty(target, key) {
  120. if (typeof key === 'string') {
  121. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  122. }
  123. return Reflect.deleteProperty(target, key);
  124. },
  125. get(target, key) {
  126. if (key === lowercaseBundleKeys) {
  127. return reservedLowercaseBundleKeys;
  128. }
  129. return Reflect.get(target, key);
  130. },
  131. set(target, key, value) {
  132. if (typeof key === 'string') {
  133. reservedLowercaseBundleKeys.add(key.toLowerCase());
  134. }
  135. return Reflect.set(target, key, value);
  136. }
  137. });
  138. };
  139. const removeUnreferencedAssets = (outputBundle) => {
  140. const unreferencedAssets = new Set();
  141. const bundleEntries = Object.values(outputBundle);
  142. for (const asset of bundleEntries) {
  143. if (asset.type === 'asset' && asset.needsCodeReference) {
  144. unreferencedAssets.add(asset.fileName);
  145. }
  146. }
  147. for (const chunk of bundleEntries) {
  148. if (chunk.type === 'chunk') {
  149. for (const referencedFile of chunk.referencedFiles) {
  150. if (unreferencedAssets.has(referencedFile)) {
  151. unreferencedAssets.delete(referencedFile);
  152. }
  153. }
  154. }
  155. }
  156. for (const file of unreferencedAssets) {
  157. delete outputBundle[file];
  158. }
  159. };
  160. function renderNamePattern(pattern, patternName, replacements) {
  161. if (parseAst_js.isPathFragment(pattern))
  162. return parseAst_js.error(parseAst_js.logFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
  163. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  164. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  165. return parseAst_js.error(parseAst_js.logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  166. }
  167. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  168. if (parseAst_js.isPathFragment(replacement))
  169. return parseAst_js.error(parseAst_js.logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  170. return replacement;
  171. });
  172. }
  173. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  174. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  175. return name;
  176. const extension = path.extname(name);
  177. name = name.slice(0, Math.max(0, name.length - extension.length));
  178. let uniqueName, uniqueIndex = 1;
  179. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  180. ;
  181. return uniqueName;
  182. }
  183. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  184. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  185. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  186. ? outputOptions.assetFileNames({
  187. // Additionally, this should be non-enumerable in the next major
  188. get name() {
  189. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
  190. return name;
  191. },
  192. names,
  193. // Additionally, this should be non-enumerable in the next major
  194. get originalFileName() {
  195. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, inputOptions);
  196. return originalFileName;
  197. },
  198. originalFileNames,
  199. source,
  200. type: 'asset'
  201. })
  202. : outputOptions.assetFileNames, 'output.assetFileNames', {
  203. ext: () => path.extname(emittedName).slice(1),
  204. extname: () => path.extname(emittedName),
  205. hash: size => sourceHash.slice(0, Math.max(0, size || DEFAULT_HASH_SIZE)),
  206. name: () => emittedName.slice(0, Math.max(0, emittedName.length - path.extname(emittedName).length))
  207. }), bundle);
  208. }
  209. function reserveFileNameInBundle(fileName, { bundle }, log) {
  210. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  211. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logFileNameConflict(fileName));
  212. }
  213. else {
  214. bundle[fileName] = FILE_PLACEHOLDER;
  215. }
  216. }
  217. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  218. function hasValidType(emittedFile) {
  219. return Boolean(emittedFile &&
  220. emittedFileTypes.has(emittedFile.type));
  221. }
  222. function hasValidName(emittedFile) {
  223. const validatedName = emittedFile.fileName || emittedFile.name;
  224. return !validatedName || (typeof validatedName === 'string' && !parseAst_js.isPathFragment(validatedName));
  225. }
  226. function getValidSource(source, emittedFile, fileReferenceId) {
  227. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  228. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  229. return parseAst_js.error(parseAst_js.logFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  230. }
  231. return source;
  232. }
  233. function getAssetFileName(file, referenceId) {
  234. if (typeof file.fileName !== 'string') {
  235. return parseAst_js.error(parseAst_js.logAssetNotFinalisedForFileName(file.name || referenceId));
  236. }
  237. return file.fileName;
  238. }
  239. function getChunkFileName(file, facadeChunkByModule) {
  240. if (file.fileName) {
  241. return file.fileName;
  242. }
  243. if (facadeChunkByModule) {
  244. return facadeChunkByModule.get(file.module).getFileName();
  245. }
  246. return parseAst_js.error(parseAst_js.logChunkNotGeneratedForFileName(file.fileName || file.name));
  247. }
  248. class FileEmitter {
  249. constructor(graph, options, baseFileEmitter) {
  250. this.graph = graph;
  251. this.options = options;
  252. this.facadeChunkByModule = null;
  253. this.nextIdBase = 1;
  254. this.output = null;
  255. this.outputFileEmitters = [];
  256. this.emitFile = (emittedFile) => {
  257. if (!hasValidType(emittedFile)) {
  258. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  259. }
  260. if (emittedFile.type === 'prebuilt-chunk') {
  261. return this.emitPrebuiltChunk(emittedFile);
  262. }
  263. if (!hasValidName(emittedFile)) {
  264. return parseAst_js.error(parseAst_js.logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  265. }
  266. if (emittedFile.type === 'chunk') {
  267. return this.emitChunk(emittedFile);
  268. }
  269. return this.emitAsset(emittedFile);
  270. };
  271. this.finaliseAssets = () => {
  272. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  273. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  274. return parseAst_js.error(parseAst_js.logNoAssetSourceSet(emittedFile.name || referenceId));
  275. }
  276. };
  277. this.getFileName = (fileReferenceId) => {
  278. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  279. if (!emittedFile)
  280. return parseAst_js.error(parseAst_js.logFileReferenceIdNotFoundForFilename(fileReferenceId));
  281. if (emittedFile.type === 'chunk') {
  282. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  283. }
  284. if (emittedFile.type === 'prebuilt-chunk') {
  285. return emittedFile.fileName;
  286. }
  287. return getAssetFileName(emittedFile, fileReferenceId);
  288. };
  289. this.setAssetSource = (referenceId, requestedSource) => {
  290. const consumedFile = this.filesByReferenceId.get(referenceId);
  291. if (!consumedFile)
  292. return parseAst_js.error(parseAst_js.logAssetReferenceIdNotFoundForSetSource(referenceId));
  293. if (consumedFile.type !== 'asset') {
  294. return parseAst_js.error(parseAst_js.logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  295. }
  296. if (consumedFile.source !== undefined) {
  297. return parseAst_js.error(parseAst_js.logAssetSourceAlreadySet(consumedFile.name || referenceId));
  298. }
  299. const source = getValidSource(requestedSource, consumedFile, referenceId);
  300. if (this.output) {
  301. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  302. }
  303. else {
  304. consumedFile.source = source;
  305. for (const emitter of this.outputFileEmitters) {
  306. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  307. }
  308. }
  309. };
  310. this.setChunkInformation = (facadeChunkByModule) => {
  311. this.facadeChunkByModule = facadeChunkByModule;
  312. };
  313. this.setOutputBundle = (bundle, outputOptions) => {
  314. const getHash = hasherByType[outputOptions.hashCharacters];
  315. const output = (this.output = {
  316. bundle,
  317. fileNamesBySourceHash: new Map(),
  318. getHash,
  319. outputOptions
  320. });
  321. for (const emittedFile of this.filesByReferenceId.values()) {
  322. if (emittedFile.fileName) {
  323. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  324. }
  325. }
  326. const consumedAssetsByHash = new Map();
  327. for (const consumedFile of this.filesByReferenceId.values()) {
  328. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  329. if (consumedFile.fileName) {
  330. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  331. }
  332. else {
  333. const sourceHash = getHash(consumedFile.source);
  334. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  335. }
  336. }
  337. else if (consumedFile.type === 'prebuilt-chunk') {
  338. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  339. }
  340. }
  341. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  342. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  343. }
  344. };
  345. this.filesByReferenceId = baseFileEmitter
  346. ? new Map(baseFileEmitter.filesByReferenceId)
  347. : new Map();
  348. baseFileEmitter?.addOutputFileEmitter(this);
  349. }
  350. addOutputFileEmitter(outputFileEmitter) {
  351. this.outputFileEmitters.push(outputFileEmitter);
  352. }
  353. assignReferenceId(file, idBase) {
  354. let referenceId = idBase;
  355. do {
  356. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  357. } while (this.filesByReferenceId.has(referenceId) ||
  358. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  359. file.referenceId = referenceId;
  360. this.filesByReferenceId.set(referenceId, file);
  361. for (const { filesByReferenceId } of this.outputFileEmitters) {
  362. filesByReferenceId.set(referenceId, file);
  363. }
  364. return referenceId;
  365. }
  366. createPrebuiltChunk(prebuiltChunk) {
  367. return {
  368. code: prebuiltChunk.code,
  369. dynamicImports: [],
  370. exports: prebuiltChunk.exports || [],
  371. facadeModuleId: null,
  372. fileName: prebuiltChunk.fileName,
  373. implicitlyLoadedBefore: [],
  374. importedBindings: {},
  375. imports: [],
  376. isDynamicEntry: false,
  377. isEntry: false,
  378. isImplicitEntry: false,
  379. map: prebuiltChunk.map || null,
  380. moduleIds: [],
  381. modules: {},
  382. name: prebuiltChunk.fileName,
  383. preliminaryFileName: prebuiltChunk.fileName,
  384. referencedFiles: [],
  385. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  386. type: 'chunk'
  387. };
  388. }
  389. emitAsset(emittedAsset) {
  390. const source = emittedAsset.source === undefined
  391. ? undefined
  392. : getValidSource(emittedAsset.source, emittedAsset, null);
  393. const originalFileName = emittedAsset.originalFileName || null;
  394. if (typeof originalFileName === 'string') {
  395. this.graph.watchFiles[originalFileName] = true;
  396. }
  397. const consumedAsset = {
  398. fileName: emittedAsset.fileName,
  399. name: emittedAsset.name,
  400. needsCodeReference: !!emittedAsset.needsCodeReference,
  401. originalFileName,
  402. referenceId: '',
  403. source,
  404. type: 'asset'
  405. };
  406. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  407. if (this.output) {
  408. this.emitAssetWithReferenceId(consumedAsset, this.output);
  409. }
  410. else {
  411. for (const fileEmitter of this.outputFileEmitters) {
  412. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  413. }
  414. }
  415. return referenceId;
  416. }
  417. emitAssetWithReferenceId(consumedAsset, output) {
  418. const { fileName, source } = consumedAsset;
  419. if (fileName) {
  420. reserveFileNameInBundle(fileName, output, this.options.onLog);
  421. }
  422. if (source !== undefined) {
  423. this.finalizeAdditionalAsset(consumedAsset, source, output);
  424. }
  425. }
  426. emitChunk(emittedChunk) {
  427. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  428. return parseAst_js.error(parseAst_js.logInvalidRollupPhaseForChunkEmission());
  429. }
  430. if (typeof emittedChunk.id !== 'string') {
  431. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  432. }
  433. const consumedChunk = {
  434. fileName: emittedChunk.fileName,
  435. module: null,
  436. name: emittedChunk.name || emittedChunk.id,
  437. referenceId: '',
  438. type: 'chunk'
  439. };
  440. this.graph.moduleLoader
  441. .emitChunk(emittedChunk)
  442. .then(module => (consumedChunk.module = module))
  443. .catch(() => {
  444. // Avoid unhandled Promise rejection as the error will be thrown later
  445. // once module loading has finished
  446. });
  447. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  448. }
  449. emitPrebuiltChunk(emitPrebuiltChunk) {
  450. if (typeof emitPrebuiltChunk.code !== 'string') {
  451. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  452. }
  453. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  454. parseAst_js.isPathFragment(emitPrebuiltChunk.fileName)) {
  455. return parseAst_js.error(parseAst_js.logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  456. }
  457. const consumedPrebuiltChunk = {
  458. code: emitPrebuiltChunk.code,
  459. exports: emitPrebuiltChunk.exports,
  460. fileName: emitPrebuiltChunk.fileName,
  461. map: emitPrebuiltChunk.map,
  462. referenceId: '',
  463. type: 'prebuilt-chunk'
  464. };
  465. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  466. if (this.output) {
  467. this.output.bundle[consumedPrebuiltChunk.fileName] =
  468. this.createPrebuiltChunk(consumedPrebuiltChunk);
  469. }
  470. return referenceId;
  471. }
  472. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  473. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  474. // Deduplicate assets if an explicit fileName is not provided
  475. if (!fileName) {
  476. const sourceHash = getHash(source);
  477. fileName = fileNamesBySourceHash.get(sourceHash);
  478. if (!fileName) {
  479. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  480. fileNamesBySourceHash.set(sourceHash, fileName);
  481. }
  482. }
  483. // We must not modify the original assets to avoid interaction between outputs
  484. const assetWithFileName = { ...consumedFile, fileName, source };
  485. this.filesByReferenceId.set(referenceId, assetWithFileName);
  486. const existingAsset = bundle[fileName];
  487. if (existingAsset?.type === 'asset') {
  488. existingAsset.needsCodeReference &&= needsCodeReference;
  489. if (name) {
  490. existingAsset.names.push(name);
  491. }
  492. if (originalFileName) {
  493. existingAsset.originalFileNames.push(originalFileName);
  494. }
  495. }
  496. else {
  497. const { options } = this;
  498. bundle[fileName] = {
  499. fileName,
  500. get name() {
  501. // Additionally, this should be non-enumerable in the next major
  502. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  503. return name;
  504. },
  505. names: name ? [name] : [],
  506. needsCodeReference,
  507. get originalFileName() {
  508. // Additionally, this should be non-enumerable in the next major
  509. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  510. return originalFileName;
  511. },
  512. originalFileNames: originalFileName ? [originalFileName] : [],
  513. source,
  514. type: 'asset'
  515. };
  516. }
  517. }
  518. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  519. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  520. let fileName = '';
  521. let usedConsumedFile;
  522. let needsCodeReference = true;
  523. for (const consumedFile of consumedFiles) {
  524. needsCodeReference &&= consumedFile.needsCodeReference;
  525. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  526. if (!fileName ||
  527. assetFileName.length < fileName.length ||
  528. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  529. fileName = assetFileName;
  530. usedConsumedFile = consumedFile;
  531. }
  532. }
  533. fileNamesBySourceHash.set(sourceHash, fileName);
  534. for (const consumedFile of consumedFiles) {
  535. // We must not modify the original assets to avoid interaction between outputs
  536. const assetWithFileName = { ...consumedFile, fileName };
  537. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  538. }
  539. const { options } = this;
  540. bundle[fileName] = {
  541. fileName,
  542. get name() {
  543. // Additionally, this should be non-enumerable in the next major
  544. parseAst_js.warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  545. return usedConsumedFile.name;
  546. },
  547. names,
  548. needsCodeReference,
  549. get originalFileName() {
  550. // Additionally, this should be non-enumerable in the next major
  551. parseAst_js.warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', parseAst_js.URL_GENERATEBUNDLE, false, options);
  552. return usedConsumedFile.originalFileName;
  553. },
  554. originalFileNames,
  555. source: usedConsumedFile.source,
  556. type: 'asset'
  557. };
  558. }
  559. }
  560. function getNamesFromAssets(consumedFiles) {
  561. const names = [];
  562. const originalFileNames = [];
  563. for (const { name, originalFileName } of consumedFiles) {
  564. if (typeof name === 'string') {
  565. names.push(name);
  566. }
  567. if (originalFileName) {
  568. originalFileNames.push(originalFileName);
  569. }
  570. }
  571. originalFileNames.sort();
  572. // Sort by length first and then alphabetically so that the order is stable
  573. // and the shortest names come first
  574. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  575. return { names, originalFileNames };
  576. }
  577. const doNothing = () => { };
  578. async function asyncFlatten(array) {
  579. do {
  580. array = (await Promise.all(array)).flat(Infinity);
  581. } while (array.some((v) => v?.then));
  582. return array;
  583. }
  584. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  585. const { onwarn, onLog } = config;
  586. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  587. if (onLog) {
  588. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  589. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  590. if (level === parseAst_js.LOGLEVEL_ERROR) {
  591. return parseAst_js.error(normalizeLog(handledLog));
  592. }
  593. if (parseAst_js.logLevelPriority[level] >= minimalPriority) {
  594. defaultOnLog(level, normalizeLog(handledLog));
  595. }
  596. });
  597. }
  598. return defaultOnLog;
  599. };
  600. const getDefaultOnLog = (printLog, onwarn) => onwarn
  601. ? (level, log) => {
  602. if (level === parseAst_js.LOGLEVEL_WARN) {
  603. onwarn(addLogToString(log), warning => printLog(parseAst_js.LOGLEVEL_WARN, normalizeLog(warning)));
  604. }
  605. else {
  606. printLog(level, log);
  607. }
  608. }
  609. : printLog;
  610. const addLogToString = (log) => {
  611. Object.defineProperty(log, 'toString', {
  612. value: () => log.message,
  613. writable: true
  614. });
  615. return log;
  616. };
  617. const normalizeLog = (log) => typeof log === 'string'
  618. ? { message: log }
  619. : typeof log === 'function'
  620. ? normalizeLog(log())
  621. : log;
  622. const defaultPrintLog = (level, { message }) => {
  623. switch (level) {
  624. case parseAst_js.LOGLEVEL_WARN: {
  625. return console.warn(message);
  626. }
  627. case parseAst_js.LOGLEVEL_DEBUG: {
  628. return console.debug(message);
  629. }
  630. default: {
  631. return console.info(message);
  632. }
  633. }
  634. };
  635. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  636. const validOptionSet = new Set(validOptions);
  637. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  638. if (unknownOptions.length > 0) {
  639. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  640. }
  641. }
  642. const treeshakePresets = {
  643. recommended: {
  644. annotations: true,
  645. correctVarValueBeforeDeclaration: false,
  646. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  647. moduleSideEffects: () => true,
  648. propertyReadSideEffects: true,
  649. tryCatchDeoptimization: true,
  650. unknownGlobalSideEffects: false
  651. },
  652. safest: {
  653. annotations: true,
  654. correctVarValueBeforeDeclaration: true,
  655. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  656. moduleSideEffects: () => true,
  657. propertyReadSideEffects: true,
  658. tryCatchDeoptimization: true,
  659. unknownGlobalSideEffects: true
  660. },
  661. smallest: {
  662. annotations: true,
  663. correctVarValueBeforeDeclaration: false,
  664. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  665. moduleSideEffects: () => false,
  666. propertyReadSideEffects: false,
  667. tryCatchDeoptimization: false,
  668. unknownGlobalSideEffects: false
  669. }
  670. };
  671. const jsxPresets = {
  672. preserve: {
  673. factory: null,
  674. fragment: null,
  675. importSource: null,
  676. mode: 'preserve'
  677. },
  678. 'preserve-react': {
  679. factory: 'React.createElement',
  680. fragment: 'React.Fragment',
  681. importSource: 'react',
  682. mode: 'preserve'
  683. },
  684. react: {
  685. factory: 'React.createElement',
  686. fragment: 'React.Fragment',
  687. importSource: 'react',
  688. mode: 'classic'
  689. },
  690. 'react-jsx': {
  691. factory: 'React.createElement',
  692. importSource: 'react',
  693. jsxImportSource: 'react/jsx-runtime',
  694. mode: 'automatic'
  695. }
  696. };
  697. const generatedCodePresets = {
  698. es2015: {
  699. arrowFunctions: true,
  700. constBindings: true,
  701. objectShorthand: true,
  702. reservedNamesAsProps: true,
  703. symbols: true
  704. },
  705. es5: {
  706. arrowFunctions: false,
  707. constBindings: false,
  708. objectShorthand: false,
  709. reservedNamesAsProps: true,
  710. symbols: false
  711. }
  712. };
  713. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  714. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  715. if (typeof value === 'string') {
  716. const preset = presets[value];
  717. if (preset) {
  718. return preset;
  719. }
  720. parseAst_js.error(parseAst_js.logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${parseAst_js.printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  721. }
  722. return objectifyOption(value);
  723. };
  724. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  725. const presetName = value?.preset;
  726. if (presetName) {
  727. const preset = presets[presetName];
  728. if (preset) {
  729. return { ...preset, ...value };
  730. }
  731. else {
  732. parseAst_js.error(parseAst_js.logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${parseAst_js.printQuotedStringList(Object.keys(presets))}`, presetName));
  733. }
  734. }
  735. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  736. };
  737. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  738. function getLogHandler(level, code, logger, pluginName, logLevel) {
  739. if (parseAst_js.logLevelPriority[level] < parseAst_js.logLevelPriority[logLevel]) {
  740. return doNothing;
  741. }
  742. return (log, pos) => {
  743. if (pos != null) {
  744. logger(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidLogPosition(pluginName));
  745. }
  746. log = normalizeLog(log);
  747. if (log.code && !log.pluginCode) {
  748. log.pluginCode = log.code;
  749. }
  750. log.code = code;
  751. log.plugin = pluginName;
  752. logger(level, log);
  753. };
  754. }
  755. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  756. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  757. function createPluginCache(cache) {
  758. return {
  759. delete(id) {
  760. return delete cache[id];
  761. },
  762. get(id) {
  763. const item = cache[id];
  764. if (!item)
  765. return;
  766. item[0] = 0;
  767. return item[1];
  768. },
  769. has(id) {
  770. const item = cache[id];
  771. if (!item)
  772. return false;
  773. item[0] = 0;
  774. return true;
  775. },
  776. set(id, value) {
  777. cache[id] = [0, value];
  778. }
  779. };
  780. }
  781. function getTrackedPluginCache(pluginCache, onUse) {
  782. return {
  783. delete(id) {
  784. onUse();
  785. return pluginCache.delete(id);
  786. },
  787. get(id) {
  788. onUse();
  789. return pluginCache.get(id);
  790. },
  791. has(id) {
  792. onUse();
  793. return pluginCache.has(id);
  794. },
  795. set(id, value) {
  796. onUse();
  797. return pluginCache.set(id, value);
  798. }
  799. };
  800. }
  801. const NO_CACHE = {
  802. delete() {
  803. return false;
  804. },
  805. get() {
  806. return undefined;
  807. },
  808. has() {
  809. return false;
  810. },
  811. set() { }
  812. };
  813. function uncacheablePluginError(pluginName) {
  814. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  815. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  816. return parseAst_js.error(parseAst_js.logAnonymousPluginCache());
  817. }
  818. return parseAst_js.error(parseAst_js.logDuplicatePluginName(pluginName));
  819. }
  820. function getCacheForUncacheablePlugin(pluginName) {
  821. return {
  822. delete() {
  823. return uncacheablePluginError(pluginName);
  824. },
  825. get() {
  826. return uncacheablePluginError(pluginName);
  827. },
  828. has() {
  829. return uncacheablePluginError(pluginName);
  830. },
  831. set() {
  832. return uncacheablePluginError(pluginName);
  833. }
  834. };
  835. }
  836. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  837. const { logLevel, onLog } = options;
  838. let cacheable = true;
  839. if (typeof plugin.cacheKey !== 'string') {
  840. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  841. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  842. existingPluginNames.has(plugin.name)) {
  843. cacheable = false;
  844. }
  845. else {
  846. existingPluginNames.add(plugin.name);
  847. }
  848. }
  849. let cacheInstance;
  850. if (!pluginCache) {
  851. cacheInstance = NO_CACHE;
  852. }
  853. else if (cacheable) {
  854. const cacheKey = plugin.cacheKey || plugin.name;
  855. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  856. }
  857. else {
  858. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  859. }
  860. return {
  861. addWatchFile(id) {
  862. graph.watchFiles[id] = true;
  863. },
  864. cache: cacheInstance,
  865. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  866. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  867. error(error_) {
  868. return parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), plugin.name));
  869. },
  870. getFileName: fileEmitter.getFileName,
  871. getModuleIds: () => graph.modulesById.keys(),
  872. getModuleInfo: graph.getModuleInfo,
  873. getWatchFiles: () => Object.keys(graph.watchFiles),
  874. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  875. load(resolvedId) {
  876. return graph.moduleLoader.preloadModule(resolvedId);
  877. },
  878. meta: {
  879. rollupVersion: version,
  880. watchMode: graph.watchMode
  881. },
  882. parse: parseAst_js.parseAst,
  883. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) {
  884. skipSelf ??= true;
  885. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  886. },
  887. setAssetSource: fileEmitter.setAssetSource,
  888. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  889. };
  890. }
  891. // This will make sure no input hook is omitted
  892. const inputHookNames = {
  893. buildEnd: 1,
  894. buildStart: 1,
  895. closeBundle: 1,
  896. closeWatcher: 1,
  897. load: 1,
  898. moduleParsed: 1,
  899. onLog: 1,
  900. options: 1,
  901. resolveDynamicImport: 1,
  902. resolveId: 1,
  903. shouldTransformCachedModule: 1,
  904. transform: 1,
  905. watchChange: 1
  906. };
  907. const inputHooks = Object.keys(inputHookNames);
  908. class PluginDriver {
  909. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  910. this.graph = graph;
  911. this.options = options;
  912. this.pluginCache = pluginCache;
  913. this.sortedPlugins = new Map();
  914. this.unfulfilledActions = new Set();
  915. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  916. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  917. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  918. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  919. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  920. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  921. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  922. const existingPluginNames = new Set();
  923. this.pluginContexts = new Map(this.plugins.map(plugin => [
  924. plugin,
  925. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  926. ]));
  927. if (basePluginDriver) {
  928. for (const plugin of userPlugins) {
  929. for (const hook of inputHooks) {
  930. if (hook in plugin) {
  931. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInputHookInOutputPlugin(plugin.name, hook));
  932. }
  933. }
  934. }
  935. }
  936. }
  937. createOutputPluginDriver(plugins) {
  938. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  939. }
  940. getUnfulfilledHookActions() {
  941. return this.unfulfilledActions;
  942. }
  943. // chains, first non-null result stops and returns
  944. hookFirst(hookName, parameters, replaceContext, skipped) {
  945. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  946. }
  947. // chains, first non-null result stops and returns result and last plugin
  948. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  949. for (const plugin of this.getSortedPlugins(hookName)) {
  950. if (skipped?.has(plugin))
  951. continue;
  952. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  953. if (result != null)
  954. return [result, plugin];
  955. }
  956. return null;
  957. }
  958. // chains synchronously, first non-null result stops and returns
  959. hookFirstSync(hookName, parameters, replaceContext) {
  960. for (const plugin of this.getSortedPlugins(hookName)) {
  961. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  962. if (result != null)
  963. return result;
  964. }
  965. return null;
  966. }
  967. // parallel, ignores returns
  968. async hookParallel(hookName, parameters, replaceContext) {
  969. const parallelPromises = [];
  970. for (const plugin of this.getSortedPlugins(hookName)) {
  971. if (plugin[hookName].sequential) {
  972. await Promise.all(parallelPromises);
  973. parallelPromises.length = 0;
  974. await this.runHook(hookName, parameters, plugin, replaceContext);
  975. }
  976. else {
  977. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  978. }
  979. }
  980. await Promise.all(parallelPromises);
  981. }
  982. // chains, reduces returned value, handling the reduced value as the first hook argument
  983. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  984. let promise = Promise.resolve(argument0);
  985. for (const plugin of this.getSortedPlugins(hookName)) {
  986. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  987. }
  988. return promise;
  989. }
  990. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  991. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  992. for (const plugin of this.getSortedPlugins(hookName)) {
  993. const parameters = [argument0, ...rest];
  994. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  995. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  996. }
  997. return argument0;
  998. }
  999. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  1000. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  1001. const results = [];
  1002. const parallelResults = [];
  1003. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  1004. if (plugin[hookName].sequential) {
  1005. results.push(...(await Promise.all(parallelResults)));
  1006. parallelResults.length = 0;
  1007. results.push(await this.runHook(hookName, parameters, plugin));
  1008. }
  1009. else {
  1010. parallelResults.push(this.runHook(hookName, parameters, plugin));
  1011. }
  1012. }
  1013. results.push(...(await Promise.all(parallelResults)));
  1014. return results.reduce(reducer, await initialValue);
  1015. }
  1016. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  1017. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  1018. let accumulator = initialValue;
  1019. for (const plugin of this.getSortedPlugins(hookName)) {
  1020. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1021. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  1022. }
  1023. return accumulator;
  1024. }
  1025. // chains, ignores returns
  1026. hookSeq(hookName, parameters, replaceContext) {
  1027. let promise = Promise.resolve();
  1028. for (const plugin of this.getSortedPlugins(hookName)) {
  1029. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  1030. }
  1031. return promise.then(noReturn);
  1032. }
  1033. getSortedPlugins(hookName, validateHandler) {
  1034. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  1035. }
  1036. // Implementation signature
  1037. runHook(hookName, parameters, plugin, replaceContext) {
  1038. // We always filter for plugins that support the hook before running it
  1039. const hook = plugin[hookName];
  1040. const handler = typeof hook === 'object' ? hook.handler : hook;
  1041. let context = this.pluginContexts.get(plugin);
  1042. if (replaceContext) {
  1043. context = replaceContext(context, plugin);
  1044. }
  1045. let action = null;
  1046. return Promise.resolve()
  1047. .then(() => {
  1048. if (typeof handler !== 'function') {
  1049. return handler;
  1050. }
  1051. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  1052. const hookResult = handler.apply(context, parameters);
  1053. if (!hookResult?.then) {
  1054. // short circuit for non-thenables and non-Promises
  1055. return hookResult;
  1056. }
  1057. // Track pending hook actions to properly error out when
  1058. // unfulfilled promises cause rollup to abruptly and confusingly
  1059. // exit with a successful 0 return code but without producing any
  1060. // output, errors or warnings.
  1061. action = [plugin.name, hookName, parameters];
  1062. this.unfulfilledActions.add(action);
  1063. // Although it would be more elegant to just return hookResult here
  1064. // and put the .then() handler just above the .catch() handler below,
  1065. // doing so would subtly change the defacto async event dispatch order
  1066. // which at least one test and some plugins in the wild may depend on.
  1067. return Promise.resolve(hookResult).then(result => {
  1068. // action was fulfilled
  1069. this.unfulfilledActions.delete(action);
  1070. return result;
  1071. });
  1072. })
  1073. .catch(error_ => {
  1074. if (action !== null) {
  1075. // action considered to be fulfilled since error being handled
  1076. this.unfulfilledActions.delete(action);
  1077. }
  1078. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  1079. });
  1080. }
  1081. /**
  1082. * Run a sync plugin hook and return the result.
  1083. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  1084. * @param args Arguments passed to the plugin hook.
  1085. * @param plugin The acutal plugin
  1086. * @param replaceContext When passed, the plugin context can be overridden.
  1087. */
  1088. runHookSync(hookName, parameters, plugin, replaceContext) {
  1089. const hook = plugin[hookName];
  1090. const handler = typeof hook === 'object' ? hook.handler : hook;
  1091. let context = this.pluginContexts.get(plugin);
  1092. if (replaceContext) {
  1093. context = replaceContext(context, plugin);
  1094. }
  1095. try {
  1096. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  1097. return handler.apply(context, parameters);
  1098. }
  1099. catch (error_) {
  1100. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  1101. }
  1102. }
  1103. }
  1104. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  1105. const pre = [];
  1106. const normal = [];
  1107. const post = [];
  1108. for (const plugin of plugins) {
  1109. const hook = plugin[hookName];
  1110. if (hook) {
  1111. if (typeof hook === 'object') {
  1112. validateHandler(hook.handler, hookName, plugin);
  1113. if (hook.order === 'pre') {
  1114. pre.push(plugin);
  1115. continue;
  1116. }
  1117. if (hook.order === 'post') {
  1118. post.push(plugin);
  1119. continue;
  1120. }
  1121. }
  1122. else {
  1123. validateHandler(hook, hookName, plugin);
  1124. }
  1125. normal.push(plugin);
  1126. }
  1127. }
  1128. return [...pre, ...normal, ...post];
  1129. }
  1130. function validateFunctionPluginHandler(handler, hookName, plugin) {
  1131. if (typeof handler !== 'function') {
  1132. parseAst_js.error(parseAst_js.logInvalidFunctionPluginHook(hookName, plugin.name));
  1133. }
  1134. }
  1135. function validateAddonPluginHandler(handler, hookName, plugin) {
  1136. if (typeof handler !== 'string' && typeof handler !== 'function') {
  1137. return parseAst_js.error(parseAst_js.logInvalidAddonPluginHook(hookName, plugin.name));
  1138. }
  1139. }
  1140. function noReturn() { }
  1141. function getLogger(plugins, onLog, watchMode, logLevel) {
  1142. plugins = getSortedValidatedPlugins('onLog', plugins);
  1143. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  1144. const logger = (level, log, skipped = parseAst_js.EMPTY_SET) => {
  1145. parseAst_js.augmentLogMessage(log);
  1146. const logPriority = parseAst_js.logLevelPriority[level];
  1147. if (logPriority < minimalPriority) {
  1148. return;
  1149. }
  1150. for (const plugin of plugins) {
  1151. if (skipped.has(plugin))
  1152. continue;
  1153. const { onLog: pluginOnLog } = plugin;
  1154. const getLogHandler = (level) => {
  1155. if (parseAst_js.logLevelPriority[level] < minimalPriority) {
  1156. return doNothing;
  1157. }
  1158. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  1159. };
  1160. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  1161. if (handler.call({
  1162. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG),
  1163. error: (log) => parseAst_js.error(normalizeLog(log)),
  1164. info: getLogHandler(parseAst_js.LOGLEVEL_INFO),
  1165. meta: { rollupVersion: version, watchMode },
  1166. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN)
  1167. }, level, log) === false) {
  1168. return;
  1169. }
  1170. }
  1171. onLog(level, log);
  1172. };
  1173. return logger;
  1174. }
  1175. const commandAliases = {
  1176. c: 'config',
  1177. d: 'dir',
  1178. e: 'external',
  1179. f: 'format',
  1180. g: 'globals',
  1181. h: 'help',
  1182. i: 'input',
  1183. m: 'sourcemap',
  1184. n: 'name',
  1185. o: 'file',
  1186. p: 'plugin',
  1187. v: 'version',
  1188. w: 'watch'
  1189. };
  1190. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  1191. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  1192. const command = getCommandOptions(rawCommandOptions);
  1193. const plugins = await normalizePluginOption(config.plugins);
  1194. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  1195. const onLog = getOnLog(config, logLevel, printLog);
  1196. const log = getLogger(plugins, onLog, watchMode, logLevel);
  1197. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  1198. if (command.output) {
  1199. Object.assign(command, command.output);
  1200. }
  1201. const outputOptionsArray = ensureArray$1(config.output);
  1202. if (outputOptionsArray.length === 0)
  1203. outputOptionsArray.push({});
  1204. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  1205. warnUnknownOptions(command, [
  1206. ...Object.keys(inputOptions),
  1207. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  1208. ...Object.keys(commandAliases),
  1209. 'bundleConfigAsCjs',
  1210. 'config',
  1211. 'configImportAttributesKey',
  1212. 'configPlugin',
  1213. 'environment',
  1214. 'failAfterWarnings',
  1215. 'filterLogs',
  1216. 'forceExit',
  1217. 'plugin',
  1218. 'silent',
  1219. 'stdin',
  1220. 'waitForBundleInput'
  1221. ], 'CLI flags', log, /^_$|output$|config/);
  1222. inputOptions.output = outputOptions;
  1223. return inputOptions;
  1224. }
  1225. function getCommandOptions(rawCommandOptions) {
  1226. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  1227. ? rawCommandOptions.external.split(',')
  1228. : [];
  1229. return {
  1230. ...rawCommandOptions,
  1231. external,
  1232. globals: typeof rawCommandOptions.globals === 'string'
  1233. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  1234. const [id, variableName] = globalDefinition.split(':');
  1235. globals[id] = variableName;
  1236. if (!external.includes(id)) {
  1237. external.push(id);
  1238. }
  1239. return globals;
  1240. }, Object.create(null))
  1241. : undefined
  1242. };
  1243. }
  1244. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  1245. const getOption = (name) => overrides[name] ?? config[name];
  1246. const inputOptions = {
  1247. cache: config.cache,
  1248. context: getOption('context'),
  1249. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  1250. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  1251. external: getExternal(config, overrides),
  1252. input: getOption('input') || [],
  1253. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ')),
  1254. logLevel: getOption('logLevel'),
  1255. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  1256. maxParallelFileOps: getOption('maxParallelFileOps'),
  1257. moduleContext: getOption('moduleContext'),
  1258. onLog,
  1259. onwarn: undefined,
  1260. perf: getOption('perf'),
  1261. plugins,
  1262. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  1263. preserveSymlinks: getOption('preserveSymlinks'),
  1264. shimMissingExports: getOption('shimMissingExports'),
  1265. strictDeprecations: getOption('strictDeprecations'),
  1266. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ')),
  1267. watch: getWatch(config, overrides)
  1268. };
  1269. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  1270. return inputOptions;
  1271. }
  1272. const getExternal = (config, overrides) => {
  1273. const configExternal = config.external;
  1274. return typeof configExternal === 'function'
  1275. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  1276. : [...ensureArray$1(configExternal), ...overrides.external];
  1277. };
  1278. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  1279. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  1280. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  1281. if (commandOption !== undefined) {
  1282. return commandOption && { ...configOption, ...commandOption };
  1283. }
  1284. return configOption;
  1285. };
  1286. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  1287. const isWatchEnabled = (optionValue) => {
  1288. if (Array.isArray(optionValue)) {
  1289. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  1290. }
  1291. return optionValue === true;
  1292. };
  1293. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  1294. if (!optionValue) {
  1295. return optionValue;
  1296. }
  1297. if (Array.isArray(optionValue)) {
  1298. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  1299. }
  1300. return objectifyValue(optionValue);
  1301. };
  1302. async function mergeOutputOptions(config, overrides, log) {
  1303. const getOption = (name) => overrides[name] ?? config[name];
  1304. const outputOptions = {
  1305. amd: getObjectOption(config, overrides, 'amd'),
  1306. assetFileNames: getOption('assetFileNames'),
  1307. banner: getOption('banner'),
  1308. chunkFileNames: getOption('chunkFileNames'),
  1309. compact: getOption('compact'),
  1310. dir: getOption('dir'),
  1311. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  1312. entryFileNames: getOption('entryFileNames'),
  1313. esModule: getOption('esModule'),
  1314. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  1315. exports: getOption('exports'),
  1316. extend: getOption('extend'),
  1317. externalImportAssertions: getOption('externalImportAssertions'),
  1318. externalImportAttributes: getOption('externalImportAttributes'),
  1319. externalLiveBindings: getOption('externalLiveBindings'),
  1320. file: getOption('file'),
  1321. footer: getOption('footer'),
  1322. format: getOption('format'),
  1323. freeze: getOption('freeze'),
  1324. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '')),
  1325. globals: getOption('globals'),
  1326. hashCharacters: getOption('hashCharacters'),
  1327. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  1328. importAttributesKey: getOption('importAttributesKey'),
  1329. indent: getOption('indent'),
  1330. inlineDynamicImports: getOption('inlineDynamicImports'),
  1331. interop: getOption('interop'),
  1332. intro: getOption('intro'),
  1333. manualChunks: getOption('manualChunks'),
  1334. minifyInternalExports: getOption('minifyInternalExports'),
  1335. name: getOption('name'),
  1336. noConflict: getOption('noConflict'),
  1337. outro: getOption('outro'),
  1338. paths: getOption('paths'),
  1339. plugins: await normalizePluginOption(config.plugins),
  1340. preserveModules: getOption('preserveModules'),
  1341. preserveModulesRoot: getOption('preserveModulesRoot'),
  1342. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  1343. sanitizeFileName: getOption('sanitizeFileName'),
  1344. sourcemap: getOption('sourcemap'),
  1345. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  1346. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  1347. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  1348. sourcemapFile: getOption('sourcemapFile'),
  1349. sourcemapFileNames: getOption('sourcemapFileNames'),
  1350. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  1351. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  1352. strict: getOption('strict'),
  1353. systemNullSetters: getOption('systemNullSetters'),
  1354. validate: getOption('validate'),
  1355. virtualDirname: getOption('virtualDirname')
  1356. };
  1357. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  1358. return outputOptions;
  1359. }
  1360. function getDefaultExportFromCjs (x) {
  1361. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1362. }
  1363. function getAugmentedNamespace(n) {
  1364. if (n.__esModule) return n;
  1365. var f = n.default;
  1366. if (typeof f == "function") {
  1367. var a = function a () {
  1368. if (this instanceof a) {
  1369. return Reflect.construct(f, arguments, this.constructor);
  1370. }
  1371. return f.apply(this, arguments);
  1372. };
  1373. a.prototype = f.prototype;
  1374. } else a = {};
  1375. Object.defineProperty(a, '__esModule', {value: true});
  1376. Object.keys(n).forEach(function (k) {
  1377. var d = Object.getOwnPropertyDescriptor(n, k);
  1378. Object.defineProperty(a, k, d.get ? d : {
  1379. enumerable: true,
  1380. get: function () {
  1381. return n[k];
  1382. }
  1383. });
  1384. });
  1385. return a;
  1386. }
  1387. var picocolors = {exports: {}};
  1388. var hasRequiredPicocolors;
  1389. function requirePicocolors () {
  1390. if (hasRequiredPicocolors) return picocolors.exports;
  1391. hasRequiredPicocolors = 1;
  1392. let p = process || {}, argv = p.argv || [], env = p.env || {};
  1393. let isColorSupported =
  1394. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  1395. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  1396. let formatter = (open, close, replace = open) =>
  1397. input => {
  1398. let string = "" + input, index = string.indexOf(close, open.length);
  1399. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  1400. };
  1401. let replaceClose = (string, close, replace, index) => {
  1402. let result = "", cursor = 0;
  1403. do {
  1404. result += string.substring(cursor, index) + replace;
  1405. cursor = index + close.length;
  1406. index = string.indexOf(close, cursor);
  1407. } while (~index)
  1408. return result + string.substring(cursor)
  1409. };
  1410. let createColors = (enabled = isColorSupported) => {
  1411. let f = enabled ? formatter : () => String;
  1412. return {
  1413. isColorSupported: enabled,
  1414. reset: f("\x1b[0m", "\x1b[0m"),
  1415. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  1416. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  1417. italic: f("\x1b[3m", "\x1b[23m"),
  1418. underline: f("\x1b[4m", "\x1b[24m"),
  1419. inverse: f("\x1b[7m", "\x1b[27m"),
  1420. hidden: f("\x1b[8m", "\x1b[28m"),
  1421. strikethrough: f("\x1b[9m", "\x1b[29m"),
  1422. black: f("\x1b[30m", "\x1b[39m"),
  1423. red: f("\x1b[31m", "\x1b[39m"),
  1424. green: f("\x1b[32m", "\x1b[39m"),
  1425. yellow: f("\x1b[33m", "\x1b[39m"),
  1426. blue: f("\x1b[34m", "\x1b[39m"),
  1427. magenta: f("\x1b[35m", "\x1b[39m"),
  1428. cyan: f("\x1b[36m", "\x1b[39m"),
  1429. white: f("\x1b[37m", "\x1b[39m"),
  1430. gray: f("\x1b[90m", "\x1b[39m"),
  1431. bgBlack: f("\x1b[40m", "\x1b[49m"),
  1432. bgRed: f("\x1b[41m", "\x1b[49m"),
  1433. bgGreen: f("\x1b[42m", "\x1b[49m"),
  1434. bgYellow: f("\x1b[43m", "\x1b[49m"),
  1435. bgBlue: f("\x1b[44m", "\x1b[49m"),
  1436. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  1437. bgCyan: f("\x1b[46m", "\x1b[49m"),
  1438. bgWhite: f("\x1b[47m", "\x1b[49m"),
  1439. blackBright: f("\x1b[90m", "\x1b[39m"),
  1440. redBright: f("\x1b[91m", "\x1b[39m"),
  1441. greenBright: f("\x1b[92m", "\x1b[39m"),
  1442. yellowBright: f("\x1b[93m", "\x1b[39m"),
  1443. blueBright: f("\x1b[94m", "\x1b[39m"),
  1444. magentaBright: f("\x1b[95m", "\x1b[39m"),
  1445. cyanBright: f("\x1b[96m", "\x1b[39m"),
  1446. whiteBright: f("\x1b[97m", "\x1b[39m"),
  1447. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  1448. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  1449. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  1450. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  1451. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  1452. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  1453. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  1454. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  1455. }
  1456. };
  1457. picocolors.exports = createColors();
  1458. picocolors.exports.createColors = createColors;
  1459. return picocolors.exports;
  1460. }
  1461. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  1462. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  1463. // @see https://no-color.org
  1464. // @see https://www.npmjs.com/package/chalk
  1465. const { bold, cyan, dim, gray, green, red, underline, yellow } = pc.createColors(process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR);
  1466. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  1467. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  1468. function handleError(error, recover = false) {
  1469. const name = error.name || error.cause?.name;
  1470. const nameSection = name ? `${name}: ` : '';
  1471. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  1472. const message = `${pluginSection}${nameSection}${error.message}`;
  1473. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  1474. if (error.url) {
  1475. outputLines.push(cyan(error.url));
  1476. }
  1477. if (error.loc) {
  1478. outputLines.push(`${parseAst_js.relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  1479. }
  1480. else if (error.id) {
  1481. outputLines.push(parseAst_js.relativeId(error.id));
  1482. }
  1483. if (error.frame) {
  1484. outputLines.push(dim(error.frame));
  1485. }
  1486. if (error.stack) {
  1487. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  1488. }
  1489. // ES2022: Error.prototype.cause is optional
  1490. if (error.cause) {
  1491. let cause = error.cause;
  1492. const causeErrorLines = [];
  1493. let indent = '';
  1494. while (cause) {
  1495. indent += ' ';
  1496. const message = cause.stack || cause;
  1497. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  1498. cause = cause.cause;
  1499. }
  1500. outputLines.push(dim(causeErrorLines.join('\n')));
  1501. }
  1502. outputLines.push('', '');
  1503. stderr(outputLines.join('\n'));
  1504. if (!recover)
  1505. process$1.exit(1);
  1506. }
  1507. const comma = ','.charCodeAt(0);
  1508. const semicolon = ';'.charCodeAt(0);
  1509. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1510. const intToChar = new Uint8Array(64); // 64 possible chars.
  1511. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  1512. for (let i = 0; i < chars.length; i++) {
  1513. const c = chars.charCodeAt(i);
  1514. intToChar[i] = c;
  1515. charToInt[c] = i;
  1516. }
  1517. function decodeInteger(reader, relative) {
  1518. let value = 0;
  1519. let shift = 0;
  1520. let integer = 0;
  1521. do {
  1522. const c = reader.next();
  1523. integer = charToInt[c];
  1524. value |= (integer & 31) << shift;
  1525. shift += 5;
  1526. } while (integer & 32);
  1527. const shouldNegate = value & 1;
  1528. value >>>= 1;
  1529. if (shouldNegate) {
  1530. value = -2147483648 | -value;
  1531. }
  1532. return relative + value;
  1533. }
  1534. function encodeInteger(builder, num, relative) {
  1535. let delta = num - relative;
  1536. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  1537. do {
  1538. let clamped = delta & 0b011111;
  1539. delta >>>= 5;
  1540. if (delta > 0)
  1541. clamped |= 0b100000;
  1542. builder.write(intToChar[clamped]);
  1543. } while (delta > 0);
  1544. return num;
  1545. }
  1546. function hasMoreVlq(reader, max) {
  1547. if (reader.pos >= max)
  1548. return false;
  1549. return reader.peek() !== comma;
  1550. }
  1551. const bufLength = 1024 * 16;
  1552. // Provide a fallback for older environments.
  1553. const td = typeof TextDecoder !== 'undefined'
  1554. ? /* #__PURE__ */ new TextDecoder()
  1555. : typeof Buffer !== 'undefined'
  1556. ? {
  1557. decode(buf) {
  1558. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  1559. return out.toString();
  1560. },
  1561. }
  1562. : {
  1563. decode(buf) {
  1564. let out = '';
  1565. for (let i = 0; i < buf.length; i++) {
  1566. out += String.fromCharCode(buf[i]);
  1567. }
  1568. return out;
  1569. },
  1570. };
  1571. class StringWriter {
  1572. constructor() {
  1573. this.pos = 0;
  1574. this.out = '';
  1575. this.buffer = new Uint8Array(bufLength);
  1576. }
  1577. write(v) {
  1578. const { buffer } = this;
  1579. buffer[this.pos++] = v;
  1580. if (this.pos === bufLength) {
  1581. this.out += td.decode(buffer);
  1582. this.pos = 0;
  1583. }
  1584. }
  1585. flush() {
  1586. const { buffer, out, pos } = this;
  1587. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  1588. }
  1589. }
  1590. class StringReader {
  1591. constructor(buffer) {
  1592. this.pos = 0;
  1593. this.buffer = buffer;
  1594. }
  1595. next() {
  1596. return this.buffer.charCodeAt(this.pos++);
  1597. }
  1598. peek() {
  1599. return this.buffer.charCodeAt(this.pos);
  1600. }
  1601. indexOf(char) {
  1602. const { buffer, pos } = this;
  1603. const idx = buffer.indexOf(char, pos);
  1604. return idx === -1 ? buffer.length : idx;
  1605. }
  1606. }
  1607. function decode(mappings) {
  1608. const { length } = mappings;
  1609. const reader = new StringReader(mappings);
  1610. const decoded = [];
  1611. let genColumn = 0;
  1612. let sourcesIndex = 0;
  1613. let sourceLine = 0;
  1614. let sourceColumn = 0;
  1615. let namesIndex = 0;
  1616. do {
  1617. const semi = reader.indexOf(';');
  1618. const line = [];
  1619. let sorted = true;
  1620. let lastCol = 0;
  1621. genColumn = 0;
  1622. while (reader.pos < semi) {
  1623. let seg;
  1624. genColumn = decodeInteger(reader, genColumn);
  1625. if (genColumn < lastCol)
  1626. sorted = false;
  1627. lastCol = genColumn;
  1628. if (hasMoreVlq(reader, semi)) {
  1629. sourcesIndex = decodeInteger(reader, sourcesIndex);
  1630. sourceLine = decodeInteger(reader, sourceLine);
  1631. sourceColumn = decodeInteger(reader, sourceColumn);
  1632. if (hasMoreVlq(reader, semi)) {
  1633. namesIndex = decodeInteger(reader, namesIndex);
  1634. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  1635. }
  1636. else {
  1637. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  1638. }
  1639. }
  1640. else {
  1641. seg = [genColumn];
  1642. }
  1643. line.push(seg);
  1644. reader.pos++;
  1645. }
  1646. if (!sorted)
  1647. sort(line);
  1648. decoded.push(line);
  1649. reader.pos = semi + 1;
  1650. } while (reader.pos <= length);
  1651. return decoded;
  1652. }
  1653. function sort(line) {
  1654. line.sort(sortComparator);
  1655. }
  1656. function sortComparator(a, b) {
  1657. return a[0] - b[0];
  1658. }
  1659. function encode(decoded) {
  1660. const writer = new StringWriter();
  1661. let sourcesIndex = 0;
  1662. let sourceLine = 0;
  1663. let sourceColumn = 0;
  1664. let namesIndex = 0;
  1665. for (let i = 0; i < decoded.length; i++) {
  1666. const line = decoded[i];
  1667. if (i > 0)
  1668. writer.write(semicolon);
  1669. if (line.length === 0)
  1670. continue;
  1671. let genColumn = 0;
  1672. for (let j = 0; j < line.length; j++) {
  1673. const segment = line[j];
  1674. if (j > 0)
  1675. writer.write(comma);
  1676. genColumn = encodeInteger(writer, segment[0], genColumn);
  1677. if (segment.length === 1)
  1678. continue;
  1679. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  1680. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  1681. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  1682. if (segment.length === 4)
  1683. continue;
  1684. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  1685. }
  1686. }
  1687. return writer.flush();
  1688. }
  1689. class BitSet {
  1690. constructor(arg) {
  1691. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  1692. }
  1693. add(n) {
  1694. this.bits[n >> 5] |= 1 << (n & 31);
  1695. }
  1696. has(n) {
  1697. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  1698. }
  1699. }
  1700. let Chunk$1 = class Chunk {
  1701. constructor(start, end, content) {
  1702. this.start = start;
  1703. this.end = end;
  1704. this.original = content;
  1705. this.intro = '';
  1706. this.outro = '';
  1707. this.content = content;
  1708. this.storeName = false;
  1709. this.edited = false;
  1710. {
  1711. this.previous = null;
  1712. this.next = null;
  1713. }
  1714. }
  1715. appendLeft(content) {
  1716. this.outro += content;
  1717. }
  1718. appendRight(content) {
  1719. this.intro = this.intro + content;
  1720. }
  1721. clone() {
  1722. const chunk = new Chunk(this.start, this.end, this.original);
  1723. chunk.intro = this.intro;
  1724. chunk.outro = this.outro;
  1725. chunk.content = this.content;
  1726. chunk.storeName = this.storeName;
  1727. chunk.edited = this.edited;
  1728. return chunk;
  1729. }
  1730. contains(index) {
  1731. return this.start < index && index < this.end;
  1732. }
  1733. eachNext(fn) {
  1734. let chunk = this;
  1735. while (chunk) {
  1736. fn(chunk);
  1737. chunk = chunk.next;
  1738. }
  1739. }
  1740. eachPrevious(fn) {
  1741. let chunk = this;
  1742. while (chunk) {
  1743. fn(chunk);
  1744. chunk = chunk.previous;
  1745. }
  1746. }
  1747. edit(content, storeName, contentOnly) {
  1748. this.content = content;
  1749. if (!contentOnly) {
  1750. this.intro = '';
  1751. this.outro = '';
  1752. }
  1753. this.storeName = storeName;
  1754. this.edited = true;
  1755. return this;
  1756. }
  1757. prependLeft(content) {
  1758. this.outro = content + this.outro;
  1759. }
  1760. prependRight(content) {
  1761. this.intro = content + this.intro;
  1762. }
  1763. reset() {
  1764. this.intro = '';
  1765. this.outro = '';
  1766. if (this.edited) {
  1767. this.content = this.original;
  1768. this.storeName = false;
  1769. this.edited = false;
  1770. }
  1771. }
  1772. split(index) {
  1773. const sliceIndex = index - this.start;
  1774. const originalBefore = this.original.slice(0, sliceIndex);
  1775. const originalAfter = this.original.slice(sliceIndex);
  1776. this.original = originalBefore;
  1777. const newChunk = new Chunk(index, this.end, originalAfter);
  1778. newChunk.outro = this.outro;
  1779. this.outro = '';
  1780. this.end = index;
  1781. if (this.edited) {
  1782. // after split we should save the edit content record into the correct chunk
  1783. // to make sure sourcemap correct
  1784. // For example:
  1785. // ' test'.trim()
  1786. // split -> ' ' + 'test'
  1787. // ✔️ edit -> '' + 'test'
  1788. // ✖️ edit -> 'test' + ''
  1789. // TODO is this block necessary?...
  1790. newChunk.edit('', false);
  1791. this.content = '';
  1792. } else {
  1793. this.content = originalBefore;
  1794. }
  1795. newChunk.next = this.next;
  1796. if (newChunk.next) newChunk.next.previous = newChunk;
  1797. newChunk.previous = this;
  1798. this.next = newChunk;
  1799. return newChunk;
  1800. }
  1801. toString() {
  1802. return this.intro + this.content + this.outro;
  1803. }
  1804. trimEnd(rx) {
  1805. this.outro = this.outro.replace(rx, '');
  1806. if (this.outro.length) return true;
  1807. const trimmed = this.content.replace(rx, '');
  1808. if (trimmed.length) {
  1809. if (trimmed !== this.content) {
  1810. this.split(this.start + trimmed.length).edit('', undefined, true);
  1811. if (this.edited) {
  1812. // save the change, if it has been edited
  1813. this.edit(trimmed, this.storeName, true);
  1814. }
  1815. }
  1816. return true;
  1817. } else {
  1818. this.edit('', undefined, true);
  1819. this.intro = this.intro.replace(rx, '');
  1820. if (this.intro.length) return true;
  1821. }
  1822. }
  1823. trimStart(rx) {
  1824. this.intro = this.intro.replace(rx, '');
  1825. if (this.intro.length) return true;
  1826. const trimmed = this.content.replace(rx, '');
  1827. if (trimmed.length) {
  1828. if (trimmed !== this.content) {
  1829. const newChunk = this.split(this.end - trimmed.length);
  1830. if (this.edited) {
  1831. // save the change, if it has been edited
  1832. newChunk.edit(trimmed, this.storeName, true);
  1833. }
  1834. this.edit('', undefined, true);
  1835. }
  1836. return true;
  1837. } else {
  1838. this.edit('', undefined, true);
  1839. this.outro = this.outro.replace(rx, '');
  1840. if (this.outro.length) return true;
  1841. }
  1842. }
  1843. };
  1844. function getBtoa() {
  1845. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  1846. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  1847. } else if (typeof Buffer === 'function') {
  1848. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  1849. } else {
  1850. return () => {
  1851. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  1852. };
  1853. }
  1854. }
  1855. const btoa = /*#__PURE__*/ getBtoa();
  1856. class SourceMap {
  1857. constructor(properties) {
  1858. this.version = 3;
  1859. this.file = properties.file;
  1860. this.sources = properties.sources;
  1861. this.sourcesContent = properties.sourcesContent;
  1862. this.names = properties.names;
  1863. this.mappings = encode(properties.mappings);
  1864. if (typeof properties.x_google_ignoreList !== 'undefined') {
  1865. this.x_google_ignoreList = properties.x_google_ignoreList;
  1866. }
  1867. if (typeof properties.debugId !== 'undefined') {
  1868. this.debugId = properties.debugId;
  1869. }
  1870. }
  1871. toString() {
  1872. return JSON.stringify(this);
  1873. }
  1874. toUrl() {
  1875. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  1876. }
  1877. }
  1878. function guessIndent(code) {
  1879. const lines = code.split('\n');
  1880. const tabbed = lines.filter((line) => /^\t+/.test(line));
  1881. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  1882. if (tabbed.length === 0 && spaced.length === 0) {
  1883. return null;
  1884. }
  1885. // More lines tabbed than spaced? Assume tabs, and
  1886. // default to tabs in the case of a tie (or nothing
  1887. // to go on)
  1888. if (tabbed.length >= spaced.length) {
  1889. return '\t';
  1890. }
  1891. // Otherwise, we need to guess the multiple
  1892. const min = spaced.reduce((previous, current) => {
  1893. const numSpaces = /^ +/.exec(current)[0].length;
  1894. return Math.min(numSpaces, previous);
  1895. }, Infinity);
  1896. return new Array(min + 1).join(' ');
  1897. }
  1898. function getRelativePath(from, to) {
  1899. const fromParts = from.split(/[/\\]/);
  1900. const toParts = to.split(/[/\\]/);
  1901. fromParts.pop(); // get dirname
  1902. while (fromParts[0] === toParts[0]) {
  1903. fromParts.shift();
  1904. toParts.shift();
  1905. }
  1906. if (fromParts.length) {
  1907. let i = fromParts.length;
  1908. while (i--) fromParts[i] = '..';
  1909. }
  1910. return fromParts.concat(toParts).join('/');
  1911. }
  1912. const toString = Object.prototype.toString;
  1913. function isObject(thing) {
  1914. return toString.call(thing) === '[object Object]';
  1915. }
  1916. function getLocator(source) {
  1917. const originalLines = source.split('\n');
  1918. const lineOffsets = [];
  1919. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  1920. lineOffsets.push(pos);
  1921. pos += originalLines[i].length + 1;
  1922. }
  1923. return function locate(index) {
  1924. let i = 0;
  1925. let j = lineOffsets.length;
  1926. while (i < j) {
  1927. const m = (i + j) >> 1;
  1928. if (index < lineOffsets[m]) {
  1929. j = m;
  1930. } else {
  1931. i = m + 1;
  1932. }
  1933. }
  1934. const line = i - 1;
  1935. const column = index - lineOffsets[line];
  1936. return { line, column };
  1937. };
  1938. }
  1939. const wordRegex = /\w/;
  1940. class Mappings {
  1941. constructor(hires) {
  1942. this.hires = hires;
  1943. this.generatedCodeLine = 0;
  1944. this.generatedCodeColumn = 0;
  1945. this.raw = [];
  1946. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1947. this.pending = null;
  1948. }
  1949. addEdit(sourceIndex, content, loc, nameIndex) {
  1950. if (content.length) {
  1951. const contentLengthMinusOne = content.length - 1;
  1952. let contentLineEnd = content.indexOf('\n', 0);
  1953. let previousContentLineEnd = -1;
  1954. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  1955. // else code afterwards would fill one line too many
  1956. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  1957. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1958. if (nameIndex >= 0) {
  1959. segment.push(nameIndex);
  1960. }
  1961. this.rawSegments.push(segment);
  1962. this.generatedCodeLine += 1;
  1963. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1964. this.generatedCodeColumn = 0;
  1965. previousContentLineEnd = contentLineEnd;
  1966. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  1967. }
  1968. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1969. if (nameIndex >= 0) {
  1970. segment.push(nameIndex);
  1971. }
  1972. this.rawSegments.push(segment);
  1973. this.advance(content.slice(previousContentLineEnd + 1));
  1974. } else if (this.pending) {
  1975. this.rawSegments.push(this.pending);
  1976. this.advance(content);
  1977. }
  1978. this.pending = null;
  1979. }
  1980. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1981. let originalCharIndex = chunk.start;
  1982. let first = true;
  1983. // when iterating each char, check if it's in a word boundary
  1984. let charInHiresBoundary = false;
  1985. while (originalCharIndex < chunk.end) {
  1986. if (original[originalCharIndex] === '\n') {
  1987. loc.line += 1;
  1988. loc.column = 0;
  1989. this.generatedCodeLine += 1;
  1990. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1991. this.generatedCodeColumn = 0;
  1992. first = true;
  1993. charInHiresBoundary = false;
  1994. } else {
  1995. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1996. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1997. if (this.hires === 'boundary') {
  1998. // in hires "boundary", group segments per word boundary than per char
  1999. if (wordRegex.test(original[originalCharIndex])) {
  2000. // for first char in the boundary found, start the boundary by pushing a segment
  2001. if (!charInHiresBoundary) {
  2002. this.rawSegments.push(segment);
  2003. charInHiresBoundary = true;
  2004. }
  2005. } else {
  2006. // for non-word char, end the boundary by pushing a segment
  2007. this.rawSegments.push(segment);
  2008. charInHiresBoundary = false;
  2009. }
  2010. } else {
  2011. this.rawSegments.push(segment);
  2012. }
  2013. }
  2014. loc.column += 1;
  2015. this.generatedCodeColumn += 1;
  2016. first = false;
  2017. }
  2018. originalCharIndex += 1;
  2019. }
  2020. this.pending = null;
  2021. }
  2022. advance(str) {
  2023. if (!str) return;
  2024. const lines = str.split('\n');
  2025. if (lines.length > 1) {
  2026. for (let i = 0; i < lines.length - 1; i++) {
  2027. this.generatedCodeLine++;
  2028. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2029. }
  2030. this.generatedCodeColumn = 0;
  2031. }
  2032. this.generatedCodeColumn += lines[lines.length - 1].length;
  2033. }
  2034. }
  2035. const n = '\n';
  2036. const warned = {
  2037. insertLeft: false,
  2038. insertRight: false,
  2039. storeName: false,
  2040. };
  2041. class MagicString {
  2042. constructor(string, options = {}) {
  2043. const chunk = new Chunk$1(0, string.length, string);
  2044. Object.defineProperties(this, {
  2045. original: { writable: true, value: string },
  2046. outro: { writable: true, value: '' },
  2047. intro: { writable: true, value: '' },
  2048. firstChunk: { writable: true, value: chunk },
  2049. lastChunk: { writable: true, value: chunk },
  2050. lastSearchedChunk: { writable: true, value: chunk },
  2051. byStart: { writable: true, value: {} },
  2052. byEnd: { writable: true, value: {} },
  2053. filename: { writable: true, value: options.filename },
  2054. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  2055. sourcemapLocations: { writable: true, value: new BitSet() },
  2056. storedNames: { writable: true, value: {} },
  2057. indentStr: { writable: true, value: undefined },
  2058. ignoreList: { writable: true, value: options.ignoreList },
  2059. offset: { writable: true, value: options.offset || 0 },
  2060. });
  2061. this.byStart[0] = chunk;
  2062. this.byEnd[string.length] = chunk;
  2063. }
  2064. addSourcemapLocation(char) {
  2065. this.sourcemapLocations.add(char);
  2066. }
  2067. append(content) {
  2068. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2069. this.outro += content;
  2070. return this;
  2071. }
  2072. appendLeft(index, content) {
  2073. index = index + this.offset;
  2074. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2075. this._split(index);
  2076. const chunk = this.byEnd[index];
  2077. if (chunk) {
  2078. chunk.appendLeft(content);
  2079. } else {
  2080. this.intro += content;
  2081. }
  2082. return this;
  2083. }
  2084. appendRight(index, content) {
  2085. index = index + this.offset;
  2086. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2087. this._split(index);
  2088. const chunk = this.byStart[index];
  2089. if (chunk) {
  2090. chunk.appendRight(content);
  2091. } else {
  2092. this.outro += content;
  2093. }
  2094. return this;
  2095. }
  2096. clone() {
  2097. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  2098. let originalChunk = this.firstChunk;
  2099. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  2100. while (originalChunk) {
  2101. cloned.byStart[clonedChunk.start] = clonedChunk;
  2102. cloned.byEnd[clonedChunk.end] = clonedChunk;
  2103. const nextOriginalChunk = originalChunk.next;
  2104. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  2105. if (nextClonedChunk) {
  2106. clonedChunk.next = nextClonedChunk;
  2107. nextClonedChunk.previous = clonedChunk;
  2108. clonedChunk = nextClonedChunk;
  2109. }
  2110. originalChunk = nextOriginalChunk;
  2111. }
  2112. cloned.lastChunk = clonedChunk;
  2113. if (this.indentExclusionRanges) {
  2114. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  2115. }
  2116. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  2117. cloned.intro = this.intro;
  2118. cloned.outro = this.outro;
  2119. return cloned;
  2120. }
  2121. generateDecodedMap(options) {
  2122. options = options || {};
  2123. const sourceIndex = 0;
  2124. const names = Object.keys(this.storedNames);
  2125. const mappings = new Mappings(options.hires);
  2126. const locate = getLocator(this.original);
  2127. if (this.intro) {
  2128. mappings.advance(this.intro);
  2129. }
  2130. this.firstChunk.eachNext((chunk) => {
  2131. const loc = locate(chunk.start);
  2132. if (chunk.intro.length) mappings.advance(chunk.intro);
  2133. if (chunk.edited) {
  2134. mappings.addEdit(
  2135. sourceIndex,
  2136. chunk.content,
  2137. loc,
  2138. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2139. );
  2140. } else {
  2141. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  2142. }
  2143. if (chunk.outro.length) mappings.advance(chunk.outro);
  2144. });
  2145. return {
  2146. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2147. sources: [
  2148. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  2149. ],
  2150. sourcesContent: options.includeContent ? [this.original] : undefined,
  2151. names,
  2152. mappings: mappings.raw,
  2153. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  2154. };
  2155. }
  2156. generateMap(options) {
  2157. return new SourceMap(this.generateDecodedMap(options));
  2158. }
  2159. _ensureindentStr() {
  2160. if (this.indentStr === undefined) {
  2161. this.indentStr = guessIndent(this.original);
  2162. }
  2163. }
  2164. _getRawIndentString() {
  2165. this._ensureindentStr();
  2166. return this.indentStr;
  2167. }
  2168. getIndentString() {
  2169. this._ensureindentStr();
  2170. return this.indentStr === null ? '\t' : this.indentStr;
  2171. }
  2172. indent(indentStr, options) {
  2173. const pattern = /^[^\r\n]/gm;
  2174. if (isObject(indentStr)) {
  2175. options = indentStr;
  2176. indentStr = undefined;
  2177. }
  2178. if (indentStr === undefined) {
  2179. this._ensureindentStr();
  2180. indentStr = this.indentStr || '\t';
  2181. }
  2182. if (indentStr === '') return this; // noop
  2183. options = options || {};
  2184. // Process exclusion ranges
  2185. const isExcluded = {};
  2186. if (options.exclude) {
  2187. const exclusions =
  2188. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  2189. exclusions.forEach((exclusion) => {
  2190. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  2191. isExcluded[i] = true;
  2192. }
  2193. });
  2194. }
  2195. let shouldIndentNextCharacter = options.indentStart !== false;
  2196. const replacer = (match) => {
  2197. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  2198. shouldIndentNextCharacter = true;
  2199. return match;
  2200. };
  2201. this.intro = this.intro.replace(pattern, replacer);
  2202. let charIndex = 0;
  2203. let chunk = this.firstChunk;
  2204. while (chunk) {
  2205. const end = chunk.end;
  2206. if (chunk.edited) {
  2207. if (!isExcluded[charIndex]) {
  2208. chunk.content = chunk.content.replace(pattern, replacer);
  2209. if (chunk.content.length) {
  2210. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  2211. }
  2212. }
  2213. } else {
  2214. charIndex = chunk.start;
  2215. while (charIndex < end) {
  2216. if (!isExcluded[charIndex]) {
  2217. const char = this.original[charIndex];
  2218. if (char === '\n') {
  2219. shouldIndentNextCharacter = true;
  2220. } else if (char !== '\r' && shouldIndentNextCharacter) {
  2221. shouldIndentNextCharacter = false;
  2222. if (charIndex === chunk.start) {
  2223. chunk.prependRight(indentStr);
  2224. } else {
  2225. this._splitChunk(chunk, charIndex);
  2226. chunk = chunk.next;
  2227. chunk.prependRight(indentStr);
  2228. }
  2229. }
  2230. }
  2231. charIndex += 1;
  2232. }
  2233. }
  2234. charIndex = chunk.end;
  2235. chunk = chunk.next;
  2236. }
  2237. this.outro = this.outro.replace(pattern, replacer);
  2238. return this;
  2239. }
  2240. insert() {
  2241. throw new Error(
  2242. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  2243. );
  2244. }
  2245. insertLeft(index, content) {
  2246. if (!warned.insertLeft) {
  2247. console.warn(
  2248. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  2249. );
  2250. warned.insertLeft = true;
  2251. }
  2252. return this.appendLeft(index, content);
  2253. }
  2254. insertRight(index, content) {
  2255. if (!warned.insertRight) {
  2256. console.warn(
  2257. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  2258. );
  2259. warned.insertRight = true;
  2260. }
  2261. return this.prependRight(index, content);
  2262. }
  2263. move(start, end, index) {
  2264. start = start + this.offset;
  2265. end = end + this.offset;
  2266. index = index + this.offset;
  2267. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  2268. this._split(start);
  2269. this._split(end);
  2270. this._split(index);
  2271. const first = this.byStart[start];
  2272. const last = this.byEnd[end];
  2273. const oldLeft = first.previous;
  2274. const oldRight = last.next;
  2275. const newRight = this.byStart[index];
  2276. if (!newRight && last === this.lastChunk) return this;
  2277. const newLeft = newRight ? newRight.previous : this.lastChunk;
  2278. if (oldLeft) oldLeft.next = oldRight;
  2279. if (oldRight) oldRight.previous = oldLeft;
  2280. if (newLeft) newLeft.next = first;
  2281. if (newRight) newRight.previous = last;
  2282. if (!first.previous) this.firstChunk = last.next;
  2283. if (!last.next) {
  2284. this.lastChunk = first.previous;
  2285. this.lastChunk.next = null;
  2286. }
  2287. first.previous = newLeft;
  2288. last.next = newRight || null;
  2289. if (!newLeft) this.firstChunk = first;
  2290. if (!newRight) this.lastChunk = last;
  2291. return this;
  2292. }
  2293. overwrite(start, end, content, options) {
  2294. options = options || {};
  2295. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  2296. }
  2297. update(start, end, content, options) {
  2298. start = start + this.offset;
  2299. end = end + this.offset;
  2300. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  2301. if (this.original.length !== 0) {
  2302. while (start < 0) start += this.original.length;
  2303. while (end < 0) end += this.original.length;
  2304. }
  2305. if (end > this.original.length) throw new Error('end is out of bounds');
  2306. if (start === end)
  2307. throw new Error(
  2308. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  2309. );
  2310. this._split(start);
  2311. this._split(end);
  2312. if (options === true) {
  2313. if (!warned.storeName) {
  2314. console.warn(
  2315. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  2316. );
  2317. warned.storeName = true;
  2318. }
  2319. options = { storeName: true };
  2320. }
  2321. const storeName = options !== undefined ? options.storeName : false;
  2322. const overwrite = options !== undefined ? options.overwrite : false;
  2323. if (storeName) {
  2324. const original = this.original.slice(start, end);
  2325. Object.defineProperty(this.storedNames, original, {
  2326. writable: true,
  2327. value: true,
  2328. enumerable: true,
  2329. });
  2330. }
  2331. const first = this.byStart[start];
  2332. const last = this.byEnd[end];
  2333. if (first) {
  2334. let chunk = first;
  2335. while (chunk !== last) {
  2336. if (chunk.next !== this.byStart[chunk.end]) {
  2337. throw new Error('Cannot overwrite across a split point');
  2338. }
  2339. chunk = chunk.next;
  2340. chunk.edit('', false);
  2341. }
  2342. first.edit(content, storeName, !overwrite);
  2343. } else {
  2344. // must be inserting at the end
  2345. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  2346. // TODO last chunk in the array may not be the last chunk, if it's moved...
  2347. last.next = newChunk;
  2348. newChunk.previous = last;
  2349. }
  2350. return this;
  2351. }
  2352. prepend(content) {
  2353. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2354. this.intro = content + this.intro;
  2355. return this;
  2356. }
  2357. prependLeft(index, content) {
  2358. index = index + this.offset;
  2359. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2360. this._split(index);
  2361. const chunk = this.byEnd[index];
  2362. if (chunk) {
  2363. chunk.prependLeft(content);
  2364. } else {
  2365. this.intro = content + this.intro;
  2366. }
  2367. return this;
  2368. }
  2369. prependRight(index, content) {
  2370. index = index + this.offset;
  2371. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2372. this._split(index);
  2373. const chunk = this.byStart[index];
  2374. if (chunk) {
  2375. chunk.prependRight(content);
  2376. } else {
  2377. this.outro = content + this.outro;
  2378. }
  2379. return this;
  2380. }
  2381. remove(start, end) {
  2382. start = start + this.offset;
  2383. end = end + this.offset;
  2384. if (this.original.length !== 0) {
  2385. while (start < 0) start += this.original.length;
  2386. while (end < 0) end += this.original.length;
  2387. }
  2388. if (start === end) return this;
  2389. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2390. if (start > end) throw new Error('end must be greater than start');
  2391. this._split(start);
  2392. this._split(end);
  2393. let chunk = this.byStart[start];
  2394. while (chunk) {
  2395. chunk.intro = '';
  2396. chunk.outro = '';
  2397. chunk.edit('');
  2398. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2399. }
  2400. return this;
  2401. }
  2402. reset(start, end) {
  2403. start = start + this.offset;
  2404. end = end + this.offset;
  2405. if (this.original.length !== 0) {
  2406. while (start < 0) start += this.original.length;
  2407. while (end < 0) end += this.original.length;
  2408. }
  2409. if (start === end) return this;
  2410. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2411. if (start > end) throw new Error('end must be greater than start');
  2412. this._split(start);
  2413. this._split(end);
  2414. let chunk = this.byStart[start];
  2415. while (chunk) {
  2416. chunk.reset();
  2417. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2418. }
  2419. return this;
  2420. }
  2421. lastChar() {
  2422. if (this.outro.length) return this.outro[this.outro.length - 1];
  2423. let chunk = this.lastChunk;
  2424. do {
  2425. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  2426. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  2427. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  2428. } while ((chunk = chunk.previous));
  2429. if (this.intro.length) return this.intro[this.intro.length - 1];
  2430. return '';
  2431. }
  2432. lastLine() {
  2433. let lineIndex = this.outro.lastIndexOf(n);
  2434. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  2435. let lineStr = this.outro;
  2436. let chunk = this.lastChunk;
  2437. do {
  2438. if (chunk.outro.length > 0) {
  2439. lineIndex = chunk.outro.lastIndexOf(n);
  2440. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  2441. lineStr = chunk.outro + lineStr;
  2442. }
  2443. if (chunk.content.length > 0) {
  2444. lineIndex = chunk.content.lastIndexOf(n);
  2445. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  2446. lineStr = chunk.content + lineStr;
  2447. }
  2448. if (chunk.intro.length > 0) {
  2449. lineIndex = chunk.intro.lastIndexOf(n);
  2450. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  2451. lineStr = chunk.intro + lineStr;
  2452. }
  2453. } while ((chunk = chunk.previous));
  2454. lineIndex = this.intro.lastIndexOf(n);
  2455. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  2456. return this.intro + lineStr;
  2457. }
  2458. slice(start = 0, end = this.original.length - this.offset) {
  2459. start = start + this.offset;
  2460. end = end + this.offset;
  2461. if (this.original.length !== 0) {
  2462. while (start < 0) start += this.original.length;
  2463. while (end < 0) end += this.original.length;
  2464. }
  2465. let result = '';
  2466. // find start chunk
  2467. let chunk = this.firstChunk;
  2468. while (chunk && (chunk.start > start || chunk.end <= start)) {
  2469. // found end chunk before start
  2470. if (chunk.start < end && chunk.end >= end) {
  2471. return result;
  2472. }
  2473. chunk = chunk.next;
  2474. }
  2475. if (chunk && chunk.edited && chunk.start !== start)
  2476. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  2477. const startChunk = chunk;
  2478. while (chunk) {
  2479. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  2480. result += chunk.intro;
  2481. }
  2482. const containsEnd = chunk.start < end && chunk.end >= end;
  2483. if (containsEnd && chunk.edited && chunk.end !== end)
  2484. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  2485. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  2486. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  2487. result += chunk.content.slice(sliceStart, sliceEnd);
  2488. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  2489. result += chunk.outro;
  2490. }
  2491. if (containsEnd) {
  2492. break;
  2493. }
  2494. chunk = chunk.next;
  2495. }
  2496. return result;
  2497. }
  2498. // TODO deprecate this? not really very useful
  2499. snip(start, end) {
  2500. const clone = this.clone();
  2501. clone.remove(0, start);
  2502. clone.remove(end, clone.original.length);
  2503. return clone;
  2504. }
  2505. _split(index) {
  2506. if (this.byStart[index] || this.byEnd[index]) return;
  2507. let chunk = this.lastSearchedChunk;
  2508. const searchForward = index > chunk.end;
  2509. while (chunk) {
  2510. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  2511. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  2512. }
  2513. }
  2514. _splitChunk(chunk, index) {
  2515. if (chunk.edited && chunk.content.length) {
  2516. // zero-length edited chunks are a special case (overlapping replacements)
  2517. const loc = getLocator(this.original)(index);
  2518. throw new Error(
  2519. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  2520. );
  2521. }
  2522. const newChunk = chunk.split(index);
  2523. this.byEnd[index] = chunk;
  2524. this.byStart[index] = newChunk;
  2525. this.byEnd[newChunk.end] = newChunk;
  2526. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  2527. this.lastSearchedChunk = chunk;
  2528. return true;
  2529. }
  2530. toString() {
  2531. let str = this.intro;
  2532. let chunk = this.firstChunk;
  2533. while (chunk) {
  2534. str += chunk.toString();
  2535. chunk = chunk.next;
  2536. }
  2537. return str + this.outro;
  2538. }
  2539. isEmpty() {
  2540. let chunk = this.firstChunk;
  2541. do {
  2542. if (
  2543. (chunk.intro.length && chunk.intro.trim()) ||
  2544. (chunk.content.length && chunk.content.trim()) ||
  2545. (chunk.outro.length && chunk.outro.trim())
  2546. )
  2547. return false;
  2548. } while ((chunk = chunk.next));
  2549. return true;
  2550. }
  2551. length() {
  2552. let chunk = this.firstChunk;
  2553. let length = 0;
  2554. do {
  2555. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  2556. } while ((chunk = chunk.next));
  2557. return length;
  2558. }
  2559. trimLines() {
  2560. return this.trim('[\\r\\n]');
  2561. }
  2562. trim(charType) {
  2563. return this.trimStart(charType).trimEnd(charType);
  2564. }
  2565. trimEndAborted(charType) {
  2566. const rx = new RegExp((charType || '\\s') + '+$');
  2567. this.outro = this.outro.replace(rx, '');
  2568. if (this.outro.length) return true;
  2569. let chunk = this.lastChunk;
  2570. do {
  2571. const end = chunk.end;
  2572. const aborted = chunk.trimEnd(rx);
  2573. // if chunk was trimmed, we have a new lastChunk
  2574. if (chunk.end !== end) {
  2575. if (this.lastChunk === chunk) {
  2576. this.lastChunk = chunk.next;
  2577. }
  2578. this.byEnd[chunk.end] = chunk;
  2579. this.byStart[chunk.next.start] = chunk.next;
  2580. this.byEnd[chunk.next.end] = chunk.next;
  2581. }
  2582. if (aborted) return true;
  2583. chunk = chunk.previous;
  2584. } while (chunk);
  2585. return false;
  2586. }
  2587. trimEnd(charType) {
  2588. this.trimEndAborted(charType);
  2589. return this;
  2590. }
  2591. trimStartAborted(charType) {
  2592. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2593. this.intro = this.intro.replace(rx, '');
  2594. if (this.intro.length) return true;
  2595. let chunk = this.firstChunk;
  2596. do {
  2597. const end = chunk.end;
  2598. const aborted = chunk.trimStart(rx);
  2599. if (chunk.end !== end) {
  2600. // special case...
  2601. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  2602. this.byEnd[chunk.end] = chunk;
  2603. this.byStart[chunk.next.start] = chunk.next;
  2604. this.byEnd[chunk.next.end] = chunk.next;
  2605. }
  2606. if (aborted) return true;
  2607. chunk = chunk.next;
  2608. } while (chunk);
  2609. return false;
  2610. }
  2611. trimStart(charType) {
  2612. this.trimStartAborted(charType);
  2613. return this;
  2614. }
  2615. hasChanged() {
  2616. return this.original !== this.toString();
  2617. }
  2618. _replaceRegexp(searchValue, replacement) {
  2619. function getReplacement(match, str) {
  2620. if (typeof replacement === 'string') {
  2621. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  2622. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  2623. if (i === '$') return '$';
  2624. if (i === '&') return match[0];
  2625. const num = +i;
  2626. if (num < match.length) return match[+i];
  2627. return `$${i}`;
  2628. });
  2629. } else {
  2630. return replacement(...match, match.index, str, match.groups);
  2631. }
  2632. }
  2633. function matchAll(re, str) {
  2634. let match;
  2635. const matches = [];
  2636. while ((match = re.exec(str))) {
  2637. matches.push(match);
  2638. }
  2639. return matches;
  2640. }
  2641. if (searchValue.global) {
  2642. const matches = matchAll(searchValue, this.original);
  2643. matches.forEach((match) => {
  2644. if (match.index != null) {
  2645. const replacement = getReplacement(match, this.original);
  2646. if (replacement !== match[0]) {
  2647. this.overwrite(match.index, match.index + match[0].length, replacement);
  2648. }
  2649. }
  2650. });
  2651. } else {
  2652. const match = this.original.match(searchValue);
  2653. if (match && match.index != null) {
  2654. const replacement = getReplacement(match, this.original);
  2655. if (replacement !== match[0]) {
  2656. this.overwrite(match.index, match.index + match[0].length, replacement);
  2657. }
  2658. }
  2659. }
  2660. return this;
  2661. }
  2662. _replaceString(string, replacement) {
  2663. const { original } = this;
  2664. const index = original.indexOf(string);
  2665. if (index !== -1) {
  2666. this.overwrite(index, index + string.length, replacement);
  2667. }
  2668. return this;
  2669. }
  2670. replace(searchValue, replacement) {
  2671. if (typeof searchValue === 'string') {
  2672. return this._replaceString(searchValue, replacement);
  2673. }
  2674. return this._replaceRegexp(searchValue, replacement);
  2675. }
  2676. _replaceAllString(string, replacement) {
  2677. const { original } = this;
  2678. const stringLength = string.length;
  2679. for (
  2680. let index = original.indexOf(string);
  2681. index !== -1;
  2682. index = original.indexOf(string, index + stringLength)
  2683. ) {
  2684. const previous = original.slice(index, index + stringLength);
  2685. if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
  2686. }
  2687. return this;
  2688. }
  2689. replaceAll(searchValue, replacement) {
  2690. if (typeof searchValue === 'string') {
  2691. return this._replaceAllString(searchValue, replacement);
  2692. }
  2693. if (!searchValue.global) {
  2694. throw new TypeError(
  2695. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  2696. );
  2697. }
  2698. return this._replaceRegexp(searchValue, replacement);
  2699. }
  2700. }
  2701. const hasOwnProp = Object.prototype.hasOwnProperty;
  2702. let Bundle$1 = class Bundle {
  2703. constructor(options = {}) {
  2704. this.intro = options.intro || '';
  2705. this.separator = options.separator !== undefined ? options.separator : '\n';
  2706. this.sources = [];
  2707. this.uniqueSources = [];
  2708. this.uniqueSourceIndexByFilename = {};
  2709. }
  2710. addSource(source) {
  2711. if (source instanceof MagicString) {
  2712. return this.addSource({
  2713. content: source,
  2714. filename: source.filename,
  2715. separator: this.separator,
  2716. });
  2717. }
  2718. if (!isObject(source) || !source.content) {
  2719. throw new Error(
  2720. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  2721. );
  2722. }
  2723. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  2724. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  2725. });
  2726. if (source.separator === undefined) {
  2727. // TODO there's a bunch of this sort of thing, needs cleaning up
  2728. source.separator = this.separator;
  2729. }
  2730. if (source.filename) {
  2731. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  2732. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  2733. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  2734. } else {
  2735. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  2736. if (source.content.original !== uniqueSource.content) {
  2737. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  2738. }
  2739. }
  2740. }
  2741. this.sources.push(source);
  2742. return this;
  2743. }
  2744. append(str, options) {
  2745. this.addSource({
  2746. content: new MagicString(str),
  2747. separator: (options && options.separator) || '',
  2748. });
  2749. return this;
  2750. }
  2751. clone() {
  2752. const bundle = new Bundle({
  2753. intro: this.intro,
  2754. separator: this.separator,
  2755. });
  2756. this.sources.forEach((source) => {
  2757. bundle.addSource({
  2758. filename: source.filename,
  2759. content: source.content.clone(),
  2760. separator: source.separator,
  2761. });
  2762. });
  2763. return bundle;
  2764. }
  2765. generateDecodedMap(options = {}) {
  2766. const names = [];
  2767. let x_google_ignoreList = undefined;
  2768. this.sources.forEach((source) => {
  2769. Object.keys(source.content.storedNames).forEach((name) => {
  2770. if (!~names.indexOf(name)) names.push(name);
  2771. });
  2772. });
  2773. const mappings = new Mappings(options.hires);
  2774. if (this.intro) {
  2775. mappings.advance(this.intro);
  2776. }
  2777. this.sources.forEach((source, i) => {
  2778. if (i > 0) {
  2779. mappings.advance(this.separator);
  2780. }
  2781. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  2782. const magicString = source.content;
  2783. const locate = getLocator(magicString.original);
  2784. if (magicString.intro) {
  2785. mappings.advance(magicString.intro);
  2786. }
  2787. magicString.firstChunk.eachNext((chunk) => {
  2788. const loc = locate(chunk.start);
  2789. if (chunk.intro.length) mappings.advance(chunk.intro);
  2790. if (source.filename) {
  2791. if (chunk.edited) {
  2792. mappings.addEdit(
  2793. sourceIndex,
  2794. chunk.content,
  2795. loc,
  2796. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2797. );
  2798. } else {
  2799. mappings.addUneditedChunk(
  2800. sourceIndex,
  2801. chunk,
  2802. magicString.original,
  2803. loc,
  2804. magicString.sourcemapLocations,
  2805. );
  2806. }
  2807. } else {
  2808. mappings.advance(chunk.content);
  2809. }
  2810. if (chunk.outro.length) mappings.advance(chunk.outro);
  2811. });
  2812. if (magicString.outro) {
  2813. mappings.advance(magicString.outro);
  2814. }
  2815. if (source.ignoreList && sourceIndex !== -1) {
  2816. if (x_google_ignoreList === undefined) {
  2817. x_google_ignoreList = [];
  2818. }
  2819. x_google_ignoreList.push(sourceIndex);
  2820. }
  2821. });
  2822. return {
  2823. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2824. sources: this.uniqueSources.map((source) => {
  2825. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  2826. }),
  2827. sourcesContent: this.uniqueSources.map((source) => {
  2828. return options.includeContent ? source.content : null;
  2829. }),
  2830. names,
  2831. mappings: mappings.raw,
  2832. x_google_ignoreList,
  2833. };
  2834. }
  2835. generateMap(options) {
  2836. return new SourceMap(this.generateDecodedMap(options));
  2837. }
  2838. getIndentString() {
  2839. const indentStringCounts = {};
  2840. this.sources.forEach((source) => {
  2841. const indentStr = source.content._getRawIndentString();
  2842. if (indentStr === null) return;
  2843. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  2844. indentStringCounts[indentStr] += 1;
  2845. });
  2846. return (
  2847. Object.keys(indentStringCounts).sort((a, b) => {
  2848. return indentStringCounts[a] - indentStringCounts[b];
  2849. })[0] || '\t'
  2850. );
  2851. }
  2852. indent(indentStr) {
  2853. if (!arguments.length) {
  2854. indentStr = this.getIndentString();
  2855. }
  2856. if (indentStr === '') return this; // noop
  2857. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  2858. this.sources.forEach((source, i) => {
  2859. const separator = source.separator !== undefined ? source.separator : this.separator;
  2860. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  2861. source.content.indent(indentStr, {
  2862. exclude: source.indentExclusionRanges,
  2863. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  2864. });
  2865. trailingNewline = source.content.lastChar() === '\n';
  2866. });
  2867. if (this.intro) {
  2868. this.intro =
  2869. indentStr +
  2870. this.intro.replace(/^[^\n]/gm, (match, index) => {
  2871. return index > 0 ? indentStr + match : match;
  2872. });
  2873. }
  2874. return this;
  2875. }
  2876. prepend(str) {
  2877. this.intro = str + this.intro;
  2878. return this;
  2879. }
  2880. toString() {
  2881. const body = this.sources
  2882. .map((source, i) => {
  2883. const separator = source.separator !== undefined ? source.separator : this.separator;
  2884. const str = (i > 0 ? separator : '') + source.content.toString();
  2885. return str;
  2886. })
  2887. .join('');
  2888. return this.intro + body;
  2889. }
  2890. isEmpty() {
  2891. if (this.intro.length && this.intro.trim()) return false;
  2892. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  2893. return true;
  2894. }
  2895. length() {
  2896. return this.sources.reduce(
  2897. (length, source) => length + source.content.length(),
  2898. this.intro.length,
  2899. );
  2900. }
  2901. trimLines() {
  2902. return this.trim('[\\r\\n]');
  2903. }
  2904. trim(charType) {
  2905. return this.trimStart(charType).trimEnd(charType);
  2906. }
  2907. trimStart(charType) {
  2908. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2909. this.intro = this.intro.replace(rx, '');
  2910. if (!this.intro) {
  2911. let source;
  2912. let i = 0;
  2913. do {
  2914. source = this.sources[i++];
  2915. if (!source) {
  2916. break;
  2917. }
  2918. } while (!source.content.trimStartAborted(charType));
  2919. }
  2920. return this;
  2921. }
  2922. trimEnd(charType) {
  2923. const rx = new RegExp((charType || '\\s') + '+$');
  2924. let source;
  2925. let i = this.sources.length - 1;
  2926. do {
  2927. source = this.sources[i--];
  2928. if (!source) {
  2929. this.intro = this.intro.replace(rx, '');
  2930. break;
  2931. }
  2932. } while (!source.content.trimEndAborted(charType));
  2933. return this;
  2934. }
  2935. };
  2936. function treeshakeNode(node, code, start, end) {
  2937. code.remove(start, end);
  2938. node.removeAnnotations(code);
  2939. }
  2940. const NO_SEMICOLON = { isNoStatement: true };
  2941. // This assumes there are only white-space and comments between start and the string we are looking for
  2942. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  2943. let searchPos, charCodeAfterSlash;
  2944. searchPos = code.indexOf(searchString, start);
  2945. while (true) {
  2946. start = code.indexOf('/', start);
  2947. if (start === -1 || start >= searchPos)
  2948. return searchPos;
  2949. charCodeAfterSlash = code.charCodeAt(++start);
  2950. ++start;
  2951. // With our assumption, '/' always starts a comment. Determine comment type:
  2952. start =
  2953. charCodeAfterSlash === 47 /*"/"*/
  2954. ? code.indexOf('\n', start) + 1
  2955. : code.indexOf('*/', start) + 2;
  2956. if (start > searchPos) {
  2957. searchPos = code.indexOf(searchString, start);
  2958. }
  2959. }
  2960. }
  2961. const NON_WHITESPACE = /\S/g;
  2962. function findNonWhiteSpace(code, index) {
  2963. NON_WHITESPACE.lastIndex = index;
  2964. const result = NON_WHITESPACE.exec(code);
  2965. return result.index;
  2966. }
  2967. const WHITESPACE = /\s/;
  2968. function findLastWhiteSpaceReverse(code, start, end) {
  2969. while (true) {
  2970. if (start >= end) {
  2971. return end;
  2972. }
  2973. if (WHITESPACE.test(code[end - 1])) {
  2974. end--;
  2975. }
  2976. else {
  2977. return end;
  2978. }
  2979. }
  2980. }
  2981. // This assumes "code" only contains white-space and comments
  2982. // Returns position of line-comment if applicable
  2983. function findFirstLineBreakOutsideComment(code) {
  2984. let lineBreakPos, charCodeAfterSlash, start = 0;
  2985. lineBreakPos = code.indexOf('\n', start);
  2986. while (true) {
  2987. start = code.indexOf('/', start);
  2988. if (start === -1 || start > lineBreakPos)
  2989. return [lineBreakPos, lineBreakPos + 1];
  2990. // With our assumption, '/' always starts a comment. Determine comment type:
  2991. charCodeAfterSlash = code.charCodeAt(start + 1);
  2992. if (charCodeAfterSlash === 47 /*"/"*/)
  2993. return [start, lineBreakPos + 1];
  2994. start = code.indexOf('*/', start + 2) + 2;
  2995. if (start > lineBreakPos) {
  2996. lineBreakPos = code.indexOf('\n', start);
  2997. }
  2998. }
  2999. }
  3000. function renderStatementList(statements, code, start, end, options) {
  3001. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  3002. let nextNode = statements[0];
  3003. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  3004. if (nextNodeNeedsBoundaries) {
  3005. nextNodeStart =
  3006. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  3007. }
  3008. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  3009. currentNode = nextNode;
  3010. currentNodeStart = nextNodeStart;
  3011. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  3012. nextNode = statements[nextIndex];
  3013. nextNodeNeedsBoundaries =
  3014. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  3015. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  3016. nextNodeStart =
  3017. currentNode.end +
  3018. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  3019. if (currentNode.included) {
  3020. if (currentNodeNeedsBoundaries) {
  3021. currentNode.render(code, options, {
  3022. end: nextNodeStart,
  3023. start: currentNodeStart
  3024. });
  3025. }
  3026. else {
  3027. currentNode.render(code, options);
  3028. }
  3029. }
  3030. else {
  3031. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  3032. }
  3033. }
  3034. else {
  3035. currentNode.render(code, options);
  3036. }
  3037. }
  3038. }
  3039. // This assumes that the first character is not part of the first node
  3040. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  3041. const splitUpNodes = [];
  3042. let node, nextNodeStart, contentEnd, char;
  3043. let separator = start - 1;
  3044. for (const nextNode of nodes) {
  3045. if (node !== undefined) {
  3046. separator =
  3047. node.end +
  3048. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  3049. }
  3050. nextNodeStart = contentEnd =
  3051. separator +
  3052. 1 +
  3053. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  3054. while (((char = code.original.charCodeAt(nextNodeStart)),
  3055. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  3056. nextNodeStart++;
  3057. if (node !== undefined) {
  3058. splitUpNodes.push({
  3059. contentEnd,
  3060. end: nextNodeStart,
  3061. node,
  3062. separator,
  3063. start
  3064. });
  3065. }
  3066. node = nextNode;
  3067. start = nextNodeStart;
  3068. }
  3069. splitUpNodes.push({
  3070. contentEnd: end,
  3071. end,
  3072. node: node,
  3073. separator: null,
  3074. start
  3075. });
  3076. return splitUpNodes;
  3077. }
  3078. // This assumes there are only white-space and comments between start and end
  3079. function removeLineBreaks(code, start, end) {
  3080. while (true) {
  3081. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  3082. if (removeStart === -1) {
  3083. break;
  3084. }
  3085. code.remove(start + removeStart, (start += removeEnd));
  3086. }
  3087. }
  3088. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  3089. if (exportedVariables.length === 1 &&
  3090. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  3091. const variable = exportedVariables[0];
  3092. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  3093. }
  3094. else {
  3095. const fields = [];
  3096. for (const variable of exportedVariables) {
  3097. for (const exportName of exportNamesByVariable.get(variable)) {
  3098. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  3099. }
  3100. }
  3101. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  3102. }
  3103. }
  3104. // This is only invoked if there is exactly one export name
  3105. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  3106. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  3107. code.appendLeft(expressionEnd, ')');
  3108. }
  3109. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  3110. const { _, getDirectReturnIifeLeft } = options.snippets;
  3111. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  3112. code.appendLeft(expressionEnd, ')');
  3113. }
  3114. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  3115. const { _, getPropertyAccess } = options.snippets;
  3116. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  3117. if (needsParens) {
  3118. code.prependRight(expressionStart, '(');
  3119. code.appendLeft(expressionEnd, ')');
  3120. }
  3121. }
  3122. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  3123. const { _ } = options.snippets;
  3124. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  3125. if (needsParens) {
  3126. code.prependRight(expressionStart, '(');
  3127. code.appendLeft(expressionEnd, ')');
  3128. }
  3129. }
  3130. const UnknownKey = Symbol('Unknown Key');
  3131. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  3132. const UnknownInteger = Symbol('Unknown Integer');
  3133. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  3134. const EMPTY_PATH = [];
  3135. const UNKNOWN_PATH = [UnknownKey];
  3136. // For deoptimizations, this means we are modifying an unknown property but did
  3137. // not lose track of the object or are creating a setter/getter;
  3138. // For assignment effects it means we do not check for setter/getter effects
  3139. // but only if something is mutated that is included, which is relevant for
  3140. // Object.defineProperty
  3141. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  3142. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  3143. const EntitiesKey = Symbol('Entities');
  3144. class EntityPathTracker {
  3145. constructor() {
  3146. this.entityPaths = Object.create(null, {
  3147. [EntitiesKey]: { value: new Set() }
  3148. });
  3149. }
  3150. trackEntityAtPathAndGetIfTracked(path, entity) {
  3151. const trackedEntities = this.getEntities(path);
  3152. if (trackedEntities.has(entity))
  3153. return true;
  3154. trackedEntities.add(entity);
  3155. return false;
  3156. }
  3157. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  3158. const trackedEntities = this.getEntities(path);
  3159. if (trackedEntities.has(entity))
  3160. return returnIfTracked;
  3161. trackedEntities.add(entity);
  3162. const result = onUntracked();
  3163. trackedEntities.delete(entity);
  3164. return result;
  3165. }
  3166. getEntities(path) {
  3167. let currentPaths = this.entityPaths;
  3168. for (const pathSegment of path) {
  3169. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  3170. [EntitiesKey]: { value: new Set() }
  3171. });
  3172. }
  3173. return currentPaths[EntitiesKey];
  3174. }
  3175. }
  3176. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  3177. class DiscriminatedPathTracker {
  3178. constructor() {
  3179. this.entityPaths = Object.create(null, {
  3180. [EntitiesKey]: { value: new Map() }
  3181. });
  3182. }
  3183. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  3184. let currentPaths = this.entityPaths;
  3185. for (const pathSegment of path) {
  3186. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  3187. [EntitiesKey]: { value: new Map() }
  3188. });
  3189. }
  3190. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  3191. if (trackedEntities.has(entity))
  3192. return true;
  3193. trackedEntities.add(entity);
  3194. return false;
  3195. }
  3196. }
  3197. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: parseAst_js.EMPTY_OBJECT });
  3198. class IncludedFullPathTracker {
  3199. constructor() {
  3200. this.includedPaths = null;
  3201. }
  3202. includePathAndGetIfIncluded(path) {
  3203. let included = true;
  3204. let parent = this;
  3205. let parentSegment = 'includedPaths';
  3206. let currentPaths = (this.includedPaths ||=
  3207. ((included = false), Object.create(null)));
  3208. for (const pathSegment of path) {
  3209. // This means from here, all paths are included
  3210. if (currentPaths[UnknownKey]) {
  3211. return true;
  3212. }
  3213. // Including UnknownKey automatically includes all nested paths.
  3214. // From above, we know that UnknownKey is not included yet.
  3215. if (typeof pathSegment === 'symbol') {
  3216. // Hopefully, this saves some memory over just setting
  3217. // currentPaths[UnknownKey] = EMPTY_OBJECT
  3218. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  3219. return false;
  3220. }
  3221. parent = currentPaths;
  3222. parentSegment = pathSegment;
  3223. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  3224. }
  3225. return included;
  3226. }
  3227. }
  3228. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  3229. [UnknownKey]: true
  3230. });
  3231. class IncludedTopLevelPathTracker {
  3232. constructor() {
  3233. this.includedPaths = null;
  3234. }
  3235. includePathAndGetIfIncluded(path) {
  3236. let included = true;
  3237. const includedPaths = (this.includedPaths ||=
  3238. ((included = false), Object.create(null)));
  3239. if (includedPaths[UnknownKey]) {
  3240. return true;
  3241. }
  3242. const [firstPathSegment, secondPathSegment] = path;
  3243. if (!firstPathSegment) {
  3244. return included;
  3245. }
  3246. if (typeof firstPathSegment === 'symbol') {
  3247. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  3248. return false;
  3249. }
  3250. if (secondPathSegment) {
  3251. if (includedPaths[firstPathSegment] === UnknownKey) {
  3252. return true;
  3253. }
  3254. includedPaths[firstPathSegment] = UnknownKey;
  3255. return false;
  3256. }
  3257. if (includedPaths[firstPathSegment]) {
  3258. return true;
  3259. }
  3260. includedPaths[firstPathSegment] = true;
  3261. return false;
  3262. }
  3263. includeAllPaths(entity, context, basePath) {
  3264. const { includedPaths } = this;
  3265. if (includedPaths) {
  3266. if (includedPaths[UnknownKey]) {
  3267. entity.includePath([...basePath, UnknownKey], context);
  3268. }
  3269. else {
  3270. const inclusionEntries = Object.entries(includedPaths);
  3271. if (inclusionEntries.length === 0) {
  3272. entity.includePath(basePath, context);
  3273. }
  3274. else {
  3275. for (const [key, value] of inclusionEntries) {
  3276. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  3277. }
  3278. }
  3279. }
  3280. }
  3281. }
  3282. }
  3283. /** @import { Node } from 'estree' */
  3284. /**
  3285. * @param {Node} node
  3286. * @param {Node} parent
  3287. * @returns {boolean}
  3288. */
  3289. function is_reference(node, parent) {
  3290. if (node.type === 'MemberExpression') {
  3291. return !node.computed && is_reference(node.object, node);
  3292. }
  3293. if (node.type !== 'Identifier') return false;
  3294. switch (parent?.type) {
  3295. // disregard `bar` in `foo.bar`
  3296. case 'MemberExpression':
  3297. return parent.computed || node === parent.object;
  3298. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  3299. case 'MethodDefinition':
  3300. return parent.computed;
  3301. // disregard the `meta` in `import.meta`
  3302. case 'MetaProperty':
  3303. return parent.meta === node;
  3304. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  3305. case 'PropertyDefinition':
  3306. return parent.computed || node === parent.value;
  3307. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  3308. case 'Property':
  3309. return parent.computed || node === parent.value;
  3310. // disregard the `bar` in `export { foo as bar }` or
  3311. // the foo in `import { foo as bar }`
  3312. case 'ExportSpecifier':
  3313. case 'ImportSpecifier':
  3314. return node === parent.local;
  3315. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  3316. case 'LabeledStatement':
  3317. case 'BreakStatement':
  3318. case 'ContinueStatement':
  3319. return false;
  3320. default:
  3321. return true;
  3322. }
  3323. }
  3324. function createInclusionContext() {
  3325. return {
  3326. brokenFlow: false,
  3327. hasBreak: false,
  3328. hasContinue: false,
  3329. includedCallArguments: new Set(),
  3330. includedLabels: new Set()
  3331. };
  3332. }
  3333. function createHasEffectsContext() {
  3334. return {
  3335. accessed: new EntityPathTracker(),
  3336. assigned: new EntityPathTracker(),
  3337. brokenFlow: false,
  3338. called: new DiscriminatedPathTracker(),
  3339. hasBreak: false,
  3340. hasContinue: false,
  3341. ignore: {
  3342. breaks: false,
  3343. continues: false,
  3344. labels: new Set(),
  3345. returnYield: false,
  3346. this: false
  3347. },
  3348. includedLabels: new Set(),
  3349. instantiated: new DiscriminatedPathTracker(),
  3350. replacedVariableInits: new Map()
  3351. };
  3352. }
  3353. function isFlagSet(flags, flag) {
  3354. return (flags & flag) !== 0;
  3355. }
  3356. function setFlag(flags, flag, value) {
  3357. return (flags & ~flag) | (-value & flag);
  3358. }
  3359. const UnknownValue = Symbol('Unknown Value');
  3360. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  3361. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  3362. class ExpressionEntity {
  3363. constructor() {
  3364. this.flags = 0;
  3365. }
  3366. get included() {
  3367. return isFlagSet(this.flags, 1 /* Flag.included */);
  3368. }
  3369. set included(value) {
  3370. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  3371. }
  3372. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  3373. deoptimizeInteraction(interaction);
  3374. }
  3375. deoptimizePath(_path) { }
  3376. /**
  3377. * If possible it returns a stringifyable literal value for this node that
  3378. * can be used for inlining or comparing values. Otherwise, it should return
  3379. * UnknownValue.
  3380. */
  3381. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  3382. return UnknownValue;
  3383. }
  3384. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  3385. return UNKNOWN_RETURN_EXPRESSION;
  3386. }
  3387. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  3388. return true;
  3389. }
  3390. include(context, _includeChildrenRecursively, _options) {
  3391. if (!this.included)
  3392. this.includeNode(context);
  3393. }
  3394. includeNode(_context) {
  3395. this.included = true;
  3396. }
  3397. includePath(_path, context) {
  3398. if (!this.included)
  3399. this.includeNode(context);
  3400. }
  3401. /* We are both including and including an unknown path here as the former
  3402. * ensures that nested nodes are included while the latter ensures that all
  3403. * paths of the expression are included.
  3404. * */
  3405. includeCallArguments(interaction, context) {
  3406. includeInteraction(interaction, context);
  3407. }
  3408. shouldBeIncluded(_context) {
  3409. return true;
  3410. }
  3411. }
  3412. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  3413. })();
  3414. const UNKNOWN_RETURN_EXPRESSION = [
  3415. UNKNOWN_EXPRESSION,
  3416. false
  3417. ];
  3418. const deoptimizeInteraction = (interaction) => {
  3419. for (const argument of interaction.args) {
  3420. argument?.deoptimizePath(UNKNOWN_PATH);
  3421. }
  3422. };
  3423. const includeInteraction = ({ args }, context) => {
  3424. // We do not re-include the "this" argument as we expect this is already
  3425. // re-included at the call site
  3426. args[0]?.includePath(UNKNOWN_PATH, context);
  3427. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  3428. const argument = args[argumentIndex];
  3429. if (argument) {
  3430. argument.includePath(UNKNOWN_PATH, context);
  3431. argument.include(context, false);
  3432. }
  3433. }
  3434. };
  3435. const INTERACTION_ACCESSED = 0;
  3436. const INTERACTION_ASSIGNED = 1;
  3437. const INTERACTION_CALLED = 2;
  3438. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  3439. args: [null],
  3440. type: INTERACTION_ACCESSED
  3441. };
  3442. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  3443. args: [null, UNKNOWN_EXPRESSION],
  3444. type: INTERACTION_ASSIGNED
  3445. };
  3446. // While this is technically a call without arguments, we can compare against
  3447. // this reference in places where precise values or this argument would make a
  3448. // difference
  3449. const NODE_INTERACTION_UNKNOWN_CALL = {
  3450. args: [null],
  3451. type: INTERACTION_CALLED,
  3452. withNew: false
  3453. };
  3454. const PureFunctionKey = Symbol('PureFunction');
  3455. const getPureFunctions = ({ treeshake }) => {
  3456. const pureFunctions = Object.create(null);
  3457. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  3458. let currentFunctions = pureFunctions;
  3459. for (const pathSegment of functionName.split('.')) {
  3460. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  3461. }
  3462. currentFunctions[PureFunctionKey] = true;
  3463. }
  3464. return pureFunctions;
  3465. };
  3466. class Variable extends ExpressionEntity {
  3467. markReassigned() {
  3468. this.isReassigned = true;
  3469. }
  3470. constructor(name) {
  3471. super();
  3472. this.name = name;
  3473. this.alwaysRendered = false;
  3474. this.forbiddenNames = null;
  3475. this.globalName = null;
  3476. this.initReached = false;
  3477. this.isId = false;
  3478. this.kind = null;
  3479. this.renderBaseName = null;
  3480. this.renderName = null;
  3481. this.isReassigned = false;
  3482. this.onlyFunctionCallUsed = true;
  3483. }
  3484. /**
  3485. * Binds identifiers that reference this variable to this variable.
  3486. * Necessary to be able to change variable names.
  3487. */
  3488. addReference(_identifier) { }
  3489. /**
  3490. * Check if the identifier variable is only used as function call
  3491. * @returns true if the variable is only used as function call
  3492. */
  3493. getOnlyFunctionCallUsed() {
  3494. return this.onlyFunctionCallUsed;
  3495. }
  3496. /**
  3497. * Collect the places where the identifier variable is used
  3498. * @param usedPlace Where the variable is used
  3499. */
  3500. addUsedPlace(usedPlace) {
  3501. const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
  3502. usedPlace.parent.callee === usedPlace;
  3503. if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
  3504. this.onlyFunctionCallUsed = false;
  3505. }
  3506. }
  3507. /**
  3508. * Prevent this variable from being renamed to this name to avoid name
  3509. * collisions
  3510. */
  3511. forbidName(name) {
  3512. (this.forbiddenNames ||= new Set()).add(name);
  3513. }
  3514. getBaseVariableName() {
  3515. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  3516. this.renderBaseName ||
  3517. this.renderName ||
  3518. this.name);
  3519. }
  3520. getName(getPropertyAccess, useOriginalName) {
  3521. if (this.globalName) {
  3522. return this.globalName;
  3523. }
  3524. if (useOriginalName?.(this)) {
  3525. return this.name;
  3526. }
  3527. if (this.renderedLikeHoisted) {
  3528. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  3529. }
  3530. const name = this.renderName || this.name;
  3531. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  3532. }
  3533. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  3534. return type !== INTERACTION_ACCESSED || path.length > 0;
  3535. }
  3536. /**
  3537. * Marks this variable as being part of the bundle, which is usually the case
  3538. * when one of its identifiers becomes part of the bundle. Returns true if it
  3539. * has not been included previously. Once a variable is included, it should
  3540. * take care all its declarations are included.
  3541. */
  3542. includePath(path, context) {
  3543. this.included = true;
  3544. this.renderedLikeHoisted?.includePath(path, context);
  3545. }
  3546. /**
  3547. * Links the rendered name of this variable to another variable and includes
  3548. * this variable if the other variable is included.
  3549. */
  3550. renderLikeHoisted(variable) {
  3551. this.renderedLikeHoisted = variable;
  3552. }
  3553. markCalledFromTryStatement() { }
  3554. setRenderNames(baseName, name) {
  3555. this.renderBaseName = baseName;
  3556. this.renderName = name;
  3557. }
  3558. }
  3559. class ExternalVariable extends Variable {
  3560. constructor(module, name) {
  3561. super(name);
  3562. this.referenced = false;
  3563. this.module = module;
  3564. this.isNamespace = name === '*';
  3565. }
  3566. addReference(identifier) {
  3567. this.referenced = true;
  3568. if (this.name === 'default' || this.name === '*') {
  3569. this.module.suggestName(identifier.name);
  3570. }
  3571. }
  3572. hasEffectsOnInteractionAtPath(path, { type }) {
  3573. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  3574. }
  3575. includePath(path, context) {
  3576. super.includePath(path, context);
  3577. this.module.used = true;
  3578. }
  3579. }
  3580. function cacheObjectGetters(object, getterProperties) {
  3581. for (const property of getterProperties) {
  3582. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  3583. Object.defineProperty(object, property, {
  3584. get() {
  3585. const value = propertyGetter.call(object);
  3586. // This replaces the getter with a fixed value for subsequent calls
  3587. Object.defineProperty(object, property, { value });
  3588. return value;
  3589. }
  3590. });
  3591. }
  3592. }
  3593. const RESERVED_NAMES = new Set([
  3594. 'await',
  3595. 'break',
  3596. 'case',
  3597. 'catch',
  3598. 'class',
  3599. 'const',
  3600. 'continue',
  3601. 'debugger',
  3602. 'default',
  3603. 'delete',
  3604. 'do',
  3605. 'else',
  3606. 'enum',
  3607. 'eval',
  3608. 'export',
  3609. 'extends',
  3610. 'false',
  3611. 'finally',
  3612. 'for',
  3613. 'function',
  3614. 'if',
  3615. 'implements',
  3616. 'import',
  3617. 'in',
  3618. 'instanceof',
  3619. 'interface',
  3620. 'let',
  3621. 'NaN',
  3622. 'new',
  3623. 'null',
  3624. 'package',
  3625. 'private',
  3626. 'protected',
  3627. 'public',
  3628. 'return',
  3629. 'static',
  3630. 'super',
  3631. 'switch',
  3632. 'this',
  3633. 'throw',
  3634. 'true',
  3635. 'try',
  3636. 'typeof',
  3637. 'undefined',
  3638. 'var',
  3639. 'void',
  3640. 'while',
  3641. 'with',
  3642. 'yield'
  3643. ]);
  3644. const illegalCharacters = /[^\w$]/g;
  3645. const startsWithDigit = (value) => /\d/.test(value[0]);
  3646. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  3647. function isLegal(value) {
  3648. if (needsEscape(value)) {
  3649. return false;
  3650. }
  3651. return !illegalCharacters.test(value);
  3652. }
  3653. function makeLegal(value) {
  3654. value = value
  3655. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  3656. .replace(illegalCharacters, '_');
  3657. if (needsEscape(value))
  3658. value = `_${value}`;
  3659. return value || '_';
  3660. }
  3661. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  3662. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  3663. function stringifyObjectKeyIfNeeded(key) {
  3664. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  3665. return key === '__proto__' ? '["__proto__"]' : key;
  3666. }
  3667. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  3668. return key;
  3669. }
  3670. return JSON.stringify(key);
  3671. }
  3672. function stringifyIdentifierIfNeeded(key) {
  3673. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  3674. return key;
  3675. }
  3676. return JSON.stringify(key);
  3677. }
  3678. class ExternalModule {
  3679. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  3680. this.options = options;
  3681. this.id = id;
  3682. this.renormalizeRenderPath = renormalizeRenderPath;
  3683. this.dynamicImporters = [];
  3684. this.execIndex = Infinity;
  3685. this.exportedVariables = new Map();
  3686. this.importers = [];
  3687. this.reexported = false;
  3688. this.used = false;
  3689. this.declarations = new Map();
  3690. this.mostCommonSuggestion = 0;
  3691. this.nameSuggestions = new Map();
  3692. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  3693. const { importers, dynamicImporters } = this;
  3694. this.info = {
  3695. ast: null,
  3696. attributes,
  3697. code: null,
  3698. dynamicallyImportedIdResolutions: parseAst_js.EMPTY_ARRAY,
  3699. dynamicallyImportedIds: parseAst_js.EMPTY_ARRAY,
  3700. get dynamicImporters() {
  3701. return dynamicImporters.sort();
  3702. },
  3703. exportedBindings: null,
  3704. exports: null,
  3705. hasDefaultExport: null,
  3706. id,
  3707. implicitlyLoadedAfterOneOf: parseAst_js.EMPTY_ARRAY,
  3708. implicitlyLoadedBefore: parseAst_js.EMPTY_ARRAY,
  3709. importedIdResolutions: parseAst_js.EMPTY_ARRAY,
  3710. importedIds: parseAst_js.EMPTY_ARRAY,
  3711. get importers() {
  3712. return importers.sort();
  3713. },
  3714. isEntry: false,
  3715. isExternal: true,
  3716. isIncluded: null,
  3717. meta,
  3718. moduleSideEffects,
  3719. syntheticNamedExports: false
  3720. };
  3721. }
  3722. cacheInfoGetters() {
  3723. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  3724. }
  3725. getVariableForExportName(name) {
  3726. const declaration = this.declarations.get(name);
  3727. if (declaration)
  3728. return [declaration];
  3729. const externalVariable = new ExternalVariable(this, name);
  3730. this.declarations.set(name, externalVariable);
  3731. this.exportedVariables.set(externalVariable, name);
  3732. return [externalVariable];
  3733. }
  3734. suggestName(name) {
  3735. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  3736. this.nameSuggestions.set(name, value);
  3737. if (value > this.mostCommonSuggestion) {
  3738. this.mostCommonSuggestion = value;
  3739. this.suggestedVariableName = name;
  3740. }
  3741. }
  3742. warnUnusedImports() {
  3743. const unused = [...this.declarations]
  3744. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  3745. .map(([name]) => name);
  3746. if (unused.length === 0)
  3747. return;
  3748. const importersSet = new Set();
  3749. for (const name of unused) {
  3750. for (const importer of this.declarations.get(name).module.importers) {
  3751. importersSet.add(importer);
  3752. }
  3753. }
  3754. const importersArray = [...importersSet];
  3755. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnusedExternalImports(this.id, unused, importersArray));
  3756. }
  3757. }
  3758. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  3759. baseModule.isExecuted = true;
  3760. const modules = [baseModule];
  3761. const visitedModules = new Set();
  3762. for (const module of modules) {
  3763. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  3764. if (!(dependency instanceof ExternalModule) &&
  3765. !dependency.isExecuted &&
  3766. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  3767. !visitedModules.has(dependency.id)) {
  3768. dependency.isExecuted = true;
  3769. visitedModules.add(dependency.id);
  3770. modules.push(dependency);
  3771. }
  3772. }
  3773. }
  3774. }
  3775. // This file is generated by scripts/generate-child-node-keys.js.
  3776. // Do not edit this file directly.
  3777. const childNodeKeys = {
  3778. ArrayExpression: ['elements'],
  3779. ArrayPattern: ['elements'],
  3780. ArrowFunctionExpression: ['params', 'body'],
  3781. AssignmentExpression: ['left', 'right'],
  3782. AssignmentPattern: ['left', 'right'],
  3783. AwaitExpression: ['argument'],
  3784. BinaryExpression: ['left', 'right'],
  3785. BlockStatement: ['body'],
  3786. BreakStatement: ['label'],
  3787. CallExpression: ['callee', 'arguments'],
  3788. CatchClause: ['param', 'body'],
  3789. ChainExpression: ['expression'],
  3790. ClassBody: ['body'],
  3791. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  3792. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  3793. ConditionalExpression: ['test', 'consequent', 'alternate'],
  3794. ContinueStatement: ['label'],
  3795. DebuggerStatement: [],
  3796. Decorator: ['expression'],
  3797. DoWhileStatement: ['body', 'test'],
  3798. EmptyStatement: [],
  3799. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  3800. ExportDefaultDeclaration: ['declaration'],
  3801. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  3802. ExportSpecifier: ['local', 'exported'],
  3803. ExpressionStatement: ['expression'],
  3804. ForInStatement: ['left', 'right', 'body'],
  3805. ForOfStatement: ['left', 'right', 'body'],
  3806. ForStatement: ['init', 'test', 'update', 'body'],
  3807. FunctionDeclaration: ['id', 'params', 'body'],
  3808. FunctionExpression: ['id', 'params', 'body'],
  3809. Identifier: [],
  3810. IfStatement: ['test', 'consequent', 'alternate'],
  3811. ImportAttribute: ['key', 'value'],
  3812. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  3813. ImportDefaultSpecifier: ['local'],
  3814. ImportExpression: ['source', 'options'],
  3815. ImportNamespaceSpecifier: ['local'],
  3816. ImportSpecifier: ['imported', 'local'],
  3817. JSXAttribute: ['name', 'value'],
  3818. JSXClosingElement: ['name'],
  3819. JSXClosingFragment: [],
  3820. JSXElement: ['openingElement', 'children', 'closingElement'],
  3821. JSXEmptyExpression: [],
  3822. JSXExpressionContainer: ['expression'],
  3823. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  3824. JSXIdentifier: [],
  3825. JSXMemberExpression: ['object', 'property'],
  3826. JSXNamespacedName: ['namespace', 'name'],
  3827. JSXOpeningElement: ['name', 'attributes'],
  3828. JSXOpeningFragment: [],
  3829. JSXSpreadAttribute: ['argument'],
  3830. JSXSpreadChild: ['expression'],
  3831. JSXText: [],
  3832. LabeledStatement: ['label', 'body'],
  3833. Literal: [],
  3834. LogicalExpression: ['left', 'right'],
  3835. MemberExpression: ['object', 'property'],
  3836. MetaProperty: ['meta', 'property'],
  3837. MethodDefinition: ['decorators', 'key', 'value'],
  3838. NewExpression: ['callee', 'arguments'],
  3839. ObjectExpression: ['properties'],
  3840. ObjectPattern: ['properties'],
  3841. PanicError: [],
  3842. ParseError: [],
  3843. PrivateIdentifier: [],
  3844. Program: ['body'],
  3845. Property: ['key', 'value'],
  3846. PropertyDefinition: ['decorators', 'key', 'value'],
  3847. RestElement: ['argument'],
  3848. ReturnStatement: ['argument'],
  3849. SequenceExpression: ['expressions'],
  3850. SpreadElement: ['argument'],
  3851. StaticBlock: ['body'],
  3852. Super: [],
  3853. SwitchCase: ['test', 'consequent'],
  3854. SwitchStatement: ['discriminant', 'cases'],
  3855. TaggedTemplateExpression: ['tag', 'quasi'],
  3856. TemplateElement: [],
  3857. TemplateLiteral: ['quasis', 'expressions'],
  3858. ThisExpression: [],
  3859. ThrowStatement: ['argument'],
  3860. TryStatement: ['block', 'handler', 'finalizer'],
  3861. UnaryExpression: ['argument'],
  3862. UpdateExpression: ['argument'],
  3863. VariableDeclaration: ['declarations'],
  3864. VariableDeclarator: ['id', 'init'],
  3865. WhileStatement: ['test', 'body'],
  3866. YieldExpression: ['argument']
  3867. };
  3868. const INCLUDE_PARAMETERS = 'variables';
  3869. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  3870. class NodeBase extends ExpressionEntity {
  3871. /**
  3872. * Nodes can apply custom deoptimizations once they become part of the
  3873. * executed code. To do this, they must initialize this as false, implement
  3874. * applyDeoptimizations and call this from include and hasEffects if they have
  3875. * custom handlers
  3876. */
  3877. get deoptimized() {
  3878. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  3879. }
  3880. set deoptimized(value) {
  3881. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  3882. }
  3883. constructor(parent, parentScope) {
  3884. super();
  3885. this.parent = parent;
  3886. this.scope = parentScope;
  3887. this.createScope(parentScope);
  3888. }
  3889. addExportedVariables(_variables, _exportNamesByVariable) { }
  3890. /**
  3891. * Override this to bind assignments to variables and do any initialisations
  3892. * that require the scopes to be populated with variables.
  3893. */
  3894. bind() {
  3895. for (const key of childNodeKeys[this.type]) {
  3896. const value = this[key];
  3897. if (Array.isArray(value)) {
  3898. for (const child of value) {
  3899. child?.bind();
  3900. }
  3901. }
  3902. else if (value) {
  3903. value.bind();
  3904. }
  3905. }
  3906. }
  3907. /**
  3908. * Override if this node should receive a different scope than the parent
  3909. * scope.
  3910. */
  3911. createScope(parentScope) {
  3912. this.scope = parentScope;
  3913. }
  3914. hasEffects(context) {
  3915. if (!this.deoptimized)
  3916. this.applyDeoptimizations();
  3917. for (const key of childNodeKeys[this.type]) {
  3918. const value = this[key];
  3919. if (value === null)
  3920. continue;
  3921. if (Array.isArray(value)) {
  3922. for (const child of value) {
  3923. if (child?.hasEffects(context))
  3924. return true;
  3925. }
  3926. }
  3927. else if (value.hasEffects(context))
  3928. return true;
  3929. }
  3930. return false;
  3931. }
  3932. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  3933. return (this.hasEffects(context) ||
  3934. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  3935. }
  3936. include(context, includeChildrenRecursively, _options) {
  3937. if (!this.included)
  3938. this.includeNode(context);
  3939. for (const key of childNodeKeys[this.type]) {
  3940. const value = this[key];
  3941. if (value === null)
  3942. continue;
  3943. if (Array.isArray(value)) {
  3944. for (const child of value) {
  3945. child?.include(context, includeChildrenRecursively);
  3946. }
  3947. }
  3948. else {
  3949. value.include(context, includeChildrenRecursively);
  3950. }
  3951. }
  3952. }
  3953. includeNode(context) {
  3954. this.included = true;
  3955. if (!this.deoptimized)
  3956. this.applyDeoptimizations();
  3957. for (const key of childNodeKeys[this.type]) {
  3958. const value = this[key];
  3959. if (value === null)
  3960. continue;
  3961. if (Array.isArray(value)) {
  3962. for (const child of value) {
  3963. child?.includePath(UNKNOWN_PATH, context);
  3964. }
  3965. }
  3966. else {
  3967. value.includePath(UNKNOWN_PATH, context);
  3968. }
  3969. }
  3970. }
  3971. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  3972. this.include(context, includeChildrenRecursively);
  3973. }
  3974. /**
  3975. * Override to perform special initialisation steps after the scope is
  3976. * initialised
  3977. */
  3978. initialise() {
  3979. this.scope.context.magicString.addSourcemapLocation(this.start);
  3980. this.scope.context.magicString.addSourcemapLocation(this.end);
  3981. }
  3982. parseNode(esTreeNode) {
  3983. for (const [key, value] of Object.entries(esTreeNode)) {
  3984. // Skip properties defined on the class already.
  3985. // This way, we can override this function to add custom initialisation and then call super.parseNode
  3986. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  3987. // in bitfields. Those are still assigned from the value in the esTreeNode.
  3988. if (this.hasOwnProperty(key))
  3989. continue;
  3990. if (key.charCodeAt(0) === 95 /* _ */) {
  3991. if (key === parseAst_js.ANNOTATION_KEY) {
  3992. this.annotations = value;
  3993. }
  3994. else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
  3995. this.invalidAnnotations = value;
  3996. }
  3997. }
  3998. else if (typeof value !== 'object' || value === null) {
  3999. this[key] = value;
  4000. }
  4001. else if (Array.isArray(value)) {
  4002. this[key] = new Array(value.length);
  4003. let index = 0;
  4004. for (const child of value) {
  4005. this[key][index++] =
  4006. child === null
  4007. ? null
  4008. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  4009. }
  4010. }
  4011. else {
  4012. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  4013. }
  4014. }
  4015. // extend child keys for unknown node types
  4016. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  4017. this.initialise();
  4018. return this;
  4019. }
  4020. removeAnnotations(code) {
  4021. if (this.annotations) {
  4022. for (const annotation of this.annotations) {
  4023. code.remove(annotation.start, annotation.end);
  4024. }
  4025. }
  4026. }
  4027. render(code, options) {
  4028. for (const key of childNodeKeys[this.type]) {
  4029. const value = this[key];
  4030. if (value === null)
  4031. continue;
  4032. if (Array.isArray(value)) {
  4033. for (const child of value) {
  4034. child?.render(code, options);
  4035. }
  4036. }
  4037. else {
  4038. value.render(code, options);
  4039. }
  4040. }
  4041. }
  4042. setAssignedValue(value) {
  4043. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  4044. }
  4045. shouldBeIncluded(context) {
  4046. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4047. }
  4048. /**
  4049. * Just deoptimize everything by default so that when e.g. we do not track
  4050. * something properly, it is deoptimized.
  4051. * @protected
  4052. */
  4053. applyDeoptimizations() {
  4054. this.deoptimized = true;
  4055. for (const key of childNodeKeys[this.type]) {
  4056. const value = this[key];
  4057. if (value === null)
  4058. continue;
  4059. if (Array.isArray(value)) {
  4060. for (const child of value) {
  4061. child?.deoptimizePath(UNKNOWN_PATH);
  4062. }
  4063. }
  4064. else {
  4065. value.deoptimizePath(UNKNOWN_PATH);
  4066. }
  4067. }
  4068. this.scope.context.requestTreeshakingPass();
  4069. }
  4070. }
  4071. function createChildNodeKeysForNode(esTreeNode) {
  4072. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4073. }
  4074. function onlyIncludeSelf() {
  4075. this.included = true;
  4076. if (!this.deoptimized)
  4077. this.applyDeoptimizations();
  4078. }
  4079. function onlyIncludeSelfNoDeoptimize() {
  4080. this.included = true;
  4081. }
  4082. function doNotDeoptimize() {
  4083. this.deoptimized = true;
  4084. }
  4085. function isObjectExpressionNode(node) {
  4086. return node instanceof NodeBase && node.type === parseAst_js.ObjectExpression;
  4087. }
  4088. function isPropertyNode(node) {
  4089. return node.type === parseAst_js.Property;
  4090. }
  4091. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4092. return Object.create(inheritedDescriptions, memberDescriptions);
  4093. }
  4094. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4095. getLiteralValueAtPath(path) {
  4096. return path.length > 0 ? UnknownValue : undefined;
  4097. }
  4098. })();
  4099. const returnsUnknown = {
  4100. value: {
  4101. hasEffectsWhenCalled: null,
  4102. returns: UNKNOWN_EXPRESSION
  4103. }
  4104. };
  4105. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4106. getReturnExpressionWhenCalledAtPath(path) {
  4107. if (path.length === 1) {
  4108. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4109. }
  4110. return UNKNOWN_RETURN_EXPRESSION;
  4111. }
  4112. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4113. if (interaction.type === INTERACTION_ACCESSED) {
  4114. return path.length > 1;
  4115. }
  4116. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4117. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4118. }
  4119. return true;
  4120. }
  4121. })();
  4122. const returnsBoolean = {
  4123. value: {
  4124. hasEffectsWhenCalled: null,
  4125. returns: UNKNOWN_LITERAL_BOOLEAN
  4126. }
  4127. };
  4128. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4129. getReturnExpressionWhenCalledAtPath(path) {
  4130. if (path.length === 1) {
  4131. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4132. }
  4133. return UNKNOWN_RETURN_EXPRESSION;
  4134. }
  4135. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4136. if (interaction.type === INTERACTION_ACCESSED) {
  4137. return path.length > 1;
  4138. }
  4139. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4140. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4141. }
  4142. return true;
  4143. }
  4144. })();
  4145. const returnsNumber = {
  4146. value: {
  4147. hasEffectsWhenCalled: null,
  4148. returns: UNKNOWN_LITERAL_NUMBER
  4149. }
  4150. };
  4151. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4152. getReturnExpressionWhenCalledAtPath(path) {
  4153. if (path.length === 1) {
  4154. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4155. }
  4156. return UNKNOWN_RETURN_EXPRESSION;
  4157. }
  4158. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4159. if (interaction.type === INTERACTION_ACCESSED) {
  4160. return path.length > 1;
  4161. }
  4162. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4163. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4164. }
  4165. return true;
  4166. }
  4167. })();
  4168. const returnsString = {
  4169. value: {
  4170. hasEffectsWhenCalled: null,
  4171. returns: UNKNOWN_LITERAL_STRING
  4172. }
  4173. };
  4174. const stringReplace = {
  4175. value: {
  4176. hasEffectsWhenCalled({ args }, context) {
  4177. const argument1 = args[2];
  4178. return (args.length < 3 ||
  4179. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4180. deoptimizeCache() { }
  4181. }) === 'symbol' &&
  4182. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4183. },
  4184. returns: UNKNOWN_LITERAL_STRING
  4185. }
  4186. };
  4187. const objectMembers = assembleMemberDescriptions({
  4188. hasOwnProperty: returnsBoolean,
  4189. isPrototypeOf: returnsBoolean,
  4190. propertyIsEnumerable: returnsBoolean,
  4191. toLocaleString: returnsString,
  4192. toString: returnsString,
  4193. valueOf: returnsUnknown
  4194. });
  4195. const literalBooleanMembers = assembleMemberDescriptions({
  4196. valueOf: returnsBoolean
  4197. }, objectMembers);
  4198. const literalNumberMembers = assembleMemberDescriptions({
  4199. toExponential: returnsString,
  4200. toFixed: returnsString,
  4201. toLocaleString: returnsString,
  4202. toPrecision: returnsString,
  4203. valueOf: returnsNumber
  4204. }, objectMembers);
  4205. /**
  4206. * RegExp are stateful when they have the global or sticky flags set.
  4207. * But if we actually don't use them, the side effect does not matter.
  4208. * the check logic in `hasEffectsOnInteractionAtPath`.
  4209. */
  4210. const literalRegExpMembers = assembleMemberDescriptions({
  4211. exec: returnsUnknown,
  4212. test: returnsBoolean
  4213. }, objectMembers);
  4214. const literalStringMembers = assembleMemberDescriptions({
  4215. anchor: returnsString,
  4216. at: returnsUnknown,
  4217. big: returnsString,
  4218. blink: returnsString,
  4219. bold: returnsString,
  4220. charAt: returnsString,
  4221. charCodeAt: returnsNumber,
  4222. codePointAt: returnsUnknown,
  4223. concat: returnsString,
  4224. endsWith: returnsBoolean,
  4225. fixed: returnsString,
  4226. fontcolor: returnsString,
  4227. fontsize: returnsString,
  4228. includes: returnsBoolean,
  4229. indexOf: returnsNumber,
  4230. italics: returnsString,
  4231. lastIndexOf: returnsNumber,
  4232. link: returnsString,
  4233. localeCompare: returnsNumber,
  4234. match: returnsUnknown,
  4235. matchAll: returnsUnknown,
  4236. normalize: returnsString,
  4237. padEnd: returnsString,
  4238. padStart: returnsString,
  4239. repeat: returnsString,
  4240. replace: stringReplace,
  4241. replaceAll: stringReplace,
  4242. search: returnsNumber,
  4243. slice: returnsString,
  4244. small: returnsString,
  4245. split: returnsUnknown,
  4246. startsWith: returnsBoolean,
  4247. strike: returnsString,
  4248. sub: returnsString,
  4249. substr: returnsString,
  4250. substring: returnsString,
  4251. sup: returnsString,
  4252. toLocaleLowerCase: returnsString,
  4253. toLocaleUpperCase: returnsString,
  4254. toLowerCase: returnsString,
  4255. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  4256. toUpperCase: returnsString,
  4257. trim: returnsString,
  4258. trimEnd: returnsString,
  4259. trimLeft: returnsString,
  4260. trimRight: returnsString,
  4261. trimStart: returnsString,
  4262. valueOf: returnsString
  4263. }, objectMembers);
  4264. function getLiteralMembersForValue(value) {
  4265. if (value instanceof RegExp) {
  4266. return literalRegExpMembers;
  4267. }
  4268. switch (typeof value) {
  4269. case 'boolean': {
  4270. return literalBooleanMembers;
  4271. }
  4272. case 'number': {
  4273. return literalNumberMembers;
  4274. }
  4275. case 'string': {
  4276. return literalStringMembers;
  4277. }
  4278. }
  4279. return Object.create(null);
  4280. }
  4281. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4282. if (typeof memberName !== 'string' || !members[memberName]) {
  4283. return true;
  4284. }
  4285. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  4286. }
  4287. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4288. if (typeof memberName !== 'string' || !members[memberName])
  4289. return UNKNOWN_RETURN_EXPRESSION;
  4290. return [members[memberName].returns, false];
  4291. }
  4292. class Method extends ExpressionEntity {
  4293. constructor(description) {
  4294. super();
  4295. this.description = description;
  4296. }
  4297. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  4298. if (type === INTERACTION_CALLED && path.length === 0) {
  4299. if (this.description.mutatesSelfAsArray) {
  4300. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4301. }
  4302. if (this.description.mutatesArgs) {
  4303. for (let index = 1; index < args.length; index++) {
  4304. args[index].deoptimizePath(UNKNOWN_PATH);
  4305. }
  4306. }
  4307. }
  4308. }
  4309. getReturnExpressionWhenCalledAtPath(path, { args }) {
  4310. if (path.length > 0) {
  4311. return UNKNOWN_RETURN_EXPRESSION;
  4312. }
  4313. return [
  4314. this.description.returnsPrimitive ||
  4315. (this.description.returns === 'self'
  4316. ? args[0] || UNKNOWN_EXPRESSION
  4317. : this.description.returns()),
  4318. false
  4319. ];
  4320. }
  4321. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  4322. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4323. return true;
  4324. }
  4325. if (type === INTERACTION_CALLED) {
  4326. if (this.description.mutatesSelfAsArray === true &&
  4327. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  4328. return true;
  4329. }
  4330. if (this.description.callsArgs) {
  4331. for (const argumentIndex of this.description.callsArgs) {
  4332. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4333. return true;
  4334. }
  4335. }
  4336. }
  4337. }
  4338. return false;
  4339. }
  4340. }
  4341. const METHOD_RETURNS_BOOLEAN = [
  4342. new Method({
  4343. callsArgs: null,
  4344. mutatesArgs: false,
  4345. mutatesSelfAsArray: false,
  4346. returns: null,
  4347. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4348. })
  4349. ];
  4350. const METHOD_RETURNS_STRING = [
  4351. new Method({
  4352. callsArgs: null,
  4353. mutatesArgs: false,
  4354. mutatesSelfAsArray: false,
  4355. returns: null,
  4356. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4357. })
  4358. ];
  4359. const METHOD_RETURNS_NUMBER = [
  4360. new Method({
  4361. callsArgs: null,
  4362. mutatesArgs: false,
  4363. mutatesSelfAsArray: false,
  4364. returns: null,
  4365. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4366. })
  4367. ];
  4368. const METHOD_RETURNS_UNKNOWN = [
  4369. new Method({
  4370. callsArgs: null,
  4371. mutatesArgs: false,
  4372. mutatesSelfAsArray: false,
  4373. returns: null,
  4374. returnsPrimitive: UNKNOWN_EXPRESSION
  4375. })
  4376. ];
  4377. const INTEGER_REG_EXP = /^\d+$/;
  4378. class ObjectEntity extends ExpressionEntity {
  4379. get hasLostTrack() {
  4380. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  4381. }
  4382. set hasLostTrack(value) {
  4383. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  4384. }
  4385. get hasUnknownDeoptimizedInteger() {
  4386. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  4387. }
  4388. set hasUnknownDeoptimizedInteger(value) {
  4389. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  4390. }
  4391. get hasUnknownDeoptimizedProperty() {
  4392. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  4393. }
  4394. set hasUnknownDeoptimizedProperty(value) {
  4395. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  4396. }
  4397. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4398. // and we assume there are no setters or getters
  4399. constructor(properties, prototypeExpression, immutable = false) {
  4400. super();
  4401. this.prototypeExpression = prototypeExpression;
  4402. this.immutable = immutable;
  4403. this.additionalExpressionsToBeDeoptimized = new Set();
  4404. this.allProperties = [];
  4405. this.deoptimizedPaths = Object.create(null);
  4406. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4407. this.gettersByKey = Object.create(null);
  4408. this.propertiesAndGettersByKey = Object.create(null);
  4409. this.propertiesAndSettersByKey = Object.create(null);
  4410. this.settersByKey = Object.create(null);
  4411. this.unknownIntegerProps = [];
  4412. this.unmatchableGetters = [];
  4413. this.unmatchablePropertiesAndGetters = [];
  4414. this.unmatchablePropertiesAndSetters = [];
  4415. this.unmatchableSetters = [];
  4416. if (Array.isArray(properties)) {
  4417. this.buildPropertyMaps(properties);
  4418. }
  4419. else {
  4420. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4421. for (const propertiesForKey of Object.values(properties)) {
  4422. this.allProperties.push(...propertiesForKey);
  4423. }
  4424. }
  4425. }
  4426. deoptimizeAllProperties(noAccessors) {
  4427. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4428. if (noAccessors) {
  4429. this.hasUnknownDeoptimizedProperty = true;
  4430. }
  4431. else {
  4432. this.hasLostTrack = true;
  4433. }
  4434. if (isDeoptimized) {
  4435. return;
  4436. }
  4437. for (const properties of [
  4438. ...Object.values(this.propertiesAndGettersByKey),
  4439. ...Object.values(this.settersByKey)
  4440. ]) {
  4441. for (const property of properties) {
  4442. property.deoptimizePath(UNKNOWN_PATH);
  4443. }
  4444. }
  4445. // While the prototype itself cannot be mutated, each property can
  4446. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  4447. this.deoptimizeCachedEntities();
  4448. }
  4449. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4450. const [key, ...subPath] = path;
  4451. const { args, type } = interaction;
  4452. if (this.hasLostTrack ||
  4453. // single paths that are deoptimized will not become getters or setters
  4454. ((type === INTERACTION_CALLED || path.length > 1) &&
  4455. (this.hasUnknownDeoptimizedProperty ||
  4456. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4457. deoptimizeInteraction(interaction);
  4458. return;
  4459. }
  4460. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  4461. ? [
  4462. this.propertiesAndGettersByKey,
  4463. this.propertiesAndGettersByKey,
  4464. this.unmatchablePropertiesAndGetters
  4465. ]
  4466. : type === INTERACTION_ACCESSED
  4467. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4468. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4469. if (typeof key === 'string') {
  4470. if (propertiesForExactMatchByKey[key]) {
  4471. const properties = relevantPropertiesByKey[key];
  4472. if (properties) {
  4473. for (const property of properties) {
  4474. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4475. }
  4476. }
  4477. if (!this.immutable) {
  4478. for (const argument of args) {
  4479. if (argument) {
  4480. this.additionalExpressionsToBeDeoptimized.add(argument);
  4481. }
  4482. }
  4483. }
  4484. return;
  4485. }
  4486. for (const property of relevantUnmatchableProperties) {
  4487. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4488. }
  4489. if (INTEGER_REG_EXP.test(key)) {
  4490. for (const property of this.unknownIntegerProps) {
  4491. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4492. }
  4493. }
  4494. }
  4495. else {
  4496. for (const properties of [
  4497. ...Object.values(relevantPropertiesByKey),
  4498. relevantUnmatchableProperties
  4499. ]) {
  4500. for (const property of properties) {
  4501. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4502. }
  4503. }
  4504. for (const property of this.unknownIntegerProps) {
  4505. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4506. }
  4507. }
  4508. if (!this.immutable) {
  4509. for (const argument of args) {
  4510. if (argument) {
  4511. this.additionalExpressionsToBeDeoptimized.add(argument);
  4512. }
  4513. }
  4514. }
  4515. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4516. }
  4517. deoptimizeIntegerProperties() {
  4518. if (this.hasLostTrack ||
  4519. this.hasUnknownDeoptimizedProperty ||
  4520. this.hasUnknownDeoptimizedInteger) {
  4521. return;
  4522. }
  4523. this.hasUnknownDeoptimizedInteger = true;
  4524. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4525. if (INTEGER_REG_EXP.test(key)) {
  4526. for (const property of propertiesAndGetters) {
  4527. property.deoptimizePath(UNKNOWN_PATH);
  4528. }
  4529. }
  4530. }
  4531. this.deoptimizeCachedIntegerEntities();
  4532. }
  4533. // Assumption: If only a specific path is deoptimized, no accessors are created
  4534. deoptimizePath(path) {
  4535. if (this.hasLostTrack || this.immutable) {
  4536. return;
  4537. }
  4538. const key = path[0];
  4539. if (path.length === 1) {
  4540. if (key === UnknownInteger) {
  4541. return this.deoptimizeIntegerProperties();
  4542. }
  4543. else if (typeof key !== 'string') {
  4544. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4545. }
  4546. if (!this.deoptimizedPaths[key]) {
  4547. this.deoptimizedPaths[key] = true;
  4548. // we only deoptimizeCache exact matches as in all other cases,
  4549. // we do not return a literal value or return expression
  4550. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4551. if (expressionsToBeDeoptimized) {
  4552. for (const expression of expressionsToBeDeoptimized) {
  4553. expression.deoptimizeCache();
  4554. }
  4555. }
  4556. }
  4557. }
  4558. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4559. for (const property of typeof key === 'string'
  4560. ? [
  4561. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  4562. ...(this.settersByKey[key] || this.unmatchableSetters)
  4563. ]
  4564. : this.allProperties) {
  4565. property.deoptimizePath(subPath);
  4566. }
  4567. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  4568. }
  4569. getLiteralValueAtPath(path, recursionTracker, origin) {
  4570. if (path.length === 0) {
  4571. // This should actually be "UnknownTruthyValue". However, this currently
  4572. // causes an issue with TypeScript enums in files with moduleSideEffects:
  4573. // false because we cannot properly track whether a "var" has been
  4574. // initialized. This should be reverted once we can properly track this.
  4575. // return UnknownTruthyValue;
  4576. return UnknownValue;
  4577. }
  4578. const key = path[0];
  4579. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4580. if (expressionAtPath) {
  4581. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4582. }
  4583. if (this.prototypeExpression) {
  4584. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4585. }
  4586. if (path.length === 1) {
  4587. return undefined;
  4588. }
  4589. return UnknownValue;
  4590. }
  4591. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4592. if (path.length === 0) {
  4593. return UNKNOWN_RETURN_EXPRESSION;
  4594. }
  4595. const [key, ...subPath] = path;
  4596. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4597. if (expressionAtPath) {
  4598. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4599. }
  4600. if (this.prototypeExpression) {
  4601. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4602. }
  4603. return UNKNOWN_RETURN_EXPRESSION;
  4604. }
  4605. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4606. const [key, ...subPath] = path;
  4607. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  4608. const expressionAtPath = this.getMemberExpression(key);
  4609. if (expressionAtPath) {
  4610. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  4611. }
  4612. if (this.prototypeExpression) {
  4613. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4614. }
  4615. return true;
  4616. }
  4617. if (key === UnknownNonAccessorKey)
  4618. return false;
  4619. if (this.hasLostTrack)
  4620. return true;
  4621. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  4622. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4623. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4624. if (typeof key === 'string') {
  4625. if (propertiesAndAccessorsByKey[key]) {
  4626. const accessors = accessorsByKey[key];
  4627. if (accessors) {
  4628. for (const accessor of accessors) {
  4629. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4630. return true;
  4631. }
  4632. }
  4633. return false;
  4634. }
  4635. for (const accessor of unmatchableAccessors) {
  4636. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  4637. return true;
  4638. }
  4639. }
  4640. }
  4641. else {
  4642. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  4643. for (const accessor of accessors) {
  4644. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4645. return true;
  4646. }
  4647. }
  4648. }
  4649. if (this.prototypeExpression) {
  4650. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4651. }
  4652. return false;
  4653. }
  4654. include(context, includeChildrenRecursively) {
  4655. this.included = true;
  4656. for (const property of this.allProperties) {
  4657. if (includeChildrenRecursively || property.shouldBeIncluded(context)) {
  4658. property.include(context, includeChildrenRecursively);
  4659. }
  4660. }
  4661. this.prototypeExpression?.include(context, includeChildrenRecursively);
  4662. }
  4663. includePath(path, context) {
  4664. this.included = true;
  4665. if (path.length === 0)
  4666. return;
  4667. const [key, ...subPath] = path;
  4668. const [includedMembers, includedPath] = typeof key === 'string'
  4669. ? [
  4670. new Set([
  4671. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  4672. ...(this.propertiesAndSettersByKey[key] || this.unmatchablePropertiesAndSetters)
  4673. ]),
  4674. subPath
  4675. ]
  4676. : [this.allProperties, UNKNOWN_PATH];
  4677. for (const property of includedMembers) {
  4678. property.includePath(includedPath, context);
  4679. }
  4680. this.prototypeExpression?.includePath(path, context);
  4681. }
  4682. buildPropertyMaps(properties) {
  4683. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  4684. for (let index = properties.length - 1; index >= 0; index--) {
  4685. const { key, kind, property } = properties[index];
  4686. allProperties.push(property);
  4687. if (typeof key === 'string') {
  4688. if (kind === 'set') {
  4689. if (!propertiesAndSettersByKey[key]) {
  4690. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4691. settersByKey[key] = [property, ...unmatchableSetters];
  4692. }
  4693. }
  4694. else if (kind === 'get') {
  4695. if (!propertiesAndGettersByKey[key]) {
  4696. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4697. gettersByKey[key] = [property, ...unmatchableGetters];
  4698. }
  4699. }
  4700. else {
  4701. if (!propertiesAndSettersByKey[key]) {
  4702. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4703. }
  4704. if (!propertiesAndGettersByKey[key]) {
  4705. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4706. }
  4707. }
  4708. }
  4709. else {
  4710. if (key === UnknownInteger) {
  4711. unknownIntegerProps.push(property);
  4712. continue;
  4713. }
  4714. if (kind === 'set')
  4715. unmatchableSetters.push(property);
  4716. if (kind === 'get')
  4717. unmatchableGetters.push(property);
  4718. if (kind !== 'get')
  4719. unmatchablePropertiesAndSetters.push(property);
  4720. if (kind !== 'set')
  4721. unmatchablePropertiesAndGetters.push(property);
  4722. }
  4723. }
  4724. }
  4725. deoptimizeCachedEntities() {
  4726. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  4727. for (const expression of expressionsToBeDeoptimized) {
  4728. expression.deoptimizeCache();
  4729. }
  4730. }
  4731. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4732. expression.deoptimizePath(UNKNOWN_PATH);
  4733. }
  4734. }
  4735. deoptimizeCachedIntegerEntities() {
  4736. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  4737. if (INTEGER_REG_EXP.test(key)) {
  4738. for (const expression of expressionsToBeDeoptimized) {
  4739. expression.deoptimizeCache();
  4740. }
  4741. }
  4742. }
  4743. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4744. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4745. }
  4746. }
  4747. getMemberExpression(key) {
  4748. if (this.hasLostTrack ||
  4749. this.hasUnknownDeoptimizedProperty ||
  4750. typeof key !== 'string' ||
  4751. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  4752. this.deoptimizedPaths[key]) {
  4753. return UNKNOWN_EXPRESSION;
  4754. }
  4755. const properties = this.propertiesAndGettersByKey[key];
  4756. if (properties?.length === 1) {
  4757. return properties[0];
  4758. }
  4759. if (properties ||
  4760. this.unmatchablePropertiesAndGetters.length > 0 ||
  4761. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  4762. return UNKNOWN_EXPRESSION;
  4763. }
  4764. return null;
  4765. }
  4766. getMemberExpressionAndTrackDeopt(key, origin) {
  4767. if (typeof key !== 'string') {
  4768. return UNKNOWN_EXPRESSION;
  4769. }
  4770. const expression = this.getMemberExpression(key);
  4771. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  4772. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  4773. this.expressionsToBeDeoptimizedByKey[key] || []);
  4774. expressionsToBeDeoptimized.push(origin);
  4775. }
  4776. return expression;
  4777. }
  4778. }
  4779. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  4780. // This makes sure unknown properties are not handled as "undefined" but as
  4781. // "unknown" but without access side effects. An exception is done for numeric
  4782. // properties as we do not expect new builtin properties to be numbers, this
  4783. // will improve tree-shaking for out-of-bounds array properties
  4784. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  4785. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  4786. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  4787. deoptimizeInteraction(interaction);
  4788. }
  4789. }
  4790. getLiteralValueAtPath(path) {
  4791. // We ignore number properties as we do not expect new properties to be
  4792. // numbers and also want to keep handling out-of-bound array elements as
  4793. // "undefined"
  4794. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  4795. }
  4796. hasEffectsOnInteractionAtPath(path, { type }) {
  4797. return path.length > 1 || type === INTERACTION_CALLED;
  4798. }
  4799. })();
  4800. const OBJECT_PROTOTYPE = new ObjectEntity({
  4801. __proto__: null,
  4802. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  4803. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  4804. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  4805. toLocaleString: METHOD_RETURNS_STRING,
  4806. toString: METHOD_RETURNS_STRING,
  4807. valueOf: METHOD_RETURNS_UNKNOWN
  4808. }, OBJECT_PROTOTYPE_FALLBACK, true);
  4809. const NEW_ARRAY_PROPERTIES = [
  4810. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  4811. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  4812. ];
  4813. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  4814. new Method({
  4815. callsArgs: [0],
  4816. mutatesArgs: false,
  4817. mutatesSelfAsArray: 'deopt-only',
  4818. returns: null,
  4819. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4820. })
  4821. ];
  4822. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  4823. new Method({
  4824. callsArgs: [0],
  4825. mutatesArgs: false,
  4826. mutatesSelfAsArray: 'deopt-only',
  4827. returns: null,
  4828. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4829. })
  4830. ];
  4831. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  4832. new Method({
  4833. callsArgs: null,
  4834. mutatesArgs: false,
  4835. mutatesSelfAsArray: true,
  4836. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4837. returnsPrimitive: null
  4838. })
  4839. ];
  4840. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4841. new Method({
  4842. callsArgs: null,
  4843. mutatesArgs: false,
  4844. mutatesSelfAsArray: 'deopt-only',
  4845. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4846. returnsPrimitive: null
  4847. })
  4848. ];
  4849. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4850. new Method({
  4851. callsArgs: [0],
  4852. mutatesArgs: false,
  4853. mutatesSelfAsArray: 'deopt-only',
  4854. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4855. returnsPrimitive: null
  4856. })
  4857. ];
  4858. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  4859. new Method({
  4860. callsArgs: null,
  4861. mutatesArgs: true,
  4862. mutatesSelfAsArray: true,
  4863. returns: null,
  4864. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4865. })
  4866. ];
  4867. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  4868. new Method({
  4869. callsArgs: null,
  4870. mutatesArgs: false,
  4871. mutatesSelfAsArray: true,
  4872. returns: null,
  4873. returnsPrimitive: UNKNOWN_EXPRESSION
  4874. })
  4875. ];
  4876. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4877. new Method({
  4878. callsArgs: null,
  4879. mutatesArgs: false,
  4880. mutatesSelfAsArray: 'deopt-only',
  4881. returns: null,
  4882. returnsPrimitive: UNKNOWN_EXPRESSION
  4883. })
  4884. ];
  4885. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4886. new Method({
  4887. callsArgs: [0],
  4888. mutatesArgs: false,
  4889. mutatesSelfAsArray: 'deopt-only',
  4890. returns: null,
  4891. returnsPrimitive: UNKNOWN_EXPRESSION
  4892. })
  4893. ];
  4894. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  4895. new Method({
  4896. callsArgs: null,
  4897. mutatesArgs: false,
  4898. mutatesSelfAsArray: true,
  4899. returns: 'self',
  4900. returnsPrimitive: null
  4901. })
  4902. ];
  4903. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  4904. new Method({
  4905. callsArgs: [0],
  4906. mutatesArgs: false,
  4907. mutatesSelfAsArray: true,
  4908. returns: 'self',
  4909. returnsPrimitive: null
  4910. })
  4911. ];
  4912. const ARRAY_PROTOTYPE = new ObjectEntity({
  4913. __proto__: null,
  4914. // We assume that accessors have effects as we do not track the accessed value afterwards
  4915. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  4916. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4917. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  4918. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4919. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4920. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  4921. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4922. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4923. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4924. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4925. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4926. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4927. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4928. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4929. includes: METHOD_RETURNS_BOOLEAN,
  4930. indexOf: METHOD_RETURNS_NUMBER,
  4931. join: METHOD_RETURNS_STRING,
  4932. keys: METHOD_RETURNS_UNKNOWN,
  4933. lastIndexOf: METHOD_RETURNS_NUMBER,
  4934. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4935. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4936. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4937. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4938. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4939. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  4940. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4941. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4942. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4943. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  4944. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  4945. toLocaleString: METHOD_RETURNS_STRING,
  4946. toString: METHOD_RETURNS_STRING,
  4947. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4948. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  4949. }, OBJECT_PROTOTYPE, true);
  4950. class SpreadElement extends NodeBase {
  4951. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4952. if (path.length > 0) {
  4953. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  4954. }
  4955. }
  4956. hasEffects(context) {
  4957. if (!this.deoptimized)
  4958. this.applyDeoptimizations();
  4959. const { propertyReadSideEffects } = this.scope.context.options
  4960. .treeshake;
  4961. return (this.argument.hasEffects(context) ||
  4962. (propertyReadSideEffects &&
  4963. (propertyReadSideEffects === 'always' ||
  4964. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4965. }
  4966. includeNode(context) {
  4967. this.included = true;
  4968. if (!this.deoptimized)
  4969. this.applyDeoptimizations();
  4970. this.argument.includePath(UNKNOWN_PATH, context);
  4971. }
  4972. applyDeoptimizations() {
  4973. this.deoptimized = true;
  4974. // Only properties of properties of the argument could become subject to reassignment
  4975. // This will also reassign the return values of iterators
  4976. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4977. this.scope.context.requestTreeshakingPass();
  4978. }
  4979. }
  4980. class ArrayExpression extends NodeBase {
  4981. constructor() {
  4982. super(...arguments);
  4983. this.objectEntity = null;
  4984. }
  4985. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4986. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4987. }
  4988. deoptimizePath(path) {
  4989. this.getObjectEntity().deoptimizePath(path);
  4990. }
  4991. getLiteralValueAtPath(path, recursionTracker, origin) {
  4992. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  4993. }
  4994. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4995. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4996. }
  4997. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4998. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  4999. }
  5000. includeNode(context) {
  5001. this.included = true;
  5002. if (!this.deoptimized)
  5003. this.applyDeoptimizations();
  5004. for (const element of this.elements) {
  5005. if (element) {
  5006. element?.includePath(UNKNOWN_PATH, context);
  5007. }
  5008. }
  5009. }
  5010. applyDeoptimizations() {
  5011. this.deoptimized = true;
  5012. let hasSpread = false;
  5013. for (let index = 0; index < this.elements.length; index++) {
  5014. const element = this.elements[index];
  5015. if (element && (hasSpread || element instanceof SpreadElement)) {
  5016. hasSpread = true;
  5017. element.deoptimizePath(UNKNOWN_PATH);
  5018. }
  5019. }
  5020. this.scope.context.requestTreeshakingPass();
  5021. }
  5022. getObjectEntity() {
  5023. if (this.objectEntity !== null) {
  5024. return this.objectEntity;
  5025. }
  5026. const properties = [
  5027. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5028. ];
  5029. let hasSpread = false;
  5030. for (let index = 0; index < this.elements.length; index++) {
  5031. const element = this.elements[index];
  5032. if (hasSpread || element instanceof SpreadElement) {
  5033. if (element) {
  5034. hasSpread = true;
  5035. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5036. }
  5037. }
  5038. else if (element) {
  5039. properties.push({ key: String(index), kind: 'init', property: element });
  5040. }
  5041. else {
  5042. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5043. }
  5044. }
  5045. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5046. }
  5047. }
  5048. /* eslint sort-keys: "off" */
  5049. const ValueProperties = Symbol('Value Properties');
  5050. const getUnknownValue = () => UnknownValue;
  5051. const returnFalse = () => false;
  5052. const returnTrue = () => true;
  5053. const PURE = {
  5054. deoptimizeArgumentsOnCall: doNothing,
  5055. getLiteralValue: getUnknownValue,
  5056. hasEffectsWhenCalled: returnFalse
  5057. };
  5058. const IMPURE = {
  5059. deoptimizeArgumentsOnCall: doNothing,
  5060. getLiteralValue: getUnknownValue,
  5061. hasEffectsWhenCalled: returnTrue
  5062. };
  5063. const PURE_WITH_ARRAY = {
  5064. deoptimizeArgumentsOnCall: doNothing,
  5065. getLiteralValue: getUnknownValue,
  5066. hasEffectsWhenCalled({ args }) {
  5067. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  5068. }
  5069. };
  5070. const GETTER_ACCESS = {
  5071. deoptimizeArgumentsOnCall: doNothing,
  5072. getLiteralValue: getUnknownValue,
  5073. hasEffectsWhenCalled({ args }, context) {
  5074. const [_thisArgument, firstArgument] = args;
  5075. return (!(firstArgument instanceof ExpressionEntity) ||
  5076. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5077. }
  5078. };
  5079. // We use shortened variables to reduce file size here
  5080. /* OBJECT */
  5081. const O = {
  5082. __proto__: null,
  5083. [ValueProperties]: IMPURE
  5084. };
  5085. /* PURE FUNCTION */
  5086. const PF = {
  5087. __proto__: null,
  5088. [ValueProperties]: PURE
  5089. };
  5090. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  5091. const PF_NO_GETTER = {
  5092. __proto__: null,
  5093. [ValueProperties]: GETTER_ACCESS
  5094. };
  5095. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5096. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5097. __proto__: null,
  5098. [ValueProperties]: {
  5099. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  5100. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  5101. },
  5102. getLiteralValue: getUnknownValue,
  5103. hasEffectsWhenCalled({ args }, context) {
  5104. return (args.length <= 1 ||
  5105. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5106. }
  5107. }
  5108. };
  5109. /* CONSTRUCTOR */
  5110. const C = {
  5111. __proto__: null,
  5112. [ValueProperties]: IMPURE,
  5113. prototype: O
  5114. };
  5115. /* PURE CONSTRUCTOR */
  5116. const PC = {
  5117. __proto__: null,
  5118. [ValueProperties]: PURE,
  5119. prototype: O
  5120. };
  5121. const PC_WITH_ARRAY = {
  5122. __proto__: null,
  5123. [ValueProperties]: PURE_WITH_ARRAY,
  5124. prototype: O
  5125. };
  5126. const ARRAY_TYPE = {
  5127. __proto__: null,
  5128. [ValueProperties]: PURE,
  5129. from: O,
  5130. of: PF,
  5131. prototype: O
  5132. };
  5133. const INTL_MEMBER = {
  5134. __proto__: null,
  5135. [ValueProperties]: PURE,
  5136. supportedLocalesOf: PC
  5137. };
  5138. const knownGlobals = {
  5139. // Placeholders for global objects to avoid shape mutations
  5140. global: O,
  5141. globalThis: O,
  5142. self: O,
  5143. window: O,
  5144. // Common globals
  5145. __proto__: null,
  5146. [ValueProperties]: IMPURE,
  5147. Array: {
  5148. __proto__: null,
  5149. [ValueProperties]: IMPURE,
  5150. from: O,
  5151. isArray: PF,
  5152. of: PF,
  5153. prototype: O
  5154. },
  5155. ArrayBuffer: {
  5156. __proto__: null,
  5157. [ValueProperties]: PURE,
  5158. isView: PF,
  5159. prototype: O
  5160. },
  5161. AggregateError: PC_WITH_ARRAY,
  5162. Atomics: O,
  5163. BigInt: C,
  5164. BigInt64Array: C,
  5165. BigUint64Array: C,
  5166. Boolean: PC,
  5167. constructor: C,
  5168. DataView: PC,
  5169. Date: {
  5170. __proto__: null,
  5171. [ValueProperties]: PURE,
  5172. now: PF,
  5173. parse: PF,
  5174. prototype: O,
  5175. UTC: PF
  5176. },
  5177. decodeURI: PF,
  5178. decodeURIComponent: PF,
  5179. encodeURI: PF,
  5180. encodeURIComponent: PF,
  5181. Error: PC,
  5182. escape: PF,
  5183. eval: O,
  5184. EvalError: PC,
  5185. FinalizationRegistry: C,
  5186. Float32Array: ARRAY_TYPE,
  5187. Float64Array: ARRAY_TYPE,
  5188. Function: C,
  5189. hasOwnProperty: O,
  5190. Infinity: O,
  5191. Int16Array: ARRAY_TYPE,
  5192. Int32Array: ARRAY_TYPE,
  5193. Int8Array: ARRAY_TYPE,
  5194. isFinite: PF,
  5195. isNaN: PF,
  5196. isPrototypeOf: O,
  5197. JSON: O,
  5198. Map: PC_WITH_ARRAY,
  5199. Math: {
  5200. __proto__: null,
  5201. [ValueProperties]: IMPURE,
  5202. abs: PF,
  5203. acos: PF,
  5204. acosh: PF,
  5205. asin: PF,
  5206. asinh: PF,
  5207. atan: PF,
  5208. atan2: PF,
  5209. atanh: PF,
  5210. cbrt: PF,
  5211. ceil: PF,
  5212. clz32: PF,
  5213. cos: PF,
  5214. cosh: PF,
  5215. exp: PF,
  5216. expm1: PF,
  5217. floor: PF,
  5218. fround: PF,
  5219. hypot: PF,
  5220. imul: PF,
  5221. log: PF,
  5222. log10: PF,
  5223. log1p: PF,
  5224. log2: PF,
  5225. max: PF,
  5226. min: PF,
  5227. pow: PF,
  5228. random: PF,
  5229. round: PF,
  5230. sign: PF,
  5231. sin: PF,
  5232. sinh: PF,
  5233. sqrt: PF,
  5234. tan: PF,
  5235. tanh: PF,
  5236. trunc: PF
  5237. },
  5238. NaN: O,
  5239. Number: {
  5240. __proto__: null,
  5241. [ValueProperties]: PURE,
  5242. isFinite: PF,
  5243. isInteger: PF,
  5244. isNaN: PF,
  5245. isSafeInteger: PF,
  5246. parseFloat: PF,
  5247. parseInt: PF,
  5248. prototype: O
  5249. },
  5250. Object: {
  5251. __proto__: null,
  5252. [ValueProperties]: PURE,
  5253. create: PF,
  5254. // Technically those can throw in certain situations, but we ignore this as
  5255. // code that relies on this will hopefully wrap this in a try-catch, which
  5256. // deoptimizes everything anyway
  5257. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5258. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5259. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  5260. getOwnPropertyDescriptor: PF,
  5261. getOwnPropertyDescriptors: PF,
  5262. getOwnPropertyNames: PF,
  5263. getOwnPropertySymbols: PF,
  5264. getPrototypeOf: PF,
  5265. hasOwn: PF,
  5266. is: PF,
  5267. isExtensible: PF,
  5268. isFrozen: PF,
  5269. isSealed: PF,
  5270. keys: PF,
  5271. fromEntries: O,
  5272. entries: PF_NO_GETTER,
  5273. values: PF_NO_GETTER,
  5274. prototype: O
  5275. },
  5276. parseFloat: PF,
  5277. parseInt: PF,
  5278. Promise: {
  5279. __proto__: null,
  5280. [ValueProperties]: IMPURE,
  5281. all: O,
  5282. allSettled: O,
  5283. any: O,
  5284. prototype: O,
  5285. race: O,
  5286. reject: O,
  5287. resolve: O
  5288. },
  5289. propertyIsEnumerable: O,
  5290. Proxy: {
  5291. __proto__: null,
  5292. [ValueProperties]: {
  5293. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  5294. if (isObjectExpressionNode(parameter)) {
  5295. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  5296. if (!hasSpreadElement) {
  5297. for (const property of parameter.properties) {
  5298. property.deoptimizeArgumentsOnInteractionAtPath({
  5299. args: [null, target],
  5300. type: INTERACTION_CALLED,
  5301. withNew: false
  5302. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  5303. }
  5304. return;
  5305. }
  5306. }
  5307. target.deoptimizePath(UNKNOWN_PATH);
  5308. },
  5309. getLiteralValue: getUnknownValue,
  5310. hasEffectsWhenCalled: returnTrue
  5311. }
  5312. },
  5313. RangeError: PC,
  5314. ReferenceError: PC,
  5315. Reflect: O,
  5316. RegExp: PC,
  5317. Set: PC_WITH_ARRAY,
  5318. SharedArrayBuffer: C,
  5319. String: {
  5320. __proto__: null,
  5321. [ValueProperties]: PURE,
  5322. fromCharCode: PF,
  5323. fromCodePoint: PF,
  5324. prototype: O,
  5325. raw: PF
  5326. },
  5327. Symbol: {
  5328. __proto__: null,
  5329. [ValueProperties]: PURE,
  5330. for: PF,
  5331. keyFor: PF,
  5332. prototype: O,
  5333. toStringTag: {
  5334. __proto__: null,
  5335. [ValueProperties]: {
  5336. deoptimizeArgumentsOnCall: doNothing,
  5337. getLiteralValue() {
  5338. return SymbolToStringTag;
  5339. },
  5340. hasEffectsWhenCalled: returnTrue
  5341. }
  5342. }
  5343. },
  5344. SyntaxError: PC,
  5345. toLocaleString: O,
  5346. toString: O,
  5347. TypeError: PC,
  5348. Uint16Array: ARRAY_TYPE,
  5349. Uint32Array: ARRAY_TYPE,
  5350. Uint8Array: ARRAY_TYPE,
  5351. Uint8ClampedArray: ARRAY_TYPE,
  5352. // Technically, this is a global, but it needs special handling
  5353. // undefined: ?,
  5354. unescape: PF,
  5355. URIError: PC,
  5356. valueOf: O,
  5357. WeakMap: PC_WITH_ARRAY,
  5358. WeakRef: C,
  5359. WeakSet: PC_WITH_ARRAY,
  5360. // Additional globals shared by Node and Browser that are not strictly part of the language
  5361. clearInterval: C,
  5362. clearTimeout: C,
  5363. console: {
  5364. __proto__: null,
  5365. [ValueProperties]: IMPURE,
  5366. assert: C,
  5367. clear: C,
  5368. count: C,
  5369. countReset: C,
  5370. debug: C,
  5371. dir: C,
  5372. dirxml: C,
  5373. error: C,
  5374. exception: C,
  5375. group: C,
  5376. groupCollapsed: C,
  5377. groupEnd: C,
  5378. info: C,
  5379. log: C,
  5380. table: C,
  5381. time: C,
  5382. timeEnd: C,
  5383. timeLog: C,
  5384. trace: C,
  5385. warn: C
  5386. },
  5387. Intl: {
  5388. __proto__: null,
  5389. [ValueProperties]: IMPURE,
  5390. Collator: INTL_MEMBER,
  5391. DateTimeFormat: INTL_MEMBER,
  5392. DisplayNames: INTL_MEMBER,
  5393. ListFormat: INTL_MEMBER,
  5394. Locale: INTL_MEMBER,
  5395. NumberFormat: INTL_MEMBER,
  5396. PluralRules: INTL_MEMBER,
  5397. RelativeTimeFormat: INTL_MEMBER,
  5398. Segmenter: INTL_MEMBER
  5399. },
  5400. setInterval: C,
  5401. setTimeout: C,
  5402. TextDecoder: C,
  5403. TextEncoder: C,
  5404. URL: {
  5405. __proto__: null,
  5406. [ValueProperties]: IMPURE,
  5407. prototype: O,
  5408. canParse: PF
  5409. },
  5410. URLSearchParams: C,
  5411. // Browser specific globals
  5412. AbortController: C,
  5413. AbortSignal: C,
  5414. addEventListener: O,
  5415. alert: O,
  5416. AnalyserNode: C,
  5417. Animation: C,
  5418. AnimationEvent: C,
  5419. applicationCache: O,
  5420. ApplicationCache: C,
  5421. ApplicationCacheErrorEvent: C,
  5422. atob: O,
  5423. Attr: C,
  5424. Audio: C,
  5425. AudioBuffer: C,
  5426. AudioBufferSourceNode: C,
  5427. AudioContext: C,
  5428. AudioDestinationNode: C,
  5429. AudioListener: C,
  5430. AudioNode: C,
  5431. AudioParam: C,
  5432. AudioProcessingEvent: C,
  5433. AudioScheduledSourceNode: C,
  5434. AudioWorkletNode: C,
  5435. BarProp: C,
  5436. BaseAudioContext: C,
  5437. BatteryManager: C,
  5438. BeforeUnloadEvent: C,
  5439. BiquadFilterNode: C,
  5440. Blob: C,
  5441. BlobEvent: C,
  5442. blur: O,
  5443. BroadcastChannel: C,
  5444. btoa: O,
  5445. ByteLengthQueuingStrategy: C,
  5446. Cache: C,
  5447. caches: O,
  5448. CacheStorage: C,
  5449. cancelAnimationFrame: O,
  5450. cancelIdleCallback: O,
  5451. CanvasCaptureMediaStreamTrack: C,
  5452. CanvasGradient: C,
  5453. CanvasPattern: C,
  5454. CanvasRenderingContext2D: C,
  5455. ChannelMergerNode: C,
  5456. ChannelSplitterNode: C,
  5457. CharacterData: C,
  5458. clientInformation: O,
  5459. ClipboardEvent: C,
  5460. close: O,
  5461. closed: O,
  5462. CloseEvent: C,
  5463. Comment: C,
  5464. CompositionEvent: C,
  5465. confirm: O,
  5466. ConstantSourceNode: C,
  5467. ConvolverNode: C,
  5468. CountQueuingStrategy: C,
  5469. createImageBitmap: O,
  5470. Credential: C,
  5471. CredentialsContainer: C,
  5472. crypto: O,
  5473. Crypto: C,
  5474. CryptoKey: C,
  5475. CSS: C,
  5476. CSSConditionRule: C,
  5477. CSSFontFaceRule: C,
  5478. CSSGroupingRule: C,
  5479. CSSImportRule: C,
  5480. CSSKeyframeRule: C,
  5481. CSSKeyframesRule: C,
  5482. CSSMediaRule: C,
  5483. CSSNamespaceRule: C,
  5484. CSSPageRule: C,
  5485. CSSRule: C,
  5486. CSSRuleList: C,
  5487. CSSStyleDeclaration: C,
  5488. CSSStyleRule: C,
  5489. CSSStyleSheet: C,
  5490. CSSSupportsRule: C,
  5491. CustomElementRegistry: C,
  5492. customElements: O,
  5493. CustomEvent: {
  5494. __proto__: null,
  5495. [ValueProperties]: {
  5496. deoptimizeArgumentsOnCall({ args }) {
  5497. args[2]?.deoptimizePath(['detail']);
  5498. },
  5499. getLiteralValue: getUnknownValue,
  5500. hasEffectsWhenCalled: returnFalse
  5501. },
  5502. prototype: O
  5503. },
  5504. DataTransfer: C,
  5505. DataTransferItem: C,
  5506. DataTransferItemList: C,
  5507. defaultstatus: O,
  5508. defaultStatus: O,
  5509. DelayNode: C,
  5510. DeviceMotionEvent: C,
  5511. DeviceOrientationEvent: C,
  5512. devicePixelRatio: O,
  5513. dispatchEvent: O,
  5514. document: O,
  5515. Document: C,
  5516. DocumentFragment: C,
  5517. DocumentType: C,
  5518. DOMError: C,
  5519. DOMException: C,
  5520. DOMImplementation: C,
  5521. DOMMatrix: C,
  5522. DOMMatrixReadOnly: C,
  5523. DOMParser: C,
  5524. DOMPoint: C,
  5525. DOMPointReadOnly: C,
  5526. DOMQuad: C,
  5527. DOMRect: C,
  5528. DOMRectReadOnly: C,
  5529. DOMStringList: C,
  5530. DOMStringMap: C,
  5531. DOMTokenList: C,
  5532. DragEvent: C,
  5533. DynamicsCompressorNode: C,
  5534. Element: C,
  5535. ErrorEvent: C,
  5536. Event: C,
  5537. EventSource: C,
  5538. EventTarget: C,
  5539. external: O,
  5540. fetch: O,
  5541. File: C,
  5542. FileList: C,
  5543. FileReader: C,
  5544. find: O,
  5545. focus: O,
  5546. FocusEvent: C,
  5547. FontFace: C,
  5548. FontFaceSetLoadEvent: C,
  5549. FormData: C,
  5550. frames: O,
  5551. GainNode: C,
  5552. Gamepad: C,
  5553. GamepadButton: C,
  5554. GamepadEvent: C,
  5555. getComputedStyle: O,
  5556. getSelection: O,
  5557. HashChangeEvent: C,
  5558. Headers: C,
  5559. history: O,
  5560. History: C,
  5561. HTMLAllCollection: C,
  5562. HTMLAnchorElement: C,
  5563. HTMLAreaElement: C,
  5564. HTMLAudioElement: C,
  5565. HTMLBaseElement: C,
  5566. HTMLBodyElement: C,
  5567. HTMLBRElement: C,
  5568. HTMLButtonElement: C,
  5569. HTMLCanvasElement: C,
  5570. HTMLCollection: C,
  5571. HTMLContentElement: C,
  5572. HTMLDataElement: C,
  5573. HTMLDataListElement: C,
  5574. HTMLDetailsElement: C,
  5575. HTMLDialogElement: C,
  5576. HTMLDirectoryElement: C,
  5577. HTMLDivElement: C,
  5578. HTMLDListElement: C,
  5579. HTMLDocument: C,
  5580. HTMLElement: C,
  5581. HTMLEmbedElement: C,
  5582. HTMLFieldSetElement: C,
  5583. HTMLFontElement: C,
  5584. HTMLFormControlsCollection: C,
  5585. HTMLFormElement: C,
  5586. HTMLFrameElement: C,
  5587. HTMLFrameSetElement: C,
  5588. HTMLHeadElement: C,
  5589. HTMLHeadingElement: C,
  5590. HTMLHRElement: C,
  5591. HTMLHtmlElement: C,
  5592. HTMLIFrameElement: C,
  5593. HTMLImageElement: C,
  5594. HTMLInputElement: C,
  5595. HTMLLabelElement: C,
  5596. HTMLLegendElement: C,
  5597. HTMLLIElement: C,
  5598. HTMLLinkElement: C,
  5599. HTMLMapElement: C,
  5600. HTMLMarqueeElement: C,
  5601. HTMLMediaElement: C,
  5602. HTMLMenuElement: C,
  5603. HTMLMetaElement: C,
  5604. HTMLMeterElement: C,
  5605. HTMLModElement: C,
  5606. HTMLObjectElement: C,
  5607. HTMLOListElement: C,
  5608. HTMLOptGroupElement: C,
  5609. HTMLOptionElement: C,
  5610. HTMLOptionsCollection: C,
  5611. HTMLOutputElement: C,
  5612. HTMLParagraphElement: C,
  5613. HTMLParamElement: C,
  5614. HTMLPictureElement: C,
  5615. HTMLPreElement: C,
  5616. HTMLProgressElement: C,
  5617. HTMLQuoteElement: C,
  5618. HTMLScriptElement: C,
  5619. HTMLSelectElement: C,
  5620. HTMLShadowElement: C,
  5621. HTMLSlotElement: C,
  5622. HTMLSourceElement: C,
  5623. HTMLSpanElement: C,
  5624. HTMLStyleElement: C,
  5625. HTMLTableCaptionElement: C,
  5626. HTMLTableCellElement: C,
  5627. HTMLTableColElement: C,
  5628. HTMLTableElement: C,
  5629. HTMLTableRowElement: C,
  5630. HTMLTableSectionElement: C,
  5631. HTMLTemplateElement: C,
  5632. HTMLTextAreaElement: C,
  5633. HTMLTimeElement: C,
  5634. HTMLTitleElement: C,
  5635. HTMLTrackElement: C,
  5636. HTMLUListElement: C,
  5637. HTMLUnknownElement: C,
  5638. HTMLVideoElement: C,
  5639. IDBCursor: C,
  5640. IDBCursorWithValue: C,
  5641. IDBDatabase: C,
  5642. IDBFactory: C,
  5643. IDBIndex: C,
  5644. IDBKeyRange: C,
  5645. IDBObjectStore: C,
  5646. IDBOpenDBRequest: C,
  5647. IDBRequest: C,
  5648. IDBTransaction: C,
  5649. IDBVersionChangeEvent: C,
  5650. IdleDeadline: C,
  5651. IIRFilterNode: C,
  5652. Image: C,
  5653. ImageBitmap: C,
  5654. ImageBitmapRenderingContext: C,
  5655. ImageCapture: C,
  5656. ImageData: C,
  5657. indexedDB: O,
  5658. innerHeight: O,
  5659. innerWidth: O,
  5660. InputEvent: C,
  5661. IntersectionObserver: C,
  5662. IntersectionObserverEntry: C,
  5663. isSecureContext: O,
  5664. KeyboardEvent: C,
  5665. KeyframeEffect: C,
  5666. length: O,
  5667. localStorage: O,
  5668. location: O,
  5669. Location: C,
  5670. locationbar: O,
  5671. matchMedia: O,
  5672. MediaDeviceInfo: C,
  5673. MediaDevices: C,
  5674. MediaElementAudioSourceNode: C,
  5675. MediaEncryptedEvent: C,
  5676. MediaError: C,
  5677. MediaKeyMessageEvent: C,
  5678. MediaKeySession: C,
  5679. MediaKeyStatusMap: C,
  5680. MediaKeySystemAccess: C,
  5681. MediaList: C,
  5682. MediaQueryList: C,
  5683. MediaQueryListEvent: C,
  5684. MediaRecorder: C,
  5685. MediaSettingsRange: C,
  5686. MediaSource: C,
  5687. MediaStream: C,
  5688. MediaStreamAudioDestinationNode: C,
  5689. MediaStreamAudioSourceNode: C,
  5690. MediaStreamEvent: C,
  5691. MediaStreamTrack: C,
  5692. MediaStreamTrackEvent: C,
  5693. menubar: O,
  5694. MessageChannel: C,
  5695. MessageEvent: C,
  5696. MessagePort: C,
  5697. MIDIAccess: C,
  5698. MIDIConnectionEvent: C,
  5699. MIDIInput: C,
  5700. MIDIInputMap: C,
  5701. MIDIMessageEvent: C,
  5702. MIDIOutput: C,
  5703. MIDIOutputMap: C,
  5704. MIDIPort: C,
  5705. MimeType: C,
  5706. MimeTypeArray: C,
  5707. MouseEvent: C,
  5708. moveBy: O,
  5709. moveTo: O,
  5710. MutationEvent: C,
  5711. MutationObserver: C,
  5712. MutationRecord: C,
  5713. name: O,
  5714. NamedNodeMap: C,
  5715. NavigationPreloadManager: C,
  5716. navigator: O,
  5717. Navigator: C,
  5718. NetworkInformation: C,
  5719. Node: C,
  5720. NodeFilter: O,
  5721. NodeIterator: C,
  5722. NodeList: C,
  5723. Notification: C,
  5724. OfflineAudioCompletionEvent: C,
  5725. OfflineAudioContext: C,
  5726. offscreenBuffering: O,
  5727. OffscreenCanvas: C,
  5728. open: O,
  5729. openDatabase: O,
  5730. Option: C,
  5731. origin: O,
  5732. OscillatorNode: C,
  5733. outerHeight: O,
  5734. outerWidth: O,
  5735. PageTransitionEvent: C,
  5736. pageXOffset: O,
  5737. pageYOffset: O,
  5738. PannerNode: C,
  5739. parent: O,
  5740. Path2D: C,
  5741. PaymentAddress: C,
  5742. PaymentRequest: C,
  5743. PaymentRequestUpdateEvent: C,
  5744. PaymentResponse: C,
  5745. performance: O,
  5746. Performance: C,
  5747. PerformanceEntry: C,
  5748. PerformanceLongTaskTiming: C,
  5749. PerformanceMark: C,
  5750. PerformanceMeasure: C,
  5751. PerformanceNavigation: C,
  5752. PerformanceNavigationTiming: C,
  5753. PerformanceObserver: C,
  5754. PerformanceObserverEntryList: C,
  5755. PerformancePaintTiming: C,
  5756. PerformanceResourceTiming: C,
  5757. PerformanceTiming: C,
  5758. PeriodicWave: C,
  5759. Permissions: C,
  5760. PermissionStatus: C,
  5761. personalbar: O,
  5762. PhotoCapabilities: C,
  5763. Plugin: C,
  5764. PluginArray: C,
  5765. PointerEvent: C,
  5766. PopStateEvent: C,
  5767. postMessage: O,
  5768. Presentation: C,
  5769. PresentationAvailability: C,
  5770. PresentationConnection: C,
  5771. PresentationConnectionAvailableEvent: C,
  5772. PresentationConnectionCloseEvent: C,
  5773. PresentationConnectionList: C,
  5774. PresentationReceiver: C,
  5775. PresentationRequest: C,
  5776. print: O,
  5777. ProcessingInstruction: C,
  5778. ProgressEvent: C,
  5779. PromiseRejectionEvent: C,
  5780. prompt: O,
  5781. PushManager: C,
  5782. PushSubscription: C,
  5783. PushSubscriptionOptions: C,
  5784. queueMicrotask: O,
  5785. RadioNodeList: C,
  5786. Range: C,
  5787. ReadableStream: C,
  5788. RemotePlayback: C,
  5789. removeEventListener: O,
  5790. Request: C,
  5791. requestAnimationFrame: O,
  5792. requestIdleCallback: O,
  5793. resizeBy: O,
  5794. ResizeObserver: C,
  5795. ResizeObserverEntry: C,
  5796. resizeTo: O,
  5797. Response: C,
  5798. RTCCertificate: C,
  5799. RTCDataChannel: C,
  5800. RTCDataChannelEvent: C,
  5801. RTCDtlsTransport: C,
  5802. RTCIceCandidate: C,
  5803. RTCIceTransport: C,
  5804. RTCPeerConnection: C,
  5805. RTCPeerConnectionIceEvent: C,
  5806. RTCRtpReceiver: C,
  5807. RTCRtpSender: C,
  5808. RTCSctpTransport: C,
  5809. RTCSessionDescription: C,
  5810. RTCStatsReport: C,
  5811. RTCTrackEvent: C,
  5812. screen: O,
  5813. Screen: C,
  5814. screenLeft: O,
  5815. ScreenOrientation: C,
  5816. screenTop: O,
  5817. screenX: O,
  5818. screenY: O,
  5819. ScriptProcessorNode: C,
  5820. scroll: O,
  5821. scrollbars: O,
  5822. scrollBy: O,
  5823. scrollTo: O,
  5824. scrollX: O,
  5825. scrollY: O,
  5826. SecurityPolicyViolationEvent: C,
  5827. Selection: C,
  5828. ServiceWorker: C,
  5829. ServiceWorkerContainer: C,
  5830. ServiceWorkerRegistration: C,
  5831. sessionStorage: O,
  5832. ShadowRoot: C,
  5833. SharedWorker: C,
  5834. SourceBuffer: C,
  5835. SourceBufferList: C,
  5836. speechSynthesis: O,
  5837. SpeechSynthesisEvent: C,
  5838. SpeechSynthesisUtterance: C,
  5839. StaticRange: C,
  5840. status: O,
  5841. statusbar: O,
  5842. StereoPannerNode: C,
  5843. stop: O,
  5844. Storage: C,
  5845. StorageEvent: C,
  5846. StorageManager: C,
  5847. styleMedia: O,
  5848. StyleSheet: C,
  5849. StyleSheetList: C,
  5850. SubtleCrypto: C,
  5851. SVGAElement: C,
  5852. SVGAngle: C,
  5853. SVGAnimatedAngle: C,
  5854. SVGAnimatedBoolean: C,
  5855. SVGAnimatedEnumeration: C,
  5856. SVGAnimatedInteger: C,
  5857. SVGAnimatedLength: C,
  5858. SVGAnimatedLengthList: C,
  5859. SVGAnimatedNumber: C,
  5860. SVGAnimatedNumberList: C,
  5861. SVGAnimatedPreserveAspectRatio: C,
  5862. SVGAnimatedRect: C,
  5863. SVGAnimatedString: C,
  5864. SVGAnimatedTransformList: C,
  5865. SVGAnimateElement: C,
  5866. SVGAnimateMotionElement: C,
  5867. SVGAnimateTransformElement: C,
  5868. SVGAnimationElement: C,
  5869. SVGCircleElement: C,
  5870. SVGClipPathElement: C,
  5871. SVGComponentTransferFunctionElement: C,
  5872. SVGDefsElement: C,
  5873. SVGDescElement: C,
  5874. SVGDiscardElement: C,
  5875. SVGElement: C,
  5876. SVGEllipseElement: C,
  5877. SVGFEBlendElement: C,
  5878. SVGFEColorMatrixElement: C,
  5879. SVGFEComponentTransferElement: C,
  5880. SVGFECompositeElement: C,
  5881. SVGFEConvolveMatrixElement: C,
  5882. SVGFEDiffuseLightingElement: C,
  5883. SVGFEDisplacementMapElement: C,
  5884. SVGFEDistantLightElement: C,
  5885. SVGFEDropShadowElement: C,
  5886. SVGFEFloodElement: C,
  5887. SVGFEFuncAElement: C,
  5888. SVGFEFuncBElement: C,
  5889. SVGFEFuncGElement: C,
  5890. SVGFEFuncRElement: C,
  5891. SVGFEGaussianBlurElement: C,
  5892. SVGFEImageElement: C,
  5893. SVGFEMergeElement: C,
  5894. SVGFEMergeNodeElement: C,
  5895. SVGFEMorphologyElement: C,
  5896. SVGFEOffsetElement: C,
  5897. SVGFEPointLightElement: C,
  5898. SVGFESpecularLightingElement: C,
  5899. SVGFESpotLightElement: C,
  5900. SVGFETileElement: C,
  5901. SVGFETurbulenceElement: C,
  5902. SVGFilterElement: C,
  5903. SVGForeignObjectElement: C,
  5904. SVGGElement: C,
  5905. SVGGeometryElement: C,
  5906. SVGGradientElement: C,
  5907. SVGGraphicsElement: C,
  5908. SVGImageElement: C,
  5909. SVGLength: C,
  5910. SVGLengthList: C,
  5911. SVGLinearGradientElement: C,
  5912. SVGLineElement: C,
  5913. SVGMarkerElement: C,
  5914. SVGMaskElement: C,
  5915. SVGMatrix: C,
  5916. SVGMetadataElement: C,
  5917. SVGMPathElement: C,
  5918. SVGNumber: C,
  5919. SVGNumberList: C,
  5920. SVGPathElement: C,
  5921. SVGPatternElement: C,
  5922. SVGPoint: C,
  5923. SVGPointList: C,
  5924. SVGPolygonElement: C,
  5925. SVGPolylineElement: C,
  5926. SVGPreserveAspectRatio: C,
  5927. SVGRadialGradientElement: C,
  5928. SVGRect: C,
  5929. SVGRectElement: C,
  5930. SVGScriptElement: C,
  5931. SVGSetElement: C,
  5932. SVGStopElement: C,
  5933. SVGStringList: C,
  5934. SVGStyleElement: C,
  5935. SVGSVGElement: C,
  5936. SVGSwitchElement: C,
  5937. SVGSymbolElement: C,
  5938. SVGTextContentElement: C,
  5939. SVGTextElement: C,
  5940. SVGTextPathElement: C,
  5941. SVGTextPositioningElement: C,
  5942. SVGTitleElement: C,
  5943. SVGTransform: C,
  5944. SVGTransformList: C,
  5945. SVGTSpanElement: C,
  5946. SVGUnitTypes: C,
  5947. SVGUseElement: C,
  5948. SVGViewElement: C,
  5949. TaskAttributionTiming: C,
  5950. Text: C,
  5951. TextEvent: C,
  5952. TextMetrics: C,
  5953. TextTrack: C,
  5954. TextTrackCue: C,
  5955. TextTrackCueList: C,
  5956. TextTrackList: C,
  5957. TimeRanges: C,
  5958. toolbar: O,
  5959. top: O,
  5960. Touch: C,
  5961. TouchEvent: C,
  5962. TouchList: C,
  5963. TrackEvent: C,
  5964. TransitionEvent: C,
  5965. TreeWalker: C,
  5966. UIEvent: C,
  5967. ValidityState: C,
  5968. visualViewport: O,
  5969. VisualViewport: C,
  5970. VTTCue: C,
  5971. WaveShaperNode: C,
  5972. WebAssembly: O,
  5973. WebGL2RenderingContext: C,
  5974. WebGLActiveInfo: C,
  5975. WebGLBuffer: C,
  5976. WebGLContextEvent: C,
  5977. WebGLFramebuffer: C,
  5978. WebGLProgram: C,
  5979. WebGLQuery: C,
  5980. WebGLRenderbuffer: C,
  5981. WebGLRenderingContext: C,
  5982. WebGLSampler: C,
  5983. WebGLShader: C,
  5984. WebGLShaderPrecisionFormat: C,
  5985. WebGLSync: C,
  5986. WebGLTexture: C,
  5987. WebGLTransformFeedback: C,
  5988. WebGLUniformLocation: C,
  5989. WebGLVertexArrayObject: C,
  5990. WebSocket: C,
  5991. WheelEvent: C,
  5992. Window: C,
  5993. Worker: C,
  5994. WritableStream: C,
  5995. XMLDocument: C,
  5996. XMLHttpRequest: C,
  5997. XMLHttpRequestEventTarget: C,
  5998. XMLHttpRequestUpload: C,
  5999. XMLSerializer: C,
  6000. XPathEvaluator: C,
  6001. XPathExpression: C,
  6002. XPathResult: C,
  6003. XSLTProcessor: C
  6004. };
  6005. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6006. knownGlobals[global] = knownGlobals;
  6007. }
  6008. function getGlobalAtPath(path) {
  6009. let currentGlobal = knownGlobals;
  6010. for (const pathSegment of path) {
  6011. if (typeof pathSegment !== 'string') {
  6012. return null;
  6013. }
  6014. currentGlobal = currentGlobal[pathSegment];
  6015. if (!currentGlobal) {
  6016. return null;
  6017. }
  6018. }
  6019. return currentGlobal[ValueProperties];
  6020. }
  6021. class GlobalVariable extends Variable {
  6022. constructor(name) {
  6023. super(name);
  6024. // Ensure we use live-bindings for globals as we do not know if they have
  6025. // been reassigned
  6026. this.markReassigned();
  6027. }
  6028. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6029. switch (interaction.type) {
  6030. // While there is no point in testing these cases as at the moment, they
  6031. // are also covered via other means, we keep them for completeness
  6032. case INTERACTION_ACCESSED:
  6033. case INTERACTION_ASSIGNED: {
  6034. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  6035. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6036. }
  6037. return;
  6038. }
  6039. case INTERACTION_CALLED: {
  6040. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6041. if (globalAtPath) {
  6042. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  6043. }
  6044. else {
  6045. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6046. }
  6047. return;
  6048. }
  6049. }
  6050. }
  6051. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6052. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6053. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  6054. }
  6055. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6056. switch (interaction.type) {
  6057. case INTERACTION_ACCESSED: {
  6058. if (path.length === 0) {
  6059. // Technically, "undefined" is a global variable of sorts
  6060. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6061. }
  6062. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6063. }
  6064. case INTERACTION_ASSIGNED: {
  6065. return true;
  6066. }
  6067. case INTERACTION_CALLED: {
  6068. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6069. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6070. }
  6071. }
  6072. }
  6073. }
  6074. // To avoid infinite recursions
  6075. const MAX_PATH_DEPTH = 6;
  6076. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  6077. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  6078. const limitConcatenatedPathDepth = (path1, path2) => {
  6079. const { length: length1 } = path1;
  6080. const { length: length2 } = path2;
  6081. return length1 === 0
  6082. ? path2
  6083. : length2 === 0
  6084. ? path1
  6085. : length1 + length2 > MAX_PATH_DEPTH
  6086. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  6087. : [...path1, ...path2];
  6088. };
  6089. class LocalVariable extends Variable {
  6090. constructor(name, declarator, init,
  6091. /** if this is non-empty, the actual init is this path of this.init */
  6092. initPath, context, kind) {
  6093. super(name);
  6094. this.init = init;
  6095. this.initPath = initPath;
  6096. this.kind = kind;
  6097. this.calledFromTryStatement = false;
  6098. this.additionalInitializers = null;
  6099. this.includedPathTracker = new IncludedFullPathTracker();
  6100. this.expressionsToBeDeoptimized = [];
  6101. this.declarations = declarator ? [declarator] : [];
  6102. this.deoptimizationTracker = context.deoptimizationTracker;
  6103. this.module = context.module;
  6104. }
  6105. addDeclaration(identifier, init) {
  6106. this.declarations.push(identifier);
  6107. this.markInitializersForDeoptimization().push(init);
  6108. }
  6109. consolidateInitializers() {
  6110. if (this.additionalInitializers) {
  6111. for (const initializer of this.additionalInitializers) {
  6112. initializer.deoptimizePath(UNKNOWN_PATH);
  6113. }
  6114. }
  6115. }
  6116. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6117. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  6118. deoptimizeInteraction(interaction);
  6119. return;
  6120. }
  6121. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6122. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  6123. }, undefined);
  6124. }
  6125. deoptimizePath(path) {
  6126. if (this.isReassigned ||
  6127. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6128. return;
  6129. }
  6130. if (path.length === 0) {
  6131. this.markReassigned();
  6132. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6133. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  6134. for (const expression of expressionsToBeDeoptimized) {
  6135. expression.deoptimizeCache();
  6136. }
  6137. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  6138. }
  6139. else {
  6140. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  6141. }
  6142. }
  6143. getLiteralValueAtPath(path, recursionTracker, origin) {
  6144. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  6145. return UnknownValue;
  6146. }
  6147. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6148. this.expressionsToBeDeoptimized.push(origin);
  6149. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  6150. }, UnknownValue);
  6151. }
  6152. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6153. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  6154. return UNKNOWN_RETURN_EXPRESSION;
  6155. }
  6156. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6157. this.expressionsToBeDeoptimized.push(origin);
  6158. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  6159. }, UNKNOWN_RETURN_EXPRESSION);
  6160. }
  6161. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6162. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  6163. return true;
  6164. }
  6165. switch (interaction.type) {
  6166. case INTERACTION_ACCESSED: {
  6167. if (this.isReassigned)
  6168. return true;
  6169. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6170. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  6171. }
  6172. case INTERACTION_ASSIGNED: {
  6173. if (this.included)
  6174. return true;
  6175. if (path.length === 0)
  6176. return false;
  6177. if (this.isReassigned)
  6178. return true;
  6179. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6180. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  6181. }
  6182. case INTERACTION_CALLED: {
  6183. if (this.isReassigned)
  6184. return true;
  6185. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  6186. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  6187. }
  6188. }
  6189. }
  6190. includePath(path, context) {
  6191. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  6192. this.module.scope.context.requestTreeshakingPass();
  6193. if (!this.included) {
  6194. // This will reduce the number of tree-shaking passes by eagerly
  6195. // including inits. By pushing this here instead of directly including
  6196. // we avoid deep call stacks.
  6197. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  6198. }
  6199. super.includePath(path, context);
  6200. for (const declaration of this.declarations) {
  6201. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  6202. if (!declaration.included)
  6203. declaration.include(context, false);
  6204. let node = declaration.parent;
  6205. while (!node.included) {
  6206. // We do not want to properly include parents in case they are part of a dead branch
  6207. // in which case .include() might pull in more dead code
  6208. node.includeNode(context);
  6209. if (node.type === parseAst_js.Program)
  6210. break;
  6211. node = node.parent;
  6212. }
  6213. }
  6214. // We need to make sure we include the correct path of the init
  6215. if (path.length > 0) {
  6216. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  6217. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  6218. }
  6219. }
  6220. }
  6221. includeCallArguments(interaction, context) {
  6222. if (this.isReassigned ||
  6223. context.includedCallArguments.has(this.init) ||
  6224. // This can be removed again once we can include arguments when called at
  6225. // a specific path
  6226. this.initPath.length > 0) {
  6227. includeInteraction(interaction, context);
  6228. }
  6229. else {
  6230. context.includedCallArguments.add(this.init);
  6231. this.init.includeCallArguments(interaction, context);
  6232. context.includedCallArguments.delete(this.init);
  6233. }
  6234. }
  6235. markCalledFromTryStatement() {
  6236. this.calledFromTryStatement = true;
  6237. }
  6238. markInitializersForDeoptimization() {
  6239. if (this.additionalInitializers === null) {
  6240. this.additionalInitializers = [this.init];
  6241. this.init = UNKNOWN_EXPRESSION;
  6242. this.markReassigned();
  6243. }
  6244. return this.additionalInitializers;
  6245. }
  6246. }
  6247. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  6248. class IdentifierBase extends NodeBase {
  6249. constructor() {
  6250. super(...arguments);
  6251. this.variable = null;
  6252. this.isVariableReference = false;
  6253. }
  6254. get isTDZAccess() {
  6255. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  6256. return null;
  6257. }
  6258. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  6259. }
  6260. set isTDZAccess(value) {
  6261. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  6262. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  6263. }
  6264. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6265. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6266. }
  6267. deoptimizePath(path) {
  6268. if (path.length === 0 && !this.scope.contains(this.name)) {
  6269. this.disallowImportReassignment();
  6270. }
  6271. // We keep conditional chaining because an unknown Node could have an
  6272. // Identifier as property that might be deoptimized by default
  6273. this.variable?.deoptimizePath(path);
  6274. }
  6275. getLiteralValueAtPath(path, recursionTracker, origin) {
  6276. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6277. }
  6278. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6279. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6280. return [expression, isPure || this.isPureFunction(path)];
  6281. }
  6282. hasEffects(context) {
  6283. if (!this.deoptimized)
  6284. this.applyDeoptimizations();
  6285. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6286. return true;
  6287. }
  6288. return (this.scope.context.options.treeshake
  6289. .unknownGlobalSideEffects &&
  6290. this.variable instanceof GlobalVariable &&
  6291. !this.isPureFunction(EMPTY_PATH) &&
  6292. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6293. }
  6294. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6295. switch (interaction.type) {
  6296. case INTERACTION_ACCESSED: {
  6297. return (this.variable !== null &&
  6298. !this.isPureFunction(path) &&
  6299. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6300. }
  6301. case INTERACTION_ASSIGNED: {
  6302. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6303. }
  6304. case INTERACTION_CALLED: {
  6305. return (!this.isPureFunction(path) &&
  6306. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6307. }
  6308. }
  6309. }
  6310. include(context, includeChildrenRecursively) {
  6311. if (!this.included)
  6312. this.includeNode(context);
  6313. if (includeChildrenRecursively) {
  6314. this.variable?.includePath(UNKNOWN_PATH, context);
  6315. }
  6316. }
  6317. includeNode(context) {
  6318. this.included = true;
  6319. if (!this.deoptimized)
  6320. this.applyDeoptimizations();
  6321. if (this.variable !== null) {
  6322. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  6323. }
  6324. }
  6325. includePath(path, context) {
  6326. if (!this.included) {
  6327. this.included = true;
  6328. if (!this.deoptimized)
  6329. this.applyDeoptimizations();
  6330. if (this.variable !== null) {
  6331. this.scope.context.includeVariableInModule(this.variable, path, context);
  6332. }
  6333. }
  6334. else if (path.length > 0) {
  6335. this.variable?.includePath(path, context);
  6336. }
  6337. }
  6338. includeCallArguments(interaction, context) {
  6339. this.variable.includeCallArguments(interaction, context);
  6340. }
  6341. isPossibleTDZ() {
  6342. // return cached value to avoid issues with the next tree-shaking pass
  6343. const cachedTdzAccess = this.isTDZAccess;
  6344. if (cachedTdzAccess !== null)
  6345. return cachedTdzAccess;
  6346. if (!(this.variable instanceof LocalVariable &&
  6347. this.variable.kind &&
  6348. tdzVariableKinds.has(this.variable.kind) &&
  6349. // We ignore modules that did not receive a treeshaking pass yet as that
  6350. // causes many false positives due to circular dependencies or disabled
  6351. // moduleSideEffects.
  6352. this.variable.module.hasTreeShakingPassStarted)) {
  6353. return (this.isTDZAccess = false);
  6354. }
  6355. let decl_id;
  6356. if (this.variable.declarations &&
  6357. this.variable.declarations.length === 1 &&
  6358. (decl_id = this.variable.declarations[0]) &&
  6359. this.start < decl_id.start &&
  6360. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6361. // a variable accessed before its declaration
  6362. // in the same function or at top level of module
  6363. return (this.isTDZAccess = true);
  6364. }
  6365. if (!this.variable.initReached) {
  6366. // Either a const/let TDZ violation or
  6367. // var use before declaration was encountered.
  6368. return (this.isTDZAccess = true);
  6369. }
  6370. return (this.isTDZAccess = false);
  6371. }
  6372. applyDeoptimizations() {
  6373. this.deoptimized = true;
  6374. if (this.variable instanceof LocalVariable) {
  6375. // When accessing a variable from a module without side effects, this
  6376. // means we use an export of that module and therefore need to potentially
  6377. // include it in the bundle.
  6378. if (!this.variable.module.isExecuted) {
  6379. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  6380. }
  6381. this.variable.consolidateInitializers();
  6382. this.scope.context.requestTreeshakingPass();
  6383. }
  6384. if (this.isVariableReference) {
  6385. this.variable.addUsedPlace(this);
  6386. this.scope.context.requestTreeshakingPass();
  6387. }
  6388. }
  6389. disallowImportReassignment() {
  6390. return this.scope.context.error(parseAst_js.logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  6391. }
  6392. getVariableRespectingTDZ() {
  6393. if (this.isPossibleTDZ()) {
  6394. return UNKNOWN_EXPRESSION;
  6395. }
  6396. return this.variable;
  6397. }
  6398. isPureFunction(path) {
  6399. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  6400. for (const segment of path) {
  6401. if (currentPureFunction) {
  6402. if (currentPureFunction[PureFunctionKey]) {
  6403. return true;
  6404. }
  6405. currentPureFunction = currentPureFunction[segment];
  6406. }
  6407. else {
  6408. return false;
  6409. }
  6410. }
  6411. return currentPureFunction?.[PureFunctionKey];
  6412. }
  6413. }
  6414. function closestParentFunctionOrProgram(node) {
  6415. while (node && !/^Program|Function/.test(node.type)) {
  6416. node = node.parent;
  6417. }
  6418. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6419. return node;
  6420. }
  6421. class ObjectMember extends ExpressionEntity {
  6422. constructor(object, path) {
  6423. super();
  6424. this.object = object;
  6425. this.path = path;
  6426. }
  6427. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6428. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  6429. }
  6430. deoptimizePath(path) {
  6431. this.object.deoptimizePath([...this.path, ...path]);
  6432. }
  6433. getLiteralValueAtPath(path, recursionTracker, origin) {
  6434. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  6435. }
  6436. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6437. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  6438. }
  6439. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6440. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  6441. }
  6442. }
  6443. class Identifier extends IdentifierBase {
  6444. constructor() {
  6445. super(...arguments);
  6446. this.variable = null;
  6447. }
  6448. get isDestructuringDeoptimized() {
  6449. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  6450. }
  6451. set isDestructuringDeoptimized(value) {
  6452. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  6453. }
  6454. addExportedVariables(variables, exportNamesByVariable) {
  6455. if (exportNamesByVariable.has(this.variable)) {
  6456. variables.push(this.variable);
  6457. }
  6458. }
  6459. bind() {
  6460. if (!this.variable && is_reference(this, this.parent)) {
  6461. this.variable = this.scope.findVariable(this.name);
  6462. this.variable.addReference(this);
  6463. this.isVariableReference = true;
  6464. }
  6465. }
  6466. declare(kind, destructuredInitPath, init) {
  6467. let variable;
  6468. const { treeshake } = this.scope.context.options;
  6469. if (kind === 'parameter') {
  6470. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  6471. }
  6472. else {
  6473. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  6474. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6475. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6476. variable.markInitializersForDeoptimization();
  6477. }
  6478. }
  6479. return [(this.variable = variable)];
  6480. }
  6481. deoptimizeAssignment(destructuredInitPath, init) {
  6482. this.deoptimizePath(EMPTY_PATH);
  6483. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  6484. }
  6485. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  6486. return (destructuredInitPath.length > 0 &&
  6487. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6488. }
  6489. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  6490. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  6491. this.isDestructuringDeoptimized = true;
  6492. init.deoptimizeArgumentsOnInteractionAtPath({
  6493. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  6494. type: INTERACTION_ACCESSED
  6495. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  6496. }
  6497. const { propertyReadSideEffects } = this.scope.context.options
  6498. .treeshake;
  6499. if ((this.included ||=
  6500. destructuredInitPath.length > 0 &&
  6501. !context.brokenFlow &&
  6502. propertyReadSideEffects &&
  6503. (propertyReadSideEffects === 'always' ||
  6504. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  6505. if (this.variable && !this.variable.included) {
  6506. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  6507. }
  6508. init.includePath(destructuredInitPath, context);
  6509. return true;
  6510. }
  6511. return false;
  6512. }
  6513. markDeclarationReached() {
  6514. this.variable.initReached = true;
  6515. }
  6516. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = parseAst_js.BLANK) {
  6517. if (this.variable) {
  6518. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  6519. if (name !== this.name) {
  6520. code.overwrite(this.start, this.end, name, {
  6521. contentOnly: true,
  6522. storeName: true
  6523. });
  6524. if (isShorthandProperty) {
  6525. code.prependRight(this.start, `${this.name}: `);
  6526. }
  6527. }
  6528. // In strict mode, any variable named "eval" must be the actual "eval" function
  6529. if (name === 'eval' &&
  6530. renderedParentType === parseAst_js.CallExpression &&
  6531. isCalleeOfRenderedParent) {
  6532. code.appendRight(this.start, '0, ');
  6533. }
  6534. }
  6535. }
  6536. }
  6537. function getSafeName(baseName, usedNames, forbiddenNames) {
  6538. let safeName = baseName;
  6539. let count = 1;
  6540. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  6541. safeName = `${baseName}$${toBase64(count++)}`;
  6542. }
  6543. usedNames.add(safeName);
  6544. return safeName;
  6545. }
  6546. class Scope {
  6547. constructor() {
  6548. this.children = [];
  6549. this.variables = new Map();
  6550. }
  6551. /*
  6552. Redeclaration rules:
  6553. - var can redeclare var
  6554. - in function scopes, function and var can redeclare function and var
  6555. - var is hoisted across scopes, function remains in the scope it is declared
  6556. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  6557. - function cannot redeclare catch scope parameters
  6558. - var can redeclare catch scope parameters in a way
  6559. - if the parameter is an identifier and not a pattern
  6560. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  6561. - const, let, class, and function except in the cases above cannot redeclare anything
  6562. */
  6563. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  6564. const name = identifier.name;
  6565. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6566. if (existingVariable) {
  6567. if (kind === 'var' && existingVariable.kind === 'var') {
  6568. existingVariable.addDeclaration(identifier, init);
  6569. return existingVariable;
  6570. }
  6571. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  6572. }
  6573. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  6574. this.variables.set(name, newVariable);
  6575. return newVariable;
  6576. }
  6577. addHoistedVariable(name, variable) {
  6578. (this.hoistedVariables ||= new Map()).set(name, variable);
  6579. }
  6580. contains(name) {
  6581. return this.variables.has(name);
  6582. }
  6583. findVariable(_name) {
  6584. /* istanbul ignore next */
  6585. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  6586. }
  6587. }
  6588. class ChildScope extends Scope {
  6589. constructor(parent, context) {
  6590. super();
  6591. this.parent = parent;
  6592. this.context = context;
  6593. this.accessedOutsideVariables = new Map();
  6594. parent.children.push(this);
  6595. }
  6596. addAccessedDynamicImport(importExpression) {
  6597. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  6598. if (this.parent instanceof ChildScope) {
  6599. this.parent.addAccessedDynamicImport(importExpression);
  6600. }
  6601. }
  6602. addAccessedGlobals(globals, accessedGlobalsByScope) {
  6603. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  6604. for (const name of globals) {
  6605. accessedGlobals.add(name);
  6606. }
  6607. accessedGlobalsByScope.set(this, accessedGlobals);
  6608. if (this.parent instanceof ChildScope) {
  6609. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  6610. }
  6611. }
  6612. addNamespaceMemberAccess(name, variable) {
  6613. this.accessedOutsideVariables.set(name, variable);
  6614. this.parent.addNamespaceMemberAccess(name, variable);
  6615. }
  6616. addReturnExpression(expression) {
  6617. if (this.parent instanceof ChildScope) {
  6618. this.parent.addReturnExpression(expression);
  6619. }
  6620. }
  6621. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  6622. for (const variable of this.accessedOutsideVariables.values()) {
  6623. if (variable.included) {
  6624. usedNames.add(variable.getBaseVariableName());
  6625. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6626. usedNames.add('exports');
  6627. }
  6628. }
  6629. }
  6630. const accessedGlobals = accessedGlobalsByScope.get(this);
  6631. if (accessedGlobals) {
  6632. for (const name of accessedGlobals) {
  6633. usedNames.add(name);
  6634. }
  6635. }
  6636. }
  6637. contains(name) {
  6638. return this.variables.has(name) || this.parent.contains(name);
  6639. }
  6640. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  6641. const usedNames = new Set();
  6642. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  6643. if (this.accessedDynamicImports) {
  6644. for (const importExpression of this.accessedDynamicImports) {
  6645. if (importExpression.inlineNamespace) {
  6646. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  6647. }
  6648. }
  6649. }
  6650. for (const [name, variable] of this.variables) {
  6651. if (variable.included || variable.alwaysRendered) {
  6652. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  6653. }
  6654. }
  6655. for (const scope of this.children) {
  6656. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  6657. }
  6658. }
  6659. findLexicalBoundary() {
  6660. return this.parent.findLexicalBoundary();
  6661. }
  6662. findGlobal(name) {
  6663. const variable = this.parent.findVariable(name);
  6664. this.accessedOutsideVariables.set(name, variable);
  6665. return variable;
  6666. }
  6667. findVariable(name) {
  6668. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  6669. if (knownVariable) {
  6670. return knownVariable;
  6671. }
  6672. const variable = this.parent.findVariable(name);
  6673. this.accessedOutsideVariables.set(name, variable);
  6674. return variable;
  6675. }
  6676. }
  6677. function checkEffectForNodes(nodes, context) {
  6678. for (const node of nodes) {
  6679. if (node.hasEffects(context)) {
  6680. return true;
  6681. }
  6682. }
  6683. return false;
  6684. }
  6685. class MethodBase extends NodeBase {
  6686. constructor() {
  6687. super(...arguments);
  6688. this.accessedValue = null;
  6689. }
  6690. get computed() {
  6691. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6692. }
  6693. set computed(value) {
  6694. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6695. }
  6696. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6697. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  6698. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  6699. args: interaction.args,
  6700. type: INTERACTION_CALLED,
  6701. withNew: false
  6702. }, EMPTY_PATH, recursionTracker);
  6703. }
  6704. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  6705. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  6706. args: interaction.args,
  6707. type: INTERACTION_CALLED,
  6708. withNew: false
  6709. }, EMPTY_PATH, recursionTracker);
  6710. }
  6711. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6712. }
  6713. // As getter properties directly receive their values from fixed function
  6714. // expressions, there is no known situation where a getter is deoptimized.
  6715. deoptimizeCache() { }
  6716. deoptimizePath(path) {
  6717. this.getAccessedValue()[0].deoptimizePath(path);
  6718. }
  6719. getLiteralValueAtPath(path, recursionTracker, origin) {
  6720. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  6721. }
  6722. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6723. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6724. }
  6725. hasEffects(context) {
  6726. return this.key.hasEffects(context);
  6727. }
  6728. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6729. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  6730. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  6731. args: interaction.args,
  6732. type: INTERACTION_CALLED,
  6733. withNew: false
  6734. }, context);
  6735. }
  6736. // setters are only called for empty paths
  6737. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  6738. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  6739. args: interaction.args,
  6740. type: INTERACTION_CALLED,
  6741. withNew: false
  6742. }, context);
  6743. }
  6744. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  6745. }
  6746. getAccessedValue() {
  6747. if (this.accessedValue === null) {
  6748. if (this.kind === 'get') {
  6749. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  6750. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  6751. }
  6752. else {
  6753. return (this.accessedValue = [this.value, false]);
  6754. }
  6755. }
  6756. return this.accessedValue;
  6757. }
  6758. }
  6759. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6760. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  6761. class MethodDefinition extends MethodBase {
  6762. hasEffects(context) {
  6763. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  6764. }
  6765. }
  6766. class BlockScope extends ChildScope {
  6767. constructor(parent) {
  6768. super(parent, parent.context);
  6769. }
  6770. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  6771. if (kind === 'var') {
  6772. const name = identifier.name;
  6773. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6774. if (existingVariable) {
  6775. if (existingVariable.kind === 'var' ||
  6776. (kind === 'var' && existingVariable.kind === 'parameter')) {
  6777. existingVariable.addDeclaration(identifier, init);
  6778. return existingVariable;
  6779. }
  6780. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  6781. }
  6782. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  6783. // Necessary to make sure the init is deoptimized for conditional declarations.
  6784. // We cannot call deoptimizePath here.
  6785. declaredVariable.markInitializersForDeoptimization();
  6786. // We add the variable to this and all parent scopes to reliably detect conflicts
  6787. this.addHoistedVariable(name, declaredVariable);
  6788. return declaredVariable;
  6789. }
  6790. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  6791. }
  6792. }
  6793. class StaticBlock extends NodeBase {
  6794. createScope(parentScope) {
  6795. this.scope = new BlockScope(parentScope);
  6796. }
  6797. hasEffects(context) {
  6798. for (const node of this.body) {
  6799. if (node.hasEffects(context))
  6800. return true;
  6801. }
  6802. return false;
  6803. }
  6804. include(context, includeChildrenRecursively) {
  6805. this.included = true;
  6806. for (const node of this.body) {
  6807. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6808. node.include(context, includeChildrenRecursively);
  6809. }
  6810. }
  6811. render(code, options) {
  6812. if (this.body.length > 0) {
  6813. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  6814. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  6815. }
  6816. else {
  6817. super.render(code, options);
  6818. }
  6819. }
  6820. }
  6821. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6822. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  6823. function isStaticBlock(statement) {
  6824. return statement.type === parseAst_js.StaticBlock;
  6825. }
  6826. class ClassNode extends NodeBase {
  6827. constructor() {
  6828. super(...arguments);
  6829. this.objectEntity = null;
  6830. }
  6831. createScope(parentScope) {
  6832. this.scope = new ChildScope(parentScope, parentScope.context);
  6833. }
  6834. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6835. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6836. }
  6837. deoptimizeCache() {
  6838. this.getObjectEntity().deoptimizeAllProperties();
  6839. }
  6840. deoptimizePath(path) {
  6841. this.getObjectEntity().deoptimizePath(path);
  6842. }
  6843. getLiteralValueAtPath(path, recursionTracker, origin) {
  6844. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6845. }
  6846. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6847. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6848. }
  6849. hasEffects(context) {
  6850. if (!this.deoptimized)
  6851. this.applyDeoptimizations();
  6852. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  6853. this.id?.markDeclarationReached();
  6854. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  6855. }
  6856. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6857. return interaction.type === INTERACTION_CALLED && path.length === 0
  6858. ? !interaction.withNew ||
  6859. (this.classConstructor === null
  6860. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  6861. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  6862. false
  6863. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6864. }
  6865. include(context, includeChildrenRecursively) {
  6866. if (!this.included)
  6867. this.includeNode(context);
  6868. this.superClass?.include(context, includeChildrenRecursively);
  6869. this.body.include(context, includeChildrenRecursively);
  6870. for (const decorator of this.decorators)
  6871. decorator.include(context, includeChildrenRecursively);
  6872. if (this.id) {
  6873. this.id.markDeclarationReached();
  6874. this.id.include(context, includeChildrenRecursively);
  6875. }
  6876. }
  6877. initialise() {
  6878. super.initialise();
  6879. this.id?.declare('class', EMPTY_PATH, this);
  6880. for (const method of this.body.body) {
  6881. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  6882. this.classConstructor = method;
  6883. return;
  6884. }
  6885. }
  6886. this.classConstructor = null;
  6887. }
  6888. applyDeoptimizations() {
  6889. this.deoptimized = true;
  6890. for (const definition of this.body.body) {
  6891. if (!isStaticBlock(definition) &&
  6892. !(definition.static ||
  6893. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  6894. // Calls to methods are not tracked, ensure that the return value is deoptimized
  6895. definition.deoptimizePath(UNKNOWN_PATH);
  6896. }
  6897. }
  6898. this.scope.context.requestTreeshakingPass();
  6899. }
  6900. getObjectEntity() {
  6901. if (this.objectEntity !== null) {
  6902. return this.objectEntity;
  6903. }
  6904. const staticProperties = [];
  6905. const dynamicMethods = [];
  6906. for (const definition of this.body.body) {
  6907. if (isStaticBlock(definition))
  6908. continue;
  6909. const properties = definition.static ? staticProperties : dynamicMethods;
  6910. const definitionKind = definition.kind;
  6911. // Note that class fields do not end up on the prototype
  6912. if (properties === dynamicMethods && !definitionKind)
  6913. continue;
  6914. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  6915. let key;
  6916. if (definition.computed) {
  6917. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6918. if (typeof keyValue === 'symbol') {
  6919. properties.push({ key: UnknownKey, kind, property: definition });
  6920. continue;
  6921. }
  6922. else {
  6923. key = String(keyValue);
  6924. }
  6925. }
  6926. else {
  6927. key =
  6928. definition.key instanceof Identifier
  6929. ? definition.key.name
  6930. : String(definition.key.value);
  6931. }
  6932. properties.push({ key, kind, property: definition });
  6933. }
  6934. staticProperties.unshift({
  6935. key: 'prototype',
  6936. kind: 'init',
  6937. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  6938. });
  6939. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  6940. }
  6941. }
  6942. ClassNode.prototype.includeNode = onlyIncludeSelf;
  6943. class ClassDeclaration extends ClassNode {
  6944. initialise() {
  6945. super.initialise();
  6946. if (this.id !== null) {
  6947. this.id.variable.isId = true;
  6948. }
  6949. }
  6950. parseNode(esTreeNode) {
  6951. if (esTreeNode.id !== null) {
  6952. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6953. }
  6954. return super.parseNode(esTreeNode);
  6955. }
  6956. render(code, options) {
  6957. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  6958. if (this.id) {
  6959. const { variable, name } = this.id;
  6960. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6961. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  6962. }
  6963. const renderedVariable = variable.getName(getPropertyAccess);
  6964. if (renderedVariable !== name) {
  6965. this.decorators.map(decorator => decorator.render(code, options));
  6966. this.superClass?.render(code, options);
  6967. this.body.render(code, {
  6968. ...options,
  6969. useOriginalName: (_variable) => _variable === variable
  6970. });
  6971. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  6972. code.prependLeft(this.end, ';');
  6973. return;
  6974. }
  6975. }
  6976. super.render(code, options);
  6977. }
  6978. applyDeoptimizations() {
  6979. super.applyDeoptimizations();
  6980. const { id, scope } = this;
  6981. if (id) {
  6982. const { name, variable } = id;
  6983. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  6984. if (accessedVariable !== variable) {
  6985. accessedVariable.forbidName(name);
  6986. }
  6987. }
  6988. }
  6989. }
  6990. }
  6991. class ArgumentsVariable extends LocalVariable {
  6992. constructor(context) {
  6993. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  6994. }
  6995. addArgumentToBeDeoptimized(_argument) { }
  6996. // Only If there is at least one reference, then we need to track all
  6997. // arguments in order to be able to deoptimize them.
  6998. addReference() {
  6999. this.deoptimizedArguments = [];
  7000. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  7001. }
  7002. hasEffectsOnInteractionAtPath(path, { type }) {
  7003. return type !== INTERACTION_ACCESSED || path.length > 1;
  7004. }
  7005. includePath(path, context) {
  7006. super.includePath(path, context);
  7007. for (const argument of this.deoptimizedArguments) {
  7008. argument.deoptimizePath(UNKNOWN_PATH);
  7009. }
  7010. this.deoptimizedArguments.length = 0;
  7011. }
  7012. }
  7013. function addArgumentToBeDeoptimized(argument) {
  7014. if (this.included) {
  7015. argument.deoptimizePath(UNKNOWN_PATH);
  7016. }
  7017. else {
  7018. this.deoptimizedArguments?.push(argument);
  7019. }
  7020. }
  7021. const MAX_TRACKED_INTERACTIONS = 20;
  7022. const NO_INTERACTIONS = parseAst_js.EMPTY_ARRAY;
  7023. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  7024. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  7025. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  7026. class ParameterVariable extends LocalVariable {
  7027. constructor(name, declarator, argumentPath, context) {
  7028. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  7029. this.includedPathTracker = new IncludedTopLevelPathTracker();
  7030. this.argumentsToBeDeoptimized = new Set();
  7031. this.deoptimizationInteractions = [];
  7032. this.deoptimizations = new EntityPathTracker();
  7033. this.deoptimizedFields = new Set();
  7034. this.expressionsDependingOnKnownValue = [];
  7035. this.knownValue = null;
  7036. this.knownValueLiteral = UnknownValue;
  7037. }
  7038. addArgumentForDeoptimization(entity) {
  7039. this.updateKnownValue(entity);
  7040. if (entity === UNKNOWN_EXPRESSION) {
  7041. // As unknown expressions fully deoptimize all interactions, we can clear
  7042. // the interaction cache at this point provided we keep this optimization
  7043. // in mind when adding new interactions
  7044. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7045. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  7046. for (const { interaction } of this.deoptimizationInteractions) {
  7047. deoptimizeInteraction(interaction);
  7048. }
  7049. this.deoptimizationInteractions = NO_INTERACTIONS;
  7050. }
  7051. }
  7052. else if (this.deoptimizedFields.has(UnknownKey)) {
  7053. // This means that we already deoptimized all interactions and no longer
  7054. // track them
  7055. entity.deoptimizePath([...this.initPath, UnknownKey]);
  7056. }
  7057. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  7058. this.argumentsToBeDeoptimized.add(entity);
  7059. for (const field of this.deoptimizedFields) {
  7060. entity.deoptimizePath([...this.initPath, field]);
  7061. }
  7062. for (const { interaction, path } of this.deoptimizationInteractions) {
  7063. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  7064. }
  7065. }
  7066. }
  7067. /** This says we should not make assumptions about the value of the parameter.
  7068. * This is different from deoptimization that will also cause argument values
  7069. * to be deoptimized. */
  7070. markReassigned() {
  7071. if (this.isReassigned) {
  7072. return;
  7073. }
  7074. super.markReassigned();
  7075. for (const expression of this.expressionsDependingOnKnownValue) {
  7076. expression.deoptimizeCache();
  7077. }
  7078. this.expressionsDependingOnKnownValue = parseAst_js.EMPTY_ARRAY;
  7079. }
  7080. deoptimizeCache() {
  7081. this.markReassigned();
  7082. }
  7083. /**
  7084. * Update the known value of the parameter variable.
  7085. * Must be called for every function call, so it can track all the arguments,
  7086. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  7087. * @param argument The argument of the function call
  7088. */
  7089. updateKnownValue(argument) {
  7090. if (this.isReassigned) {
  7091. return;
  7092. }
  7093. if (this.knownValue === null) {
  7094. this.knownValue = argument;
  7095. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  7096. return;
  7097. }
  7098. // the same literal or identifier, do nothing
  7099. if (this.knownValue === argument ||
  7100. (this.knownValue instanceof Identifier &&
  7101. argument instanceof Identifier &&
  7102. this.knownValue.variable === argument.variable)) {
  7103. return;
  7104. }
  7105. const { knownValueLiteral } = this;
  7106. if (typeof knownValueLiteral === 'symbol' ||
  7107. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  7108. knownValueLiteral) {
  7109. this.markReassigned();
  7110. }
  7111. }
  7112. /**
  7113. * This function freezes the known value of the parameter variable,
  7114. * so the optimization starts with a certain ExpressionEntity.
  7115. * The optimization can be undone by calling `markReassigned`.
  7116. * @returns the frozen value
  7117. */
  7118. getKnownValue() {
  7119. return this.knownValue || UNKNOWN_EXPRESSION;
  7120. }
  7121. getLiteralValueAtPath(path, recursionTracker, origin) {
  7122. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  7123. return UnknownValue;
  7124. }
  7125. const knownValue = this.getKnownValue();
  7126. this.expressionsDependingOnKnownValue.push(origin);
  7127. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  7128. }
  7129. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7130. const { type } = interaction;
  7131. if (this.isReassigned ||
  7132. type === INTERACTION_ASSIGNED ||
  7133. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  7134. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  7135. }
  7136. return (!(type === INTERACTION_CALLED
  7137. ? (interaction.withNew
  7138. ? context.instantiated
  7139. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  7140. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  7141. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  7142. }
  7143. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7144. // For performance reasons, we fully deoptimize all deeper interactions
  7145. if (path.length >= 2 ||
  7146. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  7147. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  7148. (path.length === 1 &&
  7149. (this.deoptimizedFields.has(UnknownKey) ||
  7150. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  7151. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  7152. deoptimizeInteraction(interaction);
  7153. return;
  7154. }
  7155. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  7156. for (const entity of this.argumentsToBeDeoptimized) {
  7157. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  7158. }
  7159. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7160. this.deoptimizationInteractions.push({
  7161. interaction,
  7162. path
  7163. });
  7164. }
  7165. }
  7166. }
  7167. deoptimizePath(path) {
  7168. if (path.length === 0) {
  7169. this.markReassigned();
  7170. return;
  7171. }
  7172. if (this.deoptimizedFields.has(UnknownKey)) {
  7173. return;
  7174. }
  7175. const key = path[0];
  7176. if (this.deoptimizedFields.has(key)) {
  7177. return;
  7178. }
  7179. this.deoptimizedFields.add(key);
  7180. for (const entity of this.argumentsToBeDeoptimized) {
  7181. // We do not need a recursion tracker here as we already track whether
  7182. // this field is deoptimized
  7183. entity.deoptimizePath([...this.initPath, key]);
  7184. }
  7185. if (key === UnknownKey) {
  7186. // save some memory
  7187. this.deoptimizationInteractions = NO_INTERACTIONS;
  7188. this.deoptimizations = EMPTY_PATH_TRACKER;
  7189. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  7190. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  7191. }
  7192. }
  7193. getReturnExpressionWhenCalledAtPath(path) {
  7194. // We deoptimize everything that is called as that will trivially deoptimize
  7195. // the corresponding return expressions as well and avoid badly performing
  7196. // and complicated alternatives
  7197. if (path.length === 0) {
  7198. this.deoptimizePath(UNKNOWN_PATH);
  7199. }
  7200. else if (!this.deoptimizedFields.has(path[0])) {
  7201. this.deoptimizePath([path[0]]);
  7202. }
  7203. return UNKNOWN_RETURN_EXPRESSION;
  7204. }
  7205. includeArgumentPaths(entity, context) {
  7206. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  7207. }
  7208. }
  7209. class ThisVariable extends ParameterVariable {
  7210. constructor(context) {
  7211. super('this', null, EMPTY_PATH, context);
  7212. }
  7213. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7214. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  7215. }
  7216. }
  7217. class CatchBodyScope extends ChildScope {
  7218. constructor(parent) {
  7219. super(parent, parent.context);
  7220. this.parent = parent;
  7221. }
  7222. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  7223. if (kind === 'var') {
  7224. const name = identifier.name;
  7225. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  7226. if (existingVariable) {
  7227. const existingKind = existingVariable.kind;
  7228. if (existingKind === 'parameter' &&
  7229. // If this is a destructured parameter, it is forbidden to redeclare
  7230. existingVariable.declarations[0].parent.type === parseAst_js.CatchClause) {
  7231. // If this is a var with the same name as the catch scope parameter,
  7232. // the assignment actually goes to the parameter and the var is
  7233. // hoisted without assignment. Locally, it is shadowed by the
  7234. // parameter
  7235. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  7236. // To avoid the need to rewrite the declaration, we link the variable
  7237. // names. If we ever implement a logic that splits initialization and
  7238. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  7239. // removed again.
  7240. // We do not need to check whether there already is a linked
  7241. // variable because then declaredVariable would be that linked
  7242. // variable.
  7243. existingVariable.renderLikeHoisted(declaredVariable);
  7244. this.addHoistedVariable(name, declaredVariable);
  7245. return declaredVariable;
  7246. }
  7247. if (existingKind === 'var') {
  7248. existingVariable.addDeclaration(identifier, init);
  7249. return existingVariable;
  7250. }
  7251. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  7252. }
  7253. // We only add parameters to parameter scopes
  7254. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  7255. // Necessary to make sure the init is deoptimized for conditional declarations.
  7256. // We cannot call deoptimizePath here.
  7257. declaredVariable.markInitializersForDeoptimization();
  7258. // We add the variable to this and all parent scopes to reliably detect conflicts
  7259. this.addHoistedVariable(name, declaredVariable);
  7260. return declaredVariable;
  7261. }
  7262. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  7263. }
  7264. }
  7265. class FunctionBodyScope extends ChildScope {
  7266. constructor(parent) {
  7267. super(parent, parent.context);
  7268. }
  7269. // There is stuff that is only allowed in function scopes, i.e. functions can
  7270. // be redeclared, functions and var can redeclare each other
  7271. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  7272. const name = identifier.name;
  7273. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  7274. if (existingVariable) {
  7275. const existingKind = existingVariable.kind;
  7276. if ((kind === 'var' || kind === 'function') &&
  7277. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  7278. existingVariable.addDeclaration(identifier, init);
  7279. return existingVariable;
  7280. }
  7281. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  7282. }
  7283. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  7284. this.variables.set(name, newVariable);
  7285. return newVariable;
  7286. }
  7287. }
  7288. class ParameterScope extends ChildScope {
  7289. constructor(parent, isCatchScope) {
  7290. super(parent, parent.context);
  7291. this.hasRest = false;
  7292. this.parameters = [];
  7293. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  7294. }
  7295. /**
  7296. * Adds a parameter to this scope. Parameters must be added in the correct
  7297. * order, i.e. from left to right.
  7298. */
  7299. addParameterDeclaration(identifier, argumentPath) {
  7300. const { name, start } = identifier;
  7301. const existingParameter = this.variables.get(name);
  7302. if (existingParameter) {
  7303. return this.context.error(parseAst_js.logDuplicateArgumentNameError(name), start);
  7304. }
  7305. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  7306. this.variables.set(name, variable);
  7307. // We also add it to the body scope to detect name conflicts with local
  7308. // variables. We still need the intermediate scope, though, as parameter
  7309. // defaults are NOT taken from the body scope but from the parameters or
  7310. // outside scope.
  7311. this.bodyScope.addHoistedVariable(name, variable);
  7312. return variable;
  7313. }
  7314. addParameterVariables(parameters, hasRest) {
  7315. this.parameters = parameters;
  7316. for (const parameterList of parameters) {
  7317. for (const parameter of parameterList) {
  7318. parameter.alwaysRendered = true;
  7319. }
  7320. }
  7321. this.hasRest = hasRest;
  7322. }
  7323. includeCallArguments({ args }, context) {
  7324. let calledFromTryStatement = false;
  7325. let argumentIncluded = false;
  7326. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  7327. let lastExplicitlyIncludedIndex = args.length - 1;
  7328. // If there is a SpreadElement, we need to include all arguments after it
  7329. // because we no longer know which argument corresponds to which parameter.
  7330. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  7331. const argument = args[argumentIndex];
  7332. if (argument instanceof SpreadElement && !argumentIncluded) {
  7333. argumentIncluded = true;
  7334. lastExplicitlyIncludedIndex = argumentIndex - 1;
  7335. }
  7336. if (argumentIncluded) {
  7337. argument.includePath(UNKNOWN_PATH, context);
  7338. argument.include(context, false);
  7339. }
  7340. }
  7341. // Now we go backwards either starting from the last argument or before the
  7342. // first SpreadElement to ensure all arguments before are included as needed
  7343. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  7344. const parameterVariables = this.parameters[index - 1] || restParameter;
  7345. const argument = args[index];
  7346. if (parameterVariables) {
  7347. calledFromTryStatement = false;
  7348. if (parameterVariables.length === 0) {
  7349. // handle empty destructuring to avoid destructuring undefined
  7350. argumentIncluded = true;
  7351. }
  7352. else {
  7353. for (const parameterVariable of parameterVariables) {
  7354. if (parameterVariable.calledFromTryStatement) {
  7355. calledFromTryStatement = true;
  7356. }
  7357. if (parameterVariable.included) {
  7358. argumentIncluded = true;
  7359. if (calledFromTryStatement) {
  7360. argument.include(context, true);
  7361. }
  7362. else {
  7363. parameterVariable.includeArgumentPaths(argument, context);
  7364. argument.include(context, false);
  7365. }
  7366. }
  7367. }
  7368. }
  7369. }
  7370. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  7371. argumentIncluded = true;
  7372. argument.include(context, calledFromTryStatement);
  7373. }
  7374. }
  7375. }
  7376. }
  7377. class ReturnValueScope extends ParameterScope {
  7378. constructor() {
  7379. super(...arguments);
  7380. this.returnExpression = null;
  7381. this.returnExpressions = [];
  7382. }
  7383. addReturnExpression(expression) {
  7384. this.returnExpressions.push(expression);
  7385. }
  7386. deoptimizeArgumentsOnCall({ args }) {
  7387. const { parameters } = this;
  7388. let position = 0;
  7389. for (; position < args.length - 1; position++) {
  7390. // Only the "this" argument arg[0] can be null
  7391. const argument = args[position + 1];
  7392. if (argument instanceof SpreadElement) {
  7393. // This deoptimizes the current and remaining parameters and arguments
  7394. for (; position < parameters.length; position++) {
  7395. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  7396. for (const variable of parameters[position]) {
  7397. variable.markReassigned();
  7398. }
  7399. }
  7400. break;
  7401. }
  7402. if (this.hasRest && position >= parameters.length - 1) {
  7403. argument.deoptimizePath(UNKNOWN_PATH);
  7404. }
  7405. else {
  7406. const variables = parameters[position];
  7407. if (variables) {
  7408. for (const variable of variables) {
  7409. variable.addArgumentForDeoptimization(argument);
  7410. }
  7411. }
  7412. this.addArgumentToBeDeoptimized(argument);
  7413. }
  7414. }
  7415. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  7416. for (; position < nonRestParameterLength; position++) {
  7417. for (const variable of parameters[position]) {
  7418. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  7419. }
  7420. }
  7421. }
  7422. getReturnExpression() {
  7423. if (this.returnExpression === null)
  7424. this.updateReturnExpression();
  7425. return this.returnExpression;
  7426. }
  7427. deoptimizeAllParameters() {
  7428. for (const parameter of this.parameters) {
  7429. for (const variable of parameter) {
  7430. variable.deoptimizePath(UNKNOWN_PATH);
  7431. variable.markReassigned();
  7432. }
  7433. }
  7434. }
  7435. reassignAllParameters() {
  7436. for (const parameter of this.parameters) {
  7437. for (const variable of parameter) {
  7438. variable.markReassigned();
  7439. }
  7440. }
  7441. }
  7442. addArgumentToBeDeoptimized(_argument) { }
  7443. updateReturnExpression() {
  7444. if (this.returnExpressions.length === 1) {
  7445. this.returnExpression = this.returnExpressions[0];
  7446. }
  7447. else {
  7448. this.returnExpression = UNKNOWN_EXPRESSION;
  7449. for (const expression of this.returnExpressions) {
  7450. expression.deoptimizePath(UNKNOWN_PATH);
  7451. }
  7452. }
  7453. }
  7454. }
  7455. class FunctionScope extends ReturnValueScope {
  7456. constructor(parent, functionNode) {
  7457. super(parent, false);
  7458. this.functionNode = functionNode;
  7459. const { context } = parent;
  7460. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7461. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7462. }
  7463. findLexicalBoundary() {
  7464. return this;
  7465. }
  7466. includeCallArguments(interaction, context) {
  7467. super.includeCallArguments(interaction, context);
  7468. if (this.argumentsVariable.included) {
  7469. const { args } = interaction;
  7470. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  7471. const argument = args[argumentIndex];
  7472. if (argument) {
  7473. argument.includePath(UNKNOWN_PATH, context);
  7474. argument.include(context, false);
  7475. }
  7476. }
  7477. }
  7478. }
  7479. addArgumentToBeDeoptimized(argument) {
  7480. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  7481. }
  7482. }
  7483. class ExpressionStatement extends NodeBase {
  7484. initialise() {
  7485. super.initialise();
  7486. if (this.directive &&
  7487. this.directive !== 'use strict' &&
  7488. this.parent.type === parseAst_js.Program) {
  7489. this.scope.context.log(parseAst_js.LOGLEVEL_WARN,
  7490. // This is necessary, because either way (deleting or not) can lead to errors.
  7491. parseAst_js.logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  7492. }
  7493. }
  7494. removeAnnotations(code) {
  7495. this.expression.removeAnnotations(code);
  7496. }
  7497. render(code, options) {
  7498. super.render(code, options);
  7499. if (code.original[this.end - 1] !== ';') {
  7500. code.appendLeft(this.end, ';');
  7501. }
  7502. }
  7503. shouldBeIncluded(context) {
  7504. if (this.directive && this.directive !== 'use strict')
  7505. return this.parent.type !== parseAst_js.Program;
  7506. return super.shouldBeIncluded(context);
  7507. }
  7508. }
  7509. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  7510. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  7511. class BlockStatement extends NodeBase {
  7512. get deoptimizeBody() {
  7513. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  7514. }
  7515. set deoptimizeBody(value) {
  7516. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  7517. }
  7518. get directlyIncluded() {
  7519. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  7520. }
  7521. set directlyIncluded(value) {
  7522. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  7523. }
  7524. addImplicitReturnExpressionToScope() {
  7525. const lastStatement = this.body[this.body.length - 1];
  7526. if (!lastStatement || lastStatement.type !== parseAst_js.ReturnStatement) {
  7527. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7528. }
  7529. }
  7530. createScope(parentScope) {
  7531. this.scope = this.parent.preventChildBlockScope
  7532. ? parentScope
  7533. : new BlockScope(parentScope);
  7534. }
  7535. hasEffects(context) {
  7536. if (this.deoptimizeBody)
  7537. return true;
  7538. for (const node of this.body) {
  7539. if (context.brokenFlow)
  7540. break;
  7541. if (node.hasEffects(context))
  7542. return true;
  7543. }
  7544. return false;
  7545. }
  7546. include(context, includeChildrenRecursively) {
  7547. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7548. this.included = true;
  7549. this.directlyIncluded = true;
  7550. if (this.deoptimizeBody)
  7551. includeChildrenRecursively = true;
  7552. for (const node of this.body) {
  7553. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7554. node.include(context, includeChildrenRecursively);
  7555. }
  7556. }
  7557. }
  7558. initialise() {
  7559. super.initialise();
  7560. const firstBodyStatement = this.body[0];
  7561. this.deoptimizeBody =
  7562. firstBodyStatement instanceof ExpressionStatement &&
  7563. firstBodyStatement.directive === 'use asm';
  7564. }
  7565. render(code, options) {
  7566. if (this.body.length > 0) {
  7567. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7568. }
  7569. else {
  7570. super.render(code, options);
  7571. }
  7572. }
  7573. }
  7574. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  7575. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  7576. class RestElement extends NodeBase {
  7577. constructor() {
  7578. super(...arguments);
  7579. this.declarationInit = null;
  7580. }
  7581. addExportedVariables(variables, exportNamesByVariable) {
  7582. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7583. }
  7584. declare(kind, destructuredInitPath, init) {
  7585. this.declarationInit = init;
  7586. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  7587. }
  7588. deoptimizeAssignment(destructuredInitPath, init) {
  7589. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  7590. }
  7591. deoptimizePath(path) {
  7592. if (path.length === 0) {
  7593. this.argument.deoptimizePath(EMPTY_PATH);
  7594. }
  7595. }
  7596. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7597. return (path.length > 0 ||
  7598. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7599. }
  7600. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  7601. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  7602. }
  7603. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  7604. return (this.included =
  7605. this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init) || this.included);
  7606. }
  7607. include(context, includeChildrenRecursively) {
  7608. if (!this.included)
  7609. this.includeNode(context);
  7610. // This should just include the identifier, its properties should be
  7611. // included where the variable is used.
  7612. this.argument.include(context, includeChildrenRecursively);
  7613. }
  7614. markDeclarationReached() {
  7615. this.argument.markDeclarationReached();
  7616. }
  7617. applyDeoptimizations() {
  7618. this.deoptimized = true;
  7619. if (this.declarationInit !== null) {
  7620. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7621. this.scope.context.requestTreeshakingPass();
  7622. }
  7623. }
  7624. }
  7625. RestElement.prototype.includeNode = onlyIncludeSelf;
  7626. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  7627. ? destructuredInitPath
  7628. : [...destructuredInitPath, UnknownKey];
  7629. class FunctionBase extends NodeBase {
  7630. constructor() {
  7631. super(...arguments);
  7632. this.parameterVariableValuesDeoptimized = false;
  7633. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  7634. }
  7635. get async() {
  7636. return isFlagSet(this.flags, 256 /* Flag.async */);
  7637. }
  7638. set async(value) {
  7639. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  7640. }
  7641. get deoptimizedReturn() {
  7642. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  7643. }
  7644. set deoptimizedReturn(value) {
  7645. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  7646. }
  7647. get generator() {
  7648. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  7649. }
  7650. set generator(value) {
  7651. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  7652. }
  7653. get hasCachedEffects() {
  7654. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  7655. }
  7656. set hasCachedEffects(value) {
  7657. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  7658. }
  7659. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7660. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7661. this.scope.deoptimizeArgumentsOnCall(interaction);
  7662. }
  7663. else {
  7664. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7665. }
  7666. }
  7667. deoptimizePath(path) {
  7668. this.getObjectEntity().deoptimizePath(path);
  7669. if (path.length === 1 && path[0] === UnknownKey) {
  7670. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7671. // which means the return expression and parameters need to be reassigned
  7672. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7673. this.scope.deoptimizeAllParameters();
  7674. }
  7675. }
  7676. getLiteralValueAtPath(path, recursionTracker, origin) {
  7677. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7678. }
  7679. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7680. if (path.length > 0) {
  7681. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7682. }
  7683. if (this.async) {
  7684. if (!this.deoptimizedReturn) {
  7685. this.deoptimizedReturn = true;
  7686. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7687. this.scope.context.requestTreeshakingPass();
  7688. }
  7689. return UNKNOWN_RETURN_EXPRESSION;
  7690. }
  7691. return [this.scope.getReturnExpression(), false];
  7692. }
  7693. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7694. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7695. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7696. }
  7697. if (this.hasCachedEffects) {
  7698. return true;
  7699. }
  7700. if (this.async) {
  7701. const { propertyReadSideEffects } = this.scope.context.options
  7702. .treeshake;
  7703. const returnExpression = this.scope.getReturnExpression();
  7704. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7705. (propertyReadSideEffects &&
  7706. (propertyReadSideEffects === 'always' ||
  7707. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7708. this.hasCachedEffects = true;
  7709. return true;
  7710. }
  7711. }
  7712. const { propertyReadSideEffects } = this.scope.context.options
  7713. .treeshake;
  7714. for (let index = 0; index < this.params.length; index++) {
  7715. const parameter = this.params[index];
  7716. if (parameter.hasEffects(context) ||
  7717. (propertyReadSideEffects &&
  7718. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  7719. this.hasCachedEffects = true;
  7720. return true;
  7721. }
  7722. }
  7723. return false;
  7724. }
  7725. /**
  7726. * If the function (expression or declaration) is only used as function calls
  7727. */
  7728. onlyFunctionCallUsed() {
  7729. let variable = null;
  7730. if (this.parent.type === parseAst_js.VariableDeclarator) {
  7731. variable = this.parent.id.variable ?? null;
  7732. }
  7733. if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
  7734. variable = this.parent.variable;
  7735. }
  7736. return variable?.getOnlyFunctionCallUsed() ?? false;
  7737. }
  7738. include(context, includeChildrenRecursively) {
  7739. if (!this.included)
  7740. this.includeNode(context);
  7741. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  7742. this.parameterVariableValuesDeoptimized = true;
  7743. this.scope.reassignAllParameters();
  7744. }
  7745. const { brokenFlow } = context;
  7746. context.brokenFlow = false;
  7747. this.body.include(context, includeChildrenRecursively);
  7748. context.brokenFlow = brokenFlow;
  7749. }
  7750. initialise() {
  7751. super.initialise();
  7752. if (this.body instanceof BlockStatement) {
  7753. this.body.addImplicitReturnExpressionToScope();
  7754. }
  7755. else {
  7756. this.scope.addReturnExpression(this.body);
  7757. }
  7758. if (this.annotations &&
  7759. this.scope.context.options.treeshake.annotations) {
  7760. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  7761. }
  7762. }
  7763. parseNode(esTreeNode) {
  7764. const { body, params } = esTreeNode;
  7765. const { scope } = this;
  7766. const { bodyScope, context } = scope;
  7767. // We need to ensure that parameters are declared before the body is parsed
  7768. // so that the scope already knows all parameters and can detect conflicts
  7769. // when parsing the body.
  7770. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  7771. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  7772. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  7773. return super.parseNode(esTreeNode);
  7774. }
  7775. }
  7776. FunctionBase.prototype.preventChildBlockScope = true;
  7777. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  7778. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  7779. class FunctionNode extends FunctionBase {
  7780. constructor() {
  7781. super(...arguments);
  7782. this.objectEntity = null;
  7783. }
  7784. createScope(parentScope) {
  7785. this.scope = new FunctionScope(parentScope, this);
  7786. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  7787. // This makes sure that all deoptimizations of "this" are applied to the
  7788. // constructed entity.
  7789. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  7790. }
  7791. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7792. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7793. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  7794. // args[0] is the "this" argument
  7795. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  7796. }
  7797. }
  7798. hasEffects(context) {
  7799. if (this.annotationNoSideEffects) {
  7800. return false;
  7801. }
  7802. return !!this.id?.hasEffects(context);
  7803. }
  7804. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7805. if (this.annotationNoSideEffects &&
  7806. path.length === 0 &&
  7807. interaction.type === INTERACTION_CALLED) {
  7808. return false;
  7809. }
  7810. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  7811. return true;
  7812. }
  7813. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  7814. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7815. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  7816. const { brokenFlow, ignore, replacedVariableInits } = context;
  7817. context.ignore = {
  7818. breaks: false,
  7819. continues: false,
  7820. labels: new Set(),
  7821. returnYield: true,
  7822. this: interaction.withNew
  7823. };
  7824. if (this.body.hasEffects(context)) {
  7825. this.hasCachedEffects = true;
  7826. return true;
  7827. }
  7828. context.brokenFlow = brokenFlow;
  7829. if (thisInit) {
  7830. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7831. }
  7832. else {
  7833. replacedVariableInits.delete(this.scope.thisVariable);
  7834. }
  7835. context.ignore = ignore;
  7836. }
  7837. return false;
  7838. }
  7839. include(context, includeChildrenRecursively) {
  7840. super.include(context, includeChildrenRecursively);
  7841. this.id?.include(context, includeChildrenRecursively);
  7842. const hasArguments = this.scope.argumentsVariable.included;
  7843. for (const parameter of this.params) {
  7844. if (!(parameter instanceof Identifier) || hasArguments) {
  7845. parameter.include(context, includeChildrenRecursively);
  7846. }
  7847. }
  7848. }
  7849. includeNode(context) {
  7850. this.included = true;
  7851. const hasArguments = this.scope.argumentsVariable.included;
  7852. for (const parameter of this.params) {
  7853. if (!(parameter instanceof Identifier) || hasArguments) {
  7854. parameter.includePath(UNKNOWN_PATH, context);
  7855. }
  7856. }
  7857. }
  7858. initialise() {
  7859. super.initialise();
  7860. this.id?.declare('function', EMPTY_PATH, this);
  7861. }
  7862. getObjectEntity() {
  7863. if (this.objectEntity !== null) {
  7864. return this.objectEntity;
  7865. }
  7866. return (this.objectEntity = new ObjectEntity([
  7867. {
  7868. key: 'prototype',
  7869. kind: 'init',
  7870. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7871. }
  7872. ], OBJECT_PROTOTYPE));
  7873. }
  7874. }
  7875. class FunctionDeclaration extends FunctionNode {
  7876. initialise() {
  7877. super.initialise();
  7878. if (this.id !== null) {
  7879. this.id.variable.isId = true;
  7880. }
  7881. }
  7882. onlyFunctionCallUsed() {
  7883. // call super.onlyFunctionCallUsed for export default anonymous function
  7884. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  7885. }
  7886. parseNode(esTreeNode) {
  7887. if (esTreeNode.id !== null) {
  7888. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  7889. }
  7890. return super.parseNode(esTreeNode);
  7891. }
  7892. }
  7893. // The header ends at the first non-white-space after "default"
  7894. function getDeclarationStart(code, start) {
  7895. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  7896. }
  7897. function getFunctionIdInsertPosition(code, start) {
  7898. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  7899. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  7900. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  7901. if (generatorStarPos === -1) {
  7902. return declarationEnd;
  7903. }
  7904. return declarationEnd + generatorStarPos + 1;
  7905. }
  7906. class ExportDefaultDeclaration extends NodeBase {
  7907. include(context, includeChildrenRecursively) {
  7908. this.included = true;
  7909. this.declaration.include(context, includeChildrenRecursively);
  7910. if (includeChildrenRecursively) {
  7911. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  7912. }
  7913. }
  7914. includePath(path, context) {
  7915. this.included = true;
  7916. this.declaration.includePath(path, context);
  7917. }
  7918. initialise() {
  7919. super.initialise();
  7920. const declaration = this.declaration;
  7921. this.declarationName =
  7922. (declaration.id && declaration.id.name) || this.declaration.name;
  7923. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  7924. this.scope.context.addExport(this);
  7925. }
  7926. removeAnnotations(code) {
  7927. this.declaration.removeAnnotations(code);
  7928. }
  7929. render(code, options, nodeRenderOptions) {
  7930. const { start, end } = nodeRenderOptions;
  7931. const declarationStart = getDeclarationStart(code.original, this.start);
  7932. if (this.declaration instanceof FunctionDeclaration) {
  7933. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  7934. ? getFunctionIdInsertPosition(code.original, declarationStart)
  7935. : null, options);
  7936. }
  7937. else if (this.declaration instanceof ClassDeclaration) {
  7938. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  7939. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  7940. : null, options);
  7941. }
  7942. else if (this.variable.getOriginalVariable() !== this.variable) {
  7943. // Remove altogether to prevent re-declaring the same variable
  7944. treeshakeNode(this, code, start, end);
  7945. return;
  7946. }
  7947. else if (this.variable.included) {
  7948. this.renderVariableDeclaration(code, declarationStart, options);
  7949. }
  7950. else {
  7951. code.remove(this.start, declarationStart);
  7952. this.declaration.render(code, options, {
  7953. renderedSurroundingElement: parseAst_js.ExpressionStatement
  7954. });
  7955. if (code.original[this.end - 1] !== ';') {
  7956. code.appendLeft(this.end, ';');
  7957. }
  7958. return;
  7959. }
  7960. this.declaration.render(code, options);
  7961. }
  7962. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  7963. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  7964. const name = this.variable.getName(getPropertyAccess);
  7965. // Remove `export default`
  7966. code.remove(this.start, declarationStart);
  7967. if (idInsertPosition !== null) {
  7968. code.appendLeft(idInsertPosition, ` ${name}`);
  7969. }
  7970. if (format === 'system' &&
  7971. this.declaration instanceof ClassDeclaration &&
  7972. exportNamesByVariable.has(this.variable)) {
  7973. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  7974. }
  7975. }
  7976. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  7977. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  7978. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  7979. if (systemExportNames) {
  7980. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  7981. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  7982. }
  7983. else {
  7984. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  7985. if (!hasTrailingSemicolon) {
  7986. code.appendLeft(this.end, ';');
  7987. }
  7988. }
  7989. }
  7990. }
  7991. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  7992. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  7993. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  7994. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  7995. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  7996. const backSlashRegEx = /\\/g;
  7997. function escapeId(id) {
  7998. if (!needsEscapeRegEx.test(id))
  7999. return id;
  8000. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  8001. }
  8002. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  8003. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  8004. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  8005. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  8006. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  8007. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  8008. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  8009. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  8010. const defaultInteropHelpersByInteropType = {
  8011. auto: INTEROP_DEFAULT_VARIABLE,
  8012. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  8013. default: null,
  8014. defaultOnly: null,
  8015. esModule: null
  8016. };
  8017. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  8018. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  8019. const namespaceInteropHelpersByInteropType = {
  8020. auto: INTEROP_NAMESPACE_VARIABLE,
  8021. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  8022. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  8023. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  8024. esModule: null
  8025. };
  8026. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  8027. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  8028. const usedHelpers = new Set(additionalHelpers);
  8029. for (const variable of HELPER_NAMES) {
  8030. if (accessedGlobals.has(variable)) {
  8031. usedHelpers.add(variable);
  8032. }
  8033. }
  8034. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  8035. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  8036. : '').join('');
  8037. };
  8038. const HELPER_GENERATORS = {
  8039. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  8040. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  8041. },
  8042. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  8043. const { _, getDirectReturnFunction, n } = snippets;
  8044. const [left, right] = getDirectReturnFunction(['e'], {
  8045. functionReturn: true,
  8046. lineBreakIndent: null,
  8047. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  8048. });
  8049. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  8050. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  8051. },
  8052. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  8053. const { _, getDirectReturnFunction, n } = snippets;
  8054. const [left, right] = getDirectReturnFunction(['e'], {
  8055. functionReturn: true,
  8056. lineBreakIndent: null,
  8057. name: INTEROP_DEFAULT_VARIABLE
  8058. });
  8059. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  8060. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  8061. },
  8062. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  8063. const { _, getDirectReturnFunction, n } = snippets;
  8064. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  8065. const [left, right] = getDirectReturnFunction(['e'], {
  8066. functionReturn: true,
  8067. lineBreakIndent: null,
  8068. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  8069. });
  8070. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  8071. }
  8072. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  8073. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  8074. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  8075. `}${n}${n}`);
  8076. },
  8077. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  8078. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  8079. const [left, right] = getDirectReturnFunction(['e'], {
  8080. functionReturn: true,
  8081. lineBreakIndent: null,
  8082. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  8083. });
  8084. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  8085. [null, `__proto__:${_}null`],
  8086. ['default', 'e']
  8087. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  8088. },
  8089. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  8090. const { _, n } = snippets;
  8091. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  8092. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  8093. `}${n}${n}`);
  8094. },
  8095. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  8096. const { _, getDirectReturnFunction, n } = snippets;
  8097. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  8098. const [left, right] = getDirectReturnFunction(['e'], {
  8099. functionReturn: true,
  8100. lineBreakIndent: null,
  8101. name: INTEROP_NAMESPACE_VARIABLE
  8102. });
  8103. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  8104. }
  8105. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  8106. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  8107. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  8108. `}${n}${n}`);
  8109. },
  8110. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  8111. const { _, cnst, n } = snippets;
  8112. const useForEach = cnst === 'var' && liveBindings;
  8113. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  8114. `${t}${loopOverNamespaces(`{${n}` +
  8115. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  8116. (liveBindings
  8117. ? useForEach
  8118. ? copyOwnPropertyLiveBinding
  8119. : copyPropertyLiveBinding
  8120. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  8121. `${t}${t}${t}}${n}` +
  8122. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  8123. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  8124. `}${n}${n}`);
  8125. }
  8126. };
  8127. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  8128. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  8129. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  8130. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  8131. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  8132. const copyProperty = `{${n}` +
  8133. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  8134. `${index}${t}}`;
  8135. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  8136. `${index}if${_}(e)${_}{${n}` +
  8137. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  8138. `${index}}${n}` +
  8139. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  8140. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  8141. };
  8142. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  8143. ? `for${_}(${cnst} k in e)${_}${body}`
  8144. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  8145. isAsync: false,
  8146. name: null
  8147. })}${body})${s}`;
  8148. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  8149. if (useForEach) {
  8150. const [left, right] = getDirectReturnFunction(['e'], {
  8151. functionReturn: false,
  8152. lineBreakIndent: { base: t, t },
  8153. name: null
  8154. });
  8155. return (`m.forEach(${left}` +
  8156. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  8157. isAsync: false,
  8158. name: null
  8159. })}${body})${right});`);
  8160. }
  8161. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  8162. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  8163. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  8164. };
  8165. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  8166. const { _, n } = snippets;
  8167. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  8168. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  8169. `${index}}${n}`);
  8170. };
  8171. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  8172. const [left, right] = getDirectReturnFunction([], {
  8173. functionReturn: true,
  8174. lineBreakIndent: null,
  8175. name: null
  8176. });
  8177. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  8178. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  8179. `${index}${t}enumerable:${_}true,${n}` +
  8180. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  8181. `${index}});${n}`);
  8182. };
  8183. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  8184. const [left, right] = getDirectReturnFunction([], {
  8185. functionReturn: true,
  8186. lineBreakIndent: null,
  8187. name: null
  8188. });
  8189. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  8190. `${index}if${_}(d)${_}{${n}` +
  8191. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  8192. `${index}${t}${t}enumerable:${_}true,${n}` +
  8193. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  8194. `${index}${t}});${n}` +
  8195. `${index}}${n}`);
  8196. };
  8197. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  8198. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  8199. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  8200. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  8201. : fragment;
  8202. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  8203. function getToStringTagValue(getObject) {
  8204. return getObject([['value', "'Module'"]], {
  8205. lineBreakIndent: null
  8206. });
  8207. }
  8208. class Literal extends NodeBase {
  8209. deoptimizeArgumentsOnInteractionAtPath() { }
  8210. getLiteralValueAtPath(path) {
  8211. if (path.length > 0 ||
  8212. // unknown literals can also be null but do not start with an "n"
  8213. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  8214. typeof this.value === 'bigint' ||
  8215. // to support shims for regular expressions
  8216. this.scope.context.code.charCodeAt(this.start) === 47) {
  8217. return UnknownValue;
  8218. }
  8219. return this.value;
  8220. }
  8221. getReturnExpressionWhenCalledAtPath(path) {
  8222. if (path.length !== 1)
  8223. return UNKNOWN_RETURN_EXPRESSION;
  8224. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  8225. }
  8226. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8227. switch (interaction.type) {
  8228. case INTERACTION_ACCESSED: {
  8229. return path.length > (this.value === null ? 0 : 1);
  8230. }
  8231. case INTERACTION_ASSIGNED: {
  8232. return true;
  8233. }
  8234. case INTERACTION_CALLED: {
  8235. if (this.included &&
  8236. this.value instanceof RegExp &&
  8237. (this.value.global || this.value.sticky)) {
  8238. return true;
  8239. }
  8240. return (path.length !== 1 ||
  8241. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  8242. }
  8243. }
  8244. }
  8245. initialise() {
  8246. super.initialise();
  8247. this.members = getLiteralMembersForValue(this.value);
  8248. }
  8249. parseNode(esTreeNode) {
  8250. this.value = esTreeNode.value;
  8251. this.regex = esTreeNode.regex;
  8252. return super.parseNode(esTreeNode);
  8253. }
  8254. render(code) {
  8255. if (typeof this.value === 'string') {
  8256. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  8257. }
  8258. }
  8259. }
  8260. Literal.prototype.includeNode = onlyIncludeSelf;
  8261. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  8262. if ('getLiteralValueAtPathAsChainElement' in object) {
  8263. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  8264. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  8265. return IS_SKIPPED_CHAIN;
  8266. }
  8267. }
  8268. else if (element.optional &&
  8269. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  8270. return IS_SKIPPED_CHAIN;
  8271. }
  8272. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  8273. }
  8274. function getResolvablePropertyKey(memberExpression) {
  8275. return memberExpression.computed
  8276. ? getResolvableComputedPropertyKey(memberExpression.property)
  8277. : memberExpression.property.name;
  8278. }
  8279. function getResolvableComputedPropertyKey(propertyKey) {
  8280. if (propertyKey instanceof Literal) {
  8281. return String(propertyKey.value);
  8282. }
  8283. return null;
  8284. }
  8285. function getPathIfNotComputed(memberExpression) {
  8286. const nextPathKey = memberExpression.propertyKey;
  8287. const object = memberExpression.object;
  8288. if (typeof nextPathKey === 'string') {
  8289. if (object instanceof Identifier) {
  8290. return [
  8291. { key: object.name, pos: object.start },
  8292. { key: nextPathKey, pos: memberExpression.property.start }
  8293. ];
  8294. }
  8295. if (object instanceof MemberExpression) {
  8296. const parentPath = getPathIfNotComputed(object);
  8297. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  8298. }
  8299. }
  8300. return null;
  8301. }
  8302. function getStringFromPath(path) {
  8303. let pathString = path[0].key;
  8304. for (let index = 1; index < path.length; index++) {
  8305. pathString += '.' + path[index].key;
  8306. }
  8307. return pathString;
  8308. }
  8309. class MemberExpression extends NodeBase {
  8310. constructor() {
  8311. super(...arguments);
  8312. this.variable = null;
  8313. this.expressionsToBeDeoptimized = [];
  8314. }
  8315. get computed() {
  8316. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  8317. }
  8318. set computed(value) {
  8319. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  8320. }
  8321. get optional() {
  8322. return isFlagSet(this.flags, 128 /* Flag.optional */);
  8323. }
  8324. set optional(value) {
  8325. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  8326. }
  8327. get assignmentDeoptimized() {
  8328. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  8329. }
  8330. set assignmentDeoptimized(value) {
  8331. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  8332. }
  8333. get bound() {
  8334. return isFlagSet(this.flags, 32 /* Flag.bound */);
  8335. }
  8336. set bound(value) {
  8337. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  8338. }
  8339. get isUndefined() {
  8340. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  8341. }
  8342. set isUndefined(value) {
  8343. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  8344. }
  8345. bind() {
  8346. this.bound = true;
  8347. const path = getPathIfNotComputed(this);
  8348. const baseVariable = path && this.scope.findVariable(path[0].key);
  8349. if (baseVariable?.isNamespace) {
  8350. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  8351. if (!resolvedVariable) {
  8352. super.bind();
  8353. }
  8354. else if (resolvedVariable === 'undefined') {
  8355. this.isUndefined = true;
  8356. }
  8357. else {
  8358. this.variable = resolvedVariable;
  8359. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  8360. }
  8361. }
  8362. else {
  8363. super.bind();
  8364. }
  8365. }
  8366. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8367. if (this.variable) {
  8368. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8369. }
  8370. else if (!this.isUndefined) {
  8371. if (path.length < MAX_PATH_DEPTH) {
  8372. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  8373. }
  8374. else {
  8375. deoptimizeInteraction(interaction);
  8376. }
  8377. }
  8378. }
  8379. deoptimizeAssignment(destructuredInitPath, init) {
  8380. this.deoptimizePath(EMPTY_PATH);
  8381. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  8382. }
  8383. deoptimizeCache() {
  8384. if (this.propertyKey === this.dynamicPropertyKey)
  8385. return;
  8386. const { expressionsToBeDeoptimized, object } = this;
  8387. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  8388. this.dynamicPropertyKey = this.propertyKey;
  8389. object.deoptimizePath(UNKNOWN_PATH);
  8390. if (this.included) {
  8391. object.includePath(UNKNOWN_PATH, createInclusionContext());
  8392. }
  8393. for (const expression of expressionsToBeDeoptimized) {
  8394. expression.deoptimizeCache();
  8395. }
  8396. }
  8397. deoptimizePath(path) {
  8398. if (path.length === 0)
  8399. this.disallowNamespaceReassignment();
  8400. if (this.variable) {
  8401. this.variable.deoptimizePath(path);
  8402. }
  8403. else if (!this.isUndefined) {
  8404. const { propertyKey } = this;
  8405. this.object.deoptimizePath([
  8406. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  8407. ...(path.length < MAX_PATH_DEPTH
  8408. ? path
  8409. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  8410. ]);
  8411. }
  8412. }
  8413. getLiteralValueAtPath(path, recursionTracker, origin) {
  8414. if (this.variable) {
  8415. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8416. }
  8417. if (this.isUndefined) {
  8418. return undefined;
  8419. }
  8420. const propertyKey = this.getDynamicPropertyKey();
  8421. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8422. if (propertyKey !== this.propertyKey)
  8423. this.expressionsToBeDeoptimized.push(origin);
  8424. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  8425. }
  8426. return UnknownValue;
  8427. }
  8428. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  8429. if (this.variable) {
  8430. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8431. }
  8432. if (this.isUndefined) {
  8433. return undefined;
  8434. }
  8435. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  8436. }
  8437. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8438. if (this.variable) {
  8439. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8440. }
  8441. if (this.isUndefined) {
  8442. return [UNDEFINED_EXPRESSION, false];
  8443. }
  8444. const propertyKey = this.getDynamicPropertyKey();
  8445. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8446. if (propertyKey !== this.propertyKey)
  8447. this.expressionsToBeDeoptimized.push(origin);
  8448. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  8449. }
  8450. return UNKNOWN_RETURN_EXPRESSION;
  8451. }
  8452. hasEffects(context) {
  8453. if (!this.deoptimized)
  8454. this.applyDeoptimizations();
  8455. return (this.property.hasEffects(context) ||
  8456. this.object.hasEffects(context) ||
  8457. this.hasAccessEffect(context));
  8458. }
  8459. hasEffectsAsChainElement(context) {
  8460. if (this.variable || this.isUndefined)
  8461. return this.hasEffects(context);
  8462. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  8463. ? this.object.hasEffectsAsChainElement(context)
  8464. : this.object.hasEffects(context);
  8465. if (objectHasEffects === IS_SKIPPED_CHAIN)
  8466. return IS_SKIPPED_CHAIN;
  8467. if (this.optional &&
  8468. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  8469. return objectHasEffects || IS_SKIPPED_CHAIN;
  8470. }
  8471. // We only apply deoptimizations lazily once we know we are not skipping
  8472. if (!this.deoptimized)
  8473. this.applyDeoptimizations();
  8474. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  8475. }
  8476. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8477. if (checkAccess && !this.deoptimized)
  8478. this.applyDeoptimizations();
  8479. if (!this.assignmentDeoptimized)
  8480. this.applyAssignmentDeoptimization();
  8481. return (this.property.hasEffects(context) ||
  8482. this.object.hasEffects(context) ||
  8483. (checkAccess && this.hasAccessEffect(context)) ||
  8484. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8485. }
  8486. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8487. if (this.variable) {
  8488. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8489. }
  8490. if (this.isUndefined) {
  8491. return true;
  8492. }
  8493. if (path.length < MAX_PATH_DEPTH) {
  8494. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  8495. }
  8496. return true;
  8497. }
  8498. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  8499. return (destructuredInitPath.length > 0 &&
  8500. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8501. }
  8502. include(context, includeChildrenRecursively) {
  8503. if (!this.included)
  8504. this.includeNode(context);
  8505. this.object.include(context, includeChildrenRecursively);
  8506. this.property.include(context, includeChildrenRecursively);
  8507. }
  8508. includeNode(context) {
  8509. this.included = true;
  8510. if (!this.deoptimized)
  8511. this.applyDeoptimizations();
  8512. if (this.variable) {
  8513. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8514. }
  8515. else if (!this.isUndefined) {
  8516. this.object.includePath([this.propertyKey], context);
  8517. }
  8518. }
  8519. includeNodeAsAssignmentTarget(context) {
  8520. this.included = true;
  8521. if (!this.assignmentDeoptimized)
  8522. this.applyAssignmentDeoptimization();
  8523. if (this.variable) {
  8524. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  8525. }
  8526. else if (!this.isUndefined) {
  8527. this.object.includePath([this.propertyKey], context);
  8528. }
  8529. }
  8530. includePath(path, context) {
  8531. if (!this.included)
  8532. this.includeNode(context);
  8533. if (this.variable) {
  8534. this.variable?.includePath(path, context);
  8535. }
  8536. else if (!this.isUndefined) {
  8537. this.object.includePath([
  8538. this.propertyKey,
  8539. ...(path.length < MAX_PATH_DEPTH
  8540. ? path
  8541. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  8542. ], context);
  8543. }
  8544. }
  8545. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8546. if (!this.included)
  8547. this.includeNodeAsAssignmentTarget(context);
  8548. if (deoptimizeAccess && !this.deoptimized)
  8549. this.applyDeoptimizations();
  8550. this.object.include(context, includeChildrenRecursively);
  8551. this.property.include(context, includeChildrenRecursively);
  8552. }
  8553. includeCallArguments(interaction, context) {
  8554. if (this.variable) {
  8555. this.variable.includeCallArguments(interaction, context);
  8556. }
  8557. else {
  8558. includeInteraction(interaction, context);
  8559. }
  8560. }
  8561. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  8562. if ((this.included ||=
  8563. destructuredInitPath.length > 0 &&
  8564. !context.brokenFlow &&
  8565. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext()))) {
  8566. init.include(context, false);
  8567. return true;
  8568. }
  8569. return false;
  8570. }
  8571. initialise() {
  8572. super.initialise();
  8573. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  8574. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  8575. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  8576. }
  8577. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = parseAst_js.BLANK) {
  8578. if (this.variable || this.isUndefined) {
  8579. const { snippets: { getPropertyAccess } } = options;
  8580. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  8581. if (renderedParentType && isCalleeOfRenderedParent)
  8582. replacement = '0, ' + replacement;
  8583. code.overwrite(this.start, this.end, replacement, {
  8584. contentOnly: true,
  8585. storeName: true
  8586. });
  8587. }
  8588. else {
  8589. if (renderedParentType && isCalleeOfRenderedParent) {
  8590. code.appendRight(this.start, '0, ');
  8591. }
  8592. this.object.render(code, options, { renderedSurroundingElement });
  8593. this.property.render(code, options);
  8594. }
  8595. }
  8596. setAssignedValue(value) {
  8597. this.assignmentInteraction = {
  8598. args: [this.object, value],
  8599. type: INTERACTION_ASSIGNED
  8600. };
  8601. }
  8602. applyDeoptimizations() {
  8603. this.deoptimized = true;
  8604. const { propertyReadSideEffects } = this.scope.context.options
  8605. .treeshake;
  8606. if (
  8607. // Namespaces are not bound and should not be deoptimized
  8608. this.bound &&
  8609. propertyReadSideEffects &&
  8610. !(this.variable || this.isUndefined)) {
  8611. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  8612. this.scope.context.requestTreeshakingPass();
  8613. }
  8614. if (this.variable) {
  8615. this.variable.addUsedPlace(this);
  8616. this.scope.context.requestTreeshakingPass();
  8617. }
  8618. }
  8619. applyAssignmentDeoptimization() {
  8620. this.assignmentDeoptimized = true;
  8621. const { propertyReadSideEffects } = this.scope.context.options
  8622. .treeshake;
  8623. if (
  8624. // Namespaces are not bound and should not be deoptimized
  8625. this.bound &&
  8626. propertyReadSideEffects &&
  8627. !(this.variable || this.isUndefined)) {
  8628. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  8629. this.scope.context.requestTreeshakingPass();
  8630. }
  8631. }
  8632. disallowNamespaceReassignment() {
  8633. if (this.object instanceof Identifier) {
  8634. const variable = this.scope.findVariable(this.object.name);
  8635. if (variable.isNamespace) {
  8636. if (this.variable) {
  8637. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  8638. }
  8639. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  8640. }
  8641. }
  8642. }
  8643. getDynamicPropertyKey() {
  8644. if (this.dynamicPropertyKey === null) {
  8645. this.dynamicPropertyKey = this.propertyKey;
  8646. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8647. return (this.dynamicPropertyKey =
  8648. value === SymbolToStringTag
  8649. ? value
  8650. : typeof value === 'symbol'
  8651. ? UnknownKey
  8652. : String(value));
  8653. }
  8654. return this.dynamicPropertyKey;
  8655. }
  8656. hasAccessEffect(context) {
  8657. const { propertyReadSideEffects } = this.scope.context.options
  8658. .treeshake;
  8659. return (!(this.variable || this.isUndefined) &&
  8660. propertyReadSideEffects &&
  8661. (propertyReadSideEffects === 'always' ||
  8662. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  8663. }
  8664. }
  8665. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8666. if (path.length === 0)
  8667. return baseVariable;
  8668. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8669. return null;
  8670. const exportName = path[0].key;
  8671. const variable = baseVariable.context.traceExport(exportName);
  8672. if (!variable) {
  8673. if (path.length === 1) {
  8674. const fileName = baseVariable.context.fileName;
  8675. astContext.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  8676. return 'undefined';
  8677. }
  8678. return null;
  8679. }
  8680. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8681. }
  8682. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  8683. const IMPORT = 'import';
  8684. class MetaProperty extends NodeBase {
  8685. constructor() {
  8686. super(...arguments);
  8687. this.metaProperty = null;
  8688. this.preliminaryChunkId = null;
  8689. this.referenceId = null;
  8690. }
  8691. getReferencedFileName(outputPluginDriver) {
  8692. const { meta: { name }, metaProperty } = this;
  8693. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  8694. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  8695. }
  8696. return null;
  8697. }
  8698. hasEffects() {
  8699. return false;
  8700. }
  8701. hasEffectsOnInteractionAtPath(path, { type }) {
  8702. return path.length > 1 || type !== INTERACTION_ACCESSED;
  8703. }
  8704. include() {
  8705. if (!this.included)
  8706. this.includeNode();
  8707. }
  8708. includeNode() {
  8709. this.included = true;
  8710. if (this.meta.name === IMPORT) {
  8711. this.scope.context.addImportMeta(this);
  8712. const parent = this.parent;
  8713. const metaProperty = (this.metaProperty =
  8714. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  8715. ? parent.propertyKey
  8716. : null);
  8717. if (metaProperty?.startsWith(FILE_PREFIX)) {
  8718. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  8719. }
  8720. }
  8721. }
  8722. render(code, renderOptions) {
  8723. const { format, pluginDriver, snippets } = renderOptions;
  8724. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  8725. const { id: moduleId } = module;
  8726. if (name !== IMPORT)
  8727. return;
  8728. const chunkId = preliminaryChunkId;
  8729. if (referenceId) {
  8730. const fileName = pluginDriver.getFileName(referenceId);
  8731. const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
  8732. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  8733. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  8734. ]) || relativeUrlMechanisms[format](relativePath);
  8735. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8736. return;
  8737. }
  8738. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  8739. metaProperty,
  8740. { chunkId, format, moduleId }
  8741. ]);
  8742. if (!replacement) {
  8743. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  8744. renderOptions.accessedDocumentCurrentScript ||=
  8745. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  8746. }
  8747. if (typeof replacement === 'string') {
  8748. if (parent instanceof MemberExpression) {
  8749. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8750. }
  8751. else {
  8752. code.overwrite(start, end, replacement, { contentOnly: true });
  8753. }
  8754. }
  8755. }
  8756. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  8757. this.preliminaryChunkId = preliminaryChunkId;
  8758. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  8759. if (accessedGlobals.length > 0) {
  8760. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  8761. }
  8762. }
  8763. }
  8764. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  8765. const accessedMetaUrlGlobals = {
  8766. amd: ['document', 'module', 'URL'],
  8767. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  8768. es: [],
  8769. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  8770. system: ['module'],
  8771. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  8772. };
  8773. const accessedFileUrlGlobals = {
  8774. amd: ['document', 'require', 'URL'],
  8775. cjs: ['document', 'require', 'URL'],
  8776. es: [],
  8777. iife: ['document', 'URL'],
  8778. system: ['module', 'URL'],
  8779. umd: ['document', 'require', 'URL']
  8780. };
  8781. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  8782. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  8783. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  8784. const urlMechanism = getUrl(chunkId);
  8785. return property === null
  8786. ? `({ url: ${urlMechanism} })`
  8787. : property === 'url'
  8788. ? urlMechanism
  8789. : 'undefined';
  8790. };
  8791. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  8792. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  8793. 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)`;
  8794. const relativeUrlMechanisms = {
  8795. amd: relativePath => {
  8796. if (relativePath[0] !== '.')
  8797. relativePath = './' + relativePath;
  8798. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  8799. },
  8800. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  8801. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  8802. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  8803. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  8804. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  8805. };
  8806. const importMetaMechanisms = {
  8807. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  8808. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  8809. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  8810. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  8811. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  8812. };
  8813. class UndefinedVariable extends Variable {
  8814. constructor() {
  8815. super('undefined');
  8816. }
  8817. getLiteralValueAtPath() {
  8818. return undefined;
  8819. }
  8820. }
  8821. class ExportDefaultVariable extends LocalVariable {
  8822. constructor(name, exportDefaultDeclaration, context) {
  8823. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  8824. this.hasId = false;
  8825. this.originalId = null;
  8826. this.originalVariable = null;
  8827. const declaration = exportDefaultDeclaration.declaration;
  8828. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  8829. declaration.id) {
  8830. this.hasId = true;
  8831. this.originalId = declaration.id;
  8832. }
  8833. else if (declaration instanceof Identifier) {
  8834. this.originalId = declaration;
  8835. }
  8836. }
  8837. addReference(identifier) {
  8838. if (!this.hasId) {
  8839. this.name = identifier.name;
  8840. }
  8841. }
  8842. addUsedPlace(usedPlace) {
  8843. const original = this.getOriginalVariable();
  8844. if (original === this) {
  8845. super.addUsedPlace(usedPlace);
  8846. }
  8847. else {
  8848. original.addUsedPlace(usedPlace);
  8849. }
  8850. }
  8851. forbidName(name) {
  8852. const original = this.getOriginalVariable();
  8853. if (original === this) {
  8854. super.forbidName(name);
  8855. }
  8856. else {
  8857. original.forbidName(name);
  8858. }
  8859. }
  8860. getAssignedVariableName() {
  8861. return (this.originalId && this.originalId.name) || null;
  8862. }
  8863. getBaseVariableName() {
  8864. const original = this.getOriginalVariable();
  8865. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  8866. }
  8867. getDirectOriginalVariable() {
  8868. return this.originalId &&
  8869. (this.hasId ||
  8870. !(this.originalId.isPossibleTDZ() ||
  8871. this.originalId.variable.isReassigned ||
  8872. this.originalId.variable instanceof UndefinedVariable ||
  8873. // this avoids a circular dependency
  8874. 'syntheticNamespace' in this.originalId.variable))
  8875. ? this.originalId.variable
  8876. : null;
  8877. }
  8878. getName(getPropertyAccess) {
  8879. const original = this.getOriginalVariable();
  8880. return original === this
  8881. ? super.getName(getPropertyAccess)
  8882. : original.getName(getPropertyAccess);
  8883. }
  8884. getOriginalVariable() {
  8885. if (this.originalVariable)
  8886. return this.originalVariable;
  8887. // eslint-disable-next-line @typescript-eslint/no-this-alias
  8888. let original = this;
  8889. let currentVariable;
  8890. const checkedVariables = new Set();
  8891. do {
  8892. checkedVariables.add(original);
  8893. currentVariable = original;
  8894. original = currentVariable.getDirectOriginalVariable();
  8895. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  8896. return (this.originalVariable = original || currentVariable);
  8897. }
  8898. }
  8899. class NamespaceVariable extends Variable {
  8900. constructor(context) {
  8901. super(context.getModuleName());
  8902. this.memberVariables = null;
  8903. this.mergedNamespaces = [];
  8904. this.referencedEarly = false;
  8905. this.references = [];
  8906. this.context = context;
  8907. this.module = context.module;
  8908. }
  8909. addReference(identifier) {
  8910. this.references.push(identifier);
  8911. this.name = identifier.name;
  8912. }
  8913. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8914. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  8915. const key = path[0];
  8916. if (typeof key === 'string') {
  8917. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  8918. }
  8919. else {
  8920. deoptimizeInteraction(interaction);
  8921. }
  8922. }
  8923. }
  8924. deoptimizePath(path) {
  8925. if (path.length > 1) {
  8926. const key = path[0];
  8927. if (typeof key === 'string') {
  8928. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  8929. }
  8930. }
  8931. }
  8932. getLiteralValueAtPath(path) {
  8933. if (path[0] === SymbolToStringTag) {
  8934. return 'Module';
  8935. }
  8936. return UnknownValue;
  8937. }
  8938. getMemberVariables() {
  8939. if (this.memberVariables) {
  8940. return this.memberVariables;
  8941. }
  8942. const memberVariables = Object.create(null);
  8943. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  8944. for (const name of sortedExports) {
  8945. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  8946. const exportedVariable = this.context.traceExport(name);
  8947. if (exportedVariable) {
  8948. memberVariables[name] = exportedVariable;
  8949. }
  8950. }
  8951. }
  8952. return (this.memberVariables = memberVariables);
  8953. }
  8954. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8955. const { type } = interaction;
  8956. if (path.length === 0) {
  8957. // This can only be a call anyway
  8958. return true;
  8959. }
  8960. if (path.length === 1 && type !== INTERACTION_CALLED) {
  8961. return type === INTERACTION_ASSIGNED;
  8962. }
  8963. const key = path[0];
  8964. if (typeof key !== 'string') {
  8965. return true;
  8966. }
  8967. const memberVariable = this.getMemberVariables()[key];
  8968. return (!memberVariable ||
  8969. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  8970. }
  8971. includePath(path, context) {
  8972. super.includePath(path, context);
  8973. this.context.includeAllExports();
  8974. }
  8975. prepare(accessedGlobalsByScope) {
  8976. if (this.mergedNamespaces.length > 0) {
  8977. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  8978. }
  8979. }
  8980. renderBlock(options) {
  8981. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  8982. const memberVariables = this.getMemberVariables();
  8983. const members = Object.entries(memberVariables)
  8984. .filter(([_, variable]) => variable.included)
  8985. .map(([name, variable]) => {
  8986. if (this.referencedEarly || variable.isReassigned || variable === this) {
  8987. return [
  8988. null,
  8989. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  8990. ];
  8991. }
  8992. return [name, variable.getName(getPropertyAccess)];
  8993. });
  8994. members.unshift([null, `__proto__:${_}null`]);
  8995. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  8996. if (this.mergedNamespaces.length > 0) {
  8997. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  8998. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  8999. }
  9000. else {
  9001. // The helper to merge namespaces will also take care of freezing and toStringTag
  9002. if (symbols) {
  9003. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  9004. }
  9005. if (freeze) {
  9006. output = `/*#__PURE__*/Object.freeze(${output})`;
  9007. }
  9008. }
  9009. const name = this.getName(getPropertyAccess);
  9010. output = `${cnst} ${name}${_}=${_}${output};`;
  9011. if (format === 'system' && exportNamesByVariable.has(this)) {
  9012. output += `${n}${getSystemExportStatement([this], options)};`;
  9013. }
  9014. return output;
  9015. }
  9016. renderFirst() {
  9017. return this.referencedEarly;
  9018. }
  9019. setMergedNamespaces(mergedNamespaces) {
  9020. this.mergedNamespaces = mergedNamespaces;
  9021. const moduleExecIndex = this.context.getModuleExecIndex();
  9022. for (const identifier of this.references) {
  9023. const { context } = identifier.scope;
  9024. if (context.getModuleExecIndex() <= moduleExecIndex) {
  9025. this.referencedEarly = true;
  9026. break;
  9027. }
  9028. }
  9029. }
  9030. }
  9031. NamespaceVariable.prototype.isNamespace = true;
  9032. class SyntheticNamedExportVariable extends Variable {
  9033. constructor(context, name, syntheticNamespace) {
  9034. super(name);
  9035. this.baseVariable = null;
  9036. this.context = context;
  9037. this.module = context.module;
  9038. this.syntheticNamespace = syntheticNamespace;
  9039. }
  9040. getBaseVariable() {
  9041. if (this.baseVariable)
  9042. return this.baseVariable;
  9043. let baseVariable = this.syntheticNamespace;
  9044. while (baseVariable instanceof ExportDefaultVariable ||
  9045. baseVariable instanceof SyntheticNamedExportVariable) {
  9046. if (baseVariable instanceof ExportDefaultVariable) {
  9047. const original = baseVariable.getOriginalVariable();
  9048. if (original === baseVariable)
  9049. break;
  9050. baseVariable = original;
  9051. }
  9052. if (baseVariable instanceof SyntheticNamedExportVariable) {
  9053. baseVariable = baseVariable.syntheticNamespace;
  9054. }
  9055. }
  9056. return (this.baseVariable = baseVariable);
  9057. }
  9058. getBaseVariableName() {
  9059. return this.syntheticNamespace.getBaseVariableName();
  9060. }
  9061. getName(getPropertyAccess) {
  9062. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  9063. }
  9064. includePath(path, context) {
  9065. super.includePath(path, context);
  9066. this.context.includeVariableInModule(this.syntheticNamespace, path, context);
  9067. }
  9068. setRenderNames(baseName, name) {
  9069. super.setRenderNames(baseName, name);
  9070. }
  9071. }
  9072. class ExternalChunk {
  9073. constructor(module, options, inputBase) {
  9074. this.options = options;
  9075. this.inputBase = inputBase;
  9076. this.defaultVariableName = '';
  9077. this.namespaceVariableName = '';
  9078. this.variableName = '';
  9079. this.fileName = null;
  9080. this.importAttributes = null;
  9081. this.id = module.id;
  9082. this.moduleInfo = module.info;
  9083. this.renormalizeRenderPath = module.renormalizeRenderPath;
  9084. this.suggestedVariableName = module.suggestedVariableName;
  9085. }
  9086. getFileName() {
  9087. if (this.fileName) {
  9088. return this.fileName;
  9089. }
  9090. const { paths } = this.options;
  9091. return (this.fileName =
  9092. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  9093. (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
  9094. }
  9095. getImportAttributes(snippets) {
  9096. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  9097. this.options.externalImportAttributes &&
  9098. this.moduleInfo.attributes, snippets));
  9099. }
  9100. getImportPath(importer) {
  9101. return escapeId(this.renormalizeRenderPath
  9102. ? parseAst_js.getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  9103. : this.getFileName());
  9104. }
  9105. }
  9106. function formatAttributes(attributes, { getObject }) {
  9107. if (!attributes) {
  9108. return null;
  9109. }
  9110. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  9111. if (assertionEntries.length > 0) {
  9112. return getObject(assertionEntries, { lineBreakIndent: null });
  9113. }
  9114. return null;
  9115. }
  9116. function removeJsExtension(name) {
  9117. return name.endsWith('.js') ? name.slice(0, -3) : name;
  9118. }
  9119. function getCompleteAmdId(options, chunkId) {
  9120. if (options.autoId) {
  9121. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  9122. }
  9123. return options.id ?? '';
  9124. }
  9125. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  9126. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  9127. if (!namedExportsMode) {
  9128. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  9129. }
  9130. let exportBlock = '';
  9131. if (namedExportsMode) {
  9132. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  9133. if (!reexports) {
  9134. continue;
  9135. }
  9136. for (const specifier of reexports) {
  9137. if (specifier.reexported !== '*') {
  9138. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  9139. if (exportBlock)
  9140. exportBlock += n;
  9141. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  9142. const [left, right] = getDirectReturnFunction([], {
  9143. functionReturn: true,
  9144. lineBreakIndent: null,
  9145. name: null
  9146. });
  9147. exportBlock +=
  9148. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  9149. `${t}enumerable:${_}true,${n}` +
  9150. `${t}get:${_}${left}${importName}${right}${n}});`;
  9151. }
  9152. else if (specifier.reexported === '__proto__') {
  9153. exportBlock +=
  9154. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  9155. `${t}enumerable:${_}true,${n}` +
  9156. `${t}value:${_}${importName}${n}});`;
  9157. }
  9158. else {
  9159. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  9160. }
  9161. }
  9162. }
  9163. }
  9164. }
  9165. for (const { exported, local } of exports) {
  9166. const lhs = `exports${getPropertyAccess(exported)}`;
  9167. const rhs = local;
  9168. if (lhs !== rhs) {
  9169. if (exportBlock)
  9170. exportBlock += n;
  9171. exportBlock +=
  9172. exported === '__proto__'
  9173. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  9174. `${t}enumerable:${_}true,${n}` +
  9175. `${t}value:${_}${rhs}${n}});`
  9176. : `${lhs}${_}=${_}${rhs};`;
  9177. }
  9178. }
  9179. if (namedExportsMode) {
  9180. for (const { name, reexports } of dependencies) {
  9181. if (!reexports) {
  9182. continue;
  9183. }
  9184. for (const specifier of reexports) {
  9185. if (specifier.reexported === '*') {
  9186. if (exportBlock)
  9187. exportBlock += n;
  9188. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  9189. const protoString = "'__proto__'";
  9190. exportBlock +=
  9191. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  9192. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  9193. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  9194. `${t}${t}enumerable:${_}true,${n}` +
  9195. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  9196. `${t}});${n}${n}`;
  9197. }
  9198. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  9199. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  9200. isAsync: false,
  9201. name: null
  9202. })}${copyPropertyIfNecessary});`;
  9203. }
  9204. }
  9205. }
  9206. }
  9207. if (exportBlock) {
  9208. return `${n}${n}${exportBlock}`;
  9209. }
  9210. return '';
  9211. }
  9212. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  9213. if (exports.length > 0) {
  9214. return exports[0].local;
  9215. }
  9216. else {
  9217. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  9218. if (reexports) {
  9219. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  9220. }
  9221. }
  9222. }
  9223. }
  9224. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  9225. if (imported === 'default') {
  9226. if (!isChunk) {
  9227. const moduleInterop = interop(moduleId);
  9228. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  9229. ? defaultVariableName
  9230. : moduleVariableName;
  9231. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  9232. ? `${variableName}${getPropertyAccess('default')}`
  9233. : variableName;
  9234. }
  9235. return depNamedExportsMode
  9236. ? `${moduleVariableName}${getPropertyAccess('default')}`
  9237. : moduleVariableName;
  9238. }
  9239. if (imported === '*') {
  9240. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  9241. ? namespaceVariableName
  9242. : moduleVariableName;
  9243. }
  9244. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  9245. }
  9246. function getEsModuleValue(getObject) {
  9247. return getObject([['value', 'true']], {
  9248. lineBreakIndent: null
  9249. });
  9250. }
  9251. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  9252. if (hasNamedExports) {
  9253. if (addEsModule) {
  9254. if (addNamespaceToStringTag) {
  9255. return `Object.defineProperties(exports,${_}${getObject([
  9256. ['__esModule', getEsModuleValue(getObject)],
  9257. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  9258. ], {
  9259. lineBreakIndent: null
  9260. })});`;
  9261. }
  9262. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  9263. }
  9264. if (addNamespaceToStringTag) {
  9265. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  9266. }
  9267. }
  9268. return '';
  9269. }
  9270. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  9271. if (needsLiveBinding) {
  9272. const [left, right] = getDirectReturnFunction([], {
  9273. functionReturn: true,
  9274. lineBreakIndent: null,
  9275. name: null
  9276. });
  9277. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  9278. `${t}${t}enumerable:${_}true,${n}` +
  9279. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  9280. }
  9281. return `exports[k]${_}=${_}${name}[k]`;
  9282. };
  9283. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  9284. const { _, cnst, n } = snippets;
  9285. const neededInteropHelpers = new Set();
  9286. const interopStatements = [];
  9287. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  9288. neededInteropHelpers.add(helper);
  9289. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  9290. };
  9291. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  9292. if (isChunk) {
  9293. for (const { imported, reexported } of [
  9294. ...(imports || []),
  9295. ...(reexports || [])
  9296. ]) {
  9297. if (imported === '*' && reexported !== '*') {
  9298. if (!namedExportsMode) {
  9299. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  9300. }
  9301. break;
  9302. }
  9303. }
  9304. }
  9305. else {
  9306. const moduleInterop = interop(importPath);
  9307. let hasDefault = false;
  9308. let hasNamespace = false;
  9309. for (const { imported, reexported } of [
  9310. ...(imports || []),
  9311. ...(reexports || [])
  9312. ]) {
  9313. let helper;
  9314. let variableName;
  9315. if (imported === 'default') {
  9316. if (!hasDefault) {
  9317. hasDefault = true;
  9318. if (defaultVariableName !== namespaceVariableName) {
  9319. variableName = defaultVariableName;
  9320. helper = defaultInteropHelpersByInteropType[moduleInterop];
  9321. }
  9322. }
  9323. }
  9324. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  9325. hasNamespace = true;
  9326. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  9327. variableName = namespaceVariableName;
  9328. }
  9329. if (helper) {
  9330. addInteropStatement(variableName, helper, name);
  9331. }
  9332. }
  9333. }
  9334. }
  9335. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  9336. }
  9337. function addJsExtension(name) {
  9338. return name.endsWith('.js') ? name : name + '.js';
  9339. }
  9340. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  9341. // The assumption is that this makes sense for all relative ids:
  9342. // https://requirejs.org/docs/api.html#jsfiles
  9343. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  9344. if (id[0] !== '.') {
  9345. return id;
  9346. }
  9347. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  9348. }
  9349. const builtinModules = [
  9350. "assert",
  9351. "assert/strict",
  9352. "async_hooks",
  9353. "buffer",
  9354. "child_process",
  9355. "cluster",
  9356. "console",
  9357. "constants",
  9358. "crypto",
  9359. "dgram",
  9360. "diagnostics_channel",
  9361. "dns",
  9362. "dns/promises",
  9363. "domain",
  9364. "events",
  9365. "fs",
  9366. "fs/promises",
  9367. "http",
  9368. "http2",
  9369. "https",
  9370. "inspector",
  9371. "inspector/promises",
  9372. "module",
  9373. "net",
  9374. "os",
  9375. "path",
  9376. "path/posix",
  9377. "path/win32",
  9378. "perf_hooks",
  9379. "process",
  9380. "punycode",
  9381. "querystring",
  9382. "readline",
  9383. "readline/promises",
  9384. "repl",
  9385. "stream",
  9386. "stream/consumers",
  9387. "stream/promises",
  9388. "stream/web",
  9389. "string_decoder",
  9390. "timers",
  9391. "timers/promises",
  9392. "tls",
  9393. "trace_events",
  9394. "tty",
  9395. "url",
  9396. "util",
  9397. "util/types",
  9398. "v8",
  9399. "vm",
  9400. "wasi",
  9401. "worker_threads",
  9402. "zlib"
  9403. ];
  9404. const nodeBuiltins = new Set(builtinModules);
  9405. function warnOnBuiltins(log, dependencies) {
  9406. const externalBuiltins = dependencies
  9407. .map(({ importPath }) => importPath)
  9408. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  9409. if (externalBuiltins.length === 0)
  9410. return;
  9411. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNodeBuiltins(externalBuiltins));
  9412. }
  9413. 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 }) {
  9414. warnOnBuiltins(log, dependencies);
  9415. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  9416. const parameters = dependencies.map(m => m.name);
  9417. const { n, getNonArrowFunctionIntro, _ } = snippets;
  9418. if (namedExportsMode && hasExports) {
  9419. parameters.unshift(`exports`);
  9420. deps.unshift(`'exports'`);
  9421. }
  9422. if (accessedGlobals.has('require')) {
  9423. parameters.unshift('require');
  9424. deps.unshift(`'require'`);
  9425. }
  9426. if (accessedGlobals.has('module')) {
  9427. parameters.unshift('module');
  9428. deps.unshift(`'module'`);
  9429. }
  9430. const completeAmdId = getCompleteAmdId(amd, id);
  9431. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  9432. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  9433. const useStrict = strict ? `${_}'use strict';` : '';
  9434. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  9435. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9436. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  9437. if (namespaceMarkers) {
  9438. namespaceMarkers = n + n + namespaceMarkers;
  9439. }
  9440. magicString
  9441. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9442. .indent(t)
  9443. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9444. // cf. https://v8.dev/blog/preparser#pife
  9445. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  9446. isAsync: false,
  9447. name: null
  9448. })}{${useStrict}${n}${n}`)
  9449. .append(`${n}${n}}));`);
  9450. }
  9451. 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 }) {
  9452. const { _, n } = snippets;
  9453. const useStrict = strict ? `'use strict';${n}${n}` : '';
  9454. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  9455. if (namespaceMarkers) {
  9456. namespaceMarkers += n + n;
  9457. }
  9458. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  9459. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  9460. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  9461. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  9462. magicString.append(`${exportBlock}${outro}`);
  9463. }
  9464. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  9465. let importBlock = '';
  9466. let definingVariable = false;
  9467. for (const { importPath, name, reexports, imports } of dependencies) {
  9468. if (!reexports && !imports) {
  9469. if (importBlock) {
  9470. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  9471. }
  9472. definingVariable = false;
  9473. importBlock += `require('${importPath}')`;
  9474. }
  9475. else {
  9476. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  9477. definingVariable = true;
  9478. importBlock += `${name}${_}=${_}require('${importPath}')`;
  9479. }
  9480. }
  9481. if (importBlock) {
  9482. return `${importBlock};${n}${n}`;
  9483. }
  9484. return '';
  9485. }
  9486. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  9487. const { n } = snippets;
  9488. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  9489. if (importBlock.length > 0)
  9490. intro += importBlock.join(n) + n + n;
  9491. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  9492. if (intro)
  9493. magicString.prepend(intro);
  9494. const exportBlock = getExportBlock(exports, snippets);
  9495. if (exportBlock.length > 0)
  9496. magicString.append(n + n + exportBlock.join(n).trim());
  9497. if (outro)
  9498. magicString.append(outro);
  9499. magicString.trim();
  9500. }
  9501. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  9502. const importBlock = [];
  9503. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  9504. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  9505. const pathWithAssertion = `'${importPath}'${assertion};`;
  9506. if (!reexports && !imports) {
  9507. importBlock.push(`import${_}${pathWithAssertion}`);
  9508. continue;
  9509. }
  9510. if (imports) {
  9511. let defaultImport = null;
  9512. let starImport = null;
  9513. const importedNames = [];
  9514. for (const specifier of imports) {
  9515. if (specifier.imported === 'default') {
  9516. defaultImport = specifier;
  9517. }
  9518. else if (specifier.imported === '*') {
  9519. starImport = specifier;
  9520. }
  9521. else {
  9522. importedNames.push(specifier);
  9523. }
  9524. }
  9525. if (starImport) {
  9526. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  9527. }
  9528. if (defaultImport && importedNames.length === 0) {
  9529. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  9530. }
  9531. else if (importedNames.length > 0) {
  9532. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  9533. .map(specifier => specifier.imported === specifier.local
  9534. ? specifier.imported
  9535. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  9536. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  9537. }
  9538. }
  9539. if (reexports) {
  9540. let starExport = null;
  9541. const namespaceReexports = [];
  9542. const namedReexports = [];
  9543. for (const specifier of reexports) {
  9544. if (specifier.reexported === '*') {
  9545. starExport = specifier;
  9546. }
  9547. else if (specifier.imported === '*') {
  9548. namespaceReexports.push(specifier);
  9549. }
  9550. else {
  9551. namedReexports.push(specifier);
  9552. }
  9553. }
  9554. if (starExport) {
  9555. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  9556. }
  9557. if (namespaceReexports.length > 0) {
  9558. if (!imports ||
  9559. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  9560. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  9561. }
  9562. for (const specifier of namespaceReexports) {
  9563. importBlock.push(`export${_}{${_}${name === specifier.reexported
  9564. ? name
  9565. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  9566. }
  9567. }
  9568. if (namedReexports.length > 0) {
  9569. importBlock.push(`export${_}{${_}${namedReexports
  9570. .map(specifier => specifier.imported === specifier.reexported
  9571. ? stringifyIdentifierIfNeeded(specifier.imported)
  9572. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  9573. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  9574. }
  9575. }
  9576. }
  9577. return importBlock;
  9578. }
  9579. function getExportBlock(exports, { _, cnst }) {
  9580. const exportBlock = [];
  9581. const exportDeclaration = new Array(exports.length);
  9582. let index = 0;
  9583. for (const specifier of exports) {
  9584. if (specifier.expression) {
  9585. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  9586. }
  9587. exportDeclaration[index++] =
  9588. specifier.exported === specifier.local
  9589. ? specifier.local
  9590. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  9591. }
  9592. if (exportDeclaration.length > 0) {
  9593. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  9594. }
  9595. return exportBlock;
  9596. }
  9597. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  9598. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  9599. const parts = name.split('.');
  9600. // Check if the key exists in the object's prototype.
  9601. const isReserved = parts[0] in Object.prototype;
  9602. if (log && isReserved) {
  9603. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  9604. }
  9605. parts[0] =
  9606. (typeof globals === 'function'
  9607. ? globals(parts[0])
  9608. : isReserved
  9609. ? parts[0]
  9610. : globals[parts[0]]) || parts[0];
  9611. parts.pop();
  9612. let propertyPath = root;
  9613. return (parts
  9614. .map(part => {
  9615. propertyPath += getPropertyAccess(part);
  9616. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  9617. })
  9618. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  9619. }
  9620. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  9621. const parts = deepName.split('.');
  9622. // Check if the key exists in the object's prototype.
  9623. const isReserved = parts[0] in Object.prototype;
  9624. if (log && isReserved) {
  9625. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  9626. }
  9627. parts[0] =
  9628. (typeof globals === 'function'
  9629. ? globals(parts[0])
  9630. : isReserved
  9631. ? parts[0]
  9632. : globals[parts[0]]) || parts[0];
  9633. const last = parts.pop();
  9634. let propertyPath = root;
  9635. let deepAssignment = [
  9636. ...parts.map(part => {
  9637. propertyPath += getPropertyAccess(part);
  9638. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  9639. }),
  9640. `${propertyPath}${getPropertyAccess(last)}`
  9641. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  9642. if (parts.length > 0) {
  9643. deepAssignment = `(${deepAssignment})`;
  9644. }
  9645. return deepAssignment;
  9646. }
  9647. function trimEmptyImports(dependencies) {
  9648. let index = dependencies.length;
  9649. while (index--) {
  9650. const { imports, reexports } = dependencies[index];
  9651. if (imports || reexports) {
  9652. return dependencies.slice(0, index + 1);
  9653. }
  9654. }
  9655. return [];
  9656. }
  9657. 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 }) {
  9658. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  9659. const isNamespaced = name && name.includes('.');
  9660. const useVariableAssignment = !extend && !isNamespaced;
  9661. if (name && useVariableAssignment && !isLegal(name)) {
  9662. return parseAst_js.error(parseAst_js.logIllegalIdentifierAsName(name));
  9663. }
  9664. warnOnBuiltins(log, dependencies);
  9665. const external = trimEmptyImports(dependencies);
  9666. const deps = external.map(dep => dep.globalName || 'null');
  9667. const parameters = external.map(m => m.name);
  9668. if (hasExports && !name) {
  9669. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNameOptionForIifeExport());
  9670. }
  9671. if (namedExportsMode && hasExports) {
  9672. if (extend) {
  9673. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  9674. parameters.unshift('exports');
  9675. }
  9676. else {
  9677. deps.unshift('{}');
  9678. parameters.unshift('exports');
  9679. }
  9680. }
  9681. const useStrict = strict ? `${t}'use strict';${n}` : '';
  9682. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  9683. magicString.prepend(`${intro}${interopBlock}`);
  9684. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  9685. isAsync: false,
  9686. name: null
  9687. })}{${n}${useStrict}${n}`;
  9688. if (hasExports) {
  9689. if (name && !(extend && namedExportsMode)) {
  9690. wrapperIntro =
  9691. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  9692. `${_}=${_}${wrapperIntro}`;
  9693. }
  9694. if (isNamespaced) {
  9695. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  9696. }
  9697. }
  9698. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  9699. if (hasExports && !extend && namedExportsMode) {
  9700. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  9701. }
  9702. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9703. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  9704. if (namespaceMarkers) {
  9705. namespaceMarkers = n + n + namespaceMarkers;
  9706. }
  9707. magicString
  9708. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9709. .indent(t)
  9710. .prepend(wrapperIntro)
  9711. .append(wrapperOutro);
  9712. }
  9713. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  9714. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  9715. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  9716. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  9717. const registeredName = name ? `'${name}',${_}` : '';
  9718. const wrapperParameters = accessedGlobals.has('module')
  9719. ? ['exports', 'module']
  9720. : hasExports
  9721. ? ['exports']
  9722. : [];
  9723. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9724. // cf. https://v8.dev/blog/preparser#pife
  9725. let wrapperStart = `System.register(${registeredName}[` +
  9726. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  9727. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  9728. isAsync: false,
  9729. name: null
  9730. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  9731. getStarExcludesBlock(starExcludes, t, snippets) +
  9732. getImportBindingsBlock(importBindings, t, snippets) +
  9733. `${n}${t}return${_}{${setters.length > 0
  9734. ? `${n}${t}${t}setters:${_}[${setters
  9735. .map(setter => setter
  9736. ? `${getFunctionIntro(['module'], {
  9737. isAsync: false,
  9738. name: null
  9739. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  9740. : systemNullSetters
  9741. ? `null`
  9742. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  9743. .join(`,${_}`)}],`
  9744. : ''}${n}`;
  9745. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  9746. isAsync: usesTopLevelAwait,
  9747. name: null
  9748. })}{${n}${n}`;
  9749. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  9750. magicString
  9751. .prepend(intro +
  9752. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  9753. getHoistedExportsBlock(exports, t, snippets))
  9754. .append(`${outro}${n}${n}` +
  9755. getSyntheticExportsBlock(exports, t, snippets) +
  9756. getMissingExportsBlock(exports, t, snippets))
  9757. .indent(`${t}${t}${t}`)
  9758. .append(wrapperEnd)
  9759. .prepend(wrapperStart);
  9760. }
  9761. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  9762. const importBindings = [];
  9763. const setters = [];
  9764. let starExcludes = null;
  9765. for (const { imports, reexports } of dependencies) {
  9766. const setter = [];
  9767. if (imports) {
  9768. for (const specifier of imports) {
  9769. importBindings.push(specifier.local);
  9770. if (specifier.imported === '*') {
  9771. setter.push(`${specifier.local}${_}=${_}module;`);
  9772. }
  9773. else {
  9774. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  9775. }
  9776. }
  9777. }
  9778. if (reexports) {
  9779. const reexportedNames = [];
  9780. let hasStarReexport = false;
  9781. for (const { imported, reexported } of reexports) {
  9782. if (reexported === '*') {
  9783. hasStarReexport = true;
  9784. }
  9785. else {
  9786. reexportedNames.push([
  9787. reexported,
  9788. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  9789. ]);
  9790. }
  9791. }
  9792. if (reexportedNames.length > 1 || hasStarReexport) {
  9793. if (hasStarReexport) {
  9794. if (!starExcludes) {
  9795. starExcludes = getStarExcludes({ dependencies, exports });
  9796. }
  9797. reexportedNames.unshift([null, `__proto__:${_}null`]);
  9798. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  9799. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  9800. }
  9801. else {
  9802. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  9803. setter.push(`exports(${exportMapping});`);
  9804. }
  9805. }
  9806. else {
  9807. const [key, value] = reexportedNames[0];
  9808. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  9809. }
  9810. }
  9811. setters.push(setter.join(`${n}${t}${t}${t}`));
  9812. }
  9813. return { importBindings, setters, starExcludes };
  9814. }
  9815. const getStarExcludes = ({ dependencies, exports }) => {
  9816. const starExcludes = new Set(exports.map(expt => expt.exported));
  9817. starExcludes.add('default');
  9818. for (const { reexports } of dependencies) {
  9819. if (reexports) {
  9820. for (const reexport of reexports) {
  9821. if (reexport.reexported !== '*')
  9822. starExcludes.add(reexport.reexported);
  9823. }
  9824. }
  9825. }
  9826. return starExcludes;
  9827. };
  9828. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  9829. if (starExcludes) {
  9830. const fields = [...starExcludes].map(property => [
  9831. property,
  9832. '1'
  9833. ]);
  9834. fields.unshift([null, `__proto__:${_}null`]);
  9835. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  9836. lineBreakIndent: { base: t, t }
  9837. })};`;
  9838. }
  9839. return '';
  9840. };
  9841. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  9842. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  9843. function getExportsBlock(exports, t, { _, n }) {
  9844. if (exports.length === 0) {
  9845. return '';
  9846. }
  9847. if (exports.length === 1) {
  9848. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  9849. }
  9850. return (`exports({${n}` +
  9851. exports
  9852. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  9853. .join(`,${n}`) +
  9854. `${n}});${n}${n}`);
  9855. }
  9856. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  9857. .filter(expt => expt.expression)
  9858. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  9859. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  9860. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  9861. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  9862. function globalProperty(name, globalVariable, getPropertyAccess) {
  9863. if (!name)
  9864. return 'null';
  9865. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  9866. }
  9867. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  9868. let propertyPath = globalVariable;
  9869. return name
  9870. .split('.')
  9871. .map(part => (propertyPath += getPropertyAccess(part)))
  9872. .join(`${_}&&${_}`);
  9873. }
  9874. 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 }) {
  9875. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  9876. const factoryVariable = compact ? 'f' : 'factory';
  9877. const globalVariable = compact ? 'g' : 'global';
  9878. if (hasExports && !name) {
  9879. return parseAst_js.error(parseAst_js.logMissingNameOptionForUmdExport());
  9880. }
  9881. warnOnBuiltins(log, dependencies);
  9882. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  9883. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  9884. const trimmedImports = trimEmptyImports(dependencies);
  9885. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  9886. const factoryParameters = trimmedImports.map(m => m.name);
  9887. if (namedExportsMode && (hasExports || noConflict)) {
  9888. amdDeps.unshift(`'exports'`);
  9889. cjsDeps.unshift(`exports`);
  9890. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  9891. factoryParameters.unshift('exports');
  9892. }
  9893. const completeAmdId = getCompleteAmdId(amd, id);
  9894. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  9895. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  9896. const define = amd.define;
  9897. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  9898. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  9899. let iifeExport;
  9900. if (noConflict) {
  9901. const noConflictExportsVariable = compact ? 'e' : 'exports';
  9902. let factory;
  9903. if (!namedExportsMode && hasExports) {
  9904. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  9905. }
  9906. else {
  9907. const module = globalDeps.shift();
  9908. factory =
  9909. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  9910. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  9911. }
  9912. iifeExport =
  9913. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  9914. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  9915. `${t}${t}${factory}${n}` +
  9916. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  9917. isAsync: false,
  9918. name: null
  9919. })}{${_}` +
  9920. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  9921. `${t}})()`;
  9922. }
  9923. else {
  9924. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  9925. if (!namedExportsMode && hasExports) {
  9926. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  9927. }
  9928. }
  9929. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  9930. const wrapperParameters = [factoryVariable];
  9931. if (iifeNeedsGlobal) {
  9932. wrapperParameters.unshift(globalVariable);
  9933. }
  9934. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  9935. const iifeStart = iifeNeedsGlobal
  9936. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  9937. : '';
  9938. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  9939. const cjsIntro = iifeNeedsGlobal
  9940. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  9941. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  9942. : '';
  9943. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  9944. cjsIntro +
  9945. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  9946. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  9947. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9948. // cf. https://v8.dev/blog/preparser#pife
  9949. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  9950. isAsync: false,
  9951. name: null
  9952. })}{${useStrict}${n}`;
  9953. const wrapperOutro = n + n + '}));';
  9954. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  9955. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9956. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  9957. if (namespaceMarkers) {
  9958. namespaceMarkers = n + n + namespaceMarkers;
  9959. }
  9960. magicString
  9961. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9962. .trim()
  9963. .indent(t)
  9964. .append(wrapperOutro)
  9965. .prepend(wrapperIntro);
  9966. }
  9967. const finalisers = { amd, cjs, es, iife, system, umd };
  9968. var utils = {};
  9969. var constants;
  9970. var hasRequiredConstants;
  9971. function requireConstants () {
  9972. if (hasRequiredConstants) return constants;
  9973. hasRequiredConstants = 1;
  9974. const WIN_SLASH = '\\\\/';
  9975. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  9976. /**
  9977. * Posix glob regex
  9978. */
  9979. const DOT_LITERAL = '\\.';
  9980. const PLUS_LITERAL = '\\+';
  9981. const QMARK_LITERAL = '\\?';
  9982. const SLASH_LITERAL = '\\/';
  9983. const ONE_CHAR = '(?=.)';
  9984. const QMARK = '[^/]';
  9985. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  9986. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  9987. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  9988. const NO_DOT = `(?!${DOT_LITERAL})`;
  9989. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  9990. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  9991. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  9992. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  9993. const STAR = `${QMARK}*?`;
  9994. const SEP = '/';
  9995. const POSIX_CHARS = {
  9996. DOT_LITERAL,
  9997. PLUS_LITERAL,
  9998. QMARK_LITERAL,
  9999. SLASH_LITERAL,
  10000. ONE_CHAR,
  10001. QMARK,
  10002. END_ANCHOR,
  10003. DOTS_SLASH,
  10004. NO_DOT,
  10005. NO_DOTS,
  10006. NO_DOT_SLASH,
  10007. NO_DOTS_SLASH,
  10008. QMARK_NO_DOT,
  10009. STAR,
  10010. START_ANCHOR,
  10011. SEP
  10012. };
  10013. /**
  10014. * Windows glob regex
  10015. */
  10016. const WINDOWS_CHARS = {
  10017. ...POSIX_CHARS,
  10018. SLASH_LITERAL: `[${WIN_SLASH}]`,
  10019. QMARK: WIN_NO_SLASH,
  10020. STAR: `${WIN_NO_SLASH}*?`,
  10021. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  10022. NO_DOT: `(?!${DOT_LITERAL})`,
  10023. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  10024. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  10025. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  10026. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  10027. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  10028. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  10029. SEP: '\\'
  10030. };
  10031. /**
  10032. * POSIX Bracket Regex
  10033. */
  10034. const POSIX_REGEX_SOURCE = {
  10035. alnum: 'a-zA-Z0-9',
  10036. alpha: 'a-zA-Z',
  10037. ascii: '\\x00-\\x7F',
  10038. blank: ' \\t',
  10039. cntrl: '\\x00-\\x1F\\x7F',
  10040. digit: '0-9',
  10041. graph: '\\x21-\\x7E',
  10042. lower: 'a-z',
  10043. print: '\\x20-\\x7E ',
  10044. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  10045. space: ' \\t\\r\\n\\v\\f',
  10046. upper: 'A-Z',
  10047. word: 'A-Za-z0-9_',
  10048. xdigit: 'A-Fa-f0-9'
  10049. };
  10050. constants = {
  10051. MAX_LENGTH: 1024 * 64,
  10052. POSIX_REGEX_SOURCE,
  10053. // regular expressions
  10054. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  10055. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  10056. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  10057. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  10058. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  10059. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  10060. // Replace globs with equivalent patterns to reduce parsing time.
  10061. REPLACEMENTS: {
  10062. '***': '*',
  10063. '**/**': '**',
  10064. '**/**/**': '**'
  10065. },
  10066. // Digits
  10067. CHAR_0: 48, /* 0 */
  10068. CHAR_9: 57, /* 9 */
  10069. // Alphabet chars.
  10070. CHAR_UPPERCASE_A: 65, /* A */
  10071. CHAR_LOWERCASE_A: 97, /* a */
  10072. CHAR_UPPERCASE_Z: 90, /* Z */
  10073. CHAR_LOWERCASE_Z: 122, /* z */
  10074. CHAR_LEFT_PARENTHESES: 40, /* ( */
  10075. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  10076. CHAR_ASTERISK: 42, /* * */
  10077. // Non-alphabetic chars.
  10078. CHAR_AMPERSAND: 38, /* & */
  10079. CHAR_AT: 64, /* @ */
  10080. CHAR_BACKWARD_SLASH: 92, /* \ */
  10081. CHAR_CARRIAGE_RETURN: 13, /* \r */
  10082. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  10083. CHAR_COLON: 58, /* : */
  10084. CHAR_COMMA: 44, /* , */
  10085. CHAR_DOT: 46, /* . */
  10086. CHAR_DOUBLE_QUOTE: 34, /* " */
  10087. CHAR_EQUAL: 61, /* = */
  10088. CHAR_EXCLAMATION_MARK: 33, /* ! */
  10089. CHAR_FORM_FEED: 12, /* \f */
  10090. CHAR_FORWARD_SLASH: 47, /* / */
  10091. CHAR_GRAVE_ACCENT: 96, /* ` */
  10092. CHAR_HASH: 35, /* # */
  10093. CHAR_HYPHEN_MINUS: 45, /* - */
  10094. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  10095. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  10096. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  10097. CHAR_LINE_FEED: 10, /* \n */
  10098. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  10099. CHAR_PERCENT: 37, /* % */
  10100. CHAR_PLUS: 43, /* + */
  10101. CHAR_QUESTION_MARK: 63, /* ? */
  10102. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  10103. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  10104. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  10105. CHAR_SEMICOLON: 59, /* ; */
  10106. CHAR_SINGLE_QUOTE: 39, /* ' */
  10107. CHAR_SPACE: 32, /* */
  10108. CHAR_TAB: 9, /* \t */
  10109. CHAR_UNDERSCORE: 95, /* _ */
  10110. CHAR_VERTICAL_LINE: 124, /* | */
  10111. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  10112. /**
  10113. * Create EXTGLOB_CHARS
  10114. */
  10115. extglobChars(chars) {
  10116. return {
  10117. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  10118. '?': { type: 'qmark', open: '(?:', close: ')?' },
  10119. '+': { type: 'plus', open: '(?:', close: ')+' },
  10120. '*': { type: 'star', open: '(?:', close: ')*' },
  10121. '@': { type: 'at', open: '(?:', close: ')' }
  10122. };
  10123. },
  10124. /**
  10125. * Create GLOB_CHARS
  10126. */
  10127. globChars(win32) {
  10128. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  10129. }
  10130. };
  10131. return constants;
  10132. }
  10133. /*global navigator*/
  10134. var hasRequiredUtils;
  10135. function requireUtils () {
  10136. if (hasRequiredUtils) return utils;
  10137. hasRequiredUtils = 1;
  10138. (function (exports) {
  10139. const {
  10140. REGEX_BACKSLASH,
  10141. REGEX_REMOVE_BACKSLASH,
  10142. REGEX_SPECIAL_CHARS,
  10143. REGEX_SPECIAL_CHARS_GLOBAL
  10144. } = /*@__PURE__*/ requireConstants();
  10145. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  10146. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  10147. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  10148. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  10149. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  10150. exports.isWindows = () => {
  10151. if (typeof navigator !== 'undefined' && navigator.platform) {
  10152. const platform = navigator.platform.toLowerCase();
  10153. return platform === 'win32' || platform === 'windows';
  10154. }
  10155. if (typeof process !== 'undefined' && process.platform) {
  10156. return process.platform === 'win32';
  10157. }
  10158. return false;
  10159. };
  10160. exports.removeBackslashes = str => {
  10161. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  10162. return match === '\\' ? '' : match;
  10163. });
  10164. };
  10165. exports.escapeLast = (input, char, lastIdx) => {
  10166. const idx = input.lastIndexOf(char, lastIdx);
  10167. if (idx === -1) return input;
  10168. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  10169. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  10170. };
  10171. exports.removePrefix = (input, state = {}) => {
  10172. let output = input;
  10173. if (output.startsWith('./')) {
  10174. output = output.slice(2);
  10175. state.prefix = './';
  10176. }
  10177. return output;
  10178. };
  10179. exports.wrapOutput = (input, state = {}, options = {}) => {
  10180. const prepend = options.contains ? '' : '^';
  10181. const append = options.contains ? '' : '$';
  10182. let output = `${prepend}(?:${input})${append}`;
  10183. if (state.negated === true) {
  10184. output = `(?:^(?!${output}).*$)`;
  10185. }
  10186. return output;
  10187. };
  10188. exports.basename = (path, { windows } = {}) => {
  10189. const segs = path.split(windows ? /[\\/]/ : '/');
  10190. const last = segs[segs.length - 1];
  10191. if (last === '') {
  10192. return segs[segs.length - 2];
  10193. }
  10194. return last;
  10195. };
  10196. } (utils));
  10197. return utils;
  10198. }
  10199. var scan_1;
  10200. var hasRequiredScan;
  10201. function requireScan () {
  10202. if (hasRequiredScan) return scan_1;
  10203. hasRequiredScan = 1;
  10204. const utils = /*@__PURE__*/ requireUtils();
  10205. const {
  10206. CHAR_ASTERISK, /* * */
  10207. CHAR_AT, /* @ */
  10208. CHAR_BACKWARD_SLASH, /* \ */
  10209. CHAR_COMMA, /* , */
  10210. CHAR_DOT, /* . */
  10211. CHAR_EXCLAMATION_MARK, /* ! */
  10212. CHAR_FORWARD_SLASH, /* / */
  10213. CHAR_LEFT_CURLY_BRACE, /* { */
  10214. CHAR_LEFT_PARENTHESES, /* ( */
  10215. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  10216. CHAR_PLUS, /* + */
  10217. CHAR_QUESTION_MARK, /* ? */
  10218. CHAR_RIGHT_CURLY_BRACE, /* } */
  10219. CHAR_RIGHT_PARENTHESES, /* ) */
  10220. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  10221. } = /*@__PURE__*/ requireConstants();
  10222. const isPathSeparator = code => {
  10223. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  10224. };
  10225. const depth = token => {
  10226. if (token.isPrefix !== true) {
  10227. token.depth = token.isGlobstar ? Infinity : 1;
  10228. }
  10229. };
  10230. /**
  10231. * Quickly scans a glob pattern and returns an object with a handful of
  10232. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  10233. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  10234. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  10235. *
  10236. * ```js
  10237. * const pm = require('picomatch');
  10238. * console.log(pm.scan('foo/bar/*.js'));
  10239. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  10240. * ```
  10241. * @param {String} `str`
  10242. * @param {Object} `options`
  10243. * @return {Object} Returns an object with tokens and regex source string.
  10244. * @api public
  10245. */
  10246. const scan = (input, options) => {
  10247. const opts = options || {};
  10248. const length = input.length - 1;
  10249. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  10250. const slashes = [];
  10251. const tokens = [];
  10252. const parts = [];
  10253. let str = input;
  10254. let index = -1;
  10255. let start = 0;
  10256. let lastIndex = 0;
  10257. let isBrace = false;
  10258. let isBracket = false;
  10259. let isGlob = false;
  10260. let isExtglob = false;
  10261. let isGlobstar = false;
  10262. let braceEscaped = false;
  10263. let backslashes = false;
  10264. let negated = false;
  10265. let negatedExtglob = false;
  10266. let finished = false;
  10267. let braces = 0;
  10268. let prev;
  10269. let code;
  10270. let token = { value: '', depth: 0, isGlob: false };
  10271. const eos = () => index >= length;
  10272. const peek = () => str.charCodeAt(index + 1);
  10273. const advance = () => {
  10274. prev = code;
  10275. return str.charCodeAt(++index);
  10276. };
  10277. while (index < length) {
  10278. code = advance();
  10279. let next;
  10280. if (code === CHAR_BACKWARD_SLASH) {
  10281. backslashes = token.backslashes = true;
  10282. code = advance();
  10283. if (code === CHAR_LEFT_CURLY_BRACE) {
  10284. braceEscaped = true;
  10285. }
  10286. continue;
  10287. }
  10288. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  10289. braces++;
  10290. while (eos() !== true && (code = advance())) {
  10291. if (code === CHAR_BACKWARD_SLASH) {
  10292. backslashes = token.backslashes = true;
  10293. advance();
  10294. continue;
  10295. }
  10296. if (code === CHAR_LEFT_CURLY_BRACE) {
  10297. braces++;
  10298. continue;
  10299. }
  10300. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  10301. isBrace = token.isBrace = true;
  10302. isGlob = token.isGlob = true;
  10303. finished = true;
  10304. if (scanToEnd === true) {
  10305. continue;
  10306. }
  10307. break;
  10308. }
  10309. if (braceEscaped !== true && code === CHAR_COMMA) {
  10310. isBrace = token.isBrace = true;
  10311. isGlob = token.isGlob = true;
  10312. finished = true;
  10313. if (scanToEnd === true) {
  10314. continue;
  10315. }
  10316. break;
  10317. }
  10318. if (code === CHAR_RIGHT_CURLY_BRACE) {
  10319. braces--;
  10320. if (braces === 0) {
  10321. braceEscaped = false;
  10322. isBrace = token.isBrace = true;
  10323. finished = true;
  10324. break;
  10325. }
  10326. }
  10327. }
  10328. if (scanToEnd === true) {
  10329. continue;
  10330. }
  10331. break;
  10332. }
  10333. if (code === CHAR_FORWARD_SLASH) {
  10334. slashes.push(index);
  10335. tokens.push(token);
  10336. token = { value: '', depth: 0, isGlob: false };
  10337. if (finished === true) continue;
  10338. if (prev === CHAR_DOT && index === (start + 1)) {
  10339. start += 2;
  10340. continue;
  10341. }
  10342. lastIndex = index + 1;
  10343. continue;
  10344. }
  10345. if (opts.noext !== true) {
  10346. const isExtglobChar = code === CHAR_PLUS
  10347. || code === CHAR_AT
  10348. || code === CHAR_ASTERISK
  10349. || code === CHAR_QUESTION_MARK
  10350. || code === CHAR_EXCLAMATION_MARK;
  10351. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  10352. isGlob = token.isGlob = true;
  10353. isExtglob = token.isExtglob = true;
  10354. finished = true;
  10355. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  10356. negatedExtglob = true;
  10357. }
  10358. if (scanToEnd === true) {
  10359. while (eos() !== true && (code = advance())) {
  10360. if (code === CHAR_BACKWARD_SLASH) {
  10361. backslashes = token.backslashes = true;
  10362. code = advance();
  10363. continue;
  10364. }
  10365. if (code === CHAR_RIGHT_PARENTHESES) {
  10366. isGlob = token.isGlob = true;
  10367. finished = true;
  10368. break;
  10369. }
  10370. }
  10371. continue;
  10372. }
  10373. break;
  10374. }
  10375. }
  10376. if (code === CHAR_ASTERISK) {
  10377. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  10378. isGlob = token.isGlob = true;
  10379. finished = true;
  10380. if (scanToEnd === true) {
  10381. continue;
  10382. }
  10383. break;
  10384. }
  10385. if (code === CHAR_QUESTION_MARK) {
  10386. isGlob = token.isGlob = true;
  10387. finished = true;
  10388. if (scanToEnd === true) {
  10389. continue;
  10390. }
  10391. break;
  10392. }
  10393. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  10394. while (eos() !== true && (next = advance())) {
  10395. if (next === CHAR_BACKWARD_SLASH) {
  10396. backslashes = token.backslashes = true;
  10397. advance();
  10398. continue;
  10399. }
  10400. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  10401. isBracket = token.isBracket = true;
  10402. isGlob = token.isGlob = true;
  10403. finished = true;
  10404. break;
  10405. }
  10406. }
  10407. if (scanToEnd === true) {
  10408. continue;
  10409. }
  10410. break;
  10411. }
  10412. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  10413. negated = token.negated = true;
  10414. start++;
  10415. continue;
  10416. }
  10417. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  10418. isGlob = token.isGlob = true;
  10419. if (scanToEnd === true) {
  10420. while (eos() !== true && (code = advance())) {
  10421. if (code === CHAR_LEFT_PARENTHESES) {
  10422. backslashes = token.backslashes = true;
  10423. code = advance();
  10424. continue;
  10425. }
  10426. if (code === CHAR_RIGHT_PARENTHESES) {
  10427. finished = true;
  10428. break;
  10429. }
  10430. }
  10431. continue;
  10432. }
  10433. break;
  10434. }
  10435. if (isGlob === true) {
  10436. finished = true;
  10437. if (scanToEnd === true) {
  10438. continue;
  10439. }
  10440. break;
  10441. }
  10442. }
  10443. if (opts.noext === true) {
  10444. isExtglob = false;
  10445. isGlob = false;
  10446. }
  10447. let base = str;
  10448. let prefix = '';
  10449. let glob = '';
  10450. if (start > 0) {
  10451. prefix = str.slice(0, start);
  10452. str = str.slice(start);
  10453. lastIndex -= start;
  10454. }
  10455. if (base && isGlob === true && lastIndex > 0) {
  10456. base = str.slice(0, lastIndex);
  10457. glob = str.slice(lastIndex);
  10458. } else if (isGlob === true) {
  10459. base = '';
  10460. glob = str;
  10461. } else {
  10462. base = str;
  10463. }
  10464. if (base && base !== '' && base !== '/' && base !== str) {
  10465. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  10466. base = base.slice(0, -1);
  10467. }
  10468. }
  10469. if (opts.unescape === true) {
  10470. if (glob) glob = utils.removeBackslashes(glob);
  10471. if (base && backslashes === true) {
  10472. base = utils.removeBackslashes(base);
  10473. }
  10474. }
  10475. const state = {
  10476. prefix,
  10477. input,
  10478. start,
  10479. base,
  10480. glob,
  10481. isBrace,
  10482. isBracket,
  10483. isGlob,
  10484. isExtglob,
  10485. isGlobstar,
  10486. negated,
  10487. negatedExtglob
  10488. };
  10489. if (opts.tokens === true) {
  10490. state.maxDepth = 0;
  10491. if (!isPathSeparator(code)) {
  10492. tokens.push(token);
  10493. }
  10494. state.tokens = tokens;
  10495. }
  10496. if (opts.parts === true || opts.tokens === true) {
  10497. let prevIndex;
  10498. for (let idx = 0; idx < slashes.length; idx++) {
  10499. const n = prevIndex ? prevIndex + 1 : start;
  10500. const i = slashes[idx];
  10501. const value = input.slice(n, i);
  10502. if (opts.tokens) {
  10503. if (idx === 0 && start !== 0) {
  10504. tokens[idx].isPrefix = true;
  10505. tokens[idx].value = prefix;
  10506. } else {
  10507. tokens[idx].value = value;
  10508. }
  10509. depth(tokens[idx]);
  10510. state.maxDepth += tokens[idx].depth;
  10511. }
  10512. if (idx !== 0 || value !== '') {
  10513. parts.push(value);
  10514. }
  10515. prevIndex = i;
  10516. }
  10517. if (prevIndex && prevIndex + 1 < input.length) {
  10518. const value = input.slice(prevIndex + 1);
  10519. parts.push(value);
  10520. if (opts.tokens) {
  10521. tokens[tokens.length - 1].value = value;
  10522. depth(tokens[tokens.length - 1]);
  10523. state.maxDepth += tokens[tokens.length - 1].depth;
  10524. }
  10525. }
  10526. state.slashes = slashes;
  10527. state.parts = parts;
  10528. }
  10529. return state;
  10530. };
  10531. scan_1 = scan;
  10532. return scan_1;
  10533. }
  10534. var parse_1;
  10535. var hasRequiredParse;
  10536. function requireParse () {
  10537. if (hasRequiredParse) return parse_1;
  10538. hasRequiredParse = 1;
  10539. const constants = /*@__PURE__*/ requireConstants();
  10540. const utils = /*@__PURE__*/ requireUtils();
  10541. /**
  10542. * Constants
  10543. */
  10544. const {
  10545. MAX_LENGTH,
  10546. POSIX_REGEX_SOURCE,
  10547. REGEX_NON_SPECIAL_CHARS,
  10548. REGEX_SPECIAL_CHARS_BACKREF,
  10549. REPLACEMENTS
  10550. } = constants;
  10551. /**
  10552. * Helpers
  10553. */
  10554. const expandRange = (args, options) => {
  10555. if (typeof options.expandRange === 'function') {
  10556. return options.expandRange(...args, options);
  10557. }
  10558. args.sort();
  10559. const value = `[${args.join('-')}]`;
  10560. return value;
  10561. };
  10562. /**
  10563. * Create the message for a syntax error
  10564. */
  10565. const syntaxError = (type, char) => {
  10566. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  10567. };
  10568. /**
  10569. * Parse the given input string.
  10570. * @param {String} input
  10571. * @param {Object} options
  10572. * @return {Object}
  10573. */
  10574. const parse = (input, options) => {
  10575. if (typeof input !== 'string') {
  10576. throw new TypeError('Expected a string');
  10577. }
  10578. input = REPLACEMENTS[input] || input;
  10579. const opts = { ...options };
  10580. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10581. let len = input.length;
  10582. if (len > max) {
  10583. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10584. }
  10585. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  10586. const tokens = [bos];
  10587. const capture = opts.capture ? '' : '?:';
  10588. // create constants based on platform, for windows or posix
  10589. const PLATFORM_CHARS = constants.globChars(opts.windows);
  10590. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  10591. const {
  10592. DOT_LITERAL,
  10593. PLUS_LITERAL,
  10594. SLASH_LITERAL,
  10595. ONE_CHAR,
  10596. DOTS_SLASH,
  10597. NO_DOT,
  10598. NO_DOT_SLASH,
  10599. NO_DOTS_SLASH,
  10600. QMARK,
  10601. QMARK_NO_DOT,
  10602. STAR,
  10603. START_ANCHOR
  10604. } = PLATFORM_CHARS;
  10605. const globstar = opts => {
  10606. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  10607. };
  10608. const nodot = opts.dot ? '' : NO_DOT;
  10609. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  10610. let star = opts.bash === true ? globstar(opts) : STAR;
  10611. if (opts.capture) {
  10612. star = `(${star})`;
  10613. }
  10614. // minimatch options support
  10615. if (typeof opts.noext === 'boolean') {
  10616. opts.noextglob = opts.noext;
  10617. }
  10618. const state = {
  10619. input,
  10620. index: -1,
  10621. start: 0,
  10622. dot: opts.dot === true,
  10623. consumed: '',
  10624. output: '',
  10625. prefix: '',
  10626. backtrack: false,
  10627. negated: false,
  10628. brackets: 0,
  10629. braces: 0,
  10630. parens: 0,
  10631. quotes: 0,
  10632. globstar: false,
  10633. tokens
  10634. };
  10635. input = utils.removePrefix(input, state);
  10636. len = input.length;
  10637. const extglobs = [];
  10638. const braces = [];
  10639. const stack = [];
  10640. let prev = bos;
  10641. let value;
  10642. /**
  10643. * Tokenizing helpers
  10644. */
  10645. const eos = () => state.index === len - 1;
  10646. const peek = state.peek = (n = 1) => input[state.index + n];
  10647. const advance = state.advance = () => input[++state.index] || '';
  10648. const remaining = () => input.slice(state.index + 1);
  10649. const consume = (value = '', num = 0) => {
  10650. state.consumed += value;
  10651. state.index += num;
  10652. };
  10653. const append = token => {
  10654. state.output += token.output != null ? token.output : token.value;
  10655. consume(token.value);
  10656. };
  10657. const negate = () => {
  10658. let count = 1;
  10659. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  10660. advance();
  10661. state.start++;
  10662. count++;
  10663. }
  10664. if (count % 2 === 0) {
  10665. return false;
  10666. }
  10667. state.negated = true;
  10668. state.start++;
  10669. return true;
  10670. };
  10671. const increment = type => {
  10672. state[type]++;
  10673. stack.push(type);
  10674. };
  10675. const decrement = type => {
  10676. state[type]--;
  10677. stack.pop();
  10678. };
  10679. /**
  10680. * Push tokens onto the tokens array. This helper speeds up
  10681. * tokenizing by 1) helping us avoid backtracking as much as possible,
  10682. * and 2) helping us avoid creating extra tokens when consecutive
  10683. * characters are plain text. This improves performance and simplifies
  10684. * lookbehinds.
  10685. */
  10686. const push = tok => {
  10687. if (prev.type === 'globstar') {
  10688. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  10689. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  10690. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  10691. state.output = state.output.slice(0, -prev.output.length);
  10692. prev.type = 'star';
  10693. prev.value = '*';
  10694. prev.output = star;
  10695. state.output += prev.output;
  10696. }
  10697. }
  10698. if (extglobs.length && tok.type !== 'paren') {
  10699. extglobs[extglobs.length - 1].inner += tok.value;
  10700. }
  10701. if (tok.value || tok.output) append(tok);
  10702. if (prev && prev.type === 'text' && tok.type === 'text') {
  10703. prev.output = (prev.output || prev.value) + tok.value;
  10704. prev.value += tok.value;
  10705. return;
  10706. }
  10707. tok.prev = prev;
  10708. tokens.push(tok);
  10709. prev = tok;
  10710. };
  10711. const extglobOpen = (type, value) => {
  10712. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  10713. token.prev = prev;
  10714. token.parens = state.parens;
  10715. token.output = state.output;
  10716. const output = (opts.capture ? '(' : '') + token.open;
  10717. increment('parens');
  10718. push({ type, value, output: state.output ? '' : ONE_CHAR });
  10719. push({ type: 'paren', extglob: true, value: advance(), output });
  10720. extglobs.push(token);
  10721. };
  10722. const extglobClose = token => {
  10723. let output = token.close + (opts.capture ? ')' : '');
  10724. let rest;
  10725. if (token.type === 'negate') {
  10726. let extglobStar = star;
  10727. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  10728. extglobStar = globstar(opts);
  10729. }
  10730. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  10731. output = token.close = `)$))${extglobStar}`;
  10732. }
  10733. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  10734. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  10735. // In this case, we need to parse the string and use it in the output of the original pattern.
  10736. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  10737. //
  10738. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  10739. const expression = parse(rest, { ...options, fastpaths: false }).output;
  10740. output = token.close = `)${expression})${extglobStar})`;
  10741. }
  10742. if (token.prev.type === 'bos') {
  10743. state.negatedExtglob = true;
  10744. }
  10745. }
  10746. push({ type: 'paren', extglob: true, value, output });
  10747. decrement('parens');
  10748. };
  10749. /**
  10750. * Fast paths
  10751. */
  10752. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  10753. let backslashes = false;
  10754. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  10755. if (first === '\\') {
  10756. backslashes = true;
  10757. return m;
  10758. }
  10759. if (first === '?') {
  10760. if (esc) {
  10761. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  10762. }
  10763. if (index === 0) {
  10764. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  10765. }
  10766. return QMARK.repeat(chars.length);
  10767. }
  10768. if (first === '.') {
  10769. return DOT_LITERAL.repeat(chars.length);
  10770. }
  10771. if (first === '*') {
  10772. if (esc) {
  10773. return esc + first + (rest ? star : '');
  10774. }
  10775. return star;
  10776. }
  10777. return esc ? m : `\\${m}`;
  10778. });
  10779. if (backslashes === true) {
  10780. if (opts.unescape === true) {
  10781. output = output.replace(/\\/g, '');
  10782. } else {
  10783. output = output.replace(/\\+/g, m => {
  10784. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  10785. });
  10786. }
  10787. }
  10788. if (output === input && opts.contains === true) {
  10789. state.output = input;
  10790. return state;
  10791. }
  10792. state.output = utils.wrapOutput(output, state, options);
  10793. return state;
  10794. }
  10795. /**
  10796. * Tokenize input until we reach end-of-string
  10797. */
  10798. while (!eos()) {
  10799. value = advance();
  10800. if (value === '\u0000') {
  10801. continue;
  10802. }
  10803. /**
  10804. * Escaped characters
  10805. */
  10806. if (value === '\\') {
  10807. const next = peek();
  10808. if (next === '/' && opts.bash !== true) {
  10809. continue;
  10810. }
  10811. if (next === '.' || next === ';') {
  10812. continue;
  10813. }
  10814. if (!next) {
  10815. value += '\\';
  10816. push({ type: 'text', value });
  10817. continue;
  10818. }
  10819. // collapse slashes to reduce potential for exploits
  10820. const match = /^\\+/.exec(remaining());
  10821. let slashes = 0;
  10822. if (match && match[0].length > 2) {
  10823. slashes = match[0].length;
  10824. state.index += slashes;
  10825. if (slashes % 2 !== 0) {
  10826. value += '\\';
  10827. }
  10828. }
  10829. if (opts.unescape === true) {
  10830. value = advance();
  10831. } else {
  10832. value += advance();
  10833. }
  10834. if (state.brackets === 0) {
  10835. push({ type: 'text', value });
  10836. continue;
  10837. }
  10838. }
  10839. /**
  10840. * If we're inside a regex character class, continue
  10841. * until we reach the closing bracket.
  10842. */
  10843. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  10844. if (opts.posix !== false && value === ':') {
  10845. const inner = prev.value.slice(1);
  10846. if (inner.includes('[')) {
  10847. prev.posix = true;
  10848. if (inner.includes(':')) {
  10849. const idx = prev.value.lastIndexOf('[');
  10850. const pre = prev.value.slice(0, idx);
  10851. const rest = prev.value.slice(idx + 2);
  10852. const posix = POSIX_REGEX_SOURCE[rest];
  10853. if (posix) {
  10854. prev.value = pre + posix;
  10855. state.backtrack = true;
  10856. advance();
  10857. if (!bos.output && tokens.indexOf(prev) === 1) {
  10858. bos.output = ONE_CHAR;
  10859. }
  10860. continue;
  10861. }
  10862. }
  10863. }
  10864. }
  10865. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  10866. value = `\\${value}`;
  10867. }
  10868. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  10869. value = `\\${value}`;
  10870. }
  10871. if (opts.posix === true && value === '!' && prev.value === '[') {
  10872. value = '^';
  10873. }
  10874. prev.value += value;
  10875. append({ value });
  10876. continue;
  10877. }
  10878. /**
  10879. * If we're inside a quoted string, continue
  10880. * until we reach the closing double quote.
  10881. */
  10882. if (state.quotes === 1 && value !== '"') {
  10883. value = utils.escapeRegex(value);
  10884. prev.value += value;
  10885. append({ value });
  10886. continue;
  10887. }
  10888. /**
  10889. * Double quotes
  10890. */
  10891. if (value === '"') {
  10892. state.quotes = state.quotes === 1 ? 0 : 1;
  10893. if (opts.keepQuotes === true) {
  10894. push({ type: 'text', value });
  10895. }
  10896. continue;
  10897. }
  10898. /**
  10899. * Parentheses
  10900. */
  10901. if (value === '(') {
  10902. increment('parens');
  10903. push({ type: 'paren', value });
  10904. continue;
  10905. }
  10906. if (value === ')') {
  10907. if (state.parens === 0 && opts.strictBrackets === true) {
  10908. throw new SyntaxError(syntaxError('opening', '('));
  10909. }
  10910. const extglob = extglobs[extglobs.length - 1];
  10911. if (extglob && state.parens === extglob.parens + 1) {
  10912. extglobClose(extglobs.pop());
  10913. continue;
  10914. }
  10915. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  10916. decrement('parens');
  10917. continue;
  10918. }
  10919. /**
  10920. * Square brackets
  10921. */
  10922. if (value === '[') {
  10923. if (opts.nobracket === true || !remaining().includes(']')) {
  10924. if (opts.nobracket !== true && opts.strictBrackets === true) {
  10925. throw new SyntaxError(syntaxError('closing', ']'));
  10926. }
  10927. value = `\\${value}`;
  10928. } else {
  10929. increment('brackets');
  10930. }
  10931. push({ type: 'bracket', value });
  10932. continue;
  10933. }
  10934. if (value === ']') {
  10935. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  10936. push({ type: 'text', value, output: `\\${value}` });
  10937. continue;
  10938. }
  10939. if (state.brackets === 0) {
  10940. if (opts.strictBrackets === true) {
  10941. throw new SyntaxError(syntaxError('opening', '['));
  10942. }
  10943. push({ type: 'text', value, output: `\\${value}` });
  10944. continue;
  10945. }
  10946. decrement('brackets');
  10947. const prevValue = prev.value.slice(1);
  10948. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  10949. value = `/${value}`;
  10950. }
  10951. prev.value += value;
  10952. append({ value });
  10953. // when literal brackets are explicitly disabled
  10954. // assume we should match with a regex character class
  10955. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  10956. continue;
  10957. }
  10958. const escaped = utils.escapeRegex(prev.value);
  10959. state.output = state.output.slice(0, -prev.value.length);
  10960. // when literal brackets are explicitly enabled
  10961. // assume we should escape the brackets to match literal characters
  10962. if (opts.literalBrackets === true) {
  10963. state.output += escaped;
  10964. prev.value = escaped;
  10965. continue;
  10966. }
  10967. // when the user specifies nothing, try to match both
  10968. prev.value = `(${capture}${escaped}|${prev.value})`;
  10969. state.output += prev.value;
  10970. continue;
  10971. }
  10972. /**
  10973. * Braces
  10974. */
  10975. if (value === '{' && opts.nobrace !== true) {
  10976. increment('braces');
  10977. const open = {
  10978. type: 'brace',
  10979. value,
  10980. output: '(',
  10981. outputIndex: state.output.length,
  10982. tokensIndex: state.tokens.length
  10983. };
  10984. braces.push(open);
  10985. push(open);
  10986. continue;
  10987. }
  10988. if (value === '}') {
  10989. const brace = braces[braces.length - 1];
  10990. if (opts.nobrace === true || !brace) {
  10991. push({ type: 'text', value, output: value });
  10992. continue;
  10993. }
  10994. let output = ')';
  10995. if (brace.dots === true) {
  10996. const arr = tokens.slice();
  10997. const range = [];
  10998. for (let i = arr.length - 1; i >= 0; i--) {
  10999. tokens.pop();
  11000. if (arr[i].type === 'brace') {
  11001. break;
  11002. }
  11003. if (arr[i].type !== 'dots') {
  11004. range.unshift(arr[i].value);
  11005. }
  11006. }
  11007. output = expandRange(range, opts);
  11008. state.backtrack = true;
  11009. }
  11010. if (brace.comma !== true && brace.dots !== true) {
  11011. const out = state.output.slice(0, brace.outputIndex);
  11012. const toks = state.tokens.slice(brace.tokensIndex);
  11013. brace.value = brace.output = '\\{';
  11014. value = output = '\\}';
  11015. state.output = out;
  11016. for (const t of toks) {
  11017. state.output += (t.output || t.value);
  11018. }
  11019. }
  11020. push({ type: 'brace', value, output });
  11021. decrement('braces');
  11022. braces.pop();
  11023. continue;
  11024. }
  11025. /**
  11026. * Pipes
  11027. */
  11028. if (value === '|') {
  11029. if (extglobs.length > 0) {
  11030. extglobs[extglobs.length - 1].conditions++;
  11031. }
  11032. push({ type: 'text', value });
  11033. continue;
  11034. }
  11035. /**
  11036. * Commas
  11037. */
  11038. if (value === ',') {
  11039. let output = value;
  11040. const brace = braces[braces.length - 1];
  11041. if (brace && stack[stack.length - 1] === 'braces') {
  11042. brace.comma = true;
  11043. output = '|';
  11044. }
  11045. push({ type: 'comma', value, output });
  11046. continue;
  11047. }
  11048. /**
  11049. * Slashes
  11050. */
  11051. if (value === '/') {
  11052. // if the beginning of the glob is "./", advance the start
  11053. // to the current index, and don't add the "./" characters
  11054. // to the state. This greatly simplifies lookbehinds when
  11055. // checking for BOS characters like "!" and "." (not "./")
  11056. if (prev.type === 'dot' && state.index === state.start + 1) {
  11057. state.start = state.index + 1;
  11058. state.consumed = '';
  11059. state.output = '';
  11060. tokens.pop();
  11061. prev = bos; // reset "prev" to the first token
  11062. continue;
  11063. }
  11064. push({ type: 'slash', value, output: SLASH_LITERAL });
  11065. continue;
  11066. }
  11067. /**
  11068. * Dots
  11069. */
  11070. if (value === '.') {
  11071. if (state.braces > 0 && prev.type === 'dot') {
  11072. if (prev.value === '.') prev.output = DOT_LITERAL;
  11073. const brace = braces[braces.length - 1];
  11074. prev.type = 'dots';
  11075. prev.output += value;
  11076. prev.value += value;
  11077. brace.dots = true;
  11078. continue;
  11079. }
  11080. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  11081. push({ type: 'text', value, output: DOT_LITERAL });
  11082. continue;
  11083. }
  11084. push({ type: 'dot', value, output: DOT_LITERAL });
  11085. continue;
  11086. }
  11087. /**
  11088. * Question marks
  11089. */
  11090. if (value === '?') {
  11091. const isGroup = prev && prev.value === '(';
  11092. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  11093. extglobOpen('qmark', value);
  11094. continue;
  11095. }
  11096. if (prev && prev.type === 'paren') {
  11097. const next = peek();
  11098. let output = value;
  11099. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  11100. output = `\\${value}`;
  11101. }
  11102. push({ type: 'text', value, output });
  11103. continue;
  11104. }
  11105. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  11106. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  11107. continue;
  11108. }
  11109. push({ type: 'qmark', value, output: QMARK });
  11110. continue;
  11111. }
  11112. /**
  11113. * Exclamation
  11114. */
  11115. if (value === '!') {
  11116. if (opts.noextglob !== true && peek() === '(') {
  11117. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  11118. extglobOpen('negate', value);
  11119. continue;
  11120. }
  11121. }
  11122. if (opts.nonegate !== true && state.index === 0) {
  11123. negate();
  11124. continue;
  11125. }
  11126. }
  11127. /**
  11128. * Plus
  11129. */
  11130. if (value === '+') {
  11131. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  11132. extglobOpen('plus', value);
  11133. continue;
  11134. }
  11135. if ((prev && prev.value === '(') || opts.regex === false) {
  11136. push({ type: 'plus', value, output: PLUS_LITERAL });
  11137. continue;
  11138. }
  11139. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  11140. push({ type: 'plus', value });
  11141. continue;
  11142. }
  11143. push({ type: 'plus', value: PLUS_LITERAL });
  11144. continue;
  11145. }
  11146. /**
  11147. * Plain text
  11148. */
  11149. if (value === '@') {
  11150. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  11151. push({ type: 'at', extglob: true, value, output: '' });
  11152. continue;
  11153. }
  11154. push({ type: 'text', value });
  11155. continue;
  11156. }
  11157. /**
  11158. * Plain text
  11159. */
  11160. if (value !== '*') {
  11161. if (value === '$' || value === '^') {
  11162. value = `\\${value}`;
  11163. }
  11164. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  11165. if (match) {
  11166. value += match[0];
  11167. state.index += match[0].length;
  11168. }
  11169. push({ type: 'text', value });
  11170. continue;
  11171. }
  11172. /**
  11173. * Stars
  11174. */
  11175. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  11176. prev.type = 'star';
  11177. prev.star = true;
  11178. prev.value += value;
  11179. prev.output = star;
  11180. state.backtrack = true;
  11181. state.globstar = true;
  11182. consume(value);
  11183. continue;
  11184. }
  11185. let rest = remaining();
  11186. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  11187. extglobOpen('star', value);
  11188. continue;
  11189. }
  11190. if (prev.type === 'star') {
  11191. if (opts.noglobstar === true) {
  11192. consume(value);
  11193. continue;
  11194. }
  11195. const prior = prev.prev;
  11196. const before = prior.prev;
  11197. const isStart = prior.type === 'slash' || prior.type === 'bos';
  11198. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  11199. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  11200. push({ type: 'star', value, output: '' });
  11201. continue;
  11202. }
  11203. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  11204. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  11205. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  11206. push({ type: 'star', value, output: '' });
  11207. continue;
  11208. }
  11209. // strip consecutive `/**/`
  11210. while (rest.slice(0, 3) === '/**') {
  11211. const after = input[state.index + 4];
  11212. if (after && after !== '/') {
  11213. break;
  11214. }
  11215. rest = rest.slice(3);
  11216. consume('/**', 3);
  11217. }
  11218. if (prior.type === 'bos' && eos()) {
  11219. prev.type = 'globstar';
  11220. prev.value += value;
  11221. prev.output = globstar(opts);
  11222. state.output = prev.output;
  11223. state.globstar = true;
  11224. consume(value);
  11225. continue;
  11226. }
  11227. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  11228. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  11229. prior.output = `(?:${prior.output}`;
  11230. prev.type = 'globstar';
  11231. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  11232. prev.value += value;
  11233. state.globstar = true;
  11234. state.output += prior.output + prev.output;
  11235. consume(value);
  11236. continue;
  11237. }
  11238. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  11239. const end = rest[1] !== void 0 ? '|$' : '';
  11240. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  11241. prior.output = `(?:${prior.output}`;
  11242. prev.type = 'globstar';
  11243. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  11244. prev.value += value;
  11245. state.output += prior.output + prev.output;
  11246. state.globstar = true;
  11247. consume(value + advance());
  11248. push({ type: 'slash', value: '/', output: '' });
  11249. continue;
  11250. }
  11251. if (prior.type === 'bos' && rest[0] === '/') {
  11252. prev.type = 'globstar';
  11253. prev.value += value;
  11254. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  11255. state.output = prev.output;
  11256. state.globstar = true;
  11257. consume(value + advance());
  11258. push({ type: 'slash', value: '/', output: '' });
  11259. continue;
  11260. }
  11261. // remove single star from output
  11262. state.output = state.output.slice(0, -prev.output.length);
  11263. // reset previous token to globstar
  11264. prev.type = 'globstar';
  11265. prev.output = globstar(opts);
  11266. prev.value += value;
  11267. // reset output with globstar
  11268. state.output += prev.output;
  11269. state.globstar = true;
  11270. consume(value);
  11271. continue;
  11272. }
  11273. const token = { type: 'star', value, output: star };
  11274. if (opts.bash === true) {
  11275. token.output = '.*?';
  11276. if (prev.type === 'bos' || prev.type === 'slash') {
  11277. token.output = nodot + token.output;
  11278. }
  11279. push(token);
  11280. continue;
  11281. }
  11282. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  11283. token.output = value;
  11284. push(token);
  11285. continue;
  11286. }
  11287. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  11288. if (prev.type === 'dot') {
  11289. state.output += NO_DOT_SLASH;
  11290. prev.output += NO_DOT_SLASH;
  11291. } else if (opts.dot === true) {
  11292. state.output += NO_DOTS_SLASH;
  11293. prev.output += NO_DOTS_SLASH;
  11294. } else {
  11295. state.output += nodot;
  11296. prev.output += nodot;
  11297. }
  11298. if (peek() !== '*') {
  11299. state.output += ONE_CHAR;
  11300. prev.output += ONE_CHAR;
  11301. }
  11302. }
  11303. push(token);
  11304. }
  11305. while (state.brackets > 0) {
  11306. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  11307. state.output = utils.escapeLast(state.output, '[');
  11308. decrement('brackets');
  11309. }
  11310. while (state.parens > 0) {
  11311. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  11312. state.output = utils.escapeLast(state.output, '(');
  11313. decrement('parens');
  11314. }
  11315. while (state.braces > 0) {
  11316. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  11317. state.output = utils.escapeLast(state.output, '{');
  11318. decrement('braces');
  11319. }
  11320. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  11321. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  11322. }
  11323. // rebuild the output if we had to backtrack at any point
  11324. if (state.backtrack === true) {
  11325. state.output = '';
  11326. for (const token of state.tokens) {
  11327. state.output += token.output != null ? token.output : token.value;
  11328. if (token.suffix) {
  11329. state.output += token.suffix;
  11330. }
  11331. }
  11332. }
  11333. return state;
  11334. };
  11335. /**
  11336. * Fast paths for creating regular expressions for common glob patterns.
  11337. * This can significantly speed up processing and has very little downside
  11338. * impact when none of the fast paths match.
  11339. */
  11340. parse.fastpaths = (input, options) => {
  11341. const opts = { ...options };
  11342. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  11343. const len = input.length;
  11344. if (len > max) {
  11345. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  11346. }
  11347. input = REPLACEMENTS[input] || input;
  11348. // create constants based on platform, for windows or posix
  11349. const {
  11350. DOT_LITERAL,
  11351. SLASH_LITERAL,
  11352. ONE_CHAR,
  11353. DOTS_SLASH,
  11354. NO_DOT,
  11355. NO_DOTS,
  11356. NO_DOTS_SLASH,
  11357. STAR,
  11358. START_ANCHOR
  11359. } = constants.globChars(opts.windows);
  11360. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  11361. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  11362. const capture = opts.capture ? '' : '?:';
  11363. const state = { negated: false, prefix: '' };
  11364. let star = opts.bash === true ? '.*?' : STAR;
  11365. if (opts.capture) {
  11366. star = `(${star})`;
  11367. }
  11368. const globstar = opts => {
  11369. if (opts.noglobstar === true) return star;
  11370. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  11371. };
  11372. const create = str => {
  11373. switch (str) {
  11374. case '*':
  11375. return `${nodot}${ONE_CHAR}${star}`;
  11376. case '.*':
  11377. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  11378. case '*.*':
  11379. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  11380. case '*/*':
  11381. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  11382. case '**':
  11383. return nodot + globstar(opts);
  11384. case '**/*':
  11385. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  11386. case '**/*.*':
  11387. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  11388. case '**/.*':
  11389. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  11390. default: {
  11391. const match = /^(.*?)\.(\w+)$/.exec(str);
  11392. if (!match) return;
  11393. const source = create(match[1]);
  11394. if (!source) return;
  11395. return source + DOT_LITERAL + match[2];
  11396. }
  11397. }
  11398. };
  11399. const output = utils.removePrefix(input, state);
  11400. let source = create(output);
  11401. if (source && opts.strictSlashes !== true) {
  11402. source += `${SLASH_LITERAL}?`;
  11403. }
  11404. return source;
  11405. };
  11406. parse_1 = parse;
  11407. return parse_1;
  11408. }
  11409. var picomatch_1$1;
  11410. var hasRequiredPicomatch$1;
  11411. function requirePicomatch$1 () {
  11412. if (hasRequiredPicomatch$1) return picomatch_1$1;
  11413. hasRequiredPicomatch$1 = 1;
  11414. const scan = /*@__PURE__*/ requireScan();
  11415. const parse = /*@__PURE__*/ requireParse();
  11416. const utils = /*@__PURE__*/ requireUtils();
  11417. const constants = /*@__PURE__*/ requireConstants();
  11418. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  11419. /**
  11420. * Creates a matcher function from one or more glob patterns. The
  11421. * returned function takes a string to match as its first argument,
  11422. * and returns true if the string is a match. The returned matcher
  11423. * function also takes a boolean as the second argument that, when true,
  11424. * returns an object with additional information.
  11425. *
  11426. * ```js
  11427. * const picomatch = require('picomatch');
  11428. * // picomatch(glob[, options]);
  11429. *
  11430. * const isMatch = picomatch('*.!(*a)');
  11431. * console.log(isMatch('a.a')); //=> false
  11432. * console.log(isMatch('a.b')); //=> true
  11433. * ```
  11434. * @name picomatch
  11435. * @param {String|Array} `globs` One or more glob patterns.
  11436. * @param {Object=} `options`
  11437. * @return {Function=} Returns a matcher function.
  11438. * @api public
  11439. */
  11440. const picomatch = (glob, options, returnState = false) => {
  11441. if (Array.isArray(glob)) {
  11442. const fns = glob.map(input => picomatch(input, options, returnState));
  11443. const arrayMatcher = str => {
  11444. for (const isMatch of fns) {
  11445. const state = isMatch(str);
  11446. if (state) return state;
  11447. }
  11448. return false;
  11449. };
  11450. return arrayMatcher;
  11451. }
  11452. const isState = isObject(glob) && glob.tokens && glob.input;
  11453. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  11454. throw new TypeError('Expected pattern to be a non-empty string');
  11455. }
  11456. const opts = options || {};
  11457. const posix = opts.windows;
  11458. const regex = isState
  11459. ? picomatch.compileRe(glob, options)
  11460. : picomatch.makeRe(glob, options, false, true);
  11461. const state = regex.state;
  11462. delete regex.state;
  11463. let isIgnored = () => false;
  11464. if (opts.ignore) {
  11465. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  11466. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  11467. }
  11468. const matcher = (input, returnObject = false) => {
  11469. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  11470. const result = { glob, state, regex, posix, input, output, match, isMatch };
  11471. if (typeof opts.onResult === 'function') {
  11472. opts.onResult(result);
  11473. }
  11474. if (isMatch === false) {
  11475. result.isMatch = false;
  11476. return returnObject ? result : false;
  11477. }
  11478. if (isIgnored(input)) {
  11479. if (typeof opts.onIgnore === 'function') {
  11480. opts.onIgnore(result);
  11481. }
  11482. result.isMatch = false;
  11483. return returnObject ? result : false;
  11484. }
  11485. if (typeof opts.onMatch === 'function') {
  11486. opts.onMatch(result);
  11487. }
  11488. return returnObject ? result : true;
  11489. };
  11490. if (returnState) {
  11491. matcher.state = state;
  11492. }
  11493. return matcher;
  11494. };
  11495. /**
  11496. * Test `input` with the given `regex`. This is used by the main
  11497. * `picomatch()` function to test the input string.
  11498. *
  11499. * ```js
  11500. * const picomatch = require('picomatch');
  11501. * // picomatch.test(input, regex[, options]);
  11502. *
  11503. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  11504. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  11505. * ```
  11506. * @param {String} `input` String to test.
  11507. * @param {RegExp} `regex`
  11508. * @return {Object} Returns an object with matching info.
  11509. * @api public
  11510. */
  11511. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  11512. if (typeof input !== 'string') {
  11513. throw new TypeError('Expected input to be a string');
  11514. }
  11515. if (input === '') {
  11516. return { isMatch: false, output: '' };
  11517. }
  11518. const opts = options || {};
  11519. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  11520. let match = input === glob;
  11521. let output = (match && format) ? format(input) : input;
  11522. if (match === false) {
  11523. output = format ? format(input) : input;
  11524. match = output === glob;
  11525. }
  11526. if (match === false || opts.capture === true) {
  11527. if (opts.matchBase === true || opts.basename === true) {
  11528. match = picomatch.matchBase(input, regex, options, posix);
  11529. } else {
  11530. match = regex.exec(output);
  11531. }
  11532. }
  11533. return { isMatch: Boolean(match), match, output };
  11534. };
  11535. /**
  11536. * Match the basename of a filepath.
  11537. *
  11538. * ```js
  11539. * const picomatch = require('picomatch');
  11540. * // picomatch.matchBase(input, glob[, options]);
  11541. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  11542. * ```
  11543. * @param {String} `input` String to test.
  11544. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  11545. * @return {Boolean}
  11546. * @api public
  11547. */
  11548. picomatch.matchBase = (input, glob, options) => {
  11549. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  11550. return regex.test(utils.basename(input));
  11551. };
  11552. /**
  11553. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  11554. *
  11555. * ```js
  11556. * const picomatch = require('picomatch');
  11557. * // picomatch.isMatch(string, patterns[, options]);
  11558. *
  11559. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  11560. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  11561. * ```
  11562. * @param {String|Array} str The string to test.
  11563. * @param {String|Array} patterns One or more glob patterns to use for matching.
  11564. * @param {Object} [options] See available [options](#options).
  11565. * @return {Boolean} Returns true if any patterns match `str`
  11566. * @api public
  11567. */
  11568. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  11569. /**
  11570. * Parse a glob pattern to create the source string for a regular
  11571. * expression.
  11572. *
  11573. * ```js
  11574. * const picomatch = require('picomatch');
  11575. * const result = picomatch.parse(pattern[, options]);
  11576. * ```
  11577. * @param {String} `pattern`
  11578. * @param {Object} `options`
  11579. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  11580. * @api public
  11581. */
  11582. picomatch.parse = (pattern, options) => {
  11583. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  11584. return parse(pattern, { ...options, fastpaths: false });
  11585. };
  11586. /**
  11587. * Scan a glob pattern to separate the pattern into segments.
  11588. *
  11589. * ```js
  11590. * const picomatch = require('picomatch');
  11591. * // picomatch.scan(input[, options]);
  11592. *
  11593. * const result = picomatch.scan('!./foo/*.js');
  11594. * console.log(result);
  11595. * { prefix: '!./',
  11596. * input: '!./foo/*.js',
  11597. * start: 3,
  11598. * base: 'foo',
  11599. * glob: '*.js',
  11600. * isBrace: false,
  11601. * isBracket: false,
  11602. * isGlob: true,
  11603. * isExtglob: false,
  11604. * isGlobstar: false,
  11605. * negated: true }
  11606. * ```
  11607. * @param {String} `input` Glob pattern to scan.
  11608. * @param {Object} `options`
  11609. * @return {Object} Returns an object with
  11610. * @api public
  11611. */
  11612. picomatch.scan = (input, options) => scan(input, options);
  11613. /**
  11614. * Compile a regular expression from the `state` object returned by the
  11615. * [parse()](#parse) method.
  11616. *
  11617. * @param {Object} `state`
  11618. * @param {Object} `options`
  11619. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  11620. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  11621. * @return {RegExp}
  11622. * @api public
  11623. */
  11624. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  11625. if (returnOutput === true) {
  11626. return state.output;
  11627. }
  11628. const opts = options || {};
  11629. const prepend = opts.contains ? '' : '^';
  11630. const append = opts.contains ? '' : '$';
  11631. let source = `${prepend}(?:${state.output})${append}`;
  11632. if (state && state.negated === true) {
  11633. source = `^(?!${source}).*$`;
  11634. }
  11635. const regex = picomatch.toRegex(source, options);
  11636. if (returnState === true) {
  11637. regex.state = state;
  11638. }
  11639. return regex;
  11640. };
  11641. /**
  11642. * Create a regular expression from a parsed glob pattern.
  11643. *
  11644. * ```js
  11645. * const picomatch = require('picomatch');
  11646. * const state = picomatch.parse('*.js');
  11647. * // picomatch.compileRe(state[, options]);
  11648. *
  11649. * console.log(picomatch.compileRe(state));
  11650. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  11651. * ```
  11652. * @param {String} `state` The object returned from the `.parse` method.
  11653. * @param {Object} `options`
  11654. * @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.
  11655. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  11656. * @return {RegExp} Returns a regex created from the given pattern.
  11657. * @api public
  11658. */
  11659. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  11660. if (!input || typeof input !== 'string') {
  11661. throw new TypeError('Expected a non-empty string');
  11662. }
  11663. let parsed = { negated: false, fastpaths: true };
  11664. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  11665. parsed.output = parse.fastpaths(input, options);
  11666. }
  11667. if (!parsed.output) {
  11668. parsed = parse(input, options);
  11669. }
  11670. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  11671. };
  11672. /**
  11673. * Create a regular expression from the given regex source string.
  11674. *
  11675. * ```js
  11676. * const picomatch = require('picomatch');
  11677. * // picomatch.toRegex(source[, options]);
  11678. *
  11679. * const { output } = picomatch.parse('*.js');
  11680. * console.log(picomatch.toRegex(output));
  11681. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  11682. * ```
  11683. * @param {String} `source` Regular expression source string.
  11684. * @param {Object} `options`
  11685. * @return {RegExp}
  11686. * @api public
  11687. */
  11688. picomatch.toRegex = (source, options) => {
  11689. try {
  11690. const opts = options || {};
  11691. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  11692. } catch (err) {
  11693. if (options && options.debug === true) throw err;
  11694. return /$^/;
  11695. }
  11696. };
  11697. /**
  11698. * Picomatch constants.
  11699. * @return {Object}
  11700. */
  11701. picomatch.constants = constants;
  11702. /**
  11703. * Expose "picomatch"
  11704. */
  11705. picomatch_1$1 = picomatch;
  11706. return picomatch_1$1;
  11707. }
  11708. var picomatch_1;
  11709. var hasRequiredPicomatch;
  11710. function requirePicomatch () {
  11711. if (hasRequiredPicomatch) return picomatch_1;
  11712. hasRequiredPicomatch = 1;
  11713. const pico = /*@__PURE__*/ requirePicomatch$1();
  11714. const utils = /*@__PURE__*/ requireUtils();
  11715. function picomatch(glob, options, returnState = false) {
  11716. // default to os.platform()
  11717. if (options && (options.windows === null || options.windows === undefined)) {
  11718. // don't mutate the original options object
  11719. options = { ...options, windows: utils.isWindows() };
  11720. }
  11721. return pico(glob, options, returnState);
  11722. }
  11723. Object.assign(picomatch, pico);
  11724. picomatch_1 = picomatch;
  11725. return picomatch_1;
  11726. }
  11727. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  11728. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  11729. const extractors = {
  11730. ArrayPattern(names, param) {
  11731. for (const element of param.elements) {
  11732. if (element)
  11733. extractors[element.type](names, element);
  11734. }
  11735. },
  11736. AssignmentPattern(names, param) {
  11737. extractors[param.left.type](names, param.left);
  11738. },
  11739. Identifier(names, param) {
  11740. names.push(param.name);
  11741. },
  11742. MemberExpression() { },
  11743. ObjectPattern(names, param) {
  11744. for (const prop of param.properties) {
  11745. // @ts-ignore Typescript reports that this is not a valid type
  11746. if (prop.type === 'RestElement') {
  11747. extractors.RestElement(names, prop);
  11748. }
  11749. else {
  11750. extractors[prop.value.type](names, prop.value);
  11751. }
  11752. }
  11753. },
  11754. RestElement(names, param) {
  11755. extractors[param.argument.type](names, param.argument);
  11756. }
  11757. };
  11758. const extractAssignedNames = function extractAssignedNames(param) {
  11759. const names = [];
  11760. extractors[param.type](names, param);
  11761. return names;
  11762. };
  11763. // Helper since Typescript can't detect readonly arrays with Array.isArray
  11764. function isArray(arg) {
  11765. return Array.isArray(arg);
  11766. }
  11767. function ensureArray(thing) {
  11768. if (isArray(thing))
  11769. return thing;
  11770. if (thing == null)
  11771. return [];
  11772. return [thing];
  11773. }
  11774. const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
  11775. const normalizePath = function normalizePath(filename) {
  11776. return filename.replace(normalizePathRegExp, require$$0.posix.sep);
  11777. };
  11778. function getMatcherString(id, resolutionBase) {
  11779. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
  11780. return normalizePath(id);
  11781. }
  11782. // resolve('') is valid and will default to process.cwd()
  11783. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  11784. // escape all possible (posix + win) path characters that might interfere with regex
  11785. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  11786. // Note that we use posix.join because:
  11787. // 1. the basePath has been normalized to use /
  11788. // 2. the incoming glob (id) matcher, also uses /
  11789. // otherwise Node will force backslash (\) on windows
  11790. return require$$0.posix.join(basePath, normalizePath(id));
  11791. }
  11792. const createFilter = function createFilter(include, exclude, options) {
  11793. const resolutionBase = options && options.resolve;
  11794. const getMatcher = (id) => id instanceof RegExp
  11795. ? id
  11796. : {
  11797. test: (what) => {
  11798. // this refactor is a tad overly verbose but makes for easy debugging
  11799. const pattern = getMatcherString(id, resolutionBase);
  11800. const fn = pm(pattern, { dot: true });
  11801. const result = fn(what);
  11802. return result;
  11803. }
  11804. };
  11805. const includeMatchers = ensureArray(include).map(getMatcher);
  11806. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  11807. if (!includeMatchers.length && !excludeMatchers.length)
  11808. return (id) => typeof id === 'string' && !id.includes('\0');
  11809. return function result(id) {
  11810. if (typeof id !== 'string')
  11811. return false;
  11812. if (id.includes('\0'))
  11813. return false;
  11814. const pathId = normalizePath(id);
  11815. for (let i = 0; i < excludeMatchers.length; ++i) {
  11816. const matcher = excludeMatchers[i];
  11817. if (matcher instanceof RegExp) {
  11818. matcher.lastIndex = 0;
  11819. }
  11820. if (matcher.test(pathId))
  11821. return false;
  11822. }
  11823. for (let i = 0; i < includeMatchers.length; ++i) {
  11824. const matcher = includeMatchers[i];
  11825. if (matcher instanceof RegExp) {
  11826. matcher.lastIndex = 0;
  11827. }
  11828. if (matcher.test(pathId))
  11829. return true;
  11830. }
  11831. return !includeMatchers.length;
  11832. };
  11833. };
  11834. 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';
  11835. 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';
  11836. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  11837. forbiddenIdentifiers.add('');
  11838. class ArrayPattern extends NodeBase {
  11839. addExportedVariables(variables, exportNamesByVariable) {
  11840. for (const element of this.elements) {
  11841. element?.addExportedVariables(variables, exportNamesByVariable);
  11842. }
  11843. }
  11844. declare(kind, destructuredInitPath, init) {
  11845. const variables = [];
  11846. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  11847. for (const element of this.elements) {
  11848. if (element !== null) {
  11849. variables.push(...element.declare(kind, includedPatternPath, init));
  11850. }
  11851. }
  11852. return variables;
  11853. }
  11854. deoptimizeAssignment(destructuredInitPath, init) {
  11855. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  11856. for (const element of this.elements) {
  11857. element?.deoptimizeAssignment(includedPatternPath, init);
  11858. }
  11859. }
  11860. // Patterns can only be deoptimized at the empty path at the moment
  11861. deoptimizePath() {
  11862. for (const element of this.elements) {
  11863. element?.deoptimizePath(EMPTY_PATH);
  11864. }
  11865. }
  11866. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  11867. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  11868. for (const element of this.elements) {
  11869. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  11870. return true;
  11871. }
  11872. }
  11873. return false;
  11874. }
  11875. // Patterns are only checked at the empty path at the moment
  11876. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  11877. for (const element of this.elements) {
  11878. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  11879. return true;
  11880. }
  11881. return false;
  11882. }
  11883. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  11884. let included = false;
  11885. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  11886. for (const element of this.elements) {
  11887. if (element) {
  11888. element.included ||= included;
  11889. included =
  11890. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  11891. }
  11892. }
  11893. if (included) {
  11894. // This is necessary so that if any pattern element is included, all are
  11895. // included for proper deconflicting
  11896. for (const element of this.elements) {
  11897. if (element && !element.included) {
  11898. element.included = true;
  11899. element.includeDestructuredIfNecessary(context, includedPatternPath, init);
  11900. }
  11901. }
  11902. }
  11903. return (this.included ||= included);
  11904. }
  11905. markDeclarationReached() {
  11906. for (const element of this.elements) {
  11907. element?.markDeclarationReached();
  11908. }
  11909. }
  11910. }
  11911. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  11912. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  11913. ? destructuredInitPath
  11914. : [...destructuredInitPath, UnknownInteger];
  11915. class ArrowFunctionExpression extends FunctionBase {
  11916. constructor() {
  11917. super(...arguments);
  11918. this.objectEntity = null;
  11919. }
  11920. get expression() {
  11921. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  11922. }
  11923. set expression(value) {
  11924. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  11925. }
  11926. createScope(parentScope) {
  11927. this.scope = new ReturnValueScope(parentScope, false);
  11928. }
  11929. hasEffects() {
  11930. return false;
  11931. }
  11932. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11933. if (this.annotationNoSideEffects &&
  11934. path.length === 0 &&
  11935. interaction.type === INTERACTION_CALLED) {
  11936. return false;
  11937. }
  11938. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  11939. return true;
  11940. }
  11941. if (interaction.type === INTERACTION_CALLED) {
  11942. const { ignore, brokenFlow } = context;
  11943. context.ignore = {
  11944. breaks: false,
  11945. continues: false,
  11946. labels: new Set(),
  11947. returnYield: true,
  11948. this: false
  11949. };
  11950. if (this.body.hasEffects(context))
  11951. return true;
  11952. context.ignore = ignore;
  11953. context.brokenFlow = brokenFlow;
  11954. }
  11955. return false;
  11956. }
  11957. onlyFunctionCallUsed() {
  11958. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  11959. this.parent.callee === this;
  11960. return isIIFE || super.onlyFunctionCallUsed();
  11961. }
  11962. include(context, includeChildrenRecursively) {
  11963. super.include(context, includeChildrenRecursively);
  11964. for (const parameter of this.params) {
  11965. if (!(parameter instanceof Identifier)) {
  11966. parameter.include(context, includeChildrenRecursively);
  11967. }
  11968. }
  11969. }
  11970. includeNode(context) {
  11971. this.included = true;
  11972. this.body.includePath(UNKNOWN_PATH, context);
  11973. for (const parameter of this.params) {
  11974. if (!(parameter instanceof Identifier)) {
  11975. parameter.includePath(UNKNOWN_PATH, context);
  11976. }
  11977. }
  11978. }
  11979. getObjectEntity() {
  11980. if (this.objectEntity !== null) {
  11981. return this.objectEntity;
  11982. }
  11983. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  11984. }
  11985. }
  11986. class ObjectPattern extends NodeBase {
  11987. addExportedVariables(variables, exportNamesByVariable) {
  11988. for (const property of this.properties) {
  11989. if (property.type === parseAst_js.Property) {
  11990. property.value.addExportedVariables(variables, exportNamesByVariable);
  11991. }
  11992. else {
  11993. property.argument.addExportedVariables(variables, exportNamesByVariable);
  11994. }
  11995. }
  11996. }
  11997. declare(kind, destructuredInitPath, init) {
  11998. const variables = [];
  11999. for (const property of this.properties) {
  12000. variables.push(...property.declare(kind, destructuredInitPath, init));
  12001. }
  12002. return variables;
  12003. }
  12004. deoptimizeAssignment(destructuredInitPath, init) {
  12005. for (const property of this.properties) {
  12006. property.deoptimizeAssignment(destructuredInitPath, init);
  12007. }
  12008. }
  12009. deoptimizePath(path) {
  12010. if (path.length === 0) {
  12011. for (const property of this.properties) {
  12012. property.deoptimizePath(path);
  12013. }
  12014. }
  12015. }
  12016. hasEffectsOnInteractionAtPath(
  12017. // At the moment, this is only triggered for assignment left-hand sides,
  12018. // where the path is empty
  12019. _path, interaction, context) {
  12020. for (const property of this.properties) {
  12021. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  12022. return true;
  12023. }
  12024. return false;
  12025. }
  12026. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12027. for (const property of this.properties) {
  12028. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  12029. return true;
  12030. }
  12031. return false;
  12032. }
  12033. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12034. if (!this.properties.length)
  12035. return false;
  12036. const lastProperty = this.properties.at(-1);
  12037. const lastPropertyIncluded = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12038. const lastPropertyIsRestElement = lastProperty.type === parseAst_js.RestElement;
  12039. let included = lastPropertyIsRestElement ? lastPropertyIncluded : false;
  12040. for (const property of this.properties.slice(0, -1)) {
  12041. if (lastPropertyIsRestElement && lastPropertyIncluded) {
  12042. property.includeNode(context);
  12043. }
  12044. included =
  12045. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  12046. }
  12047. return (this.included ||= included);
  12048. }
  12049. markDeclarationReached() {
  12050. for (const property of this.properties) {
  12051. property.markDeclarationReached();
  12052. }
  12053. }
  12054. render(code, options) {
  12055. if (this.properties.length > 0) {
  12056. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  12057. let lastSeparatorPos = null;
  12058. for (const { node, separator, start, end } of separatedNodes) {
  12059. if (!node.included) {
  12060. treeshakeNode(node, code, start, end);
  12061. continue;
  12062. }
  12063. lastSeparatorPos = separator;
  12064. node.render(code, options);
  12065. }
  12066. if (lastSeparatorPos) {
  12067. code.remove(lastSeparatorPos, this.end - 1);
  12068. }
  12069. }
  12070. }
  12071. }
  12072. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12073. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  12074. class AssignmentExpression extends NodeBase {
  12075. hasEffects(context) {
  12076. const { deoptimized, left, operator, right } = this;
  12077. if (!deoptimized)
  12078. this.applyDeoptimizations();
  12079. // MemberExpressions do not access the property before assignments if the
  12080. // operator is '='.
  12081. return (right.hasEffects(context) ||
  12082. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  12083. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  12084. }
  12085. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12086. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  12087. }
  12088. include(context, includeChildrenRecursively) {
  12089. const { deoptimized, left, right, operator } = this;
  12090. if (!deoptimized)
  12091. this.applyDeoptimizations();
  12092. if (!this.included)
  12093. this.includeNode(context);
  12094. const hasEffectsContext = createHasEffectsContext();
  12095. if (includeChildrenRecursively ||
  12096. operator !== '=' ||
  12097. left.included ||
  12098. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  12099. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  12100. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  12101. }
  12102. right.include(context, includeChildrenRecursively);
  12103. }
  12104. includeNode(context) {
  12105. this.included = true;
  12106. if (!this.deoptimized)
  12107. this.applyDeoptimizations();
  12108. this.right.includePath(UNKNOWN_PATH, context);
  12109. }
  12110. initialise() {
  12111. super.initialise();
  12112. if (this.left instanceof Identifier) {
  12113. const variable = this.scope.variables.get(this.left.name);
  12114. if (variable?.kind === 'const') {
  12115. this.scope.context.error(parseAst_js.logConstVariableReassignError(), this.left.start);
  12116. }
  12117. }
  12118. this.left.setAssignedValue(this.right);
  12119. }
  12120. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12121. const { left, right, start, end, parent } = this;
  12122. if (left.included) {
  12123. left.render(code, options);
  12124. right.render(code, options);
  12125. }
  12126. else {
  12127. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  12128. code.remove(start, inclusionStart);
  12129. if (preventASI) {
  12130. removeLineBreaks(code, inclusionStart, right.start);
  12131. }
  12132. right.render(code, options, {
  12133. renderedParentType: renderedParentType || parent.type,
  12134. renderedSurroundingElement: renderedSurroundingElement || parent.type
  12135. });
  12136. }
  12137. if (options.format === 'system') {
  12138. if (left instanceof Identifier) {
  12139. const variable = left.variable;
  12140. const exportNames = options.exportNamesByVariable.get(variable);
  12141. if (exportNames) {
  12142. if (exportNames.length === 1) {
  12143. renderSystemExportExpression(variable, start, end, code, options);
  12144. }
  12145. else {
  12146. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== parseAst_js.ExpressionStatement, code, options);
  12147. }
  12148. return;
  12149. }
  12150. }
  12151. else {
  12152. const systemPatternExports = [];
  12153. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  12154. if (systemPatternExports.length > 0) {
  12155. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === parseAst_js.ExpressionStatement, code, options);
  12156. return;
  12157. }
  12158. }
  12159. }
  12160. if (left.included &&
  12161. left instanceof ObjectPattern &&
  12162. (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  12163. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression)) {
  12164. code.appendRight(start, '(');
  12165. code.prependLeft(end, ')');
  12166. }
  12167. }
  12168. applyDeoptimizations() {
  12169. this.deoptimized = true;
  12170. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  12171. this.scope.context.requestTreeshakingPass();
  12172. }
  12173. }
  12174. class AssignmentPattern extends NodeBase {
  12175. addExportedVariables(variables, exportNamesByVariable) {
  12176. this.left.addExportedVariables(variables, exportNamesByVariable);
  12177. }
  12178. declare(kind, destructuredInitPath, init) {
  12179. return this.left.declare(kind, destructuredInitPath, init);
  12180. }
  12181. deoptimizeAssignment(destructuredInitPath, init) {
  12182. this.left.deoptimizeAssignment(destructuredInitPath, init);
  12183. }
  12184. deoptimizePath(path) {
  12185. if (path.length === 0) {
  12186. this.left.deoptimizePath(path);
  12187. }
  12188. }
  12189. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12190. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  12191. }
  12192. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  12193. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  12194. }
  12195. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  12196. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  12197. this.included;
  12198. if ((included ||= this.right.shouldBeIncluded(context))) {
  12199. this.right.include(context, false);
  12200. if (!this.left.included) {
  12201. this.left.included = true;
  12202. // Unfortunately, we need to include the left side again now, so that
  12203. // any declared variables are properly included.
  12204. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  12205. }
  12206. }
  12207. return (this.included = included);
  12208. }
  12209. includeNode(context) {
  12210. this.included = true;
  12211. if (!this.deoptimized)
  12212. this.applyDeoptimizations();
  12213. this.right.includePath(UNKNOWN_PATH, context);
  12214. }
  12215. markDeclarationReached() {
  12216. this.left.markDeclarationReached();
  12217. }
  12218. render(code, options, { isShorthandProperty } = parseAst_js.BLANK) {
  12219. this.left.render(code, options, { isShorthandProperty });
  12220. this.right.render(code, options);
  12221. }
  12222. applyDeoptimizations() {
  12223. this.deoptimized = true;
  12224. this.left.deoptimizePath(EMPTY_PATH);
  12225. this.right.deoptimizePath(UNKNOWN_PATH);
  12226. this.scope.context.requestTreeshakingPass();
  12227. }
  12228. }
  12229. class AwaitExpression extends NodeBase {
  12230. hasEffects() {
  12231. if (!this.deoptimized)
  12232. this.applyDeoptimizations();
  12233. return true;
  12234. }
  12235. include(context, includeChildrenRecursively) {
  12236. if (!this.included)
  12237. this.includeNode(context);
  12238. this.argument.include(context, includeChildrenRecursively);
  12239. }
  12240. includeNode(context) {
  12241. this.included = true;
  12242. if (!this.deoptimized)
  12243. this.applyDeoptimizations();
  12244. checkTopLevelAwait: if (!this.scope.context.usesTopLevelAwait) {
  12245. let parent = this.parent;
  12246. do {
  12247. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  12248. break checkTopLevelAwait;
  12249. } while ((parent = parent.parent));
  12250. this.scope.context.usesTopLevelAwait = true;
  12251. }
  12252. // Thenables need to be included
  12253. this.argument.includePath(THEN_PATH, context);
  12254. }
  12255. includePath(path, context) {
  12256. if (!this.deoptimized)
  12257. this.applyDeoptimizations();
  12258. if (!this.included)
  12259. this.includeNode(context);
  12260. this.argument.includePath(path, context);
  12261. }
  12262. }
  12263. const THEN_PATH = ['then'];
  12264. const binaryOperators = {
  12265. '!=': (left, right) => left != right,
  12266. '!==': (left, right) => left !== right,
  12267. '%': (left, right) => left % right,
  12268. '&': (left, right) => left & right,
  12269. '*': (left, right) => left * right,
  12270. // At the moment, "**" will be transpiled to Math.pow
  12271. '**': (left, right) => left ** right,
  12272. '+': (left, right) => left + right,
  12273. '-': (left, right) => left - right,
  12274. '/': (left, right) => left / right,
  12275. '<': (left, right) => left < right,
  12276. '<<': (left, right) => left << right,
  12277. '<=': (left, right) => left <= right,
  12278. '==': (left, right) => left == right,
  12279. '===': (left, right) => left === right,
  12280. '>': (left, right) => left > right,
  12281. '>=': (left, right) => left >= right,
  12282. '>>': (left, right) => left >> right,
  12283. '>>>': (left, right) => left >>> right,
  12284. '^': (left, right) => left ^ right,
  12285. '|': (left, right) => left | right
  12286. // We use the fallback for cases where we return something unknown
  12287. // in: () => UnknownValue,
  12288. // instanceof: () => UnknownValue,
  12289. };
  12290. class BinaryExpression extends NodeBase {
  12291. deoptimizeCache() { }
  12292. getLiteralValueAtPath(path, recursionTracker, origin) {
  12293. if (path.length > 0)
  12294. return UnknownValue;
  12295. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12296. if (typeof leftValue === 'symbol')
  12297. return UnknownValue;
  12298. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  12299. if (typeof rightValue === 'symbol')
  12300. return UnknownValue;
  12301. const operatorFunction = binaryOperators[this.operator];
  12302. if (!operatorFunction)
  12303. return UnknownValue;
  12304. return operatorFunction(leftValue, rightValue);
  12305. }
  12306. hasEffects(context) {
  12307. // support some implicit type coercion runtime errors
  12308. if (this.operator === '+' &&
  12309. this.parent instanceof ExpressionStatement &&
  12310. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  12311. return true;
  12312. }
  12313. return super.hasEffects(context);
  12314. }
  12315. hasEffectsOnInteractionAtPath(path, { type }) {
  12316. return type !== INTERACTION_ACCESSED || path.length > 1;
  12317. }
  12318. includeNode(context) {
  12319. this.included = true;
  12320. if (this.operator === 'in') {
  12321. this.right.includePath(UNKNOWN_PATH, context);
  12322. }
  12323. }
  12324. removeAnnotations(code) {
  12325. this.left.removeAnnotations(code);
  12326. }
  12327. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12328. this.left.render(code, options, { renderedSurroundingElement });
  12329. this.right.render(code, options);
  12330. }
  12331. }
  12332. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12333. class BreakStatement extends NodeBase {
  12334. hasEffects(context) {
  12335. if (this.label) {
  12336. if (!context.ignore.labels.has(this.label.name))
  12337. return true;
  12338. context.includedLabels.add(this.label.name);
  12339. }
  12340. else {
  12341. if (!context.ignore.breaks)
  12342. return true;
  12343. context.hasBreak = true;
  12344. }
  12345. context.brokenFlow = true;
  12346. return false;
  12347. }
  12348. include(context, includeChildrenRecursively) {
  12349. this.included = true;
  12350. if (this.label) {
  12351. this.label.include(context, includeChildrenRecursively);
  12352. context.includedLabels.add(this.label.name);
  12353. }
  12354. else {
  12355. context.hasBreak = true;
  12356. }
  12357. context.brokenFlow = true;
  12358. }
  12359. }
  12360. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12361. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12362. function renderCallArguments(code, options, node) {
  12363. if (node.arguments.length > 0) {
  12364. if (node.arguments[node.arguments.length - 1].included) {
  12365. for (const argument of node.arguments) {
  12366. argument.render(code, options);
  12367. }
  12368. }
  12369. else {
  12370. let lastIncludedIndex = node.arguments.length - 2;
  12371. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  12372. lastIncludedIndex--;
  12373. }
  12374. if (lastIncludedIndex >= 0) {
  12375. for (let index = 0; index <= lastIncludedIndex; index++) {
  12376. node.arguments[index].render(code, options);
  12377. }
  12378. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  12379. }
  12380. else {
  12381. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  12382. }
  12383. }
  12384. }
  12385. }
  12386. class CallExpressionBase extends NodeBase {
  12387. constructor() {
  12388. super(...arguments);
  12389. this.returnExpression = null;
  12390. this.deoptimizableDependentExpressions = [];
  12391. this.expressionsToBeDeoptimized = new Set();
  12392. }
  12393. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12394. const { args } = interaction;
  12395. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  12396. if (isPure)
  12397. return;
  12398. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  12399. if (deoptimizedExpressions.length === 0)
  12400. return;
  12401. if (returnExpression === UNKNOWN_EXPRESSION) {
  12402. for (const expression of deoptimizedExpressions) {
  12403. expression.deoptimizePath(UNKNOWN_PATH);
  12404. }
  12405. }
  12406. else {
  12407. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12408. for (const expression of deoptimizedExpressions) {
  12409. this.expressionsToBeDeoptimized.add(expression);
  12410. }
  12411. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12412. }, null);
  12413. }
  12414. }
  12415. deoptimizeCache() {
  12416. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  12417. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12418. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  12419. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_SET;
  12420. this.deoptimizableDependentExpressions = parseAst_js.EMPTY_ARRAY;
  12421. for (const expression of deoptimizableDependentExpressions) {
  12422. expression.deoptimizeCache();
  12423. }
  12424. for (const expression of expressionsToBeDeoptimized) {
  12425. expression.deoptimizePath(UNKNOWN_PATH);
  12426. }
  12427. }
  12428. }
  12429. deoptimizePath(path) {
  12430. if (path.length === 0 ||
  12431. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  12432. return;
  12433. }
  12434. const [returnExpression] = this.getReturnExpression();
  12435. if (returnExpression !== UNKNOWN_EXPRESSION) {
  12436. returnExpression.deoptimizePath(path);
  12437. }
  12438. }
  12439. getLiteralValueAtPath(path, recursionTracker, origin) {
  12440. const [returnExpression] = this.getReturnExpression(recursionTracker);
  12441. if (returnExpression === UNKNOWN_EXPRESSION) {
  12442. return UnknownValue;
  12443. }
  12444. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12445. this.deoptimizableDependentExpressions.push(origin);
  12446. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  12447. }, UnknownValue);
  12448. }
  12449. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12450. const returnExpression = this.getReturnExpression(recursionTracker);
  12451. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  12452. return returnExpression;
  12453. }
  12454. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  12455. this.deoptimizableDependentExpressions.push(origin);
  12456. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12457. return [expression, isPure || returnExpression[1]];
  12458. }, UNKNOWN_RETURN_EXPRESSION);
  12459. }
  12460. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12461. const { type } = interaction;
  12462. if (type === INTERACTION_CALLED) {
  12463. const { args, withNew } = interaction;
  12464. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  12465. return false;
  12466. }
  12467. }
  12468. else if ((type === INTERACTION_ASSIGNED
  12469. ? context.assigned
  12470. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  12471. return false;
  12472. }
  12473. const [returnExpression, isPure] = this.getReturnExpression();
  12474. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  12475. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  12476. }
  12477. }
  12478. class CallExpression extends CallExpressionBase {
  12479. get optional() {
  12480. return isFlagSet(this.flags, 128 /* Flag.optional */);
  12481. }
  12482. set optional(value) {
  12483. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  12484. }
  12485. bind() {
  12486. super.bind();
  12487. if (this.callee instanceof Identifier) {
  12488. const variable = this.scope.findVariable(this.callee.name);
  12489. if (variable.isNamespace) {
  12490. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(this.callee.name), this.start);
  12491. }
  12492. if (this.callee.name === 'eval') {
  12493. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEval(this.scope.context.module.id), this.start);
  12494. }
  12495. }
  12496. this.interaction = {
  12497. args: [
  12498. this.callee instanceof MemberExpression && !this.callee.variable
  12499. ? this.callee.object
  12500. : null,
  12501. ...this.arguments
  12502. ],
  12503. type: INTERACTION_CALLED,
  12504. withNew: false
  12505. };
  12506. }
  12507. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  12508. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  12509. }
  12510. hasEffects(context) {
  12511. if (!this.deoptimized)
  12512. this.applyDeoptimizations();
  12513. for (const argument of this.arguments) {
  12514. if (argument.hasEffects(context))
  12515. return true;
  12516. }
  12517. if (this.annotationPure) {
  12518. return false;
  12519. }
  12520. return (this.callee.hasEffects(context) ||
  12521. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12522. }
  12523. hasEffectsAsChainElement(context) {
  12524. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  12525. ? this.callee.hasEffectsAsChainElement(context)
  12526. : this.callee.hasEffects(context);
  12527. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  12528. return IS_SKIPPED_CHAIN;
  12529. if (this.optional &&
  12530. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  12531. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  12532. }
  12533. // We only apply deoptimizations lazily once we know we are not skipping
  12534. if (!this.deoptimized)
  12535. this.applyDeoptimizations();
  12536. for (const argument of this.arguments) {
  12537. if (argument.hasEffects(context))
  12538. return true;
  12539. }
  12540. return (!this.annotationPure &&
  12541. (calleeHasEffects ||
  12542. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  12543. }
  12544. include(context, includeChildrenRecursively) {
  12545. if (!this.included)
  12546. this.includeNode(context);
  12547. if (includeChildrenRecursively) {
  12548. super.include(context, true);
  12549. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  12550. this.callee instanceof Identifier &&
  12551. this.callee.variable) {
  12552. this.callee.variable.markCalledFromTryStatement();
  12553. }
  12554. }
  12555. else {
  12556. this.callee.include(context, false);
  12557. this.callee.includeCallArguments(this.interaction, context);
  12558. }
  12559. }
  12560. includeNode(context) {
  12561. this.included = true;
  12562. if (!this.deoptimized)
  12563. this.applyDeoptimizations();
  12564. this.callee.includePath(UNKNOWN_PATH, context);
  12565. }
  12566. initialise() {
  12567. super.initialise();
  12568. if (this.annotations &&
  12569. this.scope.context.options.treeshake.annotations) {
  12570. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  12571. }
  12572. }
  12573. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12574. this.callee.render(code, options, {
  12575. isCalleeOfRenderedParent: true,
  12576. renderedSurroundingElement
  12577. });
  12578. renderCallArguments(code, options, this);
  12579. }
  12580. applyDeoptimizations() {
  12581. this.deoptimized = true;
  12582. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12583. this.scope.context.requestTreeshakingPass();
  12584. }
  12585. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  12586. if (this.returnExpression === null) {
  12587. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12588. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  12589. }
  12590. return this.returnExpression;
  12591. }
  12592. }
  12593. class CatchClause extends NodeBase {
  12594. createScope(parentScope) {
  12595. this.scope = new ParameterScope(parentScope, true);
  12596. }
  12597. parseNode(esTreeNode) {
  12598. const { body, param, type } = esTreeNode;
  12599. this.type = type;
  12600. if (param) {
  12601. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  12602. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  12603. }
  12604. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  12605. return super.parseNode(esTreeNode);
  12606. }
  12607. }
  12608. CatchClause.prototype.preventChildBlockScope = true;
  12609. CatchClause.prototype.includeNode = onlyIncludeSelf;
  12610. class ChainExpression extends NodeBase {
  12611. // deoptimizations are not relevant as we are not caching values
  12612. deoptimizeCache() { }
  12613. getLiteralValueAtPath(path, recursionTracker, origin) {
  12614. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  12615. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  12616. }
  12617. hasEffects(context) {
  12618. return this.expression.hasEffectsAsChainElement(context) === true;
  12619. }
  12620. includePath(path, context) {
  12621. this.included = true;
  12622. this.expression.includePath(path, context);
  12623. }
  12624. removeAnnotations(code) {
  12625. this.expression.removeAnnotations(code);
  12626. }
  12627. }
  12628. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12629. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12630. class ClassBodyScope extends ChildScope {
  12631. constructor(parent, classNode) {
  12632. const { context } = parent;
  12633. super(parent, context);
  12634. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  12635. this.instanceScope = new ChildScope(this, context);
  12636. this.instanceScope.variables.set('this', new ThisVariable(context));
  12637. }
  12638. findLexicalBoundary() {
  12639. return this;
  12640. }
  12641. }
  12642. class ClassBody extends NodeBase {
  12643. createScope(parentScope) {
  12644. this.scope = new ClassBodyScope(parentScope, this.parent);
  12645. }
  12646. include(context, includeChildrenRecursively) {
  12647. this.included = true;
  12648. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  12649. for (const definition of this.body) {
  12650. definition.include(context, includeChildrenRecursively);
  12651. }
  12652. }
  12653. parseNode(esTreeNode) {
  12654. const body = (this.body = new Array(esTreeNode.body.length));
  12655. let index = 0;
  12656. for (const definition of esTreeNode.body) {
  12657. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  12658. }
  12659. return super.parseNode(esTreeNode);
  12660. }
  12661. }
  12662. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12663. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  12664. class ClassExpression extends ClassNode {
  12665. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12666. super.render(code, options);
  12667. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  12668. code.appendRight(this.start, '(');
  12669. code.prependLeft(this.end, ')');
  12670. }
  12671. }
  12672. }
  12673. function tryCastLiteralValueToBoolean(literalValue) {
  12674. if (typeof literalValue === 'symbol') {
  12675. if (literalValue === UnknownFalsyValue) {
  12676. return false;
  12677. }
  12678. if (literalValue === UnknownTruthyValue) {
  12679. return true;
  12680. }
  12681. return UnknownValue;
  12682. }
  12683. return !!literalValue;
  12684. }
  12685. class MultiExpression extends ExpressionEntity {
  12686. constructor(expressions) {
  12687. super();
  12688. this.expressions = expressions;
  12689. }
  12690. deoptimizePath(path) {
  12691. for (const expression of this.expressions) {
  12692. expression.deoptimizePath(path);
  12693. }
  12694. }
  12695. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12696. return [
  12697. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  12698. false
  12699. ];
  12700. }
  12701. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12702. for (const expression of this.expressions) {
  12703. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  12704. return true;
  12705. }
  12706. return false;
  12707. }
  12708. }
  12709. class ConditionalExpression extends NodeBase {
  12710. constructor() {
  12711. super(...arguments);
  12712. this.expressionsToBeDeoptimized = [];
  12713. this.usedBranch = null;
  12714. }
  12715. get isBranchResolutionAnalysed() {
  12716. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  12717. }
  12718. set isBranchResolutionAnalysed(value) {
  12719. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  12720. }
  12721. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12722. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12723. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12724. }
  12725. deoptimizeCache() {
  12726. if (this.usedBranch !== null) {
  12727. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  12728. this.usedBranch = null;
  12729. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12730. if (this.included) {
  12731. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  12732. }
  12733. const { expressionsToBeDeoptimized } = this;
  12734. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  12735. for (const expression of expressionsToBeDeoptimized) {
  12736. expression.deoptimizeCache();
  12737. }
  12738. }
  12739. }
  12740. deoptimizePath(path) {
  12741. const usedBranch = this.getUsedBranch();
  12742. if (usedBranch) {
  12743. usedBranch.deoptimizePath(path);
  12744. }
  12745. else {
  12746. this.consequent.deoptimizePath(path);
  12747. this.alternate.deoptimizePath(path);
  12748. }
  12749. }
  12750. getLiteralValueAtPath(path, recursionTracker, origin) {
  12751. const usedBranch = this.getUsedBranch();
  12752. if (!usedBranch)
  12753. return UnknownValue;
  12754. this.expressionsToBeDeoptimized.push(origin);
  12755. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12756. }
  12757. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12758. const usedBranch = this.getUsedBranch();
  12759. if (!usedBranch)
  12760. return [
  12761. new MultiExpression([
  12762. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  12763. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  12764. ]),
  12765. false
  12766. ];
  12767. this.expressionsToBeDeoptimized.push(origin);
  12768. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12769. }
  12770. hasEffects(context) {
  12771. if (this.test.hasEffects(context))
  12772. return true;
  12773. const usedBranch = this.getUsedBranch();
  12774. if (!usedBranch) {
  12775. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  12776. }
  12777. return usedBranch.hasEffects(context);
  12778. }
  12779. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12780. const usedBranch = this.getUsedBranch();
  12781. if (!usedBranch) {
  12782. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  12783. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  12784. }
  12785. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  12786. }
  12787. include(context, includeChildrenRecursively) {
  12788. this.included = true;
  12789. const usedBranch = this.getUsedBranch();
  12790. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  12791. this.test.include(context, includeChildrenRecursively);
  12792. this.consequent.include(context, includeChildrenRecursively);
  12793. this.alternate.include(context, includeChildrenRecursively);
  12794. }
  12795. else {
  12796. usedBranch.include(context, includeChildrenRecursively);
  12797. }
  12798. }
  12799. includePath(path, context) {
  12800. this.included = true;
  12801. const usedBranch = this.getUsedBranch();
  12802. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  12803. this.consequent.includePath(path, context);
  12804. this.alternate.includePath(path, context);
  12805. }
  12806. else {
  12807. usedBranch.includePath(path, context);
  12808. }
  12809. }
  12810. includeCallArguments(interaction, context) {
  12811. const usedBranch = this.getUsedBranch();
  12812. if (usedBranch) {
  12813. usedBranch.includeCallArguments(interaction, context);
  12814. }
  12815. else {
  12816. this.consequent.includeCallArguments(interaction, context);
  12817. this.alternate.includeCallArguments(interaction, context);
  12818. }
  12819. }
  12820. removeAnnotations(code) {
  12821. this.test.removeAnnotations(code);
  12822. }
  12823. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12824. if (this.test.included) {
  12825. this.test.render(code, options, { renderedSurroundingElement });
  12826. this.consequent.render(code, options);
  12827. this.alternate.render(code, options);
  12828. }
  12829. else {
  12830. const usedBranch = this.getUsedBranch();
  12831. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  12832. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  12833. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  12834. : colonPos) + 1);
  12835. if (preventASI) {
  12836. removeLineBreaks(code, inclusionStart, usedBranch.start);
  12837. }
  12838. code.remove(this.start, inclusionStart);
  12839. if (this.consequent.included) {
  12840. code.remove(colonPos, this.end);
  12841. }
  12842. this.test.removeAnnotations(code);
  12843. usedBranch.render(code, options, {
  12844. isCalleeOfRenderedParent,
  12845. preventASI: true,
  12846. renderedParentType: renderedParentType || this.parent.type,
  12847. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12848. });
  12849. }
  12850. }
  12851. getUsedBranch() {
  12852. if (this.isBranchResolutionAnalysed) {
  12853. return this.usedBranch;
  12854. }
  12855. this.isBranchResolutionAnalysed = true;
  12856. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  12857. return typeof testValue === 'symbol'
  12858. ? null
  12859. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  12860. }
  12861. }
  12862. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12863. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12864. class ContinueStatement extends NodeBase {
  12865. hasEffects(context) {
  12866. if (this.label) {
  12867. if (!context.ignore.labels.has(this.label.name))
  12868. return true;
  12869. context.includedLabels.add(this.label.name);
  12870. }
  12871. else {
  12872. if (!context.ignore.continues)
  12873. return true;
  12874. context.hasContinue = true;
  12875. }
  12876. context.brokenFlow = true;
  12877. return false;
  12878. }
  12879. include(context, includeChildrenRecursively) {
  12880. this.included = true;
  12881. if (this.label) {
  12882. this.label.include(context, includeChildrenRecursively);
  12883. context.includedLabels.add(this.label.name);
  12884. }
  12885. else {
  12886. context.hasContinue = true;
  12887. }
  12888. context.brokenFlow = true;
  12889. }
  12890. }
  12891. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12892. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12893. class DebuggerStatement extends NodeBase {
  12894. hasEffects() {
  12895. return true;
  12896. }
  12897. }
  12898. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  12899. class Decorator extends NodeBase {
  12900. hasEffects(context) {
  12901. return (this.expression.hasEffects(context) ||
  12902. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  12903. }
  12904. }
  12905. Decorator.prototype.includeNode = onlyIncludeSelf;
  12906. function hasLoopBodyEffects(context, body) {
  12907. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  12908. const { breaks, continues } = ignore;
  12909. ignore.breaks = true;
  12910. ignore.continues = true;
  12911. context.hasBreak = false;
  12912. context.hasContinue = false;
  12913. if (body.hasEffects(context))
  12914. return true;
  12915. ignore.breaks = breaks;
  12916. ignore.continues = continues;
  12917. context.hasBreak = hasBreak;
  12918. context.hasContinue = hasContinue;
  12919. context.brokenFlow = brokenFlow;
  12920. return false;
  12921. }
  12922. function includeLoopBody(context, body, includeChildrenRecursively) {
  12923. const { brokenFlow, hasBreak, hasContinue } = context;
  12924. context.hasBreak = false;
  12925. context.hasContinue = false;
  12926. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  12927. context.hasBreak = hasBreak;
  12928. context.hasContinue = hasContinue;
  12929. context.brokenFlow = brokenFlow;
  12930. }
  12931. class DoWhileStatement extends NodeBase {
  12932. hasEffects(context) {
  12933. if (this.test.hasEffects(context))
  12934. return true;
  12935. return hasLoopBodyEffects(context, this.body);
  12936. }
  12937. include(context, includeChildrenRecursively) {
  12938. this.included = true;
  12939. this.test.include(context, includeChildrenRecursively);
  12940. includeLoopBody(context, this.body, includeChildrenRecursively);
  12941. }
  12942. }
  12943. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12944. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12945. class EmptyStatement extends NodeBase {
  12946. hasEffects() {
  12947. return false;
  12948. }
  12949. }
  12950. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  12951. class ExportAllDeclaration extends NodeBase {
  12952. hasEffects() {
  12953. return false;
  12954. }
  12955. initialise() {
  12956. super.initialise();
  12957. this.scope.context.addExport(this);
  12958. }
  12959. render(code, _options, nodeRenderOptions) {
  12960. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12961. }
  12962. }
  12963. ExportAllDeclaration.prototype.needsBoundaries = true;
  12964. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12965. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12966. class ExportNamedDeclaration extends NodeBase {
  12967. bind() {
  12968. // Do not bind specifiers
  12969. this.declaration?.bind();
  12970. }
  12971. hasEffects(context) {
  12972. return !!this.declaration?.hasEffects(context);
  12973. }
  12974. initialise() {
  12975. super.initialise();
  12976. this.scope.context.addExport(this);
  12977. }
  12978. removeAnnotations(code) {
  12979. this.declaration?.removeAnnotations(code);
  12980. }
  12981. render(code, options, nodeRenderOptions) {
  12982. const { start, end } = nodeRenderOptions;
  12983. if (this.declaration === null) {
  12984. code.remove(start, end);
  12985. }
  12986. else {
  12987. code.remove(this.start, this.declaration.start);
  12988. this.declaration.render(code, options, { end, start });
  12989. }
  12990. }
  12991. }
  12992. ExportNamedDeclaration.prototype.needsBoundaries = true;
  12993. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12994. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12995. class ExportSpecifier extends NodeBase {
  12996. }
  12997. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12998. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12999. class ForInStatement extends NodeBase {
  13000. createScope(parentScope) {
  13001. this.scope = new BlockScope(parentScope);
  13002. }
  13003. hasEffects(context) {
  13004. const { body, deoptimized, left, right } = this;
  13005. if (!deoptimized)
  13006. this.applyDeoptimizations();
  13007. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  13008. return true;
  13009. return hasLoopBodyEffects(context, body);
  13010. }
  13011. include(context, includeChildrenRecursively) {
  13012. const { body, deoptimized, left, right } = this;
  13013. if (!deoptimized)
  13014. this.applyDeoptimizations();
  13015. if (!this.included)
  13016. this.includeNode(context);
  13017. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13018. right.include(context, includeChildrenRecursively);
  13019. includeLoopBody(context, body, includeChildrenRecursively);
  13020. }
  13021. includeNode(context) {
  13022. this.included = true;
  13023. if (!this.deoptimized)
  13024. this.applyDeoptimizations();
  13025. this.right.includePath(UNKNOWN_PATH, context);
  13026. }
  13027. initialise() {
  13028. super.initialise();
  13029. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13030. }
  13031. render(code, options) {
  13032. this.left.render(code, options, NO_SEMICOLON);
  13033. this.right.render(code, options, NO_SEMICOLON);
  13034. // handle no space between "in" and the right side
  13035. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  13036. code.prependLeft(this.right.start, ' ');
  13037. }
  13038. this.body.render(code, options);
  13039. }
  13040. applyDeoptimizations() {
  13041. this.deoptimized = true;
  13042. this.left.deoptimizePath(EMPTY_PATH);
  13043. this.scope.context.requestTreeshakingPass();
  13044. }
  13045. }
  13046. class ForOfStatement extends NodeBase {
  13047. get await() {
  13048. return isFlagSet(this.flags, 131072 /* Flag.await */);
  13049. }
  13050. set await(value) {
  13051. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  13052. }
  13053. createScope(parentScope) {
  13054. this.scope = new BlockScope(parentScope);
  13055. }
  13056. hasEffects() {
  13057. if (!this.deoptimized)
  13058. this.applyDeoptimizations();
  13059. // Placeholder until proper Symbol.Iterator support
  13060. return true;
  13061. }
  13062. include(context, includeChildrenRecursively) {
  13063. const { body, deoptimized, left, right } = this;
  13064. if (!deoptimized)
  13065. this.applyDeoptimizations();
  13066. if (!this.included)
  13067. this.includeNode(context);
  13068. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  13069. right.include(context, includeChildrenRecursively);
  13070. includeLoopBody(context, body, includeChildrenRecursively);
  13071. }
  13072. includeNode(context) {
  13073. this.included = true;
  13074. if (!this.deoptimized)
  13075. this.applyDeoptimizations();
  13076. this.right.includePath(UNKNOWN_PATH, context);
  13077. }
  13078. initialise() {
  13079. super.initialise();
  13080. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  13081. }
  13082. render(code, options) {
  13083. this.left.render(code, options, NO_SEMICOLON);
  13084. this.right.render(code, options, NO_SEMICOLON);
  13085. // handle no space between "of" and the right side
  13086. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  13087. code.prependLeft(this.right.start, ' ');
  13088. }
  13089. this.body.render(code, options);
  13090. }
  13091. applyDeoptimizations() {
  13092. this.deoptimized = true;
  13093. this.left.deoptimizePath(EMPTY_PATH);
  13094. this.right.deoptimizePath(UNKNOWN_PATH);
  13095. this.scope.context.requestTreeshakingPass();
  13096. }
  13097. }
  13098. class ForStatement extends NodeBase {
  13099. createScope(parentScope) {
  13100. this.scope = new BlockScope(parentScope);
  13101. }
  13102. hasEffects(context) {
  13103. if (this.init?.hasEffects(context) ||
  13104. this.test?.hasEffects(context) ||
  13105. this.update?.hasEffects(context)) {
  13106. return true;
  13107. }
  13108. return hasLoopBodyEffects(context, this.body);
  13109. }
  13110. include(context, includeChildrenRecursively) {
  13111. this.included = true;
  13112. this.init?.include(context, includeChildrenRecursively, {
  13113. asSingleStatement: true
  13114. });
  13115. this.test?.include(context, includeChildrenRecursively);
  13116. this.update?.include(context, includeChildrenRecursively);
  13117. includeLoopBody(context, this.body, includeChildrenRecursively);
  13118. }
  13119. render(code, options) {
  13120. this.init?.render(code, options, NO_SEMICOLON);
  13121. this.test?.render(code, options, NO_SEMICOLON);
  13122. this.update?.render(code, options, NO_SEMICOLON);
  13123. this.body.render(code, options);
  13124. }
  13125. }
  13126. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13127. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13128. class FunctionExpression extends FunctionNode {
  13129. createScope(parentScope) {
  13130. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  13131. }
  13132. parseNode(esTreeNode) {
  13133. if (esTreeNode.id !== null) {
  13134. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  13135. }
  13136. return super.parseNode(esTreeNode);
  13137. }
  13138. onlyFunctionCallUsed() {
  13139. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  13140. this.parent.callee === this &&
  13141. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  13142. return isIIFE || super.onlyFunctionCallUsed();
  13143. }
  13144. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13145. super.render(code, options);
  13146. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  13147. code.appendRight(this.start, '(');
  13148. code.prependLeft(this.end, ')');
  13149. }
  13150. }
  13151. }
  13152. class TrackingScope extends BlockScope {
  13153. constructor() {
  13154. super(...arguments);
  13155. this.hoistedDeclarations = [];
  13156. }
  13157. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  13158. this.hoistedDeclarations.push(identifier);
  13159. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  13160. }
  13161. }
  13162. const unset = Symbol('unset');
  13163. class IfStatement extends NodeBase {
  13164. constructor() {
  13165. super(...arguments);
  13166. this.testValue = unset;
  13167. }
  13168. deoptimizeCache() {
  13169. this.testValue = UnknownValue;
  13170. }
  13171. hasEffects(context) {
  13172. if (this.test.hasEffects(context)) {
  13173. return true;
  13174. }
  13175. const testValue = this.getTestValue();
  13176. if (typeof testValue === 'symbol') {
  13177. const { brokenFlow } = context;
  13178. if (this.consequent.hasEffects(context))
  13179. return true;
  13180. const consequentBrokenFlow = context.brokenFlow;
  13181. context.brokenFlow = brokenFlow;
  13182. if (this.alternate === null)
  13183. return false;
  13184. if (this.alternate.hasEffects(context))
  13185. return true;
  13186. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13187. return false;
  13188. }
  13189. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  13190. }
  13191. include(context, includeChildrenRecursively) {
  13192. this.included = true;
  13193. if (includeChildrenRecursively) {
  13194. this.includeRecursively(includeChildrenRecursively, context);
  13195. }
  13196. else {
  13197. const testValue = this.getTestValue();
  13198. if (typeof testValue === 'symbol') {
  13199. this.includeUnknownTest(context);
  13200. }
  13201. else {
  13202. this.includeKnownTest(context, testValue);
  13203. }
  13204. }
  13205. }
  13206. parseNode(esTreeNode) {
  13207. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  13208. if (esTreeNode.alternate) {
  13209. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  13210. }
  13211. return super.parseNode(esTreeNode);
  13212. }
  13213. render(code, options) {
  13214. const { snippets: { getPropertyAccess } } = options;
  13215. // Note that unknown test values are always included
  13216. const testValue = this.getTestValue();
  13217. const hoistedDeclarations = [];
  13218. const includesIfElse = this.test.included;
  13219. const noTreeshake = !this.scope.context.options.treeshake;
  13220. if (includesIfElse) {
  13221. this.test.render(code, options);
  13222. }
  13223. else {
  13224. code.remove(this.start, this.consequent.start);
  13225. }
  13226. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  13227. this.consequent.render(code, options);
  13228. }
  13229. else {
  13230. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  13231. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  13232. }
  13233. if (this.alternate) {
  13234. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  13235. if (includesIfElse) {
  13236. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  13237. code.prependLeft(this.alternate.start, ' ');
  13238. }
  13239. }
  13240. else {
  13241. code.remove(this.consequent.end, this.alternate.start);
  13242. }
  13243. this.alternate.render(code, options);
  13244. }
  13245. else {
  13246. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  13247. code.overwrite(this.alternate.start, this.end, ';');
  13248. }
  13249. else {
  13250. code.remove(this.consequent.end, this.end);
  13251. }
  13252. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  13253. }
  13254. }
  13255. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  13256. }
  13257. getTestValue() {
  13258. if (this.testValue === unset) {
  13259. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  13260. }
  13261. return this.testValue;
  13262. }
  13263. includeKnownTest(context, testValue) {
  13264. if (this.test.shouldBeIncluded(context)) {
  13265. this.test.include(context, false);
  13266. }
  13267. if (testValue && this.consequent.shouldBeIncluded(context)) {
  13268. this.consequent.include(context, false, { asSingleStatement: true });
  13269. }
  13270. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  13271. this.alternate.include(context, false, { asSingleStatement: true });
  13272. }
  13273. }
  13274. includeRecursively(includeChildrenRecursively, context) {
  13275. this.test.include(context, includeChildrenRecursively);
  13276. this.consequent.include(context, includeChildrenRecursively);
  13277. this.alternate?.include(context, includeChildrenRecursively);
  13278. }
  13279. includeUnknownTest(context) {
  13280. this.test.include(context, false);
  13281. const { brokenFlow } = context;
  13282. let consequentBrokenFlow = false;
  13283. if (this.consequent.shouldBeIncluded(context)) {
  13284. this.consequent.include(context, false, { asSingleStatement: true });
  13285. consequentBrokenFlow = context.brokenFlow;
  13286. context.brokenFlow = brokenFlow;
  13287. }
  13288. if (this.alternate?.shouldBeIncluded(context)) {
  13289. this.alternate.include(context, false, { asSingleStatement: true });
  13290. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  13291. }
  13292. }
  13293. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  13294. const hoistedVariables = [
  13295. ...new Set(hoistedDeclarations.map(identifier => {
  13296. const variable = identifier.variable;
  13297. return variable.included ? variable.getName(getPropertyAccess) : '';
  13298. }))
  13299. ]
  13300. .filter(Boolean)
  13301. .join(', ');
  13302. if (hoistedVariables) {
  13303. const parentType = this.parent.type;
  13304. const needsBraces = parentType !== parseAst_js.Program && parentType !== parseAst_js.BlockStatement;
  13305. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  13306. if (needsBraces) {
  13307. code.appendLeft(this.end, ` }`);
  13308. }
  13309. }
  13310. }
  13311. shouldKeepAlternateBranch() {
  13312. let currentParent = this.parent;
  13313. do {
  13314. if (currentParent instanceof IfStatement && currentParent.alternate) {
  13315. return true;
  13316. }
  13317. if (currentParent instanceof BlockStatement) {
  13318. return false;
  13319. }
  13320. currentParent = currentParent.parent;
  13321. } while (currentParent);
  13322. return false;
  13323. }
  13324. }
  13325. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13326. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13327. class ImportAttribute extends NodeBase {
  13328. }
  13329. class ImportDeclaration extends NodeBase {
  13330. // Do not bind specifiers or attributes
  13331. bind() { }
  13332. hasEffects() {
  13333. return false;
  13334. }
  13335. initialise() {
  13336. super.initialise();
  13337. this.scope.context.addImport(this);
  13338. }
  13339. render(code, _options, nodeRenderOptions) {
  13340. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  13341. }
  13342. }
  13343. ImportDeclaration.prototype.needsBoundaries = true;
  13344. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13345. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  13346. class ImportDefaultSpecifier extends NodeBase {
  13347. }
  13348. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13349. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13350. function isReassignedExportsMember(variable, exportNamesByVariable) {
  13351. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  13352. }
  13353. class VariableDeclarator extends NodeBase {
  13354. declareDeclarator(kind, isUsingDeclaration) {
  13355. this.isUsingDeclaration = isUsingDeclaration;
  13356. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  13357. }
  13358. deoptimizePath(path) {
  13359. this.id.deoptimizePath(path);
  13360. }
  13361. hasEffects(context) {
  13362. const initEffect = this.init?.hasEffects(context);
  13363. this.id.markDeclarationReached();
  13364. return (initEffect ||
  13365. this.isUsingDeclaration ||
  13366. this.id.hasEffects(context) ||
  13367. (this.scope.context.options.treeshake
  13368. .propertyReadSideEffects &&
  13369. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  13370. }
  13371. include(context, includeChildrenRecursively) {
  13372. const { id, init } = this;
  13373. if (!this.included)
  13374. this.includeNode();
  13375. init?.include(context, includeChildrenRecursively);
  13376. id.markDeclarationReached();
  13377. if (includeChildrenRecursively) {
  13378. id.include(context, includeChildrenRecursively);
  13379. }
  13380. else {
  13381. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  13382. }
  13383. }
  13384. removeAnnotations(code) {
  13385. this.init?.removeAnnotations(code);
  13386. }
  13387. render(code, options) {
  13388. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  13389. const { end, id, init, start } = this;
  13390. const renderId = id.included || this.isUsingDeclaration;
  13391. if (renderId) {
  13392. id.render(code, options);
  13393. }
  13394. else {
  13395. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  13396. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  13397. }
  13398. if (init) {
  13399. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13400. const renderedVariable = id.variable.getName(getPropertyAccess);
  13401. if (renderedVariable !== id.name) {
  13402. code.appendLeft(init.start + 5, ` ${id.name}`);
  13403. }
  13404. }
  13405. init.render(code, options, renderId ? parseAst_js.BLANK : { renderedSurroundingElement: parseAst_js.ExpressionStatement });
  13406. }
  13407. else if (id instanceof Identifier &&
  13408. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  13409. code.appendLeft(end, `${_}=${_}void 0`);
  13410. }
  13411. }
  13412. includeNode() {
  13413. this.included = true;
  13414. const { id, init } = this;
  13415. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  13416. const { name, variable } = id;
  13417. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  13418. if (accessedVariable !== variable) {
  13419. accessedVariable.forbidName(name);
  13420. }
  13421. }
  13422. }
  13423. }
  13424. }
  13425. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  13426. class ImportExpression extends NodeBase {
  13427. constructor() {
  13428. super(...arguments);
  13429. this.inlineNamespace = null;
  13430. this.hasUnknownAccessedKey = false;
  13431. this.accessedPropKey = new Set();
  13432. this.attributes = null;
  13433. this.mechanism = null;
  13434. this.namespaceExportName = undefined;
  13435. this.resolution = null;
  13436. this.resolutionString = null;
  13437. }
  13438. // Do not bind attributes
  13439. bind() {
  13440. this.source.bind();
  13441. }
  13442. /**
  13443. * Get imported variables for deterministic usage, valid cases are:
  13444. *
  13445. * - `const { foo } = await import('bar')`.
  13446. * - `(await import('bar')).foo`
  13447. * - `import('bar').then(({ foo }) => {})`
  13448. *
  13449. * Returns empty array if it's side-effect only import.
  13450. * Returns undefined if it's not fully deterministic.
  13451. */
  13452. getDeterministicImportedNames() {
  13453. const parent1 = this.parent;
  13454. // Side-effect only: import('bar')
  13455. if (parent1 instanceof ExpressionStatement) {
  13456. return parseAst_js.EMPTY_ARRAY;
  13457. }
  13458. if (parent1 instanceof AwaitExpression) {
  13459. const parent2 = parent1.parent;
  13460. // Side-effect only: await import('bar')
  13461. if (parent2 instanceof ExpressionStatement) {
  13462. return parseAst_js.EMPTY_ARRAY;
  13463. }
  13464. // Case 1: const { foo } / module = await import('bar')
  13465. if (parent2 instanceof VariableDeclarator) {
  13466. const declaration = parent2.id;
  13467. if (declaration instanceof Identifier) {
  13468. return this.hasUnknownAccessedKey ? undefined : [...this.accessedPropKey];
  13469. }
  13470. if (declaration instanceof ObjectPattern) {
  13471. return getDeterministicObjectDestructure(declaration);
  13472. }
  13473. }
  13474. // Case 2: (await import('bar')).foo
  13475. if (parent2 instanceof MemberExpression) {
  13476. const id = parent2.property;
  13477. if (!parent2.computed && id instanceof Identifier) {
  13478. return [id.name];
  13479. }
  13480. }
  13481. return;
  13482. }
  13483. // Case 3: import('bar').then(({ foo }) => {})
  13484. if (parent1 instanceof MemberExpression) {
  13485. const callExpression = parent1.parent;
  13486. const property = parent1.property;
  13487. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  13488. return;
  13489. }
  13490. const memberName = property.name;
  13491. // side-effect only, when only chaining .catch or .finally
  13492. if (callExpression.parent instanceof ExpressionStatement &&
  13493. ['catch', 'finally'].includes(memberName)) {
  13494. return parseAst_js.EMPTY_ARRAY;
  13495. }
  13496. if (memberName !== 'then')
  13497. return;
  13498. // Side-effect only: import('bar').then()
  13499. if (callExpression.arguments.length === 0) {
  13500. return parseAst_js.EMPTY_ARRAY;
  13501. }
  13502. const argument = callExpression.arguments[0];
  13503. if (callExpression.arguments.length !== 1 ||
  13504. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  13505. return;
  13506. }
  13507. // Side-effect only: import('bar').then(() => {})
  13508. if (argument.params.length === 0) {
  13509. return parseAst_js.EMPTY_ARRAY;
  13510. }
  13511. const declaration = argument.params[0];
  13512. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  13513. return getDeterministicObjectDestructure(declaration);
  13514. }
  13515. return;
  13516. }
  13517. }
  13518. hasEffects() {
  13519. return true;
  13520. }
  13521. include(context, includeChildrenRecursively) {
  13522. if (!this.included)
  13523. this.includeNode();
  13524. this.source.include(context, includeChildrenRecursively);
  13525. }
  13526. includeNode() {
  13527. this.included = true;
  13528. this.scope.context.includeDynamicImport(this);
  13529. this.scope.addAccessedDynamicImport(this);
  13530. }
  13531. includePath(path) {
  13532. if (!this.included)
  13533. this.includeNode();
  13534. // Technically, this is not correct as dynamic imports return a Promise.
  13535. if (this.hasUnknownAccessedKey)
  13536. return;
  13537. if (path[0] === UnknownKey) {
  13538. this.hasUnknownAccessedKey = true;
  13539. }
  13540. else if (typeof path[0] === 'string') {
  13541. this.accessedPropKey.add(path[0]);
  13542. }
  13543. // Update included paths
  13544. this.scope.context.includeDynamicImport(this);
  13545. }
  13546. initialise() {
  13547. super.initialise();
  13548. this.scope.context.addDynamicImport(this);
  13549. }
  13550. parseNode(esTreeNode) {
  13551. this.sourceAstNode = esTreeNode.source;
  13552. return super.parseNode(esTreeNode);
  13553. }
  13554. render(code, options) {
  13555. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  13556. if (this.inlineNamespace) {
  13557. const [left, right] = getDirectReturnFunction([], {
  13558. functionReturn: true,
  13559. lineBreakIndent: null,
  13560. name: null
  13561. });
  13562. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  13563. return;
  13564. }
  13565. if (this.mechanism) {
  13566. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  13567. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  13568. }
  13569. if (this.resolutionString) {
  13570. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  13571. if (this.namespaceExportName) {
  13572. const [left, right] = getDirectReturnFunction(['n'], {
  13573. functionReturn: true,
  13574. lineBreakIndent: null,
  13575. name: null
  13576. });
  13577. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  13578. }
  13579. }
  13580. else {
  13581. this.source.render(code, options);
  13582. }
  13583. if (this.attributes !== true) {
  13584. if (this.options) {
  13585. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  13586. }
  13587. if (this.attributes) {
  13588. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  13589. lineBreakIndent: null
  13590. })}`);
  13591. }
  13592. }
  13593. }
  13594. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes) {
  13595. const { format } = options;
  13596. this.inlineNamespace = null;
  13597. this.resolution = resolution;
  13598. this.resolutionString = resolutionString;
  13599. this.namespaceExportName = namespaceExportName;
  13600. this.attributes = attributes;
  13601. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  13602. let helper;
  13603. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  13604. if (helper) {
  13605. accessedGlobals.push(helper);
  13606. }
  13607. if (accessedGlobals.length > 0) {
  13608. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  13609. }
  13610. }
  13611. setInternalResolution(inlineNamespace) {
  13612. this.inlineNamespace = inlineNamespace;
  13613. }
  13614. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  13615. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  13616. {
  13617. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  13618. format,
  13619. moduleId: this.scope.context.module.id,
  13620. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  13621. }
  13622. ]);
  13623. if (mechanism) {
  13624. return { helper: null, mechanism };
  13625. }
  13626. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  13627. switch (format) {
  13628. case 'cjs': {
  13629. if (dynamicImportInCjs &&
  13630. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  13631. return { helper: null, mechanism: null };
  13632. }
  13633. const helper = getInteropHelper(resolution, exportMode, interop);
  13634. let left = `require(`;
  13635. let right = `)`;
  13636. if (helper) {
  13637. left = `/*#__PURE__*/${helper}(${left}`;
  13638. right += ')';
  13639. }
  13640. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  13641. functionReturn: true,
  13642. lineBreakIndent: null,
  13643. name: null
  13644. });
  13645. left = `Promise.resolve().then(${functionLeft}${left}`;
  13646. right += `${functionRight})`;
  13647. if (!arrowFunctions && hasDynamicTarget) {
  13648. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13649. needsArrowReturnParens: false,
  13650. needsWrappedFunction: true
  13651. });
  13652. right = ')';
  13653. }
  13654. return {
  13655. helper,
  13656. mechanism: { left, right }
  13657. };
  13658. }
  13659. case 'amd': {
  13660. const resolve = compact ? 'c' : 'resolve';
  13661. const reject = compact ? 'e' : 'reject';
  13662. const helper = getInteropHelper(resolution, exportMode, interop);
  13663. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  13664. functionReturn: false,
  13665. lineBreakIndent: null,
  13666. name: null
  13667. });
  13668. const resolveNamespace = helper
  13669. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  13670. : resolve;
  13671. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  13672. functionReturn: false,
  13673. lineBreakIndent: null,
  13674. name: null
  13675. });
  13676. let left = `new Promise(${handlerLeft}require([`;
  13677. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  13678. if (!arrowFunctions && hasDynamicTarget) {
  13679. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13680. needsArrowReturnParens: false,
  13681. needsWrappedFunction: true
  13682. });
  13683. right = ')';
  13684. }
  13685. return {
  13686. helper,
  13687. mechanism: { left, right }
  13688. };
  13689. }
  13690. case 'system': {
  13691. return {
  13692. helper: null,
  13693. mechanism: {
  13694. left: 'module.import(',
  13695. right: ')'
  13696. }
  13697. };
  13698. }
  13699. }
  13700. return { helper: null, mechanism: null };
  13701. }
  13702. }
  13703. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13704. function getInteropHelper(resolution, exportMode, interop) {
  13705. return exportMode === 'external'
  13706. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  13707. : exportMode === 'default'
  13708. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  13709. : null;
  13710. }
  13711. const accessedImportGlobals = {
  13712. amd: ['require'],
  13713. cjs: ['require'],
  13714. system: ['module']
  13715. };
  13716. function getDeterministicObjectDestructure(objectPattern) {
  13717. const variables = [];
  13718. for (const property of objectPattern.properties) {
  13719. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  13720. return;
  13721. variables.push(property.key.name);
  13722. }
  13723. return variables;
  13724. }
  13725. class ImportNamespaceSpecifier extends NodeBase {
  13726. }
  13727. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13728. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13729. class ImportSpecifier extends NodeBase {
  13730. }
  13731. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13732. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  13733. class JSXIdentifier extends IdentifierBase {
  13734. constructor() {
  13735. super(...arguments);
  13736. this.isNativeElement = false;
  13737. }
  13738. bind() {
  13739. const type = this.getType();
  13740. if (type === 0 /* IdentifierType.Reference */) {
  13741. this.variable = this.scope.findVariable(this.name);
  13742. this.variable.addReference(this);
  13743. }
  13744. else if (type === 1 /* IdentifierType.NativeElementName */) {
  13745. this.isNativeElement = true;
  13746. }
  13747. }
  13748. include(context) {
  13749. if (!this.included)
  13750. this.includeNode(context);
  13751. }
  13752. includeNode(context) {
  13753. this.included = true;
  13754. if (!this.deoptimized)
  13755. this.applyDeoptimizations();
  13756. if (this.variable !== null) {
  13757. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  13758. }
  13759. }
  13760. includePath(path, context) {
  13761. if (!this.included) {
  13762. this.included = true;
  13763. if (this.variable !== null) {
  13764. this.scope.context.includeVariableInModule(this.variable, path, context);
  13765. }
  13766. }
  13767. else if (path.length > 0) {
  13768. this.variable?.includePath(path, context);
  13769. }
  13770. }
  13771. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  13772. if (this.variable) {
  13773. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  13774. if (name !== this.name) {
  13775. code.overwrite(this.start, this.end, name, {
  13776. contentOnly: true,
  13777. storeName: true
  13778. });
  13779. }
  13780. }
  13781. else if (this.isNativeElement &&
  13782. this.scope.context.options.jsx.mode !== 'preserve') {
  13783. code.update(this.start, this.end, JSON.stringify(this.name));
  13784. }
  13785. }
  13786. getType() {
  13787. switch (this.parent.type) {
  13788. case 'JSXOpeningElement':
  13789. case 'JSXClosingElement': {
  13790. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  13791. ? 0 /* IdentifierType.Reference */
  13792. : 1 /* IdentifierType.NativeElementName */;
  13793. }
  13794. case 'JSXMemberExpression': {
  13795. return this.parent.object === this
  13796. ? 0 /* IdentifierType.Reference */
  13797. : 2 /* IdentifierType.Other */;
  13798. }
  13799. case 'JSXAttribute':
  13800. case 'JSXNamespacedName': {
  13801. return 2 /* IdentifierType.Other */;
  13802. }
  13803. default: {
  13804. /* istanbul ignore next */
  13805. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  13806. }
  13807. }
  13808. }
  13809. }
  13810. class JSXAttribute extends NodeBase {
  13811. render(code, options, { jsxMode } = parseAst_js.BLANK) {
  13812. super.render(code, options);
  13813. if (['classic', 'automatic'].includes(jsxMode)) {
  13814. const { name, value } = this;
  13815. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  13816. if (!(jsxMode === 'automatic' && key === 'key')) {
  13817. const safeKey = stringifyObjectKeyIfNeeded(key);
  13818. if (key !== safeKey) {
  13819. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  13820. }
  13821. if (value) {
  13822. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  13823. }
  13824. else {
  13825. code.appendLeft(name.end, ': true');
  13826. }
  13827. }
  13828. }
  13829. }
  13830. }
  13831. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  13832. class JSXClosingBase extends NodeBase {
  13833. render(code, options) {
  13834. const { mode } = this.scope.context.options.jsx;
  13835. if (mode !== 'preserve') {
  13836. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  13837. }
  13838. else {
  13839. super.render(code, options);
  13840. }
  13841. }
  13842. }
  13843. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  13844. class JSXClosingElement extends JSXClosingBase {
  13845. }
  13846. class JSXClosingFragment extends JSXClosingBase {
  13847. }
  13848. class JSXSpreadAttribute extends NodeBase {
  13849. render(code, options) {
  13850. this.argument.render(code, options);
  13851. const { mode } = this.scope.context.options.jsx;
  13852. if (mode !== 'preserve') {
  13853. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  13854. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  13855. }
  13856. }
  13857. }
  13858. class JSXEmptyExpression extends NodeBase {
  13859. }
  13860. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  13861. class JSXExpressionContainer extends NodeBase {
  13862. includeNode(context) {
  13863. this.included = true;
  13864. if (!this.deoptimized)
  13865. this.applyDeoptimizations();
  13866. this.expression.includePath(UNKNOWN_PATH, context);
  13867. }
  13868. render(code, options) {
  13869. const { mode } = this.scope.context.options.jsx;
  13870. if (mode !== 'preserve') {
  13871. code.remove(this.start, this.expression.start);
  13872. code.remove(this.expression.end, this.end);
  13873. }
  13874. this.expression.render(code, options);
  13875. }
  13876. }
  13877. function getRenderedJsxChildren(children) {
  13878. let renderedChildren = 0;
  13879. for (const child of children) {
  13880. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  13881. renderedChildren++;
  13882. }
  13883. }
  13884. return renderedChildren;
  13885. }
  13886. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  13887. const [baseName, nestedName] = factory.split('.');
  13888. let factoryVariable;
  13889. if (importSource) {
  13890. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  13891. if (preserve) {
  13892. // This pretends we are accessing an included global variable of the same name
  13893. const globalVariable = node.scope.findGlobal(baseName);
  13894. globalVariable.includePath(UNKNOWN_PATH, context);
  13895. // This excludes this variable from renaming
  13896. factoryVariable.globalName = baseName;
  13897. }
  13898. }
  13899. else {
  13900. factoryVariable = node.scope.findGlobal(baseName);
  13901. }
  13902. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  13903. if (factoryVariable instanceof LocalVariable) {
  13904. factoryVariable.consolidateInitializers();
  13905. factoryVariable.addUsedPlace(node);
  13906. node.scope.context.requestTreeshakingPass();
  13907. }
  13908. return factoryVariable;
  13909. }
  13910. class JSXElementBase extends NodeBase {
  13911. constructor() {
  13912. super(...arguments);
  13913. this.factoryVariable = null;
  13914. this.factory = null;
  13915. }
  13916. initialise() {
  13917. super.initialise();
  13918. const { importSource } = (this.jsxMode = this.getRenderingMode());
  13919. if (importSource) {
  13920. this.scope.context.addImportSource(importSource);
  13921. }
  13922. }
  13923. include(context, includeChildrenRecursively) {
  13924. if (!this.included)
  13925. this.includeNode(context);
  13926. for (const child of this.children) {
  13927. child.include(context, includeChildrenRecursively);
  13928. }
  13929. }
  13930. includeNode(context) {
  13931. this.included = true;
  13932. const { factory, importSource, mode } = this.jsxMode;
  13933. if (factory) {
  13934. this.factory = factory;
  13935. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  13936. }
  13937. }
  13938. getRenderingMode() {
  13939. const jsx = this.scope.context.options.jsx;
  13940. const { mode, factory, importSource } = jsx;
  13941. if (mode === 'automatic') {
  13942. return {
  13943. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  13944. importSource: jsx.jsxImportSource,
  13945. mode
  13946. };
  13947. }
  13948. return { factory, importSource, mode };
  13949. }
  13950. renderChildren(code, options, openingEnd) {
  13951. const { children } = this;
  13952. let hasMultipleChildren = false;
  13953. let childrenEnd = openingEnd;
  13954. let firstChild = null;
  13955. for (const child of children) {
  13956. if (child instanceof JSXExpressionContainer &&
  13957. child.expression instanceof JSXEmptyExpression) {
  13958. code.remove(childrenEnd, child.end);
  13959. }
  13960. else {
  13961. code.appendLeft(childrenEnd, ', ');
  13962. child.render(code, options);
  13963. if (firstChild) {
  13964. hasMultipleChildren = true;
  13965. }
  13966. else {
  13967. firstChild = child;
  13968. }
  13969. }
  13970. childrenEnd = child.end;
  13971. }
  13972. return { childrenEnd, firstChild, hasMultipleChildren };
  13973. }
  13974. }
  13975. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  13976. class JSXElement extends JSXElementBase {
  13977. include(context, includeChildrenRecursively) {
  13978. super.include(context, includeChildrenRecursively);
  13979. this.openingElement.include(context, includeChildrenRecursively);
  13980. this.closingElement?.include(context, includeChildrenRecursively);
  13981. }
  13982. render(code, options) {
  13983. switch (this.jsxMode.mode) {
  13984. case 'classic': {
  13985. this.renderClassicMode(code, options);
  13986. break;
  13987. }
  13988. case 'automatic': {
  13989. this.renderAutomaticMode(code, options);
  13990. break;
  13991. }
  13992. default: {
  13993. super.render(code, options);
  13994. }
  13995. }
  13996. }
  13997. getRenderingMode() {
  13998. const jsx = this.scope.context.options.jsx;
  13999. const { mode, factory, importSource } = jsx;
  14000. if (mode === 'automatic') {
  14001. // In the case there is a key after a spread attribute, we fall back to
  14002. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  14003. // for reasoning.
  14004. let hasSpread = false;
  14005. for (const attribute of this.openingElement.attributes) {
  14006. if (attribute instanceof JSXSpreadAttribute) {
  14007. hasSpread = true;
  14008. }
  14009. else if (hasSpread && attribute.name.name === 'key') {
  14010. return { factory, importSource, mode: 'classic' };
  14011. }
  14012. }
  14013. }
  14014. return super.getRenderingMode();
  14015. }
  14016. renderClassicMode(code, options) {
  14017. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14018. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  14019. const [, ...nestedName] = factory.split('.');
  14020. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  14021. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  14022. this.renderChildren(code, options, openingEnd);
  14023. if (selfClosing) {
  14024. code.appendLeft(end, ')');
  14025. }
  14026. else {
  14027. closingElement.render(code, options);
  14028. }
  14029. }
  14030. renderAutomaticMode(code, options) {
  14031. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14032. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  14033. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  14034. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  14035. if (firstChild) {
  14036. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  14037. if (!inObject) {
  14038. code.prependRight(firstChild.start, '{ ');
  14039. inObject = true;
  14040. }
  14041. previousEnd = closingElement.start;
  14042. if (hasMultipleChildren) {
  14043. code.appendLeft(previousEnd, ']');
  14044. }
  14045. }
  14046. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  14047. if (keyAttribute) {
  14048. const { value } = keyAttribute;
  14049. // This will appear to the left of the moved code...
  14050. code.appendLeft(childrenEnd, ', ');
  14051. if (value) {
  14052. code.move(value.start, value.end, childrenEnd);
  14053. }
  14054. else {
  14055. code.appendLeft(childrenEnd, 'true');
  14056. }
  14057. }
  14058. if (selfClosing) {
  14059. // Moving the key attribute will also move the parenthesis to the right position
  14060. code.appendLeft(keyAttribute?.value?.end || end, ')');
  14061. }
  14062. else {
  14063. closingElement.render(code, options);
  14064. }
  14065. }
  14066. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  14067. const { jsxMode: { mode }, openingElement } = this;
  14068. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  14069. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  14070. openingElement.render(code, options, { jsxMode: mode });
  14071. let keyAttribute = null;
  14072. let hasSpread = false;
  14073. let inObject = false;
  14074. let previousEnd = nameEnd;
  14075. let hasAttributes = false;
  14076. let firstAttribute = null;
  14077. for (const attribute of attributes) {
  14078. if (attribute instanceof JSXAttribute) {
  14079. if (extractKeyAttribute && attribute.name.name === 'key') {
  14080. keyAttribute = attribute;
  14081. code.remove(previousEnd, attribute.value?.start || attribute.end);
  14082. continue;
  14083. }
  14084. code.appendLeft(previousEnd, ',');
  14085. if (!inObject) {
  14086. code.prependRight(attribute.start, '{ ');
  14087. inObject = true;
  14088. }
  14089. hasAttributes = true;
  14090. }
  14091. else {
  14092. if (inObject) {
  14093. if (hasAttributes) {
  14094. code.appendLeft(previousEnd, ' ');
  14095. }
  14096. code.appendLeft(previousEnd, '},');
  14097. inObject = false;
  14098. }
  14099. else {
  14100. code.appendLeft(previousEnd, ',');
  14101. }
  14102. hasSpread = true;
  14103. }
  14104. previousEnd = attribute.end;
  14105. if (!firstAttribute) {
  14106. firstAttribute = attribute;
  14107. }
  14108. }
  14109. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  14110. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  14111. }
  14112. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  14113. if (inObject) {
  14114. code.appendLeft(attributesEnd, ' }');
  14115. }
  14116. if (hasSpread) {
  14117. if (hasAttributes) {
  14118. const { start } = firstAttribute;
  14119. if (firstAttribute instanceof JSXSpreadAttribute) {
  14120. code.prependRight(start, '{}, ');
  14121. }
  14122. code.prependRight(start, 'Object.assign(');
  14123. code.appendLeft(attributesEnd, ')');
  14124. }
  14125. }
  14126. else if (!hasAttributes) {
  14127. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  14128. }
  14129. }
  14130. }
  14131. class JSXFragment extends JSXElementBase {
  14132. include(context, includeChildrenRecursively) {
  14133. super.include(context, includeChildrenRecursively);
  14134. this.openingFragment.include(context, includeChildrenRecursively);
  14135. this.closingFragment.include(context, includeChildrenRecursively);
  14136. }
  14137. render(code, options) {
  14138. switch (this.jsxMode.mode) {
  14139. case 'classic': {
  14140. this.renderClassicMode(code, options);
  14141. break;
  14142. }
  14143. case 'automatic': {
  14144. this.renderAutomaticMode(code, options);
  14145. break;
  14146. }
  14147. default: {
  14148. super.render(code, options);
  14149. }
  14150. }
  14151. }
  14152. renderClassicMode(code, options) {
  14153. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14154. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  14155. const [, ...nestedName] = factory.split('.');
  14156. openingFragment.render(code, options);
  14157. code.prependRight(start, `/*#__PURE__*/${[
  14158. factoryVariable.getName(getPropertyAccess, useOriginalName),
  14159. ...nestedName
  14160. ].join('.')}(`);
  14161. code.appendLeft(openingFragment.end, ', null');
  14162. this.renderChildren(code, options, openingFragment.end);
  14163. closingFragment.render(code, options);
  14164. }
  14165. renderAutomaticMode(code, options) {
  14166. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14167. const { closingFragment, factoryVariable, openingFragment, start } = this;
  14168. openingFragment.render(code, options);
  14169. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  14170. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  14171. if (firstChild) {
  14172. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  14173. if (hasMultipleChildren) {
  14174. code.appendLeft(closingFragment.start, ']');
  14175. }
  14176. code.appendLeft(childrenEnd, ' }');
  14177. }
  14178. else {
  14179. code.appendLeft(openingFragment.end, ', {}');
  14180. }
  14181. closingFragment.render(code, options);
  14182. }
  14183. }
  14184. class JSXMemberExpression extends NodeBase {
  14185. includeNode(context) {
  14186. this.included = true;
  14187. if (!this.deoptimized)
  14188. this.applyDeoptimizations();
  14189. this.object.includePath([this.property.name], context);
  14190. }
  14191. includePath(path, context) {
  14192. if (!this.included)
  14193. this.includeNode(context);
  14194. this.object.includePath([this.property.name, ...path], context);
  14195. }
  14196. }
  14197. class JSXNamespacedName extends NodeBase {
  14198. }
  14199. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  14200. class JSXOpeningElement extends NodeBase {
  14201. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  14202. this.name.render(code, options);
  14203. for (const attribute of this.attributes) {
  14204. attribute.render(code, options, { jsxMode });
  14205. }
  14206. }
  14207. }
  14208. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  14209. class JSXOpeningFragment extends NodeBase {
  14210. constructor() {
  14211. super(...arguments);
  14212. this.fragment = null;
  14213. this.fragmentVariable = null;
  14214. }
  14215. includeNode(context) {
  14216. this.included = true;
  14217. if (!this.deoptimized)
  14218. this.applyDeoptimizations();
  14219. const jsx = this.scope.context.options.jsx;
  14220. if (jsx.mode === 'automatic') {
  14221. this.fragment = 'Fragment';
  14222. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  14223. }
  14224. else {
  14225. const { fragment, importSource, mode } = jsx;
  14226. if (fragment != null) {
  14227. this.fragment = fragment;
  14228. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  14229. }
  14230. }
  14231. }
  14232. render(code, options) {
  14233. const { mode } = this.scope.context.options.jsx;
  14234. if (mode !== 'preserve') {
  14235. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  14236. const [, ...nestedFragment] = this.fragment.split('.');
  14237. const fragment = [
  14238. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  14239. ...nestedFragment
  14240. ].join('.');
  14241. code.update(this.start, this.end, fragment);
  14242. }
  14243. }
  14244. }
  14245. class JSXSpreadChild extends NodeBase {
  14246. render(code, options) {
  14247. super.render(code, options);
  14248. const { mode } = this.scope.context.options.jsx;
  14249. if (mode !== 'preserve') {
  14250. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  14251. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  14252. }
  14253. }
  14254. }
  14255. class JSXText extends NodeBase {
  14256. render(code) {
  14257. const { mode } = this.scope.context.options.jsx;
  14258. if (mode !== 'preserve') {
  14259. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  14260. contentOnly: true
  14261. });
  14262. }
  14263. }
  14264. }
  14265. JSXText.prototype.includeNode = onlyIncludeSelf;
  14266. class LabeledStatement extends NodeBase {
  14267. hasEffects(context) {
  14268. const { brokenFlow, includedLabels } = context;
  14269. context.ignore.labels.add(this.label.name);
  14270. context.includedLabels = new Set();
  14271. let bodyHasEffects = false;
  14272. if (this.body.hasEffects(context)) {
  14273. bodyHasEffects = true;
  14274. }
  14275. else {
  14276. context.ignore.labels.delete(this.label.name);
  14277. if (context.includedLabels.has(this.label.name)) {
  14278. context.includedLabels.delete(this.label.name);
  14279. context.brokenFlow = brokenFlow;
  14280. }
  14281. }
  14282. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14283. return bodyHasEffects;
  14284. }
  14285. include(context, includeChildrenRecursively) {
  14286. if (!this.included)
  14287. this.includeNode(context);
  14288. const { brokenFlow, includedLabels } = context;
  14289. context.includedLabels = new Set();
  14290. this.body.include(context, includeChildrenRecursively);
  14291. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  14292. this.label.include(context, includeChildrenRecursively);
  14293. context.includedLabels.delete(this.label.name);
  14294. context.brokenFlow = brokenFlow;
  14295. }
  14296. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  14297. }
  14298. includeNode(context) {
  14299. this.included = true;
  14300. this.body.includePath(UNKNOWN_PATH, context);
  14301. }
  14302. render(code, options) {
  14303. if (this.label.included) {
  14304. this.label.render(code, options);
  14305. }
  14306. else {
  14307. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  14308. }
  14309. this.body.render(code, options);
  14310. }
  14311. }
  14312. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14313. class LogicalExpression extends NodeBase {
  14314. constructor() {
  14315. super(...arguments);
  14316. // We collect deoptimization information if usedBranch !== null
  14317. this.expressionsToBeDeoptimized = [];
  14318. this.usedBranch = null;
  14319. }
  14320. //private isBranchResolutionAnalysed = false;
  14321. get isBranchResolutionAnalysed() {
  14322. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  14323. }
  14324. set isBranchResolutionAnalysed(value) {
  14325. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  14326. }
  14327. get hasDeoptimizedCache() {
  14328. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  14329. }
  14330. set hasDeoptimizedCache(value) {
  14331. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  14332. }
  14333. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14334. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14335. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14336. }
  14337. deoptimizeCache() {
  14338. if (this.hasDeoptimizedCache)
  14339. return;
  14340. this.hasDeoptimizedCache = true;
  14341. if (this.usedBranch) {
  14342. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  14343. this.usedBranch = null;
  14344. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  14345. if (this.included) {
  14346. // As we are not tracking inclusions, we just include everything
  14347. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  14348. }
  14349. }
  14350. const { scope: { context }, expressionsToBeDeoptimized } = this;
  14351. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  14352. for (const expression of expressionsToBeDeoptimized) {
  14353. expression.deoptimizeCache();
  14354. }
  14355. // Request another pass because we need to ensure "include" runs again if
  14356. // it is rendered
  14357. context.requestTreeshakingPass();
  14358. }
  14359. deoptimizePath(path) {
  14360. const usedBranch = this.getUsedBranch();
  14361. if (usedBranch) {
  14362. usedBranch.deoptimizePath(path);
  14363. }
  14364. else {
  14365. this.left.deoptimizePath(path);
  14366. this.right.deoptimizePath(path);
  14367. }
  14368. }
  14369. getLiteralValueAtPath(path, recursionTracker, origin) {
  14370. if (origin === this)
  14371. return UnknownValue;
  14372. const usedBranch = this.getUsedBranch();
  14373. if (usedBranch) {
  14374. this.expressionsToBeDeoptimized.push(origin);
  14375. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  14376. }
  14377. else if (!this.hasDeoptimizedCache && !path.length) {
  14378. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  14379. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  14380. if (typeof booleanOrUnknown !== 'symbol') {
  14381. if (!booleanOrUnknown && this.operator === '&&') {
  14382. this.expressionsToBeDeoptimized.push(origin);
  14383. return UnknownFalsyValue;
  14384. }
  14385. if (booleanOrUnknown && this.operator === '||') {
  14386. this.expressionsToBeDeoptimized.push(origin);
  14387. return UnknownTruthyValue;
  14388. }
  14389. }
  14390. }
  14391. return UnknownValue;
  14392. }
  14393. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14394. const usedBranch = this.getUsedBranch();
  14395. if (usedBranch) {
  14396. this.expressionsToBeDeoptimized.push(origin);
  14397. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  14398. }
  14399. return [
  14400. new MultiExpression([
  14401. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  14402. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  14403. ]),
  14404. false
  14405. ];
  14406. }
  14407. hasEffects(context) {
  14408. if (this.left.hasEffects(context)) {
  14409. return true;
  14410. }
  14411. if (this.getUsedBranch() !== this.left) {
  14412. return this.right.hasEffects(context);
  14413. }
  14414. return false;
  14415. }
  14416. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14417. const usedBranch = this.getUsedBranch();
  14418. if (usedBranch) {
  14419. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  14420. }
  14421. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  14422. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  14423. }
  14424. include(context, includeChildrenRecursively) {
  14425. this.included = true;
  14426. const usedBranch = this.getUsedBranch();
  14427. if (includeChildrenRecursively ||
  14428. !usedBranch ||
  14429. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14430. this.left.include(context, includeChildrenRecursively);
  14431. this.right.include(context, includeChildrenRecursively);
  14432. }
  14433. else {
  14434. usedBranch.include(context, includeChildrenRecursively);
  14435. }
  14436. }
  14437. includePath(path, context) {
  14438. this.included = true;
  14439. const usedBranch = this.getUsedBranch();
  14440. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  14441. this.left.includePath(path, context);
  14442. this.right.includePath(path, context);
  14443. }
  14444. else {
  14445. usedBranch.includePath(path, context);
  14446. }
  14447. }
  14448. removeAnnotations(code) {
  14449. this.left.removeAnnotations(code);
  14450. }
  14451. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  14452. if (!this.left.included || !this.right.included) {
  14453. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  14454. if (this.right.included) {
  14455. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  14456. code.remove(this.start, removePos);
  14457. if (preventASI) {
  14458. removeLineBreaks(code, removePos, this.right.start);
  14459. }
  14460. this.left.removeAnnotations(code);
  14461. }
  14462. else {
  14463. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  14464. }
  14465. this.getUsedBranch().render(code, options, {
  14466. isCalleeOfRenderedParent,
  14467. preventASI,
  14468. renderedParentType: renderedParentType || this.parent.type,
  14469. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  14470. });
  14471. }
  14472. else {
  14473. this.left.render(code, options, {
  14474. preventASI,
  14475. renderedSurroundingElement
  14476. });
  14477. this.right.render(code, options);
  14478. }
  14479. }
  14480. getUsedBranch() {
  14481. if (!this.isBranchResolutionAnalysed) {
  14482. this.isBranchResolutionAnalysed = true;
  14483. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  14484. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  14485. if (typeof booleanOrUnknown === 'symbol') {
  14486. return null;
  14487. }
  14488. else {
  14489. this.usedBranch =
  14490. (this.operator === '||' && booleanOrUnknown) ||
  14491. (this.operator === '&&' && !booleanOrUnknown) ||
  14492. (this.operator === '??' && leftValue != null)
  14493. ? this.left
  14494. : this.right;
  14495. }
  14496. }
  14497. return this.usedBranch;
  14498. }
  14499. }
  14500. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14501. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14502. class NewExpression extends NodeBase {
  14503. hasEffects(context) {
  14504. if (!this.deoptimized)
  14505. this.applyDeoptimizations();
  14506. for (const argument of this.arguments) {
  14507. if (argument.hasEffects(context))
  14508. return true;
  14509. }
  14510. if (this.annotationPure) {
  14511. return false;
  14512. }
  14513. return (this.callee.hasEffects(context) ||
  14514. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14515. }
  14516. hasEffectsOnInteractionAtPath(path, { type }) {
  14517. return path.length > 0 || type !== INTERACTION_ACCESSED;
  14518. }
  14519. include(context, includeChildrenRecursively) {
  14520. if (!this.included)
  14521. this.includeNode(context);
  14522. if (includeChildrenRecursively) {
  14523. super.include(context, true);
  14524. }
  14525. else {
  14526. this.callee.include(context, false);
  14527. this.callee.includeCallArguments(this.interaction, context);
  14528. }
  14529. }
  14530. includeNode(context) {
  14531. this.included = true;
  14532. if (!this.deoptimized)
  14533. this.applyDeoptimizations();
  14534. this.callee.includePath(UNKNOWN_PATH, context);
  14535. }
  14536. initialise() {
  14537. super.initialise();
  14538. this.interaction = {
  14539. args: [null, ...this.arguments],
  14540. type: INTERACTION_CALLED,
  14541. withNew: true
  14542. };
  14543. if (this.annotations &&
  14544. this.scope.context.options.treeshake.annotations) {
  14545. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  14546. }
  14547. }
  14548. render(code, options) {
  14549. this.callee.render(code, options);
  14550. renderCallArguments(code, options, this);
  14551. }
  14552. applyDeoptimizations() {
  14553. this.deoptimized = true;
  14554. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  14555. this.scope.context.requestTreeshakingPass();
  14556. }
  14557. }
  14558. class ObjectExpression extends NodeBase {
  14559. constructor() {
  14560. super(...arguments);
  14561. this.objectEntity = null;
  14562. this.protoProp = null;
  14563. }
  14564. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14565. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14566. }
  14567. deoptimizeCache() {
  14568. this.getObjectEntity().deoptimizeAllProperties();
  14569. }
  14570. deoptimizePath(path) {
  14571. this.getObjectEntity().deoptimizePath(path);
  14572. }
  14573. getLiteralValueAtPath(path, recursionTracker, origin) {
  14574. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  14575. }
  14576. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14577. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  14578. }
  14579. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14580. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  14581. }
  14582. include(context, includeChildrenRecursively) {
  14583. if (!this.included)
  14584. this.includeNode(context);
  14585. this.getObjectEntity().include(context, includeChildrenRecursively);
  14586. this.protoProp?.include(context, includeChildrenRecursively);
  14587. }
  14588. includeNode(context) {
  14589. this.included = true;
  14590. this.protoProp?.includePath(UNKNOWN_PATH, context);
  14591. }
  14592. includePath(path, context) {
  14593. if (!this.included)
  14594. this.includeNode(context);
  14595. this.getObjectEntity().includePath(path, context);
  14596. }
  14597. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  14598. if (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  14599. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression) {
  14600. code.appendRight(this.start, '(');
  14601. code.prependLeft(this.end, ')');
  14602. }
  14603. if (this.properties.length > 0) {
  14604. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  14605. let lastSeparatorPos = null;
  14606. for (const { node, separator, start, end } of separatedNodes) {
  14607. if (!node.included) {
  14608. treeshakeNode(node, code, start, end);
  14609. continue;
  14610. }
  14611. lastSeparatorPos = separator;
  14612. node.render(code, options);
  14613. }
  14614. if (lastSeparatorPos) {
  14615. code.remove(lastSeparatorPos, this.end - 1);
  14616. }
  14617. }
  14618. }
  14619. getObjectEntity() {
  14620. if (this.objectEntity !== null) {
  14621. return this.objectEntity;
  14622. }
  14623. let prototype = OBJECT_PROTOTYPE;
  14624. const properties = [];
  14625. for (const property of this.properties) {
  14626. if (property instanceof SpreadElement) {
  14627. properties.push({ key: UnknownKey, kind: 'init', property });
  14628. continue;
  14629. }
  14630. let key;
  14631. if (property.computed) {
  14632. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  14633. if (typeof keyValue === 'symbol') {
  14634. properties.push({ key: UnknownKey, kind: property.kind, property });
  14635. continue;
  14636. }
  14637. else {
  14638. key = String(keyValue);
  14639. }
  14640. }
  14641. else {
  14642. key =
  14643. property.key instanceof Identifier
  14644. ? property.key.name
  14645. : String(property.key.value);
  14646. if (key === '__proto__' && property.kind === 'init') {
  14647. this.protoProp = property;
  14648. prototype =
  14649. property.value instanceof Literal && property.value.value === null
  14650. ? null
  14651. : property.value;
  14652. continue;
  14653. }
  14654. }
  14655. properties.push({ key, kind: property.kind, property });
  14656. }
  14657. return (this.objectEntity = new ObjectEntity(properties, prototype));
  14658. }
  14659. }
  14660. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14661. class PanicError extends NodeBase {
  14662. initialise() {
  14663. const id = this.scope.context.module.id;
  14664. // This simulates the current nested error structure. We could also just
  14665. // replace it with a flat error.
  14666. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message));
  14667. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  14668. return parseAst_js.error(moduleParseError);
  14669. }
  14670. }
  14671. class ParseError extends NodeBase {
  14672. initialise() {
  14673. const pos = this.start;
  14674. const id = this.scope.context.module.id;
  14675. // This simulates the current nested error structure. We could also just
  14676. // replace it with a flat error.
  14677. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message, pos));
  14678. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  14679. this.scope.context.error(moduleParseError, pos);
  14680. }
  14681. }
  14682. class PrivateIdentifier extends NodeBase {
  14683. }
  14684. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  14685. class Program extends NodeBase {
  14686. constructor() {
  14687. super(...arguments);
  14688. this.hasCachedEffect = null;
  14689. this.hasLoggedEffect = false;
  14690. }
  14691. hasCachedEffects() {
  14692. if (!this.included) {
  14693. return false;
  14694. }
  14695. return this.hasCachedEffect === null
  14696. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  14697. : this.hasCachedEffect;
  14698. }
  14699. hasEffects(context) {
  14700. for (const node of this.body) {
  14701. if (node.hasEffects(context)) {
  14702. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  14703. this.hasLoggedEffect = true;
  14704. const { code, log, module } = this.scope.context;
  14705. log(parseAst_js.LOGLEVEL_INFO, parseAst_js.logFirstSideEffect(code, module.id, parseAst_js.locate(code, node.start, { offsetLine: 1 })), node.start);
  14706. }
  14707. return (this.hasCachedEffect = true);
  14708. }
  14709. }
  14710. return false;
  14711. }
  14712. include(context, includeChildrenRecursively) {
  14713. this.included = true;
  14714. for (const node of this.body) {
  14715. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  14716. node.include(context, includeChildrenRecursively);
  14717. }
  14718. }
  14719. }
  14720. initialise() {
  14721. super.initialise();
  14722. if (this.invalidAnnotations)
  14723. for (const { start, end, type } of this.invalidAnnotations) {
  14724. this.scope.context.magicString.remove(start, end);
  14725. if (type === 'pure' || type === 'noSideEffects') {
  14726. 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);
  14727. }
  14728. }
  14729. }
  14730. render(code, options) {
  14731. let start = this.start;
  14732. if (code.original.startsWith('#!')) {
  14733. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  14734. code.remove(0, start);
  14735. }
  14736. if (this.body.length > 0) {
  14737. // Keep all consecutive lines that start with a comment
  14738. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  14739. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  14740. if (firstLineBreak[0] === -1) {
  14741. break;
  14742. }
  14743. start += firstLineBreak[1];
  14744. }
  14745. renderStatementList(this.body, code, start, this.end, options);
  14746. }
  14747. else {
  14748. super.render(code, options);
  14749. }
  14750. }
  14751. }
  14752. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14753. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  14754. class Property extends MethodBase {
  14755. //declare method: boolean;
  14756. get method() {
  14757. return isFlagSet(this.flags, 262144 /* Flag.method */);
  14758. }
  14759. set method(value) {
  14760. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  14761. }
  14762. //declare shorthand: boolean;
  14763. get shorthand() {
  14764. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  14765. }
  14766. set shorthand(value) {
  14767. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  14768. }
  14769. declare(kind, destructuredInitPath, init) {
  14770. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  14771. }
  14772. deoptimizeAssignment(destructuredInitPath, init) {
  14773. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  14774. }
  14775. hasEffects(context) {
  14776. return this.key.hasEffects(context) || this.value.hasEffects(context);
  14777. }
  14778. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  14779. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  14780. }
  14781. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  14782. const path = this.getPathInProperty(destructuredInitPath);
  14783. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  14784. this.included;
  14785. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  14786. this.key.include(context, false);
  14787. if (!this.value.included) {
  14788. this.value.included = true;
  14789. // Unfortunately, we need to include the value again now, so that any
  14790. // declared variables are properly included.
  14791. this.value.includeDestructuredIfNecessary(context, path, init);
  14792. }
  14793. }
  14794. return (this.included = included);
  14795. }
  14796. include(context, includeChildrenRecursively) {
  14797. this.included = true;
  14798. this.key.include(context, includeChildrenRecursively);
  14799. this.value.include(context, includeChildrenRecursively);
  14800. }
  14801. includePath(path, context) {
  14802. this.included = true;
  14803. this.value.includePath(path, context);
  14804. }
  14805. markDeclarationReached() {
  14806. this.value.markDeclarationReached();
  14807. }
  14808. render(code, options) {
  14809. if (!this.shorthand) {
  14810. this.key.render(code, options);
  14811. }
  14812. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  14813. }
  14814. getPathInProperty(destructuredInitPath) {
  14815. return destructuredInitPath.at(-1) === UnknownKey
  14816. ? destructuredInitPath
  14817. : // For now, we only consider static paths as we do not know how to
  14818. // deoptimize the path in the dynamic case.
  14819. this.computed
  14820. ? [...destructuredInitPath, UnknownKey]
  14821. : this.key instanceof Identifier
  14822. ? [...destructuredInitPath, this.key.name]
  14823. : [...destructuredInitPath, String(this.key.value)];
  14824. }
  14825. }
  14826. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14827. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  14828. class PropertyDefinition extends NodeBase {
  14829. get computed() {
  14830. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  14831. }
  14832. set computed(value) {
  14833. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  14834. }
  14835. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14836. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14837. }
  14838. deoptimizePath(path) {
  14839. this.value?.deoptimizePath(path);
  14840. }
  14841. getLiteralValueAtPath(path, recursionTracker, origin) {
  14842. return this.value
  14843. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  14844. : UnknownValue;
  14845. }
  14846. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14847. return this.value
  14848. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  14849. : UNKNOWN_RETURN_EXPRESSION;
  14850. }
  14851. hasEffects(context) {
  14852. return (this.key.hasEffects(context) ||
  14853. (this.static && !!this.value?.hasEffects(context)) ||
  14854. checkEffectForNodes(this.decorators, context));
  14855. }
  14856. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14857. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  14858. }
  14859. includeNode(context) {
  14860. this.included = true;
  14861. this.value?.includePath(UNKNOWN_PATH, context);
  14862. for (const decorator of this.decorators) {
  14863. decorator.includePath(UNKNOWN_PATH, context);
  14864. }
  14865. }
  14866. }
  14867. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  14868. class ReturnStatement extends NodeBase {
  14869. hasEffects(context) {
  14870. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  14871. return true;
  14872. context.brokenFlow = true;
  14873. return false;
  14874. }
  14875. include(context, includeChildrenRecursively) {
  14876. if (!this.included)
  14877. this.includeNode(context);
  14878. this.argument?.include(context, includeChildrenRecursively);
  14879. context.brokenFlow = true;
  14880. }
  14881. includeNode(context) {
  14882. this.included = true;
  14883. this.argument?.includePath(UNKNOWN_PATH, context);
  14884. }
  14885. initialise() {
  14886. super.initialise();
  14887. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  14888. }
  14889. render(code, options) {
  14890. if (this.argument) {
  14891. this.argument.render(code, options, { preventASI: true });
  14892. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  14893. code.prependLeft(this.start + 6, ' ');
  14894. }
  14895. }
  14896. }
  14897. }
  14898. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14899. class SequenceExpression extends NodeBase {
  14900. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14901. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14902. }
  14903. deoptimizePath(path) {
  14904. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  14905. }
  14906. getLiteralValueAtPath(path, recursionTracker, origin) {
  14907. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  14908. }
  14909. hasEffects(context) {
  14910. for (const expression of this.expressions) {
  14911. if (expression.hasEffects(context))
  14912. return true;
  14913. }
  14914. return false;
  14915. }
  14916. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14917. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  14918. }
  14919. include(context, includeChildrenRecursively) {
  14920. this.included = true;
  14921. const lastExpression = this.expressions[this.expressions.length - 1];
  14922. for (const expression of this.expressions) {
  14923. if (includeChildrenRecursively ||
  14924. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  14925. expression.shouldBeIncluded(context)) {
  14926. expression.include(context, includeChildrenRecursively);
  14927. }
  14928. }
  14929. }
  14930. includePath(path, context) {
  14931. this.included = true;
  14932. this.expressions[this.expressions.length - 1].includePath(path, context);
  14933. }
  14934. removeAnnotations(code) {
  14935. this.expressions[0].removeAnnotations(code);
  14936. }
  14937. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = parseAst_js.BLANK) {
  14938. let includedNodes = 0;
  14939. let lastSeparatorPos = null;
  14940. const lastNode = this.expressions[this.expressions.length - 1];
  14941. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  14942. if (!node.included) {
  14943. treeshakeNode(node, code, start, end);
  14944. continue;
  14945. }
  14946. includedNodes++;
  14947. lastSeparatorPos = separator;
  14948. if (includedNodes === 1 && preventASI) {
  14949. removeLineBreaks(code, start, node.start);
  14950. }
  14951. if (includedNodes === 1) {
  14952. const parentType = renderedParentType || this.parent.type;
  14953. node.render(code, options, {
  14954. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  14955. renderedParentType: parentType,
  14956. renderedSurroundingElement: parentType
  14957. });
  14958. }
  14959. else {
  14960. node.render(code, options);
  14961. }
  14962. }
  14963. if (lastSeparatorPos) {
  14964. code.remove(lastSeparatorPos, this.end);
  14965. }
  14966. }
  14967. }
  14968. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14969. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14970. class Super extends NodeBase {
  14971. bind() {
  14972. this.variable = this.scope.findVariable('this');
  14973. }
  14974. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14975. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14976. }
  14977. deoptimizePath(path) {
  14978. this.variable.deoptimizePath(path);
  14979. }
  14980. include(context) {
  14981. if (!this.included)
  14982. this.includeNode(context);
  14983. }
  14984. includeNode(context) {
  14985. this.included = true;
  14986. if (!this.deoptimized)
  14987. this.applyDeoptimizations();
  14988. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14989. }
  14990. }
  14991. class SwitchCase extends NodeBase {
  14992. hasEffects(context) {
  14993. if (this.test?.hasEffects(context))
  14994. return true;
  14995. for (const node of this.consequent) {
  14996. if (context.brokenFlow)
  14997. break;
  14998. if (node.hasEffects(context))
  14999. return true;
  15000. }
  15001. return false;
  15002. }
  15003. include(context, includeChildrenRecursively) {
  15004. this.included = true;
  15005. this.test?.include(context, includeChildrenRecursively);
  15006. for (const node of this.consequent) {
  15007. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  15008. node.include(context, includeChildrenRecursively);
  15009. }
  15010. }
  15011. render(code, options, nodeRenderOptions) {
  15012. if (this.test) {
  15013. this.test.render(code, options);
  15014. if (this.test.start === this.start + 4) {
  15015. code.prependLeft(this.test.start, ' ');
  15016. }
  15017. }
  15018. if (this.consequent.length > 0) {
  15019. const testEnd = this.test
  15020. ? this.test.end
  15021. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  15022. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  15023. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  15024. }
  15025. }
  15026. }
  15027. SwitchCase.prototype.needsBoundaries = true;
  15028. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15029. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  15030. class SwitchStatement extends NodeBase {
  15031. createScope(parentScope) {
  15032. this.parentScope = parentScope;
  15033. this.scope = new BlockScope(parentScope);
  15034. }
  15035. hasEffects(context) {
  15036. if (this.discriminant.hasEffects(context))
  15037. return true;
  15038. const { brokenFlow, hasBreak, ignore } = context;
  15039. const { breaks } = ignore;
  15040. ignore.breaks = true;
  15041. context.hasBreak = false;
  15042. let onlyHasBrokenFlow = true;
  15043. for (const switchCase of this.cases) {
  15044. if (switchCase.hasEffects(context))
  15045. return true;
  15046. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15047. context.hasBreak = false;
  15048. context.brokenFlow = brokenFlow;
  15049. }
  15050. if (this.defaultCase !== null) {
  15051. context.brokenFlow = onlyHasBrokenFlow;
  15052. }
  15053. ignore.breaks = breaks;
  15054. context.hasBreak = hasBreak;
  15055. return false;
  15056. }
  15057. include(context, includeChildrenRecursively) {
  15058. this.included = true;
  15059. this.discriminant.include(context, includeChildrenRecursively);
  15060. const { brokenFlow, hasBreak } = context;
  15061. context.hasBreak = false;
  15062. let onlyHasBrokenFlow = true;
  15063. let isCaseIncluded = includeChildrenRecursively ||
  15064. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  15065. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  15066. const switchCase = this.cases[caseIndex];
  15067. if (switchCase.included) {
  15068. isCaseIncluded = true;
  15069. }
  15070. if (!isCaseIncluded) {
  15071. const hasEffectsContext = createHasEffectsContext();
  15072. hasEffectsContext.ignore.breaks = true;
  15073. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  15074. }
  15075. if (isCaseIncluded) {
  15076. switchCase.include(context, includeChildrenRecursively);
  15077. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  15078. context.hasBreak = false;
  15079. context.brokenFlow = brokenFlow;
  15080. }
  15081. else {
  15082. onlyHasBrokenFlow = brokenFlow;
  15083. }
  15084. }
  15085. if (isCaseIncluded && this.defaultCase !== null) {
  15086. context.brokenFlow = onlyHasBrokenFlow;
  15087. }
  15088. context.hasBreak = hasBreak;
  15089. }
  15090. initialise() {
  15091. super.initialise();
  15092. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  15093. if (this.cases[caseIndex].test === null) {
  15094. this.defaultCase = caseIndex;
  15095. return;
  15096. }
  15097. }
  15098. this.defaultCase = null;
  15099. }
  15100. parseNode(esTreeNode) {
  15101. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  15102. return super.parseNode(esTreeNode);
  15103. }
  15104. render(code, options) {
  15105. this.discriminant.render(code, options);
  15106. if (this.cases.length > 0) {
  15107. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  15108. }
  15109. }
  15110. }
  15111. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15112. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15113. class TaggedTemplateExpression extends CallExpressionBase {
  15114. bind() {
  15115. super.bind();
  15116. if (this.tag.type === parseAst_js.Identifier) {
  15117. const name = this.tag.name;
  15118. const variable = this.scope.findVariable(name);
  15119. if (variable.isNamespace) {
  15120. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
  15121. }
  15122. }
  15123. }
  15124. hasEffects(context) {
  15125. if (!this.deoptimized)
  15126. this.applyDeoptimizations();
  15127. for (const argument of this.quasi.expressions) {
  15128. if (argument.hasEffects(context))
  15129. return true;
  15130. }
  15131. return (this.tag.hasEffects(context) ||
  15132. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  15133. }
  15134. include(context, includeChildrenRecursively) {
  15135. if (!this.included)
  15136. this.includeNode(context);
  15137. if (includeChildrenRecursively) {
  15138. super.include(context, true);
  15139. }
  15140. else {
  15141. this.quasi.include(context, false);
  15142. this.tag.include(context, false);
  15143. this.tag.includeCallArguments(this.interaction, context);
  15144. }
  15145. }
  15146. initialise() {
  15147. super.initialise();
  15148. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  15149. this.interaction = {
  15150. args: [
  15151. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  15152. ...this.args
  15153. ],
  15154. type: INTERACTION_CALLED,
  15155. withNew: false
  15156. };
  15157. }
  15158. render(code, options) {
  15159. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  15160. this.quasi.render(code, options);
  15161. }
  15162. applyDeoptimizations() {
  15163. this.deoptimized = true;
  15164. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  15165. this.scope.context.requestTreeshakingPass();
  15166. }
  15167. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  15168. if (this.returnExpression === null) {
  15169. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  15170. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  15171. }
  15172. return this.returnExpression;
  15173. }
  15174. }
  15175. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  15176. class TemplateElement extends NodeBase {
  15177. get tail() {
  15178. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  15179. }
  15180. set tail(value) {
  15181. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  15182. }
  15183. // Do not try to bind value
  15184. bind() { }
  15185. hasEffects() {
  15186. return false;
  15187. }
  15188. parseNode(esTreeNode) {
  15189. this.value = esTreeNode.value;
  15190. return super.parseNode(esTreeNode);
  15191. }
  15192. render() { }
  15193. }
  15194. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  15195. class TemplateLiteral extends NodeBase {
  15196. deoptimizeArgumentsOnInteractionAtPath() { }
  15197. getLiteralValueAtPath(path) {
  15198. if (path.length > 0 || this.quasis.length !== 1) {
  15199. return UnknownValue;
  15200. }
  15201. return this.quasis[0].value.cooked;
  15202. }
  15203. getReturnExpressionWhenCalledAtPath(path) {
  15204. if (path.length !== 1) {
  15205. return UNKNOWN_RETURN_EXPRESSION;
  15206. }
  15207. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  15208. }
  15209. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15210. if (interaction.type === INTERACTION_ACCESSED) {
  15211. return path.length > 1;
  15212. }
  15213. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  15214. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  15215. }
  15216. return true;
  15217. }
  15218. includeNode(context) {
  15219. this.included = true;
  15220. if (!this.deoptimized)
  15221. this.applyDeoptimizations();
  15222. for (const node of this.expressions) {
  15223. node.includePath(UNKNOWN_PATH, context);
  15224. }
  15225. }
  15226. render(code, options) {
  15227. code.indentExclusionRanges.push([this.start, this.end]);
  15228. super.render(code, options);
  15229. }
  15230. }
  15231. class ModuleScope extends ChildScope {
  15232. constructor(parent, context) {
  15233. super(parent, context);
  15234. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  15235. }
  15236. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  15237. if (this.context.module.importDescriptions.has(identifier.name)) {
  15238. context.error(parseAst_js.logRedeclarationError(identifier.name), identifier.start);
  15239. }
  15240. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  15241. }
  15242. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  15243. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  15244. this.variables.set('default', variable);
  15245. return variable;
  15246. }
  15247. addNamespaceMemberAccess() { }
  15248. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  15249. // all module level variables are already deconflicted when deconflicting the chunk
  15250. for (const scope of this.children)
  15251. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15252. }
  15253. findLexicalBoundary() {
  15254. return this;
  15255. }
  15256. findVariable(name) {
  15257. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  15258. if (knownVariable) {
  15259. return knownVariable;
  15260. }
  15261. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  15262. if (variable instanceof GlobalVariable) {
  15263. this.accessedOutsideVariables.set(name, variable);
  15264. }
  15265. return variable;
  15266. }
  15267. }
  15268. class ThisExpression extends NodeBase {
  15269. bind() {
  15270. this.variable = this.scope.findVariable('this');
  15271. }
  15272. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  15273. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  15274. }
  15275. deoptimizePath(path) {
  15276. this.variable.deoptimizePath(path);
  15277. }
  15278. hasEffectsOnInteractionAtPath(path, interaction, context) {
  15279. if (path.length === 0) {
  15280. return interaction.type !== INTERACTION_ACCESSED;
  15281. }
  15282. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  15283. }
  15284. include(context) {
  15285. if (!this.included)
  15286. this.includeNode(context);
  15287. }
  15288. includeNode(context) {
  15289. this.included = true;
  15290. if (!this.deoptimized)
  15291. this.applyDeoptimizations();
  15292. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  15293. }
  15294. includePath(path, context) {
  15295. if (!this.included) {
  15296. this.included = true;
  15297. this.scope.context.includeVariableInModule(this.variable, path, context);
  15298. }
  15299. else if (path.length > 0) {
  15300. this.variable.includePath(path, context);
  15301. }
  15302. const functionScope = findFunctionScope(this.scope, this.variable);
  15303. if (functionScope &&
  15304. functionScope.functionNode.parent instanceof Property &&
  15305. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  15306. functionScope.functionNode.parent.parent.includePath(path, context);
  15307. }
  15308. }
  15309. initialise() {
  15310. super.initialise();
  15311. this.alias =
  15312. this.scope.findLexicalBoundary() instanceof ModuleScope
  15313. ? this.scope.context.moduleContext
  15314. : null;
  15315. if (this.alias === 'undefined') {
  15316. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logThisIsUndefined(), this.start);
  15317. }
  15318. }
  15319. render(code) {
  15320. if (this.alias !== null) {
  15321. code.overwrite(this.start, this.end, this.alias, {
  15322. contentOnly: false,
  15323. storeName: true
  15324. });
  15325. }
  15326. }
  15327. }
  15328. function findFunctionScope(scope, thisVariable) {
  15329. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  15330. if (!(scope instanceof ChildScope)) {
  15331. return null;
  15332. }
  15333. scope = scope.parent;
  15334. }
  15335. return scope;
  15336. }
  15337. class ThrowStatement extends NodeBase {
  15338. hasEffects() {
  15339. return true;
  15340. }
  15341. include(context, includeChildrenRecursively) {
  15342. if (!this.included)
  15343. this.includeNode(context);
  15344. this.argument.include(context, includeChildrenRecursively);
  15345. context.brokenFlow = true;
  15346. }
  15347. includeNode(context) {
  15348. if (!this.included) {
  15349. this.included = true;
  15350. this.argument.includePath(UNKNOWN_PATH, context);
  15351. }
  15352. }
  15353. render(code, options) {
  15354. this.argument.render(code, options, { preventASI: true });
  15355. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  15356. code.prependLeft(this.start + 5, ' ');
  15357. }
  15358. }
  15359. }
  15360. class TryStatement extends NodeBase {
  15361. constructor() {
  15362. super(...arguments);
  15363. this.directlyIncluded = false;
  15364. this.includedLabelsAfterBlock = null;
  15365. }
  15366. hasEffects(context) {
  15367. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  15368. ? this.block.body.length > 0
  15369. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  15370. }
  15371. include(context, includeChildrenRecursively) {
  15372. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  15373. const { brokenFlow, includedLabels } = context;
  15374. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  15375. this.included = true;
  15376. this.directlyIncluded = true;
  15377. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  15378. if (includedLabels.size > 0) {
  15379. this.includedLabelsAfterBlock = [...includedLabels];
  15380. }
  15381. context.brokenFlow = brokenFlow;
  15382. }
  15383. else if (this.includedLabelsAfterBlock) {
  15384. for (const label of this.includedLabelsAfterBlock) {
  15385. includedLabels.add(label);
  15386. }
  15387. }
  15388. if (this.handler !== null) {
  15389. this.handler.include(context, includeChildrenRecursively);
  15390. context.brokenFlow = brokenFlow;
  15391. }
  15392. this.finalizer?.include(context, includeChildrenRecursively);
  15393. }
  15394. }
  15395. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15396. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15397. const unaryOperators = {
  15398. '!': value => !value,
  15399. '+': value => +value,
  15400. '-': value => -value,
  15401. delete: () => UnknownValue,
  15402. typeof: value => typeof value,
  15403. void: () => undefined,
  15404. '~': value => ~value
  15405. };
  15406. const UNASSIGNED = Symbol('Unassigned');
  15407. class UnaryExpression extends NodeBase {
  15408. constructor() {
  15409. super(...arguments);
  15410. this.renderedLiteralValue = UNASSIGNED;
  15411. }
  15412. get prefix() {
  15413. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  15414. }
  15415. set prefix(value) {
  15416. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  15417. }
  15418. deoptimizeCache() {
  15419. this.renderedLiteralValue = UnknownValue;
  15420. }
  15421. getLiteralValueAtPath(path, recursionTracker, origin) {
  15422. if (path.length > 0)
  15423. return UnknownValue;
  15424. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  15425. if (typeof argumentValue === 'symbol') {
  15426. if (this.operator === 'void')
  15427. return undefined;
  15428. if (this.operator === '!') {
  15429. if (argumentValue === UnknownFalsyValue)
  15430. return true;
  15431. if (argumentValue === UnknownTruthyValue)
  15432. return false;
  15433. }
  15434. return UnknownValue;
  15435. }
  15436. return unaryOperators[this.operator](argumentValue);
  15437. }
  15438. hasEffects(context) {
  15439. if (!this.deoptimized)
  15440. this.applyDeoptimizations();
  15441. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  15442. return false;
  15443. return (this.argument.hasEffects(context) ||
  15444. (this.operator === 'delete' &&
  15445. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  15446. }
  15447. hasEffectsOnInteractionAtPath(path, { type }) {
  15448. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  15449. }
  15450. applyDeoptimizations() {
  15451. this.deoptimized = true;
  15452. if (this.operator === 'delete') {
  15453. this.argument.deoptimizePath(EMPTY_PATH);
  15454. this.scope.context.requestTreeshakingPass();
  15455. }
  15456. }
  15457. getRenderedLiteralValue(includeChildrenRecursively) {
  15458. if (this.renderedLiteralValue !== UNASSIGNED)
  15459. return this.renderedLiteralValue;
  15460. return (this.renderedLiteralValue = includeChildrenRecursively
  15461. ? UnknownValue
  15462. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  15463. }
  15464. include(context, includeChildrenRecursively, _options) {
  15465. if (!this.deoptimized)
  15466. this.applyDeoptimizations();
  15467. this.included = true;
  15468. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  15469. this.argument.shouldBeIncluded(context)) {
  15470. this.argument.include(context, includeChildrenRecursively);
  15471. this.renderedLiteralValue = UnknownValue;
  15472. }
  15473. }
  15474. render(code, options) {
  15475. if (typeof this.renderedLiteralValue === 'symbol') {
  15476. super.render(code, options);
  15477. }
  15478. else {
  15479. let value = this.renderedLiteralValue;
  15480. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  15481. value = ` ${value}`;
  15482. }
  15483. code.overwrite(this.start, this.end, value);
  15484. }
  15485. }
  15486. }
  15487. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  15488. function getRenderedLiteralValue(value) {
  15489. if (value === undefined) {
  15490. // At the moment, the undefined only happens when the operator is void
  15491. return 'void 0';
  15492. }
  15493. if (typeof value === 'boolean') {
  15494. return String(value);
  15495. }
  15496. if (typeof value === 'string') {
  15497. return JSON.stringify(value);
  15498. }
  15499. if (typeof value === 'number') {
  15500. return getSimplifiedNumber(value);
  15501. }
  15502. return UnknownValue;
  15503. }
  15504. function getSimplifiedNumber(value) {
  15505. if (Object.is(-0, value)) {
  15506. return '-0';
  15507. }
  15508. const exp = value.toExponential();
  15509. const [base, exponent] = exp.split('e');
  15510. const floatLength = base.split('.')[1]?.length || 0;
  15511. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  15512. const stringifiedValue = String(value).replace('+', '');
  15513. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  15514. }
  15515. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  15516. class UpdateExpression extends NodeBase {
  15517. hasEffects(context) {
  15518. if (!this.deoptimized)
  15519. this.applyDeoptimizations();
  15520. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  15521. }
  15522. hasEffectsOnInteractionAtPath(path, { type }) {
  15523. return path.length > 1 || type !== INTERACTION_ACCESSED;
  15524. }
  15525. include(context, includeChildrenRecursively) {
  15526. if (!this.included)
  15527. this.includeNode(context);
  15528. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  15529. }
  15530. initialise() {
  15531. super.initialise();
  15532. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  15533. }
  15534. render(code, options) {
  15535. const { exportNamesByVariable, format, snippets: { _ } } = options;
  15536. this.argument.render(code, options);
  15537. if (format === 'system') {
  15538. const variable = this.argument.variable;
  15539. const exportNames = exportNamesByVariable.get(variable);
  15540. if (exportNames) {
  15541. if (this.prefix) {
  15542. if (exportNames.length === 1) {
  15543. renderSystemExportExpression(variable, this.start, this.end, code, options);
  15544. }
  15545. else {
  15546. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options);
  15547. }
  15548. }
  15549. else {
  15550. const operator = this.operator[0];
  15551. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options, `${_}${operator}${_}1`);
  15552. }
  15553. }
  15554. }
  15555. }
  15556. applyDeoptimizations() {
  15557. this.deoptimized = true;
  15558. this.argument.deoptimizePath(EMPTY_PATH);
  15559. if (this.argument instanceof Identifier) {
  15560. const variable = this.scope.findVariable(this.argument.name);
  15561. variable.markReassigned();
  15562. }
  15563. this.scope.context.requestTreeshakingPass();
  15564. }
  15565. }
  15566. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  15567. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  15568. for (const declarator of declarations) {
  15569. if (!declarator.id.included)
  15570. return false;
  15571. if (declarator.id.type === parseAst_js.Identifier) {
  15572. if (exportNamesByVariable.has(declarator.id.variable))
  15573. return false;
  15574. }
  15575. else {
  15576. const exportedVariables = [];
  15577. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  15578. if (exportedVariables.length > 0)
  15579. return false;
  15580. }
  15581. }
  15582. return true;
  15583. }
  15584. class VariableDeclaration extends NodeBase {
  15585. deoptimizePath() {
  15586. for (const declarator of this.declarations) {
  15587. declarator.deoptimizePath(EMPTY_PATH);
  15588. }
  15589. }
  15590. hasEffectsOnInteractionAtPath() {
  15591. return false;
  15592. }
  15593. include(context, includeChildrenRecursively, { asSingleStatement } = parseAst_js.BLANK) {
  15594. this.included = true;
  15595. for (const declarator of this.declarations) {
  15596. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  15597. declarator.include(context, includeChildrenRecursively);
  15598. }
  15599. const { id, init } = declarator;
  15600. if (asSingleStatement) {
  15601. id.include(context, includeChildrenRecursively);
  15602. }
  15603. if (init &&
  15604. id.included &&
  15605. !init.included &&
  15606. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  15607. init.include(context, includeChildrenRecursively);
  15608. }
  15609. }
  15610. }
  15611. initialise() {
  15612. super.initialise();
  15613. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  15614. for (const declarator of this.declarations) {
  15615. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  15616. }
  15617. }
  15618. removeAnnotations(code) {
  15619. this.declarations[0].removeAnnotations(code);
  15620. }
  15621. render(code, options, nodeRenderOptions = parseAst_js.BLANK) {
  15622. if (this.isUsingDeclaration ||
  15623. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  15624. for (const declarator of this.declarations) {
  15625. declarator.render(code, options);
  15626. }
  15627. if (!nodeRenderOptions.isNoStatement &&
  15628. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  15629. code.appendLeft(this.end, ';');
  15630. }
  15631. }
  15632. else {
  15633. this.renderReplacedDeclarations(code, options);
  15634. }
  15635. }
  15636. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  15637. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  15638. code.remove(this.end - 1, this.end);
  15639. }
  15640. separatorString += ';';
  15641. if (lastSeparatorPos === null) {
  15642. code.appendLeft(renderedContentEnd, separatorString);
  15643. }
  15644. else {
  15645. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  15646. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  15647. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  15648. actualContentEnd--;
  15649. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  15650. actualContentEnd--;
  15651. }
  15652. }
  15653. if (actualContentEnd === lastSeparatorPos + 1) {
  15654. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  15655. }
  15656. else {
  15657. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  15658. code.remove(actualContentEnd, renderedContentEnd);
  15659. }
  15660. }
  15661. if (systemPatternExports.length > 0) {
  15662. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  15663. }
  15664. }
  15665. renderReplacedDeclarations(code, options) {
  15666. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  15667. let actualContentEnd, renderedContentEnd;
  15668. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  15669. let lastSeparatorPos = renderedContentEnd - 1;
  15670. code.remove(this.start, lastSeparatorPos);
  15671. let isInDeclaration = false;
  15672. let hasRenderedContent = false;
  15673. let separatorString = '', leadingString, nextSeparatorString;
  15674. const aggregatedSystemExports = [];
  15675. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  15676. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  15677. if (!node.included) {
  15678. treeshakeNode(node, code, start, end);
  15679. continue;
  15680. }
  15681. node.render(code, options);
  15682. leadingString = '';
  15683. nextSeparatorString = '';
  15684. if (!node.id.included ||
  15685. (node.id instanceof Identifier &&
  15686. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  15687. if (hasRenderedContent) {
  15688. separatorString += ';';
  15689. }
  15690. isInDeclaration = false;
  15691. }
  15692. else {
  15693. if (singleSystemExport && singleSystemExport === node.id.variable) {
  15694. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  15695. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  15696. }
  15697. if (isInDeclaration) {
  15698. separatorString += ',';
  15699. }
  15700. else {
  15701. if (hasRenderedContent) {
  15702. separatorString += ';';
  15703. }
  15704. leadingString += `${this.kind} `;
  15705. isInDeclaration = true;
  15706. }
  15707. }
  15708. if (renderedContentEnd === lastSeparatorPos + 1) {
  15709. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  15710. }
  15711. else {
  15712. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  15713. code.appendLeft(renderedContentEnd, leadingString);
  15714. }
  15715. actualContentEnd = contentEnd;
  15716. renderedContentEnd = end;
  15717. hasRenderedContent = true;
  15718. lastSeparatorPos = separator;
  15719. separatorString = nextSeparatorString;
  15720. }
  15721. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  15722. }
  15723. }
  15724. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  15725. let singleSystemExport = null;
  15726. if (options.format === 'system') {
  15727. for (const { node } of separatedNodes) {
  15728. if (node.id instanceof Identifier &&
  15729. node.init &&
  15730. aggregatedSystemExports.length === 0 &&
  15731. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  15732. singleSystemExport = node.id.variable;
  15733. aggregatedSystemExports.push(singleSystemExport);
  15734. }
  15735. else {
  15736. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  15737. }
  15738. }
  15739. if (aggregatedSystemExports.length > 1) {
  15740. singleSystemExport = null;
  15741. }
  15742. else if (singleSystemExport) {
  15743. aggregatedSystemExports.length = 0;
  15744. }
  15745. }
  15746. return singleSystemExport;
  15747. }
  15748. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15749. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  15750. class WhileStatement extends NodeBase {
  15751. hasEffects(context) {
  15752. if (this.test.hasEffects(context))
  15753. return true;
  15754. return hasLoopBodyEffects(context, this.body);
  15755. }
  15756. include(context, includeChildrenRecursively) {
  15757. this.included = true;
  15758. this.test.include(context, includeChildrenRecursively);
  15759. includeLoopBody(context, this.body, includeChildrenRecursively);
  15760. }
  15761. }
  15762. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15763. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15764. class YieldExpression extends NodeBase {
  15765. applyDeoptimizations() {
  15766. this.deoptimized = true;
  15767. this.argument?.deoptimizePath(UNKNOWN_PATH);
  15768. }
  15769. hasEffects(context) {
  15770. if (!this.deoptimized)
  15771. this.applyDeoptimizations();
  15772. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  15773. }
  15774. includeNode(context) {
  15775. this.included = true;
  15776. if (!this.deoptimized)
  15777. this.applyDeoptimizations();
  15778. this.argument?.includePath(UNKNOWN_PATH, context);
  15779. }
  15780. render(code, options) {
  15781. if (this.argument) {
  15782. this.argument.render(code, options, { preventASI: true });
  15783. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  15784. code.prependLeft(this.start + 5, ' ');
  15785. }
  15786. }
  15787. }
  15788. }
  15789. // This file is generated by scripts/generate-buffer-parsers.js.
  15790. // Do not edit this file directly.
  15791. function convertProgram(buffer, parent, parentScope) {
  15792. return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
  15793. }
  15794. const nodeTypeStrings = [
  15795. 'PanicError',
  15796. 'ParseError',
  15797. 'ArrayExpression',
  15798. 'ArrayPattern',
  15799. 'ArrowFunctionExpression',
  15800. 'AssignmentExpression',
  15801. 'AssignmentPattern',
  15802. 'AwaitExpression',
  15803. 'BinaryExpression',
  15804. 'BlockStatement',
  15805. 'BreakStatement',
  15806. 'CallExpression',
  15807. 'CatchClause',
  15808. 'ChainExpression',
  15809. 'ClassBody',
  15810. 'ClassDeclaration',
  15811. 'ClassExpression',
  15812. 'ConditionalExpression',
  15813. 'ContinueStatement',
  15814. 'DebuggerStatement',
  15815. 'Decorator',
  15816. 'ExpressionStatement',
  15817. 'DoWhileStatement',
  15818. 'EmptyStatement',
  15819. 'ExportAllDeclaration',
  15820. 'ExportDefaultDeclaration',
  15821. 'ExportNamedDeclaration',
  15822. 'ExportSpecifier',
  15823. 'ExpressionStatement',
  15824. 'ForInStatement',
  15825. 'ForOfStatement',
  15826. 'ForStatement',
  15827. 'FunctionDeclaration',
  15828. 'FunctionExpression',
  15829. 'Identifier',
  15830. 'IfStatement',
  15831. 'ImportAttribute',
  15832. 'ImportDeclaration',
  15833. 'ImportDefaultSpecifier',
  15834. 'ImportExpression',
  15835. 'ImportNamespaceSpecifier',
  15836. 'ImportSpecifier',
  15837. 'JSXAttribute',
  15838. 'JSXClosingElement',
  15839. 'JSXClosingFragment',
  15840. 'JSXElement',
  15841. 'JSXEmptyExpression',
  15842. 'JSXExpressionContainer',
  15843. 'JSXFragment',
  15844. 'JSXIdentifier',
  15845. 'JSXMemberExpression',
  15846. 'JSXNamespacedName',
  15847. 'JSXOpeningElement',
  15848. 'JSXOpeningFragment',
  15849. 'JSXSpreadAttribute',
  15850. 'JSXSpreadChild',
  15851. 'JSXText',
  15852. 'LabeledStatement',
  15853. 'Literal',
  15854. 'Literal',
  15855. 'Literal',
  15856. 'Literal',
  15857. 'Literal',
  15858. 'Literal',
  15859. 'LogicalExpression',
  15860. 'MemberExpression',
  15861. 'MetaProperty',
  15862. 'MethodDefinition',
  15863. 'NewExpression',
  15864. 'ObjectExpression',
  15865. 'ObjectPattern',
  15866. 'PrivateIdentifier',
  15867. 'Program',
  15868. 'Property',
  15869. 'PropertyDefinition',
  15870. 'RestElement',
  15871. 'ReturnStatement',
  15872. 'SequenceExpression',
  15873. 'SpreadElement',
  15874. 'StaticBlock',
  15875. 'Super',
  15876. 'SwitchCase',
  15877. 'SwitchStatement',
  15878. 'TaggedTemplateExpression',
  15879. 'TemplateElement',
  15880. 'TemplateLiteral',
  15881. 'ThisExpression',
  15882. 'ThrowStatement',
  15883. 'TryStatement',
  15884. 'UnaryExpression',
  15885. 'UpdateExpression',
  15886. 'VariableDeclaration',
  15887. 'VariableDeclarator',
  15888. 'WhileStatement',
  15889. 'YieldExpression'
  15890. ];
  15891. const nodeConstructors$1 = [
  15892. PanicError,
  15893. ParseError,
  15894. ArrayExpression,
  15895. ArrayPattern,
  15896. ArrowFunctionExpression,
  15897. AssignmentExpression,
  15898. AssignmentPattern,
  15899. AwaitExpression,
  15900. BinaryExpression,
  15901. BlockStatement,
  15902. BreakStatement,
  15903. CallExpression,
  15904. CatchClause,
  15905. ChainExpression,
  15906. ClassBody,
  15907. ClassDeclaration,
  15908. ClassExpression,
  15909. ConditionalExpression,
  15910. ContinueStatement,
  15911. DebuggerStatement,
  15912. Decorator,
  15913. ExpressionStatement,
  15914. DoWhileStatement,
  15915. EmptyStatement,
  15916. ExportAllDeclaration,
  15917. ExportDefaultDeclaration,
  15918. ExportNamedDeclaration,
  15919. ExportSpecifier,
  15920. ExpressionStatement,
  15921. ForInStatement,
  15922. ForOfStatement,
  15923. ForStatement,
  15924. FunctionDeclaration,
  15925. FunctionExpression,
  15926. Identifier,
  15927. IfStatement,
  15928. ImportAttribute,
  15929. ImportDeclaration,
  15930. ImportDefaultSpecifier,
  15931. ImportExpression,
  15932. ImportNamespaceSpecifier,
  15933. ImportSpecifier,
  15934. JSXAttribute,
  15935. JSXClosingElement,
  15936. JSXClosingFragment,
  15937. JSXElement,
  15938. JSXEmptyExpression,
  15939. JSXExpressionContainer,
  15940. JSXFragment,
  15941. JSXIdentifier,
  15942. JSXMemberExpression,
  15943. JSXNamespacedName,
  15944. JSXOpeningElement,
  15945. JSXOpeningFragment,
  15946. JSXSpreadAttribute,
  15947. JSXSpreadChild,
  15948. JSXText,
  15949. LabeledStatement,
  15950. Literal,
  15951. Literal,
  15952. Literal,
  15953. Literal,
  15954. Literal,
  15955. Literal,
  15956. LogicalExpression,
  15957. MemberExpression,
  15958. MetaProperty,
  15959. MethodDefinition,
  15960. NewExpression,
  15961. ObjectExpression,
  15962. ObjectPattern,
  15963. PrivateIdentifier,
  15964. Program,
  15965. Property,
  15966. PropertyDefinition,
  15967. RestElement,
  15968. ReturnStatement,
  15969. SequenceExpression,
  15970. SpreadElement,
  15971. StaticBlock,
  15972. Super,
  15973. SwitchCase,
  15974. SwitchStatement,
  15975. TaggedTemplateExpression,
  15976. TemplateElement,
  15977. TemplateLiteral,
  15978. ThisExpression,
  15979. ThrowStatement,
  15980. TryStatement,
  15981. UnaryExpression,
  15982. UpdateExpression,
  15983. VariableDeclaration,
  15984. VariableDeclarator,
  15985. WhileStatement,
  15986. YieldExpression
  15987. ];
  15988. const bufferParsers = [
  15989. function panicError(node, position, buffer) {
  15990. node.message = buffer.convertString(buffer[position]);
  15991. },
  15992. function parseError(node, position, buffer) {
  15993. node.message = buffer.convertString(buffer[position]);
  15994. },
  15995. function arrayExpression(node, position, buffer) {
  15996. const { scope } = node;
  15997. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  15998. },
  15999. function arrayPattern(node, position, buffer) {
  16000. const { scope } = node;
  16001. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  16002. },
  16003. function arrowFunctionExpression(node, position, buffer) {
  16004. const { scope } = node;
  16005. const flags = buffer[position];
  16006. node.async = (flags & 1) === 1;
  16007. node.expression = (flags & 2) === 2;
  16008. node.generator = (flags & 4) === 4;
  16009. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16010. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16011. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  16012. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16013. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  16014. },
  16015. function assignmentExpression(node, position, buffer) {
  16016. const { scope } = node;
  16017. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16018. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16019. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16020. },
  16021. function assignmentPattern(node, position, buffer) {
  16022. const { scope } = node;
  16023. node.left = convertNode(node, scope, buffer[position], buffer);
  16024. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16025. },
  16026. function awaitExpression(node, position, buffer) {
  16027. const { scope } = node;
  16028. node.argument = convertNode(node, scope, buffer[position], buffer);
  16029. },
  16030. function binaryExpression(node, position, buffer) {
  16031. const { scope } = node;
  16032. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16033. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16034. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16035. },
  16036. function blockStatement(node, position, buffer) {
  16037. const { scope } = node;
  16038. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16039. },
  16040. function breakStatement(node, position, buffer) {
  16041. const { scope } = node;
  16042. const labelPosition = buffer[position];
  16043. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16044. },
  16045. function callExpression(node, position, buffer) {
  16046. const { scope } = node;
  16047. const flags = buffer[position];
  16048. node.optional = (flags & 1) === 1;
  16049. node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16050. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  16051. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  16052. },
  16053. function catchClause(node, position, buffer) {
  16054. const { scope } = node;
  16055. const parameterPosition = buffer[position];
  16056. const parameter = (node.param =
  16057. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  16058. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  16059. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  16060. },
  16061. function chainExpression(node, position, buffer) {
  16062. const { scope } = node;
  16063. node.expression = convertNode(node, scope, buffer[position], buffer);
  16064. },
  16065. function classBody(node, position, buffer) {
  16066. const { scope } = node;
  16067. const bodyPosition = buffer[position];
  16068. if (bodyPosition) {
  16069. const length = buffer[bodyPosition];
  16070. const body = (node.body = new Array(length));
  16071. for (let index = 0; index < length; index++) {
  16072. const nodePosition = buffer[bodyPosition + 1 + index];
  16073. body[index] = convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer);
  16074. }
  16075. }
  16076. else {
  16077. node.body = [];
  16078. }
  16079. },
  16080. function classDeclaration(node, position, buffer) {
  16081. const { scope } = node;
  16082. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16083. const idPosition = buffer[position + 1];
  16084. node.id =
  16085. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16086. const superClassPosition = buffer[position + 2];
  16087. node.superClass =
  16088. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16089. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16090. },
  16091. function classExpression(node, position, buffer) {
  16092. const { scope } = node;
  16093. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  16094. const idPosition = buffer[position + 1];
  16095. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  16096. const superClassPosition = buffer[position + 2];
  16097. node.superClass =
  16098. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  16099. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16100. },
  16101. function conditionalExpression(node, position, buffer) {
  16102. const { scope } = node;
  16103. node.test = convertNode(node, scope, buffer[position], buffer);
  16104. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  16105. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  16106. },
  16107. function continueStatement(node, position, buffer) {
  16108. const { scope } = node;
  16109. const labelPosition = buffer[position];
  16110. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  16111. },
  16112. function debuggerStatement() { },
  16113. function decorator(node, position, buffer) {
  16114. const { scope } = node;
  16115. node.expression = convertNode(node, scope, buffer[position], buffer);
  16116. },
  16117. function directive(node, position, buffer) {
  16118. const { scope } = node;
  16119. node.directive = buffer.convertString(buffer[position]);
  16120. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  16121. },
  16122. function doWhileStatement(node, position, buffer) {
  16123. const { scope } = node;
  16124. node.body = convertNode(node, scope, buffer[position], buffer);
  16125. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  16126. },
  16127. function emptyStatement() { },
  16128. function exportAllDeclaration(node, position, buffer) {
  16129. const { scope } = node;
  16130. const exportedPosition = buffer[position];
  16131. node.exported =
  16132. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  16133. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16134. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16135. },
  16136. function exportDefaultDeclaration(node, position, buffer) {
  16137. const { scope } = node;
  16138. node.declaration = convertNode(node, scope, buffer[position], buffer);
  16139. },
  16140. function exportNamedDeclaration(node, position, buffer) {
  16141. const { scope } = node;
  16142. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16143. const sourcePosition = buffer[position + 1];
  16144. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  16145. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16146. const declarationPosition = buffer[position + 3];
  16147. node.declaration =
  16148. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  16149. },
  16150. function exportSpecifier(node, position, buffer) {
  16151. const { scope } = node;
  16152. node.local = convertNode(node, scope, buffer[position], buffer);
  16153. const exportedPosition = buffer[position + 1];
  16154. node.exported =
  16155. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  16156. },
  16157. function expressionStatement(node, position, buffer) {
  16158. const { scope } = node;
  16159. node.expression = convertNode(node, scope, buffer[position], buffer);
  16160. },
  16161. function forInStatement(node, position, buffer) {
  16162. const { scope } = node;
  16163. node.left = convertNode(node, scope, buffer[position], buffer);
  16164. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  16165. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  16166. },
  16167. function forOfStatement(node, position, buffer) {
  16168. const { scope } = node;
  16169. const flags = buffer[position];
  16170. node.await = (flags & 1) === 1;
  16171. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16172. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16173. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16174. },
  16175. function forStatement(node, position, buffer) {
  16176. const { scope } = node;
  16177. const initPosition = buffer[position];
  16178. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16179. const testPosition = buffer[position + 1];
  16180. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16181. const updatePosition = buffer[position + 2];
  16182. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  16183. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  16184. },
  16185. function functionDeclaration(node, position, buffer) {
  16186. const { scope } = node;
  16187. const flags = buffer[position];
  16188. node.async = (flags & 1) === 1;
  16189. node.generator = (flags & 2) === 2;
  16190. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16191. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16192. const idPosition = buffer[position + 2];
  16193. node.id =
  16194. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  16195. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16196. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16197. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16198. },
  16199. function functionExpression(node, position, buffer) {
  16200. const { scope } = node;
  16201. const flags = buffer[position];
  16202. node.async = (flags & 1) === 1;
  16203. node.generator = (flags & 2) === 2;
  16204. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  16205. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  16206. const idPosition = buffer[position + 2];
  16207. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  16208. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  16209. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  16210. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  16211. },
  16212. function identifier(node, position, buffer) {
  16213. node.name = buffer.convertString(buffer[position]);
  16214. },
  16215. function ifStatement(node, position, buffer) {
  16216. const { scope } = node;
  16217. node.test = convertNode(node, scope, buffer[position], buffer);
  16218. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  16219. const alternatePosition = buffer[position + 2];
  16220. node.alternate =
  16221. alternatePosition === 0
  16222. ? null
  16223. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  16224. },
  16225. function importAttribute(node, position, buffer) {
  16226. const { scope } = node;
  16227. node.key = convertNode(node, scope, buffer[position], buffer);
  16228. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  16229. },
  16230. function importDeclaration(node, position, buffer) {
  16231. const { scope } = node;
  16232. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  16233. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  16234. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16235. },
  16236. function importDefaultSpecifier(node, position, buffer) {
  16237. const { scope } = node;
  16238. node.local = convertNode(node, scope, buffer[position], buffer);
  16239. },
  16240. function importExpression(node, position, buffer) {
  16241. const { scope } = node;
  16242. node.source = convertNode(node, scope, buffer[position], buffer);
  16243. node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
  16244. const optionsPosition = buffer[position + 1];
  16245. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  16246. },
  16247. function importNamespaceSpecifier(node, position, buffer) {
  16248. const { scope } = node;
  16249. node.local = convertNode(node, scope, buffer[position], buffer);
  16250. },
  16251. function importSpecifier(node, position, buffer) {
  16252. const { scope } = node;
  16253. const importedPosition = buffer[position];
  16254. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  16255. node.imported =
  16256. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  16257. },
  16258. function jsxAttribute(node, position, buffer) {
  16259. const { scope } = node;
  16260. node.name = convertNode(node, scope, buffer[position], buffer);
  16261. const valuePosition = buffer[position + 1];
  16262. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16263. },
  16264. function jsxClosingElement(node, position, buffer) {
  16265. const { scope } = node;
  16266. node.name = convertNode(node, scope, buffer[position], buffer);
  16267. },
  16268. function jsxClosingFragment() { },
  16269. function jsxElement(node, position, buffer) {
  16270. const { scope } = node;
  16271. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  16272. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16273. const closingElementPosition = buffer[position + 2];
  16274. node.closingElement =
  16275. closingElementPosition === 0
  16276. ? null
  16277. : convertNode(node, scope, closingElementPosition, buffer);
  16278. },
  16279. function jsxEmptyExpression() { },
  16280. function jsxExpressionContainer(node, position, buffer) {
  16281. const { scope } = node;
  16282. node.expression = convertNode(node, scope, buffer[position], buffer);
  16283. },
  16284. function jsxFragment(node, position, buffer) {
  16285. const { scope } = node;
  16286. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  16287. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  16288. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  16289. },
  16290. function jsxIdentifier(node, position, buffer) {
  16291. node.name = buffer.convertString(buffer[position]);
  16292. },
  16293. function jsxMemberExpression(node, position, buffer) {
  16294. const { scope } = node;
  16295. node.object = convertNode(node, scope, buffer[position], buffer);
  16296. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16297. },
  16298. function jsxNamespacedName(node, position, buffer) {
  16299. const { scope } = node;
  16300. node.namespace = convertNode(node, scope, buffer[position], buffer);
  16301. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16302. },
  16303. function jsxOpeningElement(node, position, buffer) {
  16304. const { scope } = node;
  16305. const flags = buffer[position];
  16306. node.selfClosing = (flags & 1) === 1;
  16307. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  16308. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  16309. },
  16310. function jsxOpeningFragment(node) {
  16311. node.attributes = [];
  16312. node.selfClosing = false;
  16313. },
  16314. function jsxSpreadAttribute(node, position, buffer) {
  16315. const { scope } = node;
  16316. node.argument = convertNode(node, scope, buffer[position], buffer);
  16317. },
  16318. function jsxSpreadChild(node, position, buffer) {
  16319. const { scope } = node;
  16320. node.expression = convertNode(node, scope, buffer[position], buffer);
  16321. },
  16322. function jsxText(node, position, buffer) {
  16323. node.value = buffer.convertString(buffer[position]);
  16324. node.raw = buffer.convertString(buffer[position + 1]);
  16325. },
  16326. function labeledStatement(node, position, buffer) {
  16327. const { scope } = node;
  16328. node.label = convertNode(node, scope, buffer[position], buffer);
  16329. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16330. },
  16331. function literalBigInt(node, position, buffer) {
  16332. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  16333. node.raw = buffer.convertString(buffer[position + 1]);
  16334. node.value = BigInt(bigint);
  16335. },
  16336. function literalBoolean(node, position, buffer) {
  16337. const flags = buffer[position];
  16338. const value = (node.value = (flags & 1) === 1);
  16339. node.raw = value ? 'true' : 'false';
  16340. },
  16341. function literalNull(node) {
  16342. node.value = null;
  16343. },
  16344. function literalNumber(node, position, buffer) {
  16345. const rawPosition = buffer[position];
  16346. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16347. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  16348. },
  16349. function literalRegExp(node, position, buffer) {
  16350. const flags = buffer.convertString(buffer[position]);
  16351. const pattern = buffer.convertString(buffer[position + 1]);
  16352. node.raw = `/${pattern}/${flags}`;
  16353. node.regex = { flags, pattern };
  16354. node.value = new RegExp(pattern, flags);
  16355. },
  16356. function literalString(node, position, buffer) {
  16357. node.value = buffer.convertString(buffer[position]);
  16358. const rawPosition = buffer[position + 1];
  16359. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  16360. },
  16361. function logicalExpression(node, position, buffer) {
  16362. const { scope } = node;
  16363. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16364. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  16365. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  16366. },
  16367. function memberExpression(node, position, buffer) {
  16368. const { scope } = node;
  16369. const flags = buffer[position];
  16370. node.computed = (flags & 1) === 1;
  16371. node.optional = (flags & 2) === 2;
  16372. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  16373. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  16374. },
  16375. function metaProperty(node, position, buffer) {
  16376. const { scope } = node;
  16377. node.meta = convertNode(node, scope, buffer[position], buffer);
  16378. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  16379. },
  16380. function methodDefinition(node, position, buffer) {
  16381. const { scope } = node;
  16382. const flags = buffer[position];
  16383. node.static = (flags & 1) === 1;
  16384. node.computed = (flags & 2) === 2;
  16385. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16386. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16387. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  16388. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 4]];
  16389. },
  16390. function newExpression(node, position, buffer) {
  16391. const { scope } = node;
  16392. node.annotations = parseAst_js.convertAnnotations(buffer[position], buffer);
  16393. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  16394. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  16395. },
  16396. function objectExpression(node, position, buffer) {
  16397. const { scope } = node;
  16398. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16399. },
  16400. function objectPattern(node, position, buffer) {
  16401. const { scope } = node;
  16402. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  16403. },
  16404. function privateIdentifier(node, position, buffer) {
  16405. node.name = buffer.convertString(buffer[position]);
  16406. },
  16407. function program(node, position, buffer) {
  16408. const { scope } = node;
  16409. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16410. node.invalidAnnotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  16411. },
  16412. function property(node, position, buffer) {
  16413. const { scope } = node;
  16414. const flags = buffer[position];
  16415. node.method = (flags & 1) === 1;
  16416. node.shorthand = (flags & 2) === 2;
  16417. node.computed = (flags & 4) === 4;
  16418. const keyPosition = buffer[position + 1];
  16419. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  16420. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 3]];
  16421. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  16422. },
  16423. function propertyDefinition(node, position, buffer) {
  16424. const { scope } = node;
  16425. const flags = buffer[position];
  16426. node.static = (flags & 1) === 1;
  16427. node.computed = (flags & 2) === 2;
  16428. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  16429. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  16430. const valuePosition = buffer[position + 3];
  16431. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  16432. },
  16433. function restElement(node, position, buffer) {
  16434. const { scope } = node;
  16435. node.argument = convertNode(node, scope, buffer[position], buffer);
  16436. },
  16437. function returnStatement(node, position, buffer) {
  16438. const { scope } = node;
  16439. const argumentPosition = buffer[position];
  16440. node.argument =
  16441. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16442. },
  16443. function sequenceExpression(node, position, buffer) {
  16444. const { scope } = node;
  16445. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  16446. },
  16447. function spreadElement(node, position, buffer) {
  16448. const { scope } = node;
  16449. node.argument = convertNode(node, scope, buffer[position], buffer);
  16450. },
  16451. function staticBlock(node, position, buffer) {
  16452. const { scope } = node;
  16453. node.body = convertNodeList(node, scope, buffer[position], buffer);
  16454. },
  16455. function superElement() { },
  16456. function switchCase(node, position, buffer) {
  16457. const { scope } = node;
  16458. const testPosition = buffer[position];
  16459. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  16460. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  16461. },
  16462. function switchStatement(node, position, buffer) {
  16463. const { scope } = node;
  16464. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  16465. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  16466. },
  16467. function taggedTemplateExpression(node, position, buffer) {
  16468. const { scope } = node;
  16469. node.tag = convertNode(node, scope, buffer[position], buffer);
  16470. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  16471. },
  16472. function templateElement(node, position, buffer) {
  16473. const flags = buffer[position];
  16474. node.tail = (flags & 1) === 1;
  16475. const cookedPosition = buffer[position + 1];
  16476. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  16477. const raw = buffer.convertString(buffer[position + 2]);
  16478. node.value = { cooked, raw };
  16479. },
  16480. function templateLiteral(node, position, buffer) {
  16481. const { scope } = node;
  16482. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  16483. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  16484. },
  16485. function thisExpression() { },
  16486. function throwStatement(node, position, buffer) {
  16487. const { scope } = node;
  16488. node.argument = convertNode(node, scope, buffer[position], buffer);
  16489. },
  16490. function tryStatement(node, position, buffer) {
  16491. const { scope } = node;
  16492. node.block = convertNode(node, scope, buffer[position], buffer);
  16493. const handlerPosition = buffer[position + 1];
  16494. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  16495. const finalizerPosition = buffer[position + 2];
  16496. node.finalizer =
  16497. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  16498. },
  16499. function unaryExpression(node, position, buffer) {
  16500. const { scope } = node;
  16501. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  16502. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  16503. },
  16504. function updateExpression(node, position, buffer) {
  16505. const { scope } = node;
  16506. const flags = buffer[position];
  16507. node.prefix = (flags & 1) === 1;
  16508. node.operator = parseAst_js.FIXED_STRINGS[buffer[position + 1]];
  16509. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  16510. },
  16511. function variableDeclaration(node, position, buffer) {
  16512. const { scope } = node;
  16513. node.kind = parseAst_js.FIXED_STRINGS[buffer[position]];
  16514. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  16515. },
  16516. function variableDeclarator(node, position, buffer) {
  16517. const { scope } = node;
  16518. node.id = convertNode(node, scope, buffer[position], buffer);
  16519. const initPosition = buffer[position + 1];
  16520. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  16521. },
  16522. function whileStatement(node, position, buffer) {
  16523. const { scope } = node;
  16524. node.test = convertNode(node, scope, buffer[position], buffer);
  16525. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  16526. },
  16527. function yieldExpression(node, position, buffer) {
  16528. const { scope } = node;
  16529. const flags = buffer[position];
  16530. node.delegate = (flags & 1) === 1;
  16531. const argumentPosition = buffer[position + 1];
  16532. node.argument =
  16533. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  16534. }
  16535. ];
  16536. function convertNode(parent, parentScope, position, buffer) {
  16537. const nodeType = buffer[position];
  16538. const NodeConstructor = nodeConstructors$1[nodeType];
  16539. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  16540. if (!NodeConstructor) {
  16541. console.trace();
  16542. throw new Error(`Unknown node type: ${nodeType}`);
  16543. }
  16544. const node = new NodeConstructor(parent, parentScope);
  16545. node.type = nodeTypeStrings[nodeType];
  16546. node.start = buffer[position + 1];
  16547. node.end = buffer[position + 2];
  16548. bufferParsers[nodeType](node, position + 3, buffer);
  16549. node.initialise();
  16550. return node;
  16551. }
  16552. function convertNodeList(parent, parentScope, position, buffer) {
  16553. if (position === 0)
  16554. return parseAst_js.EMPTY_ARRAY;
  16555. const length = buffer[position++];
  16556. const list = new Array(length);
  16557. for (let index = 0; index < length; index++) {
  16558. const nodePosition = buffer[position++];
  16559. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  16560. }
  16561. return list;
  16562. }
  16563. class UnknownNode extends NodeBase {
  16564. hasEffects() {
  16565. return true;
  16566. }
  16567. include(context) {
  16568. super.include(context, true);
  16569. }
  16570. }
  16571. // This file is generated by scripts/generate-node-index.js.
  16572. // Do not edit this file directly.
  16573. const nodeConstructors = {
  16574. ArrayExpression,
  16575. ArrayPattern,
  16576. ArrowFunctionExpression,
  16577. AssignmentExpression,
  16578. AssignmentPattern,
  16579. AwaitExpression,
  16580. BinaryExpression,
  16581. BlockStatement,
  16582. BreakStatement,
  16583. CallExpression,
  16584. CatchClause,
  16585. ChainExpression,
  16586. ClassBody,
  16587. ClassDeclaration,
  16588. ClassExpression,
  16589. ConditionalExpression,
  16590. ContinueStatement,
  16591. DebuggerStatement,
  16592. Decorator,
  16593. DoWhileStatement,
  16594. EmptyStatement,
  16595. ExportAllDeclaration,
  16596. ExportDefaultDeclaration,
  16597. ExportNamedDeclaration,
  16598. ExportSpecifier,
  16599. ExpressionStatement,
  16600. ForInStatement,
  16601. ForOfStatement,
  16602. ForStatement,
  16603. FunctionDeclaration,
  16604. FunctionExpression,
  16605. Identifier,
  16606. IfStatement,
  16607. ImportAttribute,
  16608. ImportDeclaration,
  16609. ImportDefaultSpecifier,
  16610. ImportExpression,
  16611. ImportNamespaceSpecifier,
  16612. ImportSpecifier,
  16613. JSXAttribute,
  16614. JSXClosingElement,
  16615. JSXClosingFragment,
  16616. JSXElement,
  16617. JSXEmptyExpression,
  16618. JSXExpressionContainer,
  16619. JSXFragment,
  16620. JSXIdentifier,
  16621. JSXMemberExpression,
  16622. JSXNamespacedName,
  16623. JSXOpeningElement,
  16624. JSXOpeningFragment,
  16625. JSXSpreadAttribute,
  16626. JSXSpreadChild,
  16627. JSXText,
  16628. LabeledStatement,
  16629. Literal,
  16630. LogicalExpression,
  16631. MemberExpression,
  16632. MetaProperty,
  16633. MethodDefinition,
  16634. NewExpression,
  16635. ObjectExpression,
  16636. ObjectPattern,
  16637. PanicError,
  16638. ParseError,
  16639. PrivateIdentifier,
  16640. Program,
  16641. Property,
  16642. PropertyDefinition,
  16643. RestElement,
  16644. ReturnStatement,
  16645. SequenceExpression,
  16646. SpreadElement,
  16647. StaticBlock,
  16648. Super,
  16649. SwitchCase,
  16650. SwitchStatement,
  16651. TaggedTemplateExpression,
  16652. TemplateElement,
  16653. TemplateLiteral,
  16654. ThisExpression,
  16655. ThrowStatement,
  16656. TryStatement,
  16657. UnaryExpression,
  16658. UnknownNode,
  16659. UpdateExpression,
  16660. VariableDeclaration,
  16661. VariableDeclarator,
  16662. WhileStatement,
  16663. YieldExpression
  16664. };
  16665. class ExportShimVariable extends Variable {
  16666. constructor(module) {
  16667. super(MISSING_EXPORT_SHIM_VARIABLE);
  16668. this.module = module;
  16669. }
  16670. includePath(path, context) {
  16671. super.includePath(path, context);
  16672. this.module.needsExportShim = true;
  16673. }
  16674. }
  16675. const sourceMapCache = new WeakMap();
  16676. /**
  16677. * This clears the decoded array and falls back to the encoded string form.
  16678. * Sourcemap mappings arrays can be very large and holding on to them for longer
  16679. * than is necessary leads to poor heap utilization.
  16680. */
  16681. function resetCacheToEncoded(cache) {
  16682. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  16683. cache.encodedMappings = encode(cache.decodedMappings);
  16684. }
  16685. cache.decodedMappings = undefined;
  16686. }
  16687. function resetSourcemapCache(map, sourcemapChain) {
  16688. if (map) {
  16689. const cache = sourceMapCache.get(map);
  16690. if (cache) {
  16691. resetCacheToEncoded(cache);
  16692. }
  16693. }
  16694. if (!sourcemapChain) {
  16695. return;
  16696. }
  16697. for (const map of sourcemapChain) {
  16698. if (map.missing)
  16699. continue;
  16700. resetSourcemapCache(map);
  16701. }
  16702. }
  16703. function decodedSourcemap(map) {
  16704. if (!map)
  16705. return null;
  16706. if (typeof map === 'string') {
  16707. map = JSON.parse(map);
  16708. }
  16709. if (!map.mappings) {
  16710. return {
  16711. mappings: [],
  16712. names: [],
  16713. sources: [],
  16714. version: 3
  16715. };
  16716. }
  16717. const originalMappings = map.mappings;
  16718. const isAlreadyDecoded = Array.isArray(originalMappings);
  16719. const cache = {
  16720. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  16721. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  16722. };
  16723. const decodedMap = {
  16724. ...map,
  16725. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  16726. // where the mappings field is never actually accessed. This appears to greatly reduce
  16727. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  16728. get mappings() {
  16729. if (cache.decodedMappings) {
  16730. return cache.decodedMappings;
  16731. }
  16732. // If decodedMappings doesn't exist then encodedMappings should.
  16733. // The only scenario where cache.encodedMappings should be undefined is if the map
  16734. // this was constructed from was already decoded, or if mappings was set to a new
  16735. // decoded string. In either case, this line shouldn't get hit.
  16736. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  16737. cache.encodedMappings = undefined;
  16738. return cache.decodedMappings;
  16739. }
  16740. };
  16741. sourceMapCache.set(decodedMap, cache);
  16742. return decodedMap;
  16743. }
  16744. function getId(m) {
  16745. return m.id;
  16746. }
  16747. function getOriginalLocation(sourcemapChain, location) {
  16748. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  16749. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  16750. const sourcemap = filteredSourcemapChain.pop();
  16751. const line = sourcemap.mappings[location.line - 1];
  16752. if (line) {
  16753. const filteredLine = line.filter((segment) => segment.length > 1);
  16754. const lastSegment = filteredLine[filteredLine.length - 1];
  16755. for (const segment of filteredLine) {
  16756. if (segment[0] >= location.column || segment === lastSegment) {
  16757. location = {
  16758. column: segment[3],
  16759. line: segment[2] + 1
  16760. };
  16761. continue traceSourcemap;
  16762. }
  16763. }
  16764. }
  16765. throw new Error("Can't resolve original location of error.");
  16766. }
  16767. return location;
  16768. }
  16769. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  16770. function getAttributesFromImportExpression(node) {
  16771. const { scope: { context }, options, start } = node;
  16772. if (!(options instanceof ObjectExpression)) {
  16773. if (options) {
  16774. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), start);
  16775. }
  16776. return parseAst_js.EMPTY_OBJECT;
  16777. }
  16778. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  16779. if (!assertProperty) {
  16780. return parseAst_js.EMPTY_OBJECT;
  16781. }
  16782. if (!(assertProperty instanceof ObjectExpression)) {
  16783. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportOptionsAreInvalid(context.module.id), start);
  16784. return parseAst_js.EMPTY_OBJECT;
  16785. }
  16786. const assertFields = assertProperty.properties
  16787. .map(property => {
  16788. const key = getPropertyKey(property);
  16789. if (typeof key === 'string' &&
  16790. typeof property.value.value === 'string') {
  16791. return [key, property.value.value];
  16792. }
  16793. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), property.start);
  16794. return null;
  16795. })
  16796. .filter((property) => !!property);
  16797. if (assertFields.length > 0) {
  16798. return Object.fromEntries(assertFields);
  16799. }
  16800. return parseAst_js.EMPTY_OBJECT;
  16801. }
  16802. const getPropertyKey = (property) => {
  16803. const key = property.key;
  16804. return (key &&
  16805. !property.computed &&
  16806. (key.name || key.value));
  16807. };
  16808. function getAttributesFromImportExportDeclaration(attributes) {
  16809. return attributes?.length
  16810. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  16811. : parseAst_js.EMPTY_OBJECT;
  16812. }
  16813. function doAttributesDiffer(assertionA, assertionB) {
  16814. const keysA = Object.keys(assertionA);
  16815. return (keysA.length !== Object.keys(assertionB).length ||
  16816. keysA.some(key => assertionA[key] !== assertionB[key]));
  16817. }
  16818. let timers = new Map();
  16819. function getPersistedLabel(label, level) {
  16820. switch (level) {
  16821. case 1: {
  16822. return `# ${label}`;
  16823. }
  16824. case 2: {
  16825. return `## ${label}`;
  16826. }
  16827. case 3: {
  16828. return label;
  16829. }
  16830. default: {
  16831. return `- ${label}`;
  16832. }
  16833. }
  16834. }
  16835. function timeStartImpl(label, level = 3) {
  16836. label = getPersistedLabel(label, level);
  16837. const startMemory = process$1.memoryUsage().heapUsed;
  16838. const startTime = node_perf_hooks.performance.now();
  16839. const timer = timers.get(label);
  16840. if (timer === undefined) {
  16841. timers.set(label, {
  16842. memory: 0,
  16843. startMemory,
  16844. startTime,
  16845. time: 0,
  16846. totalMemory: 0
  16847. });
  16848. }
  16849. else {
  16850. timer.startMemory = startMemory;
  16851. timer.startTime = startTime;
  16852. }
  16853. }
  16854. function timeEndImpl(label, level = 3) {
  16855. label = getPersistedLabel(label, level);
  16856. const timer = timers.get(label);
  16857. if (timer !== undefined) {
  16858. const currentMemory = process$1.memoryUsage().heapUsed;
  16859. timer.memory += currentMemory - timer.startMemory;
  16860. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  16861. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  16862. }
  16863. }
  16864. function getTimings() {
  16865. const newTimings = {};
  16866. for (const [label, { memory, time, totalMemory }] of timers) {
  16867. newTimings[label] = [time, memory, totalMemory];
  16868. }
  16869. return newTimings;
  16870. }
  16871. let timeStart = doNothing;
  16872. let timeEnd = doNothing;
  16873. const TIMED_PLUGIN_HOOKS = [
  16874. 'augmentChunkHash',
  16875. 'buildEnd',
  16876. 'buildStart',
  16877. 'generateBundle',
  16878. 'load',
  16879. 'moduleParsed',
  16880. 'options',
  16881. 'outputOptions',
  16882. 'renderChunk',
  16883. 'renderDynamicImport',
  16884. 'renderStart',
  16885. 'resolveDynamicImport',
  16886. 'resolveFileUrl',
  16887. 'resolveId',
  16888. 'resolveImportMeta',
  16889. 'shouldTransformCachedModule',
  16890. 'transform',
  16891. 'writeBundle'
  16892. ];
  16893. function getPluginWithTimers(plugin, index) {
  16894. if (plugin._hasTimer)
  16895. return plugin;
  16896. plugin._hasTimer = true;
  16897. for (const hook of TIMED_PLUGIN_HOOKS) {
  16898. if (hook in plugin) {
  16899. let timerLabel = `plugin ${index}`;
  16900. if (plugin.name) {
  16901. timerLabel += ` (${plugin.name})`;
  16902. }
  16903. timerLabel += ` - ${hook}`;
  16904. const handler = function (...parameters) {
  16905. timeStart(timerLabel, 4);
  16906. const result = hookFunction.apply(this, parameters);
  16907. timeEnd(timerLabel, 4);
  16908. return result;
  16909. };
  16910. let hookFunction;
  16911. if (typeof plugin[hook].handler === 'function') {
  16912. hookFunction = plugin[hook].handler;
  16913. plugin[hook].handler = handler;
  16914. }
  16915. else {
  16916. hookFunction = plugin[hook];
  16917. plugin[hook] = handler;
  16918. }
  16919. }
  16920. }
  16921. return plugin;
  16922. }
  16923. function initialiseTimers(inputOptions) {
  16924. if (inputOptions.perf) {
  16925. timers = new Map();
  16926. timeStart = timeStartImpl;
  16927. timeEnd = timeEndImpl;
  16928. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  16929. }
  16930. else {
  16931. timeStart = doNothing;
  16932. timeEnd = doNothing;
  16933. }
  16934. }
  16935. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  16936. identifier: null,
  16937. localName: MISSING_EXPORT_SHIM_VARIABLE
  16938. };
  16939. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  16940. const searchedModules = searchedNamesAndModules.get(name);
  16941. if (searchedModules) {
  16942. if (searchedModules.has(target)) {
  16943. return isExportAllSearch ? [null] : parseAst_js.error(parseAst_js.logCircularReexport(name, target.id));
  16944. }
  16945. searchedModules.add(target);
  16946. }
  16947. else {
  16948. searchedNamesAndModules.set(name, new Set([target]));
  16949. }
  16950. return target.getVariableForExportName(name, {
  16951. importerForSideEffects,
  16952. isExportAllSearch,
  16953. searchedNamesAndModules
  16954. });
  16955. }
  16956. function getAndExtendSideEffectModules(variable, module) {
  16957. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  16958. let currentVariable = variable;
  16959. const referencedVariables = new Set([currentVariable]);
  16960. while (true) {
  16961. const importingModule = currentVariable.module;
  16962. currentVariable =
  16963. currentVariable instanceof ExportDefaultVariable
  16964. ? currentVariable.getDirectOriginalVariable()
  16965. : currentVariable instanceof SyntheticNamedExportVariable
  16966. ? currentVariable.syntheticNamespace
  16967. : null;
  16968. if (!currentVariable || referencedVariables.has(currentVariable)) {
  16969. break;
  16970. }
  16971. referencedVariables.add(currentVariable);
  16972. sideEffectModules.add(importingModule);
  16973. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  16974. if (originalSideEffects) {
  16975. for (const module of originalSideEffects) {
  16976. sideEffectModules.add(module);
  16977. }
  16978. }
  16979. }
  16980. return sideEffectModules;
  16981. }
  16982. class Module {
  16983. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  16984. this.graph = graph;
  16985. this.id = id;
  16986. this.options = options;
  16987. this.alternativeReexportModules = new Map();
  16988. this.chunkFileNames = new Set();
  16989. this.chunkNames = [];
  16990. this.cycles = new Set();
  16991. this.dependencies = new Set();
  16992. this.dynamicDependencies = new Set();
  16993. this.dynamicImporters = [];
  16994. this.dynamicImports = [];
  16995. this.execIndex = Infinity;
  16996. this.hasTreeShakingPassStarted = false;
  16997. this.implicitlyLoadedAfter = new Set();
  16998. this.implicitlyLoadedBefore = new Set();
  16999. this.importDescriptions = new Map();
  17000. this.importMetas = [];
  17001. this.importedFromNotTreeshaken = false;
  17002. this.importers = [];
  17003. this.includedDynamicImporters = [];
  17004. this.includedImports = new Set();
  17005. this.isExecuted = false;
  17006. this.isUserDefinedEntryPoint = false;
  17007. this.needsExportShim = false;
  17008. this.sideEffectDependenciesByVariable = new Map();
  17009. this.sourcesWithAttributes = new Map();
  17010. this.allExportNames = null;
  17011. this.allExportsIncluded = false;
  17012. this.ast = null;
  17013. this.exportAllModules = [];
  17014. this.exportAllSources = new Set();
  17015. this.exportNamesByVariable = null;
  17016. this.exportShimVariable = new ExportShimVariable(this);
  17017. this.exports = new Map();
  17018. this.namespaceReexportsByName = new Map();
  17019. this.reexportDescriptions = new Map();
  17020. this.relevantDependencies = null;
  17021. this.syntheticExports = new Map();
  17022. this.syntheticNamespace = null;
  17023. this.transformDependencies = [];
  17024. this.transitiveReexports = null;
  17025. this.excludeFromSourcemap = /\0/.test(id);
  17026. this.context = options.moduleContext(id);
  17027. this.preserveSignature = this.options.preserveEntrySignatures;
  17028. // eslint-disable-next-line @typescript-eslint/no-this-alias
  17029. const module = this;
  17030. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  17031. this.info = {
  17032. ast: null,
  17033. attributes,
  17034. code: null,
  17035. get dynamicallyImportedIdResolutions() {
  17036. return dynamicImports
  17037. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  17038. .filter(Boolean);
  17039. },
  17040. get dynamicallyImportedIds() {
  17041. // We cannot use this.dynamicDependencies because this is needed before
  17042. // dynamicDependencies are populated
  17043. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  17044. },
  17045. get dynamicImporters() {
  17046. return dynamicImporters.sort();
  17047. },
  17048. get exportedBindings() {
  17049. const exportBindings = { '.': [...exports.keys()] };
  17050. for (const [name, { source }] of reexportDescriptions) {
  17051. (exportBindings[source] ??= []).push(name);
  17052. }
  17053. for (const source of exportAllSources) {
  17054. (exportBindings[source] ??= []).push('*');
  17055. }
  17056. return exportBindings;
  17057. },
  17058. get exports() {
  17059. return [
  17060. ...exports.keys(),
  17061. ...reexportDescriptions.keys(),
  17062. ...[...exportAllSources].map(() => '*')
  17063. ];
  17064. },
  17065. get hasDefaultExport() {
  17066. // This information is only valid after parsing
  17067. if (!module.ast) {
  17068. return null;
  17069. }
  17070. return module.exports.has('default') || reexportDescriptions.has('default');
  17071. },
  17072. id,
  17073. get implicitlyLoadedAfterOneOf() {
  17074. return Array.from(implicitlyLoadedAfter, getId).sort();
  17075. },
  17076. get implicitlyLoadedBefore() {
  17077. return Array.from(implicitlyLoadedBefore, getId).sort();
  17078. },
  17079. get importedIdResolutions() {
  17080. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  17081. },
  17082. get importedIds() {
  17083. // We cannot use this.dependencies because this is needed before
  17084. // dependencies are populated
  17085. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  17086. },
  17087. get importers() {
  17088. return importers.sort();
  17089. },
  17090. isEntry,
  17091. isExternal: false,
  17092. get isIncluded() {
  17093. if (graph.phase !== BuildPhase.GENERATE) {
  17094. return null;
  17095. }
  17096. return module.isIncluded();
  17097. },
  17098. meta: { ...meta },
  17099. moduleSideEffects,
  17100. syntheticNamedExports
  17101. };
  17102. }
  17103. basename() {
  17104. const base = path.basename(this.id);
  17105. const extension = path.extname(this.id);
  17106. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  17107. }
  17108. bindReferences() {
  17109. this.ast.bind();
  17110. }
  17111. cacheInfoGetters() {
  17112. cacheObjectGetters(this.info, [
  17113. 'dynamicallyImportedIdResolutions',
  17114. 'dynamicallyImportedIds',
  17115. 'dynamicImporters',
  17116. 'exportedBindings',
  17117. 'exports',
  17118. 'hasDefaultExport',
  17119. 'implicitlyLoadedAfterOneOf',
  17120. 'implicitlyLoadedBefore',
  17121. 'importedIdResolutions',
  17122. 'importedIds',
  17123. 'importers'
  17124. ]);
  17125. }
  17126. error(properties, pos) {
  17127. if (pos !== undefined) {
  17128. this.addLocationToLogProps(properties, pos);
  17129. }
  17130. return parseAst_js.error(properties);
  17131. }
  17132. // sum up the length of all ast nodes that are included
  17133. estimateSize() {
  17134. let size = 0;
  17135. for (const node of this.ast.body) {
  17136. if (node.included) {
  17137. size += node.end - node.start;
  17138. }
  17139. }
  17140. return size;
  17141. }
  17142. getAllExportNames() {
  17143. if (this.allExportNames) {
  17144. return this.allExportNames;
  17145. }
  17146. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  17147. for (const module of this.exportAllModules) {
  17148. if (module instanceof ExternalModule) {
  17149. this.allExportNames.add(`*${module.id}`);
  17150. continue;
  17151. }
  17152. for (const name of module.getAllExportNames()) {
  17153. if (name !== 'default')
  17154. this.allExportNames.add(name);
  17155. }
  17156. }
  17157. // We do not count the synthetic namespace as a regular export to hide it
  17158. // from entry signatures and namespace objects
  17159. if (typeof this.info.syntheticNamedExports === 'string') {
  17160. this.allExportNames.delete(this.info.syntheticNamedExports);
  17161. }
  17162. return this.allExportNames;
  17163. }
  17164. getDependenciesToBeIncluded() {
  17165. if (this.relevantDependencies)
  17166. return this.relevantDependencies;
  17167. this.relevantDependencies = new Set();
  17168. const necessaryDependencies = new Set();
  17169. const alwaysCheckedDependencies = new Set();
  17170. const dependencyVariables = new Set(this.includedImports);
  17171. if (this.info.isEntry ||
  17172. this.includedDynamicImporters.length > 0 ||
  17173. this.namespace.included ||
  17174. this.implicitlyLoadedAfter.size > 0) {
  17175. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  17176. const [exportedVariable] = this.getVariableForExportName(exportName);
  17177. if (exportedVariable?.included) {
  17178. dependencyVariables.add(exportedVariable);
  17179. }
  17180. }
  17181. }
  17182. for (let variable of dependencyVariables) {
  17183. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  17184. if (sideEffectDependencies) {
  17185. for (const module of sideEffectDependencies) {
  17186. alwaysCheckedDependencies.add(module);
  17187. }
  17188. }
  17189. if (variable instanceof SyntheticNamedExportVariable) {
  17190. variable = variable.getBaseVariable();
  17191. }
  17192. else if (variable instanceof ExportDefaultVariable) {
  17193. variable = variable.getOriginalVariable();
  17194. }
  17195. necessaryDependencies.add(variable.module);
  17196. }
  17197. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  17198. for (const dependency of this.dependencies) {
  17199. this.relevantDependencies.add(dependency);
  17200. }
  17201. }
  17202. else {
  17203. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  17204. }
  17205. for (const dependency of necessaryDependencies) {
  17206. this.relevantDependencies.add(dependency);
  17207. }
  17208. return this.relevantDependencies;
  17209. }
  17210. getExportNamesByVariable() {
  17211. if (this.exportNamesByVariable) {
  17212. return this.exportNamesByVariable;
  17213. }
  17214. const exportNamesByVariable = new Map();
  17215. for (const exportName of this.getAllExportNames()) {
  17216. let [tracedVariable] = this.getVariableForExportName(exportName);
  17217. if (tracedVariable instanceof ExportDefaultVariable) {
  17218. tracedVariable = tracedVariable.getOriginalVariable();
  17219. }
  17220. if (!tracedVariable ||
  17221. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  17222. continue;
  17223. }
  17224. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  17225. if (existingExportNames) {
  17226. existingExportNames.push(exportName);
  17227. }
  17228. else {
  17229. exportNamesByVariable.set(tracedVariable, [exportName]);
  17230. }
  17231. }
  17232. return (this.exportNamesByVariable = exportNamesByVariable);
  17233. }
  17234. getExports() {
  17235. return [...this.exports.keys()];
  17236. }
  17237. getReexports() {
  17238. if (this.transitiveReexports) {
  17239. return this.transitiveReexports;
  17240. }
  17241. // to avoid infinite recursion when using circular `export * from X`
  17242. this.transitiveReexports = [];
  17243. const reexports = new Set(this.reexportDescriptions.keys());
  17244. for (const module of this.exportAllModules) {
  17245. if (module instanceof ExternalModule) {
  17246. reexports.add(`*${module.id}`);
  17247. }
  17248. else {
  17249. for (const name of [...module.getReexports(), ...module.getExports()]) {
  17250. if (name !== 'default')
  17251. reexports.add(name);
  17252. }
  17253. }
  17254. }
  17255. return (this.transitiveReexports = [...reexports]);
  17256. }
  17257. getRenderedExports() {
  17258. // only direct exports are counted here, not reexports at all
  17259. const renderedExports = [];
  17260. const removedExports = [];
  17261. for (const exportName of this.exports.keys()) {
  17262. const [variable] = this.getVariableForExportName(exportName);
  17263. (variable?.included ? renderedExports : removedExports).push(exportName);
  17264. }
  17265. return { removedExports, renderedExports };
  17266. }
  17267. getSyntheticNamespace() {
  17268. if (this.syntheticNamespace === null) {
  17269. this.syntheticNamespace = undefined;
  17270. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  17271. ? this.info.syntheticNamedExports
  17272. : 'default', { onlyExplicit: true });
  17273. }
  17274. if (!this.syntheticNamespace) {
  17275. return parseAst_js.error(parseAst_js.logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  17276. }
  17277. return this.syntheticNamespace;
  17278. }
  17279. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  17280. if (name[0] === '*') {
  17281. if (name.length === 1) {
  17282. // export * from './other'
  17283. return [this.namespace];
  17284. }
  17285. // export * from 'external'
  17286. const module = this.graph.modulesById.get(name.slice(1));
  17287. return module.getVariableForExportName('*');
  17288. }
  17289. // export { foo } from './other'
  17290. const reexportDeclaration = this.reexportDescriptions.get(name);
  17291. if (reexportDeclaration) {
  17292. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  17293. if (!variable) {
  17294. return this.error(parseAst_js.logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  17295. }
  17296. if (importerForSideEffects) {
  17297. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17298. if (this.info.moduleSideEffects) {
  17299. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17300. }
  17301. }
  17302. return [variable];
  17303. }
  17304. const exportDeclaration = this.exports.get(name);
  17305. if (exportDeclaration) {
  17306. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  17307. return [this.exportShimVariable];
  17308. }
  17309. const name = exportDeclaration.localName;
  17310. const variable = this.traceVariable(name, {
  17311. importerForSideEffects,
  17312. searchedNamesAndModules
  17313. });
  17314. if (importerForSideEffects) {
  17315. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  17316. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  17317. }
  17318. return [variable];
  17319. }
  17320. if (onlyExplicit) {
  17321. return [null];
  17322. }
  17323. if (name !== 'default') {
  17324. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  17325. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  17326. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  17327. if (foundNamespaceReexport[0]) {
  17328. return foundNamespaceReexport;
  17329. }
  17330. }
  17331. if (this.info.syntheticNamedExports) {
  17332. return [
  17333. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  17334. ];
  17335. }
  17336. // we don't want to create shims when we are just
  17337. // probing export * modules for exports
  17338. if (!isExportAllSearch && this.options.shimMissingExports) {
  17339. this.shimMissingExport(name);
  17340. return [this.exportShimVariable];
  17341. }
  17342. return [null];
  17343. }
  17344. hasEffects() {
  17345. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  17346. }
  17347. include() {
  17348. const context = createInclusionContext();
  17349. if (this.ast.shouldBeIncluded(context))
  17350. this.ast.include(context, false);
  17351. }
  17352. includeAllExports(includeNamespaceMembers) {
  17353. if (this.allExportsIncluded)
  17354. return;
  17355. this.allExportsIncluded = true;
  17356. if (!this.isExecuted) {
  17357. markModuleAndImpureDependenciesAsExecuted(this);
  17358. this.graph.needsTreeshakingPass = true;
  17359. }
  17360. const inclusionContext = createInclusionContext();
  17361. for (const exportName of this.exports.keys()) {
  17362. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  17363. const variable = this.getVariableForExportName(exportName)[0];
  17364. if (!variable) {
  17365. return parseAst_js.error(parseAst_js.logMissingEntryExport(exportName, this.id));
  17366. }
  17367. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17368. variable.deoptimizePath(UNKNOWN_PATH);
  17369. }
  17370. }
  17371. for (const name of this.getReexports()) {
  17372. const [variable] = this.getVariableForExportName(name);
  17373. if (variable) {
  17374. variable.deoptimizePath(UNKNOWN_PATH);
  17375. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17376. if (variable instanceof ExternalVariable) {
  17377. variable.module.reexported = true;
  17378. }
  17379. }
  17380. }
  17381. if (includeNamespaceMembers) {
  17382. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17383. }
  17384. }
  17385. includeAllInBundle() {
  17386. this.ast.include(createInclusionContext(), true);
  17387. this.includeAllExports(false);
  17388. }
  17389. includeExportsByNames(names) {
  17390. if (!this.isExecuted) {
  17391. markModuleAndImpureDependenciesAsExecuted(this);
  17392. this.graph.needsTreeshakingPass = true;
  17393. }
  17394. let includeNamespaceMembers = false;
  17395. const inclusionContext = createInclusionContext();
  17396. for (const name of names) {
  17397. const variable = this.getVariableForExportName(name)[0];
  17398. if (variable) {
  17399. variable.deoptimizePath(UNKNOWN_PATH);
  17400. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  17401. }
  17402. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  17403. includeNamespaceMembers = true;
  17404. }
  17405. }
  17406. if (includeNamespaceMembers) {
  17407. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  17408. }
  17409. }
  17410. isIncluded() {
  17411. // Modules where this.ast is missing have been loaded via this.load and are
  17412. // not yet fully processed, hence they cannot be included.
  17413. return (this.ast &&
  17414. (this.ast.included ||
  17415. this.namespace.included ||
  17416. this.importedFromNotTreeshaken ||
  17417. this.exportShimVariable.included));
  17418. }
  17419. linkImports() {
  17420. this.addModulesToImportDescriptions(this.importDescriptions);
  17421. this.addModulesToImportDescriptions(this.reexportDescriptions);
  17422. const externalExportAllModules = [];
  17423. for (const source of this.exportAllSources) {
  17424. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  17425. if (module instanceof ExternalModule) {
  17426. externalExportAllModules.push(module);
  17427. continue;
  17428. }
  17429. this.exportAllModules.push(module);
  17430. }
  17431. this.exportAllModules.push(...externalExportAllModules);
  17432. }
  17433. log(level, properties, pos) {
  17434. this.addLocationToLogProps(properties, pos);
  17435. this.options.onLog(level, properties);
  17436. }
  17437. render(options) {
  17438. const source = this.magicString.clone();
  17439. this.ast.render(source, options);
  17440. source.trim();
  17441. const { usesTopLevelAwait } = this.astContext;
  17442. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  17443. return parseAst_js.error(parseAst_js.logInvalidFormatForTopLevelAwait(this.id, options.format));
  17444. }
  17445. return { source, usesTopLevelAwait };
  17446. }
  17447. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  17448. timeStart('generate ast', 3);
  17449. if (code.startsWith('#!')) {
  17450. const shebangEndPosition = code.indexOf('\n');
  17451. this.shebang = code.slice(2, shebangEndPosition);
  17452. }
  17453. this.info.code = code;
  17454. this.originalCode = originalCode;
  17455. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  17456. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  17457. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  17458. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  17459. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  17460. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  17461. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  17462. if (transformFiles) {
  17463. this.transformFiles = transformFiles;
  17464. }
  17465. this.transformDependencies = transformDependencies;
  17466. this.customTransformCache = customTransformCache;
  17467. this.updateOptions(moduleOptions);
  17468. this.resolvedIds = resolvedIds ?? Object.create(null);
  17469. // By default, `id` is the file name. Custom resolvers and loaders
  17470. // can change that, but it makes sense to use it for the source file name
  17471. const fileName = this.id;
  17472. this.magicString = new MagicString(code, {
  17473. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  17474. indentExclusionRanges: []
  17475. });
  17476. this.astContext = {
  17477. addDynamicImport: this.addDynamicImport.bind(this),
  17478. addExport: this.addExport.bind(this),
  17479. addImport: this.addImport.bind(this),
  17480. addImportMeta: this.addImportMeta.bind(this),
  17481. addImportSource: this.addImportSource.bind(this),
  17482. code, // Only needed for debugging
  17483. deoptimizationTracker: this.graph.deoptimizationTracker,
  17484. error: this.error.bind(this),
  17485. fileName, // Needed for warnings
  17486. getExports: this.getExports.bind(this),
  17487. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  17488. getModuleExecIndex: () => this.execIndex,
  17489. getModuleName: this.basename.bind(this),
  17490. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  17491. getReexports: this.getReexports.bind(this),
  17492. importDescriptions: this.importDescriptions,
  17493. includeAllExports: () => this.includeAllExports(true),
  17494. includeDynamicImport: this.includeDynamicImport.bind(this),
  17495. includeVariableInModule: this.includeVariableInModule.bind(this),
  17496. log: this.log.bind(this),
  17497. magicString: this.magicString,
  17498. manualPureFunctions: this.graph.pureFunctions,
  17499. module: this,
  17500. moduleContext: this.context,
  17501. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  17502. options: this.options,
  17503. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  17504. traceExport: (name) => this.getVariableForExportName(name)[0],
  17505. traceVariable: this.traceVariable.bind(this),
  17506. usesTopLevelAwait: false
  17507. };
  17508. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  17509. this.namespace = new NamespaceVariable(this.astContext);
  17510. const programParent = { context: this.astContext, type: 'Module' };
  17511. if (ast) {
  17512. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  17513. this.info.ast = ast;
  17514. }
  17515. else {
  17516. // Measuring asynchronous code does not provide reasonable results
  17517. timeEnd('generate ast', 3);
  17518. const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
  17519. timeStart('generate ast', 3);
  17520. this.ast = convertProgram(astBuffer, programParent, this.scope);
  17521. // Make lazy and apply LRU cache to not hog the memory
  17522. Object.defineProperty(this.info, 'ast', {
  17523. get: () => {
  17524. if (this.graph.astLru.has(fileName)) {
  17525. return this.graph.astLru.get(fileName);
  17526. }
  17527. else {
  17528. const parsedAst = this.tryParse();
  17529. // If the cache is not disabled, we need to keep the AST in memory
  17530. // until the end when the cache is generated
  17531. if (this.options.cache !== false) {
  17532. Object.defineProperty(this.info, 'ast', {
  17533. value: parsedAst
  17534. });
  17535. return parsedAst;
  17536. }
  17537. // Otherwise, we keep it in a small LRU cache to not hog too much
  17538. // memory but allow the same AST to be requested several times.
  17539. this.graph.astLru.set(fileName, parsedAst);
  17540. return parsedAst;
  17541. }
  17542. }
  17543. });
  17544. }
  17545. timeEnd('generate ast', 3);
  17546. }
  17547. toJSON() {
  17548. return {
  17549. ast: this.info.ast,
  17550. attributes: this.info.attributes,
  17551. code: this.info.code,
  17552. customTransformCache: this.customTransformCache,
  17553. dependencies: Array.from(this.dependencies, getId),
  17554. id: this.id,
  17555. meta: this.info.meta,
  17556. moduleSideEffects: this.info.moduleSideEffects,
  17557. originalCode: this.originalCode,
  17558. originalSourcemap: this.originalSourcemap,
  17559. resolvedIds: this.resolvedIds,
  17560. sourcemapChain: this.sourcemapChain,
  17561. syntheticNamedExports: this.info.syntheticNamedExports,
  17562. transformDependencies: this.transformDependencies,
  17563. transformFiles: this.transformFiles
  17564. };
  17565. }
  17566. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  17567. const localVariable = this.scope.variables.get(name);
  17568. if (localVariable) {
  17569. return localVariable;
  17570. }
  17571. const importDescription = this.importDescriptions.get(name);
  17572. if (importDescription) {
  17573. const otherModule = importDescription.module;
  17574. if (otherModule instanceof Module && importDescription.name === '*') {
  17575. return otherModule.namespace;
  17576. }
  17577. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  17578. if (!declaration) {
  17579. return this.error(parseAst_js.logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  17580. }
  17581. return declaration;
  17582. }
  17583. return null;
  17584. }
  17585. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  17586. if (moduleSideEffects != null) {
  17587. this.info.moduleSideEffects = moduleSideEffects;
  17588. }
  17589. if (syntheticNamedExports != null) {
  17590. this.info.syntheticNamedExports = syntheticNamedExports;
  17591. }
  17592. if (meta != null) {
  17593. Object.assign(this.info.meta, meta);
  17594. }
  17595. }
  17596. addDynamicImport(node) {
  17597. let argument = node.sourceAstNode;
  17598. if (argument.type === parseAst_js.TemplateLiteral) {
  17599. if (argument.quasis.length === 1 &&
  17600. typeof argument.quasis[0].value.cooked === 'string') {
  17601. argument = argument.quasis[0].value.cooked;
  17602. }
  17603. }
  17604. else if (argument.type === parseAst_js.Literal &&
  17605. typeof argument.value === 'string') {
  17606. argument = argument.value;
  17607. }
  17608. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  17609. }
  17610. assertUniqueExportName(name, nodeStart) {
  17611. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  17612. this.error(parseAst_js.logDuplicateExportError(name), nodeStart);
  17613. }
  17614. }
  17615. addExport(node) {
  17616. if (node instanceof ExportDefaultDeclaration) {
  17617. // export default foo;
  17618. this.assertUniqueExportName('default', node.start);
  17619. this.exports.set('default', {
  17620. identifier: node.variable.getAssignedVariableName(),
  17621. localName: 'default'
  17622. });
  17623. }
  17624. else if (node instanceof ExportAllDeclaration) {
  17625. const source = node.source.value;
  17626. this.addSource(source, node);
  17627. if (node.exported) {
  17628. // export * as name from './other'
  17629. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  17630. this.assertUniqueExportName(name, node.exported.start);
  17631. this.reexportDescriptions.set(name, {
  17632. localName: '*',
  17633. module: null, // filled in later,
  17634. source,
  17635. start: node.start
  17636. });
  17637. }
  17638. else {
  17639. // export * from './other'
  17640. this.exportAllSources.add(source);
  17641. }
  17642. }
  17643. else if (node.source instanceof Literal) {
  17644. // export { name } from './other'
  17645. const source = node.source.value;
  17646. this.addSource(source, node);
  17647. for (const { exported, local, start } of node.specifiers) {
  17648. const name = exported instanceof Literal ? exported.value : exported.name;
  17649. this.assertUniqueExportName(name, start);
  17650. this.reexportDescriptions.set(name, {
  17651. localName: local instanceof Literal ? local.value : local.name,
  17652. module: null, // filled in later,
  17653. source,
  17654. start
  17655. });
  17656. }
  17657. }
  17658. else if (node.declaration) {
  17659. const declaration = node.declaration;
  17660. if (declaration instanceof VariableDeclaration) {
  17661. // export var { foo, bar } = ...
  17662. // export var foo = 1, bar = 2;
  17663. for (const declarator of declaration.declarations) {
  17664. for (const localName of extractAssignedNames(declarator.id)) {
  17665. this.assertUniqueExportName(localName, declarator.id.start);
  17666. this.exports.set(localName, { identifier: null, localName });
  17667. }
  17668. }
  17669. }
  17670. else {
  17671. // export function foo () {}
  17672. const localName = declaration.id.name;
  17673. this.assertUniqueExportName(localName, declaration.id.start);
  17674. this.exports.set(localName, { identifier: null, localName });
  17675. }
  17676. }
  17677. else {
  17678. // export { foo, bar, baz }
  17679. for (const { local, exported } of node.specifiers) {
  17680. // except for reexports, local must be an Identifier
  17681. const localName = local.name;
  17682. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  17683. this.assertUniqueExportName(exportedName, exported.start);
  17684. this.exports.set(exportedName, { identifier: null, localName });
  17685. }
  17686. }
  17687. }
  17688. addImport(node) {
  17689. const source = node.source.value;
  17690. this.addSource(source, node);
  17691. for (const specifier of node.specifiers) {
  17692. const localName = specifier.local.name;
  17693. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  17694. this.error(parseAst_js.logRedeclarationError(localName), specifier.local.start);
  17695. }
  17696. const name = specifier instanceof ImportDefaultSpecifier
  17697. ? 'default'
  17698. : specifier instanceof ImportNamespaceSpecifier
  17699. ? '*'
  17700. : specifier.imported instanceof Identifier
  17701. ? specifier.imported.name
  17702. : specifier.imported.value;
  17703. this.importDescriptions.set(localName, {
  17704. module: null, // filled in later
  17705. name,
  17706. source,
  17707. start: specifier.start
  17708. });
  17709. }
  17710. }
  17711. addImportSource(importSource) {
  17712. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  17713. this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
  17714. }
  17715. }
  17716. addImportMeta(node) {
  17717. this.importMetas.push(node);
  17718. }
  17719. addLocationToLogProps(properties, pos) {
  17720. properties.id = this.id;
  17721. properties.pos = pos;
  17722. let code = this.info.code;
  17723. const location = parseAst_js.locate(code, pos, { offsetLine: 1 });
  17724. if (location) {
  17725. let { column, line } = location;
  17726. try {
  17727. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  17728. code = this.originalCode;
  17729. }
  17730. catch (error_) {
  17731. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidSourcemapForError(error_, this.id, column, line, pos));
  17732. }
  17733. parseAst_js.augmentCodeLocation(properties, { column, line }, code, this.id);
  17734. }
  17735. }
  17736. addModulesToImportDescriptions(importDescription) {
  17737. for (const specifier of importDescription.values()) {
  17738. const { id } = this.resolvedIds[specifier.source];
  17739. specifier.module = this.graph.modulesById.get(id);
  17740. }
  17741. }
  17742. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  17743. const handledDependencies = new Set();
  17744. const addSideEffectDependencies = (possibleDependencies) => {
  17745. for (const dependency of possibleDependencies) {
  17746. if (handledDependencies.has(dependency)) {
  17747. continue;
  17748. }
  17749. handledDependencies.add(dependency);
  17750. if (necessaryDependencies.has(dependency)) {
  17751. relevantDependencies.add(dependency);
  17752. continue;
  17753. }
  17754. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  17755. continue;
  17756. }
  17757. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  17758. relevantDependencies.add(dependency);
  17759. continue;
  17760. }
  17761. addSideEffectDependencies(dependency.dependencies);
  17762. }
  17763. };
  17764. addSideEffectDependencies(this.dependencies);
  17765. addSideEffectDependencies(alwaysCheckedDependencies);
  17766. }
  17767. addSource(source, declaration) {
  17768. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  17769. const existingAttributes = this.sourcesWithAttributes.get(source);
  17770. if (existingAttributes) {
  17771. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  17772. this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  17773. }
  17774. }
  17775. else {
  17776. this.sourcesWithAttributes.set(source, parsedAttributes);
  17777. }
  17778. }
  17779. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  17780. const { id } = this.resolvedIds[importSource];
  17781. const module = this.graph.modulesById.get(id);
  17782. const [variable] = module.getVariableForExportName(baseName);
  17783. if (!variable) {
  17784. return this.error(parseAst_js.logMissingJsxExport(baseName, id, this.id), nodeStart);
  17785. }
  17786. return variable;
  17787. }
  17788. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  17789. let foundSyntheticDeclaration = null;
  17790. const foundInternalDeclarations = new Map();
  17791. const foundExternalDeclarations = new Set();
  17792. for (const module of this.exportAllModules) {
  17793. // Synthetic namespaces should not hide "regular" exports of the same name
  17794. if (module.info.syntheticNamedExports === name) {
  17795. continue;
  17796. }
  17797. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  17798. // We are creating a copy to handle the case where the same binding is
  17799. // imported through different namespace reexports gracefully
  17800. copyNameToModulesMap(searchedNamesAndModules));
  17801. if (module instanceof ExternalModule || indirectExternal) {
  17802. foundExternalDeclarations.add(variable);
  17803. }
  17804. else if (variable instanceof SyntheticNamedExportVariable) {
  17805. if (!foundSyntheticDeclaration) {
  17806. foundSyntheticDeclaration = variable;
  17807. }
  17808. }
  17809. else if (variable) {
  17810. foundInternalDeclarations.set(variable, module);
  17811. }
  17812. }
  17813. if (foundInternalDeclarations.size > 0) {
  17814. const foundDeclarationList = [...foundInternalDeclarations];
  17815. const usedDeclaration = foundDeclarationList[0][0];
  17816. if (foundDeclarationList.length === 1) {
  17817. return [usedDeclaration];
  17818. }
  17819. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  17820. // TODO we are pretending it was not found while it should behave like "undefined"
  17821. return [null];
  17822. }
  17823. if (foundExternalDeclarations.size > 0) {
  17824. const foundDeclarationList = [...foundExternalDeclarations];
  17825. const usedDeclaration = foundDeclarationList[0];
  17826. if (foundDeclarationList.length > 1) {
  17827. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  17828. }
  17829. return [usedDeclaration, true];
  17830. }
  17831. if (foundSyntheticDeclaration) {
  17832. return [foundSyntheticDeclaration];
  17833. }
  17834. return [null];
  17835. }
  17836. includeAndGetAdditionalMergedNamespaces() {
  17837. const externalNamespaces = new Set();
  17838. const syntheticNamespaces = new Set();
  17839. for (const module of [this, ...this.exportAllModules]) {
  17840. if (module instanceof ExternalModule) {
  17841. const [externalVariable] = module.getVariableForExportName('*');
  17842. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  17843. this.includedImports.add(externalVariable);
  17844. externalNamespaces.add(externalVariable);
  17845. }
  17846. else if (module.info.syntheticNamedExports) {
  17847. const syntheticNamespace = module.getSyntheticNamespace();
  17848. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  17849. this.includedImports.add(syntheticNamespace);
  17850. syntheticNamespaces.add(syntheticNamespace);
  17851. }
  17852. }
  17853. return [...syntheticNamespaces, ...externalNamespaces];
  17854. }
  17855. includeDynamicImport(node) {
  17856. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  17857. if (resolution instanceof Module) {
  17858. if (!resolution.includedDynamicImporters.includes(this)) {
  17859. resolution.includedDynamicImporters.push(this);
  17860. }
  17861. const importedNames = this.options.treeshake
  17862. ? node.getDeterministicImportedNames()
  17863. : undefined;
  17864. if (importedNames) {
  17865. resolution.includeExportsByNames(importedNames);
  17866. }
  17867. else {
  17868. resolution.includeAllExports(true);
  17869. }
  17870. }
  17871. }
  17872. includeVariable(variable, path, context) {
  17873. const { included, module: variableModule } = variable;
  17874. variable.includePath(path, context);
  17875. if (included) {
  17876. if (variableModule instanceof Module && variableModule !== this) {
  17877. getAndExtendSideEffectModules(variable, this);
  17878. }
  17879. }
  17880. else {
  17881. this.graph.needsTreeshakingPass = true;
  17882. if (variableModule instanceof Module) {
  17883. if (!variableModule.isExecuted) {
  17884. markModuleAndImpureDependenciesAsExecuted(variableModule);
  17885. }
  17886. if (variableModule !== this) {
  17887. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  17888. for (const module of sideEffectModules) {
  17889. if (!module.isExecuted) {
  17890. markModuleAndImpureDependenciesAsExecuted(module);
  17891. }
  17892. }
  17893. }
  17894. }
  17895. }
  17896. }
  17897. includeVariableInModule(variable, path, context) {
  17898. this.includeVariable(variable, path, context);
  17899. const variableModule = variable.module;
  17900. if (variableModule && variableModule !== this) {
  17901. this.includedImports.add(variable);
  17902. }
  17903. }
  17904. shimMissingExport(name) {
  17905. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
  17906. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  17907. }
  17908. tryParse() {
  17909. try {
  17910. return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
  17911. }
  17912. catch (error_) {
  17913. return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
  17914. }
  17915. }
  17916. }
  17917. // if there is a cyclic import in the reexport chain, we should not
  17918. // import from the original module but from the cyclic module to not
  17919. // mess up execution order.
  17920. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  17921. if (variable.module instanceof Module && variable.module !== reexporter) {
  17922. const exporterCycles = variable.module.cycles;
  17923. if (exporterCycles.size > 0) {
  17924. const importerCycles = reexporter.cycles;
  17925. for (const cycleSymbol of importerCycles) {
  17926. if (exporterCycles.has(cycleSymbol)) {
  17927. importer.alternativeReexportModules.set(variable, reexporter);
  17928. break;
  17929. }
  17930. }
  17931. }
  17932. }
  17933. }
  17934. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  17935. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  17936. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  17937. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  17938. async function createAddons(options, outputPluginDriver, chunk) {
  17939. try {
  17940. let [banner, footer, intro, outro] = await Promise.all([
  17941. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  17942. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  17943. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  17944. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  17945. ]);
  17946. if (intro)
  17947. intro += '\n\n';
  17948. if (outro)
  17949. outro = `\n\n${outro}`;
  17950. if (banner)
  17951. banner += '\n';
  17952. if (footer)
  17953. footer = '\n' + footer;
  17954. return { banner, footer, intro, outro };
  17955. }
  17956. catch (error_) {
  17957. return parseAst_js.error(parseAst_js.logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  17958. }
  17959. }
  17960. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  17961. amd: deconflictImportsOther,
  17962. cjs: deconflictImportsOther,
  17963. es: deconflictImportsEsmOrSystem,
  17964. iife: deconflictImportsOther,
  17965. system: deconflictImportsEsmOrSystem,
  17966. umd: deconflictImportsOther
  17967. };
  17968. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  17969. const reversedModules = [...modules].reverse();
  17970. for (const module of reversedModules) {
  17971. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  17972. }
  17973. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  17974. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  17975. for (const module of reversedModules) {
  17976. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  17977. }
  17978. }
  17979. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  17980. // This is needed for namespace reexports
  17981. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  17982. if (preserveModules || dependency instanceof ExternalChunk) {
  17983. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  17984. }
  17985. }
  17986. for (const variable of imports) {
  17987. const module = variable.module;
  17988. const name = variable.name;
  17989. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  17990. variable.setRenderNames(null, (module instanceof ExternalModule
  17991. ? externalChunkByModule.get(module)
  17992. : chunkByModule.get(module)).variableName);
  17993. }
  17994. else if (module instanceof ExternalModule && name === 'default') {
  17995. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  17996. ? module.suggestedVariableName + '__default'
  17997. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  17998. }
  17999. else {
  18000. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  18001. }
  18002. }
  18003. for (const variable of syntheticExports) {
  18004. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18005. }
  18006. }
  18007. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  18008. for (const chunk of dependencies) {
  18009. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  18010. }
  18011. for (const chunk of deconflictedNamespace) {
  18012. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  18013. }
  18014. for (const externalModule of deconflictedDefault) {
  18015. externalModule.defaultVariableName =
  18016. deconflictedNamespace.has(externalModule) &&
  18017. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  18018. ? externalModule.namespaceVariableName
  18019. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  18020. }
  18021. for (const variable of imports) {
  18022. const module = variable.module;
  18023. if (module instanceof ExternalModule) {
  18024. const chunk = externalChunkByModule.get(module);
  18025. const name = variable.name;
  18026. if (name === 'default') {
  18027. const moduleInterop = interop(module.id);
  18028. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  18029. ? chunk.defaultVariableName
  18030. : chunk.variableName;
  18031. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  18032. variable.setRenderNames(variableName, 'default');
  18033. }
  18034. else {
  18035. variable.setRenderNames(null, variableName);
  18036. }
  18037. }
  18038. else if (name === '*') {
  18039. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  18040. ? chunk.namespaceVariableName
  18041. : chunk.variableName);
  18042. }
  18043. else {
  18044. // if the second parameter is `null`, it uses its "name" for the property name
  18045. variable.setRenderNames(chunk.variableName, null);
  18046. }
  18047. }
  18048. else {
  18049. const chunk = chunkByModule.get(module);
  18050. if (preserveModules && variable.isNamespace) {
  18051. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  18052. }
  18053. else if (chunk.exportMode === 'default') {
  18054. variable.setRenderNames(null, chunk.variableName);
  18055. }
  18056. else {
  18057. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  18058. }
  18059. }
  18060. }
  18061. }
  18062. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  18063. for (const module of modules) {
  18064. for (const variable of module.scope.variables.values()) {
  18065. if (variable.included &&
  18066. // this will only happen for exports in some formats
  18067. !(variable.renderBaseName ||
  18068. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  18069. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  18070. }
  18071. }
  18072. if (includedNamespaces.has(module)) {
  18073. const namespace = module.namespace;
  18074. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  18075. }
  18076. }
  18077. }
  18078. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  18079. let nameIndex = 0;
  18080. for (const variable of exports) {
  18081. let [exportName] = variable.name;
  18082. if (exportsByName.has(exportName)) {
  18083. do {
  18084. exportName = toBase64(++nameIndex);
  18085. // skip past leading number identifiers
  18086. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  18087. nameIndex += 9 * 64 ** (exportName.length - 1);
  18088. exportName = toBase64(nameIndex);
  18089. }
  18090. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  18091. }
  18092. exportsByName.set(exportName, variable);
  18093. exportNamesByVariable.set(variable, [exportName]);
  18094. }
  18095. }
  18096. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  18097. for (const variable of exports) {
  18098. let nameIndex = 0;
  18099. let exportName = variable.name;
  18100. while (exportsByName.has(exportName)) {
  18101. exportName = variable.name + '$' + ++nameIndex;
  18102. }
  18103. exportsByName.set(exportName, variable);
  18104. exportNamesByVariable.set(variable, [exportName]);
  18105. }
  18106. }
  18107. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  18108. const exportKeys = chunk.getExportNames();
  18109. if (exportMode === 'default') {
  18110. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  18111. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  18112. }
  18113. }
  18114. else if (exportMode === 'none' && exportKeys.length > 0) {
  18115. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  18116. }
  18117. if (exportMode === 'auto') {
  18118. if (exportKeys.length === 0) {
  18119. exportMode = 'none';
  18120. }
  18121. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  18122. exportMode = 'default';
  18123. }
  18124. else {
  18125. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  18126. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMixedExport(facadeModuleId, name));
  18127. }
  18128. exportMode = 'named';
  18129. }
  18130. }
  18131. return exportMode;
  18132. }
  18133. function guessIndentString(code) {
  18134. const lines = code.split('\n');
  18135. const tabbed = lines.filter(line => /^\t+/.test(line));
  18136. const spaced = lines.filter(line => /^ {2,}/.test(line));
  18137. if (tabbed.length === 0 && spaced.length === 0) {
  18138. return null;
  18139. }
  18140. // More lines tabbed than spaced? Assume tabs, and
  18141. // default to tabs in the case of a tie (or nothing
  18142. // to go on)
  18143. if (tabbed.length >= spaced.length) {
  18144. return '\t';
  18145. }
  18146. // Otherwise, we need to guess the multiple
  18147. const min = spaced.reduce((previous, current) => {
  18148. const numberSpaces = /^ +/.exec(current)[0].length;
  18149. return Math.min(numberSpaces, previous);
  18150. }, Infinity);
  18151. return ' '.repeat(min);
  18152. }
  18153. function getIndentString(modules, options) {
  18154. if (options.indent !== true)
  18155. return options.indent;
  18156. for (const module of modules) {
  18157. const indent = guessIndentString(module.originalCode);
  18158. if (indent !== null)
  18159. return indent;
  18160. }
  18161. return '\t';
  18162. }
  18163. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  18164. const staticDependencyBlocks = [];
  18165. const handledDependencies = new Set();
  18166. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  18167. const module = orderedModules[modulePos];
  18168. if (!handledDependencies.has(module)) {
  18169. const staticDependencies = [];
  18170. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  18171. staticDependencyBlocks.unshift(staticDependencies);
  18172. }
  18173. }
  18174. const dependencies = new Set();
  18175. for (const block of staticDependencyBlocks) {
  18176. for (const dependency of block) {
  18177. dependencies.add(dependency);
  18178. }
  18179. }
  18180. return dependencies;
  18181. }
  18182. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  18183. const dependencies = module.getDependenciesToBeIncluded();
  18184. for (const dependency of dependencies) {
  18185. if (dependency instanceof ExternalModule) {
  18186. staticDependencies.push(externalChunkByModule.get(dependency));
  18187. continue;
  18188. }
  18189. const dependencyChunk = chunkByModule.get(dependency);
  18190. if (dependencyChunk !== chunk) {
  18191. staticDependencies.push(dependencyChunk);
  18192. continue;
  18193. }
  18194. if (!handledModules.has(dependency)) {
  18195. handledModules.add(dependency);
  18196. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  18197. }
  18198. }
  18199. }
  18200. const NON_ASSET_EXTENSIONS = new Set([
  18201. '.js',
  18202. '.jsx',
  18203. '.ts',
  18204. '.tsx',
  18205. '.mjs',
  18206. '.mts',
  18207. '.cjs',
  18208. '.cts'
  18209. ]);
  18210. function getGlobalName(chunk, globals, hasExports, log) {
  18211. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  18212. if (globalName) {
  18213. return globalName;
  18214. }
  18215. if (hasExports) {
  18216. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingGlobalName(chunk.id, chunk.variableName));
  18217. return chunk.variableName;
  18218. }
  18219. }
  18220. class Chunk {
  18221. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  18222. this.orderedModules = orderedModules;
  18223. this.inputOptions = inputOptions;
  18224. this.outputOptions = outputOptions;
  18225. this.unsetOptions = unsetOptions;
  18226. this.pluginDriver = pluginDriver;
  18227. this.modulesById = modulesById;
  18228. this.chunkByModule = chunkByModule;
  18229. this.externalChunkByModule = externalChunkByModule;
  18230. this.facadeChunkByModule = facadeChunkByModule;
  18231. this.includedNamespaces = includedNamespaces;
  18232. this.manualChunkAlias = manualChunkAlias;
  18233. this.getPlaceholder = getPlaceholder;
  18234. this.bundle = bundle;
  18235. this.inputBase = inputBase;
  18236. this.snippets = snippets;
  18237. this.entryModules = [];
  18238. this.exportMode = 'named';
  18239. this.facadeModule = null;
  18240. this.namespaceVariableName = '';
  18241. this.variableName = '';
  18242. this.accessedGlobalsByScope = new Map();
  18243. this.dependencies = new Set();
  18244. this.dynamicEntryModules = [];
  18245. this.dynamicName = null;
  18246. this.exportNamesByVariable = new Map();
  18247. this.exports = new Set();
  18248. this.exportsByName = new Map();
  18249. this.fileName = null;
  18250. this.implicitEntryModules = [];
  18251. this.implicitlyLoadedBefore = new Set();
  18252. this.imports = new Set();
  18253. this.includedDynamicImports = null;
  18254. this.includedReexportsByModule = new Map();
  18255. // This may be updated in the constructor
  18256. this.isEmpty = true;
  18257. this.name = null;
  18258. this.needsExportsShim = false;
  18259. this.preRenderedChunkInfo = null;
  18260. this.preliminaryFileName = null;
  18261. this.preliminarySourcemapFileName = null;
  18262. this.renderedChunkInfo = null;
  18263. this.renderedDependencies = null;
  18264. this.renderedModules = Object.create(null);
  18265. this.sortedExportNames = null;
  18266. this.strictFacade = false;
  18267. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  18268. const chunkModules = new Set(orderedModules);
  18269. for (const module of orderedModules) {
  18270. chunkByModule.set(module, this);
  18271. if (module.namespace.included && !outputOptions.preserveModules) {
  18272. includedNamespaces.add(module);
  18273. }
  18274. if (this.isEmpty && module.isIncluded()) {
  18275. this.isEmpty = false;
  18276. }
  18277. if (module.info.isEntry || outputOptions.preserveModules) {
  18278. this.entryModules.push(module);
  18279. }
  18280. for (const importer of module.includedDynamicImporters) {
  18281. if (!chunkModules.has(importer)) {
  18282. this.dynamicEntryModules.push(module);
  18283. // Modules with synthetic exports need an artificial namespace for dynamic imports
  18284. if (module.info.syntheticNamedExports) {
  18285. includedNamespaces.add(module);
  18286. this.exports.add(module.namespace);
  18287. }
  18288. }
  18289. }
  18290. if (module.implicitlyLoadedAfter.size > 0) {
  18291. this.implicitEntryModules.push(module);
  18292. }
  18293. }
  18294. this.suggestedVariableName = makeLegal(this.generateVariableName());
  18295. }
  18296. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  18297. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  18298. chunk.assignFacadeName(facadeName, facadedModule);
  18299. if (!facadeChunkByModule.has(facadedModule)) {
  18300. facadeChunkByModule.set(facadedModule, chunk);
  18301. }
  18302. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  18303. chunk.dependencies.add(dependency instanceof Module
  18304. ? chunkByModule.get(dependency)
  18305. : externalChunkByModule.get(dependency));
  18306. }
  18307. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  18308. facadedModule.info.moduleSideEffects &&
  18309. facadedModule.hasEffects()) {
  18310. chunk.dependencies.add(chunkByModule.get(facadedModule));
  18311. }
  18312. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  18313. chunk.facadeModule = facadedModule;
  18314. chunk.strictFacade = true;
  18315. return chunk;
  18316. }
  18317. canModuleBeFacade(module, exposedVariables) {
  18318. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  18319. // All exports of this chunk need to be exposed by the candidate module
  18320. for (const exposedVariable of this.exports) {
  18321. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  18322. return false;
  18323. }
  18324. }
  18325. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  18326. for (const exposedVariable of exposedVariables) {
  18327. if (!(exposedVariable.module === module ||
  18328. moduleExportNamesByVariable.has(exposedVariable) ||
  18329. (exposedVariable instanceof SyntheticNamedExportVariable &&
  18330. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  18331. return false;
  18332. }
  18333. }
  18334. return true;
  18335. }
  18336. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  18337. const renderedChunkInfo = this.getRenderedChunkInfo();
  18338. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  18339. const preliminaryFileName = renderedChunkInfo.fileName;
  18340. const fileName = (this.fileName = finalize(preliminaryFileName));
  18341. return {
  18342. ...renderedChunkInfo,
  18343. code,
  18344. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  18345. fileName,
  18346. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  18347. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  18348. finalize(fileName),
  18349. bindings
  18350. ])),
  18351. imports: renderedChunkInfo.imports.map(finalize),
  18352. map,
  18353. preliminaryFileName,
  18354. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  18355. sourcemapFileName
  18356. };
  18357. }
  18358. generateExports() {
  18359. this.sortedExportNames = null;
  18360. const remainingExports = new Set(this.exports);
  18361. if (this.facadeModule !== null &&
  18362. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  18363. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  18364. for (const [variable, exportNames] of exportNamesByVariable) {
  18365. this.exportNamesByVariable.set(variable, [...exportNames]);
  18366. for (const exportName of exportNames) {
  18367. this.exportsByName.set(exportName, variable);
  18368. }
  18369. remainingExports.delete(variable);
  18370. }
  18371. }
  18372. if (this.outputOptions.minifyInternalExports) {
  18373. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18374. }
  18375. else {
  18376. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  18377. }
  18378. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  18379. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  18380. }
  18381. generateFacades() {
  18382. const facades = [];
  18383. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  18384. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  18385. for (const module of entryModules) {
  18386. if (module.preserveSignature) {
  18387. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  18388. // We need to expose all entry exports from this chunk
  18389. if (this.chunkByModule.get(exportedVariable.module) === this) {
  18390. exposedVariables.add(exportedVariable);
  18391. }
  18392. }
  18393. }
  18394. }
  18395. for (const module of entryModules) {
  18396. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  18397. // mapping must run after Set 'name' dedupe
  18398. name => ({
  18399. name
  18400. }));
  18401. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  18402. requiredFacades.push({});
  18403. }
  18404. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  18405. if (requiredFacades.length === 0) {
  18406. requiredFacades.push({});
  18407. }
  18408. if (!this.facadeModule) {
  18409. const needsStrictFacade = !this.outputOptions.preserveModules &&
  18410. (module.preserveSignature === 'strict' ||
  18411. (module.preserveSignature === 'exports-only' &&
  18412. module.getExportNamesByVariable().size > 0));
  18413. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  18414. this.facadeModule = module;
  18415. this.facadeChunkByModule.set(module, this);
  18416. if (module.preserveSignature) {
  18417. this.strictFacade = needsStrictFacade;
  18418. }
  18419. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  18420. }
  18421. }
  18422. for (const facadeName of requiredFacades) {
  18423. 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));
  18424. }
  18425. }
  18426. for (const module of this.dynamicEntryModules) {
  18427. if (module.info.syntheticNamedExports)
  18428. continue;
  18429. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  18430. this.facadeModule = module;
  18431. this.facadeChunkByModule.set(module, this);
  18432. this.strictFacade = true;
  18433. this.dynamicName = getChunkNameFromModule(module);
  18434. }
  18435. else if (this.facadeModule === module &&
  18436. !this.strictFacade &&
  18437. this.canModuleBeFacade(module, exposedVariables)) {
  18438. this.strictFacade = true;
  18439. }
  18440. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  18441. this.includedNamespaces.add(module);
  18442. this.exports.add(module.namespace);
  18443. }
  18444. }
  18445. if (!this.outputOptions.preserveModules) {
  18446. this.addNecessaryImportsForFacades();
  18447. }
  18448. return facades;
  18449. }
  18450. getChunkName() {
  18451. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  18452. }
  18453. getExportNames() {
  18454. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  18455. }
  18456. getFileName() {
  18457. return this.fileName || this.getPreliminaryFileName().fileName;
  18458. }
  18459. getImportPath(importer) {
  18460. return escapeId(parseAst_js.getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  18461. }
  18462. getPreliminaryFileName() {
  18463. if (this.preliminaryFileName) {
  18464. return this.preliminaryFileName;
  18465. }
  18466. let fileName;
  18467. let hashPlaceholder = null;
  18468. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  18469. if (file) {
  18470. fileName = path.basename(file);
  18471. }
  18472. else if (this.fileName === null) {
  18473. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  18474. ? [entryFileNames, 'output.entryFileNames']
  18475. : [chunkFileNames, 'output.chunkFileNames'];
  18476. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  18477. format: () => format,
  18478. hash: size => hashPlaceholder ||
  18479. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  18480. name: () => this.getChunkName()
  18481. });
  18482. if (!hashPlaceholder) {
  18483. fileName = makeUnique(fileName, this.bundle);
  18484. }
  18485. }
  18486. else {
  18487. fileName = this.fileName;
  18488. }
  18489. if (!hashPlaceholder) {
  18490. this.bundle[fileName] = FILE_PLACEHOLDER;
  18491. }
  18492. // Caching is essential to not conflict with the file name reservation above
  18493. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  18494. }
  18495. getPreliminarySourcemapFileName() {
  18496. if (this.preliminarySourcemapFileName) {
  18497. return this.preliminarySourcemapFileName;
  18498. }
  18499. let sourcemapFileName = null;
  18500. let hashPlaceholder = null;
  18501. const { sourcemapFileNames, format } = this.outputOptions;
  18502. if (sourcemapFileNames) {
  18503. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  18504. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  18505. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  18506. format: () => format,
  18507. hash: size => hashPlaceholder ||
  18508. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  18509. name: () => this.getChunkName()
  18510. });
  18511. if (!hashPlaceholder) {
  18512. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  18513. }
  18514. }
  18515. else {
  18516. return null;
  18517. }
  18518. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  18519. }
  18520. getRenderedChunkInfo() {
  18521. if (this.renderedChunkInfo) {
  18522. return this.renderedChunkInfo;
  18523. }
  18524. return (this.renderedChunkInfo = {
  18525. ...this.getPreRenderedChunkInfo(),
  18526. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  18527. fileName: this.getFileName(),
  18528. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  18529. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  18530. imports: Array.from(this.dependencies, resolveFileName),
  18531. modules: this.renderedModules,
  18532. referencedFiles: this.getReferencedFiles()
  18533. });
  18534. }
  18535. getVariableExportName(variable) {
  18536. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  18537. return '*';
  18538. }
  18539. return this.exportNamesByVariable.get(variable)[0];
  18540. }
  18541. link() {
  18542. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  18543. for (const module of this.orderedModules) {
  18544. this.addImplicitlyLoadedBeforeFromModule(module);
  18545. this.setUpChunkImportsAndExportsForModule(module);
  18546. }
  18547. }
  18548. async render() {
  18549. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  18550. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  18551. // for static and dynamic entry points, add transitive dependencies to this
  18552. // chunk's dependencies to avoid loading latency
  18553. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  18554. for (const dep of dependencies) {
  18555. if (dep instanceof Chunk)
  18556. this.inlineChunkDependencies(dep);
  18557. }
  18558. }
  18559. const preliminaryFileName = this.getPreliminaryFileName();
  18560. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  18561. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  18562. const renderedDependencies = [...this.getRenderedDependencies().values()];
  18563. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  18564. let hasExports = renderedExports.length > 0;
  18565. let hasDefaultExport = false;
  18566. for (const renderedDependency of renderedDependencies) {
  18567. const { reexports } = renderedDependency;
  18568. if (reexports?.length) {
  18569. hasExports = true;
  18570. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  18571. hasDefaultExport = true;
  18572. }
  18573. if (format === 'es') {
  18574. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  18575. }
  18576. }
  18577. }
  18578. if (!hasDefaultExport) {
  18579. for (const { exported } of renderedExports) {
  18580. if (exported === 'default') {
  18581. hasDefaultExport = true;
  18582. break;
  18583. }
  18584. }
  18585. }
  18586. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  18587. finalisers[format](renderedSource, {
  18588. accessedGlobals,
  18589. dependencies: renderedDependencies,
  18590. exports: renderedExports,
  18591. hasDefaultExport,
  18592. hasExports,
  18593. id: preliminaryFileName.fileName,
  18594. indent,
  18595. intro,
  18596. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  18597. isModuleFacade: facadeModule !== null,
  18598. log: onLog,
  18599. namedExportsMode: exportMode !== 'default',
  18600. outro,
  18601. snippets,
  18602. usesTopLevelAwait
  18603. }, outputOptions);
  18604. if (banner)
  18605. magicString.prepend(banner);
  18606. if (format === 'es' || format === 'cjs') {
  18607. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  18608. if (shebang) {
  18609. magicString.prepend(`#!${shebang}\n`);
  18610. }
  18611. }
  18612. if (footer)
  18613. magicString.append(footer);
  18614. return {
  18615. chunk: this,
  18616. magicString,
  18617. preliminaryFileName,
  18618. preliminarySourcemapFileName,
  18619. usedModules
  18620. };
  18621. }
  18622. addImplicitlyLoadedBeforeFromModule(baseModule) {
  18623. const { chunkByModule, implicitlyLoadedBefore } = this;
  18624. for (const module of baseModule.implicitlyLoadedBefore) {
  18625. const chunk = chunkByModule.get(module);
  18626. if (chunk && chunk !== this) {
  18627. implicitlyLoadedBefore.add(chunk);
  18628. }
  18629. }
  18630. }
  18631. addNecessaryImportsForFacades() {
  18632. for (const [module, variables] of this.includedReexportsByModule) {
  18633. if (this.includedNamespaces.has(module)) {
  18634. for (const variable of variables) {
  18635. this.imports.add(variable);
  18636. }
  18637. }
  18638. }
  18639. }
  18640. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  18641. if (fileName) {
  18642. this.fileName = fileName;
  18643. }
  18644. else {
  18645. this.name = this.outputOptions.sanitizeFileName(name ||
  18646. (preservePath
  18647. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  18648. : getChunkNameFromModule(facadedModule)));
  18649. }
  18650. }
  18651. checkCircularDependencyImport(variable, importingModule) {
  18652. const variableModule = variable.module;
  18653. if (variableModule instanceof Module) {
  18654. const exportChunk = this.chunkByModule.get(variableModule);
  18655. let alternativeReexportModule;
  18656. do {
  18657. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  18658. if (alternativeReexportModule) {
  18659. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  18660. if (exportingChunk !== exportChunk) {
  18661. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCyclicCrossChunkReexport(
  18662. // Namespaces do not have an export name
  18663. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  18664. }
  18665. importingModule = alternativeReexportModule;
  18666. }
  18667. } while (alternativeReexportModule);
  18668. }
  18669. }
  18670. ensureReexportsAreAvailableForModule(module) {
  18671. const includedReexports = [];
  18672. const map = module.getExportNamesByVariable();
  18673. for (const exportedVariable of map.keys()) {
  18674. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  18675. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  18676. this.checkCircularDependencyImport(importedVariable, module);
  18677. // When preserving modules, we do not create namespace objects but directly
  18678. // use the actual namespaces, which would be broken by this logic.
  18679. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18680. const exportingModule = importedVariable.module;
  18681. if (exportingModule instanceof Module) {
  18682. const chunk = this.chunkByModule.get(exportingModule);
  18683. if (chunk && chunk !== this) {
  18684. chunk.exports.add(importedVariable);
  18685. includedReexports.push(importedVariable);
  18686. if (isSynthetic) {
  18687. this.imports.add(importedVariable);
  18688. }
  18689. }
  18690. }
  18691. }
  18692. }
  18693. if (includedReexports.length > 0) {
  18694. this.includedReexportsByModule.set(module, includedReexports);
  18695. }
  18696. }
  18697. generateVariableName() {
  18698. if (this.manualChunkAlias) {
  18699. return this.manualChunkAlias;
  18700. }
  18701. const moduleForNaming = this.entryModules[0] ||
  18702. this.implicitEntryModules[0] ||
  18703. this.dynamicEntryModules[0] ||
  18704. this.orderedModules[this.orderedModules.length - 1];
  18705. if (moduleForNaming) {
  18706. return getChunkNameFromModule(moduleForNaming);
  18707. }
  18708. return 'chunk';
  18709. }
  18710. getChunkExportDeclarations(format) {
  18711. const exports = [];
  18712. for (const exportName of this.getExportNames()) {
  18713. if (exportName[0] === '*')
  18714. continue;
  18715. const variable = this.exportsByName.get(exportName);
  18716. if (!(variable instanceof SyntheticNamedExportVariable)) {
  18717. const module = variable.module;
  18718. if (module) {
  18719. const chunk = this.chunkByModule.get(module);
  18720. if (chunk !== this) {
  18721. if (!chunk || format !== 'es') {
  18722. continue;
  18723. }
  18724. const chunkDep = this.renderedDependencies.get(chunk);
  18725. if (!chunkDep) {
  18726. continue;
  18727. }
  18728. const { imports, reexports } = chunkDep;
  18729. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  18730. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  18731. if (!isImported) {
  18732. continue;
  18733. }
  18734. }
  18735. }
  18736. }
  18737. let expression = null;
  18738. let hoisted = false;
  18739. let local = variable.getName(this.snippets.getPropertyAccess);
  18740. if (variable instanceof LocalVariable) {
  18741. for (const declaration of variable.declarations) {
  18742. if (declaration.parent instanceof FunctionDeclaration ||
  18743. (declaration instanceof ExportDefaultDeclaration &&
  18744. declaration.declaration instanceof FunctionDeclaration)) {
  18745. hoisted = true;
  18746. break;
  18747. }
  18748. }
  18749. }
  18750. else if (variable instanceof SyntheticNamedExportVariable) {
  18751. expression = local;
  18752. if (format === 'es') {
  18753. local = variable.renderName;
  18754. }
  18755. }
  18756. exports.push({
  18757. exported: exportName,
  18758. expression,
  18759. hoisted,
  18760. local
  18761. });
  18762. }
  18763. return exports;
  18764. }
  18765. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  18766. const dependencies = new Set();
  18767. const deconflictedDefault = new Set();
  18768. const deconflictedNamespace = new Set();
  18769. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  18770. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  18771. const module = variable.module;
  18772. if (module instanceof ExternalModule) {
  18773. const chunk = this.externalChunkByModule.get(module);
  18774. dependencies.add(chunk);
  18775. if (addNonNamespacesAndInteropHelpers) {
  18776. if (variable.name === 'default') {
  18777. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  18778. deconflictedDefault.add(chunk);
  18779. }
  18780. }
  18781. else if (variable.isNamespace &&
  18782. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  18783. (this.imports.has(variable) ||
  18784. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  18785. // We only need to deconflict it if the namespace is actually
  18786. // created as a variable, i.e. because it is used internally or
  18787. // because it is reexported as an object
  18788. deconflictedNamespace.add(chunk);
  18789. }
  18790. }
  18791. }
  18792. else {
  18793. const chunk = this.chunkByModule.get(module);
  18794. if (chunk !== this) {
  18795. dependencies.add(chunk);
  18796. if (addNonNamespacesAndInteropHelpers &&
  18797. chunk.exportMode === 'default' &&
  18798. variable.isNamespace) {
  18799. deconflictedNamespace.add(chunk);
  18800. }
  18801. }
  18802. }
  18803. }
  18804. }
  18805. if (addDependenciesWithoutBindings) {
  18806. for (const dependency of this.dependencies) {
  18807. dependencies.add(dependency);
  18808. }
  18809. }
  18810. return { deconflictedDefault, deconflictedNamespace, dependencies };
  18811. }
  18812. getDynamicDependencies() {
  18813. return this.getIncludedDynamicImports()
  18814. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  18815. resolvedDynamicImport.chunk ||
  18816. resolvedDynamicImport.externalChunk ||
  18817. resolvedDynamicImport.resolution)
  18818. .filter((resolution) => resolution !== this &&
  18819. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  18820. }
  18821. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  18822. if (resolution instanceof ExternalModule) {
  18823. const chunk = this.externalChunkByModule.get(resolution);
  18824. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  18825. }
  18826. let attributes = null;
  18827. if (['es', 'cjs'].includes(this.outputOptions.format) &&
  18828. this.outputOptions.externalImportAttributes) {
  18829. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  18830. attributes =
  18831. attributesFromImportAttributes === parseAst_js.EMPTY_OBJECT
  18832. ? true
  18833. : formatAttributes(attributesFromImportAttributes, this.snippets);
  18834. }
  18835. return [resolution || '', attributes];
  18836. }
  18837. getFallbackChunkName() {
  18838. if (this.manualChunkAlias) {
  18839. return this.manualChunkAlias;
  18840. }
  18841. if (this.dynamicName) {
  18842. return this.dynamicName;
  18843. }
  18844. if (this.fileName) {
  18845. return parseAst_js.getAliasName(this.fileName);
  18846. }
  18847. return parseAst_js.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  18848. }
  18849. getImportSpecifiers() {
  18850. const { interop } = this.outputOptions;
  18851. const importsByDependency = new Map();
  18852. for (const variable of this.imports) {
  18853. const module = variable.module;
  18854. let dependency;
  18855. let imported;
  18856. if (module instanceof ExternalModule) {
  18857. dependency = this.externalChunkByModule.get(module);
  18858. imported = variable.name;
  18859. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  18860. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, false));
  18861. }
  18862. }
  18863. else {
  18864. dependency = this.chunkByModule.get(module);
  18865. imported = dependency.getVariableExportName(variable);
  18866. }
  18867. getOrCreate(importsByDependency, dependency, getNewArray).push({
  18868. imported,
  18869. local: variable.getName(this.snippets.getPropertyAccess)
  18870. });
  18871. }
  18872. return importsByDependency;
  18873. }
  18874. getIncludedDynamicImports() {
  18875. if (this.includedDynamicImports) {
  18876. return this.includedDynamicImports;
  18877. }
  18878. const includedDynamicImports = [];
  18879. for (const module of this.orderedModules) {
  18880. for (const { node, resolution } of module.dynamicImports) {
  18881. if (!node.included) {
  18882. continue;
  18883. }
  18884. includedDynamicImports.push(resolution instanceof Module
  18885. ? {
  18886. chunk: this.chunkByModule.get(resolution),
  18887. externalChunk: null,
  18888. facadeChunk: this.facadeChunkByModule.get(resolution),
  18889. node,
  18890. resolution
  18891. }
  18892. : resolution instanceof ExternalModule
  18893. ? {
  18894. chunk: null,
  18895. externalChunk: this.externalChunkByModule.get(resolution),
  18896. facadeChunk: null,
  18897. node,
  18898. resolution
  18899. }
  18900. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  18901. }
  18902. }
  18903. return (this.includedDynamicImports = includedDynamicImports);
  18904. }
  18905. getPreRenderedChunkInfo() {
  18906. if (this.preRenderedChunkInfo) {
  18907. return this.preRenderedChunkInfo;
  18908. }
  18909. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  18910. return (this.preRenderedChunkInfo = {
  18911. exports: this.getExportNames(),
  18912. facadeModuleId: facadeModule && facadeModule.id,
  18913. isDynamicEntry: dynamicEntryModules.length > 0,
  18914. isEntry: !!facadeModule?.info.isEntry,
  18915. isImplicitEntry: implicitEntryModules.length > 0,
  18916. moduleIds: orderedModules.map(({ id }) => id),
  18917. name: this.getChunkName(),
  18918. type: 'chunk'
  18919. });
  18920. }
  18921. getPreserveModulesChunkNameFromModule(module) {
  18922. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  18923. if (predefinedChunkName)
  18924. return predefinedChunkName;
  18925. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  18926. const sanitizedId = sanitizeFileName(parseAst_js.normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  18927. const extensionName = path.extname(sanitizedId);
  18928. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  18929. ? sanitizedId.slice(0, -extensionName.length)
  18930. : sanitizedId;
  18931. if (parseAst_js.isAbsolute(idWithoutExtension)) {
  18932. if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
  18933. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  18934. }
  18935. else {
  18936. // handle edge case in Windows
  18937. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  18938. return parseAst_js.relative(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  18939. }
  18940. return parseAst_js.relative(this.inputBase, idWithoutExtension);
  18941. }
  18942. }
  18943. else {
  18944. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
  18945. }
  18946. }
  18947. getReexportSpecifiers() {
  18948. const { externalLiveBindings, interop } = this.outputOptions;
  18949. const reexportSpecifiers = new Map();
  18950. for (let exportName of this.getExportNames()) {
  18951. let dependency;
  18952. let imported;
  18953. let needsLiveBinding = false;
  18954. if (exportName[0] === '*') {
  18955. const id = exportName.slice(1);
  18956. if (interop(id) === 'defaultOnly') {
  18957. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnexpectedNamespaceReexport(id));
  18958. }
  18959. needsLiveBinding = externalLiveBindings;
  18960. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  18961. imported = exportName = '*';
  18962. }
  18963. else {
  18964. const variable = this.exportsByName.get(exportName);
  18965. if (variable instanceof SyntheticNamedExportVariable)
  18966. continue;
  18967. const module = variable.module;
  18968. if (module instanceof Module) {
  18969. dependency = this.chunkByModule.get(module);
  18970. if (dependency === this)
  18971. continue;
  18972. imported = dependency.getVariableExportName(variable);
  18973. needsLiveBinding = variable.isReassigned;
  18974. }
  18975. else {
  18976. dependency = this.externalChunkByModule.get(module);
  18977. imported = variable.name;
  18978. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  18979. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, true));
  18980. }
  18981. needsLiveBinding =
  18982. externalLiveBindings &&
  18983. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  18984. }
  18985. }
  18986. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  18987. imported,
  18988. needsLiveBinding,
  18989. reexported: exportName
  18990. });
  18991. }
  18992. return reexportSpecifiers;
  18993. }
  18994. getReferencedFiles() {
  18995. const referencedFiles = new Set();
  18996. for (const module of this.orderedModules) {
  18997. for (const meta of module.importMetas) {
  18998. const fileName = meta.getReferencedFileName(this.pluginDriver);
  18999. if (fileName) {
  19000. referencedFiles.add(fileName);
  19001. }
  19002. }
  19003. }
  19004. return [...referencedFiles];
  19005. }
  19006. getRenderedDependencies() {
  19007. if (this.renderedDependencies) {
  19008. return this.renderedDependencies;
  19009. }
  19010. const importSpecifiers = this.getImportSpecifiers();
  19011. const reexportSpecifiers = this.getReexportSpecifiers();
  19012. const renderedDependencies = new Map();
  19013. const fileName = this.getFileName();
  19014. for (const dependency of this.dependencies) {
  19015. const imports = importSpecifiers.get(dependency) || null;
  19016. const reexports = reexportSpecifiers.get(dependency) || null;
  19017. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  19018. const importPath = dependency.getImportPath(fileName);
  19019. renderedDependencies.set(dependency, {
  19020. attributes: dependency instanceof ExternalChunk
  19021. ? dependency.getImportAttributes(this.snippets)
  19022. : null,
  19023. defaultVariableName: dependency.defaultVariableName,
  19024. globalName: dependency instanceof ExternalChunk &&
  19025. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  19026. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  19027. importPath,
  19028. imports,
  19029. isChunk: dependency instanceof Chunk,
  19030. name: dependency.variableName,
  19031. namedExportsMode,
  19032. namespaceVariableName: dependency.namespaceVariableName,
  19033. reexports
  19034. });
  19035. }
  19036. return (this.renderedDependencies = renderedDependencies);
  19037. }
  19038. inlineChunkDependencies(chunk) {
  19039. for (const dep of chunk.dependencies) {
  19040. if (this.dependencies.has(dep))
  19041. continue;
  19042. this.dependencies.add(dep);
  19043. if (dep instanceof Chunk) {
  19044. this.inlineChunkDependencies(dep);
  19045. }
  19046. }
  19047. }
  19048. // This method changes properties on the AST before rendering and must not be async
  19049. renderModules(fileName) {
  19050. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  19051. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  19052. const { _, cnst, n } = snippets;
  19053. this.setDynamicImportResolutions(fileName);
  19054. this.setImportMetaResolutions(fileName);
  19055. this.setIdentifierRenderResolutions();
  19056. const magicString = new Bundle$1({ separator: `${n}${n}` });
  19057. const indent = getIndentString(orderedModules, outputOptions);
  19058. const usedModules = [];
  19059. let hoistedSource = '';
  19060. const accessedGlobals = new Set();
  19061. const renderedModuleSources = new Map();
  19062. const renderOptions = {
  19063. accessedDocumentCurrentScript: false,
  19064. exportNamesByVariable,
  19065. format,
  19066. freeze,
  19067. importAttributesKey,
  19068. indent,
  19069. pluginDriver,
  19070. snippets,
  19071. symbols,
  19072. useOriginalName: null
  19073. };
  19074. let usesTopLevelAwait = false;
  19075. for (const module of orderedModules) {
  19076. let renderedLength = 0;
  19077. let source;
  19078. if (module.isIncluded() || includedNamespaces.has(module)) {
  19079. const rendered = module.render(renderOptions);
  19080. if (!renderOptions.accessedDocumentCurrentScript &&
  19081. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  19082. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  19083. }
  19084. renderOptions.accessedDocumentCurrentScript = false;
  19085. ({ source } = rendered);
  19086. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  19087. renderedLength = source.length();
  19088. if (renderedLength) {
  19089. if (compact && source.lastLine().includes('//'))
  19090. source.append('\n');
  19091. renderedModuleSources.set(module, source);
  19092. magicString.addSource(source);
  19093. usedModules.push(module);
  19094. }
  19095. const namespace = module.namespace;
  19096. if (includedNamespaces.has(module)) {
  19097. const rendered = namespace.renderBlock(renderOptions);
  19098. if (namespace.renderFirst())
  19099. hoistedSource += n + rendered;
  19100. else
  19101. magicString.addSource(new MagicString(rendered));
  19102. }
  19103. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  19104. if (accessedGlobalVariables) {
  19105. for (const name of accessedGlobalVariables) {
  19106. accessedGlobals.add(name);
  19107. }
  19108. }
  19109. }
  19110. const { renderedExports, removedExports } = module.getRenderedExports();
  19111. renderedModules[module.id] = {
  19112. get code() {
  19113. return source?.toString() ?? null;
  19114. },
  19115. originalLength: module.originalCode.length,
  19116. removedExports,
  19117. renderedExports,
  19118. renderedLength
  19119. };
  19120. }
  19121. if (hoistedSource)
  19122. magicString.prepend(hoistedSource + n + n);
  19123. if (this.needsExportsShim) {
  19124. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  19125. }
  19126. const renderedSource = compact ? magicString : magicString.trim();
  19127. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  19128. onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyChunk(this.getChunkName()));
  19129. }
  19130. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  19131. }
  19132. setDynamicImportResolutions(fileName) {
  19133. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  19134. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  19135. if (resolvedDynamicImport.chunk) {
  19136. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  19137. if (chunk === this) {
  19138. node.setInternalResolution(resolution.namespace);
  19139. }
  19140. else {
  19141. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  19142. }
  19143. }
  19144. else {
  19145. const { node, resolution } = resolvedDynamicImport;
  19146. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  19147. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes);
  19148. }
  19149. }
  19150. }
  19151. setIdentifierRenderResolutions() {
  19152. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  19153. const syntheticExports = new Set();
  19154. for (const exportName of this.getExportNames()) {
  19155. const exportVariable = this.exportsByName.get(exportName);
  19156. if (format !== 'es' &&
  19157. format !== 'system' &&
  19158. exportVariable.isReassigned &&
  19159. !exportVariable.isId) {
  19160. exportVariable.setRenderNames('exports', exportName);
  19161. }
  19162. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  19163. syntheticExports.add(exportVariable);
  19164. }
  19165. else {
  19166. exportVariable.setRenderNames(null, null);
  19167. }
  19168. }
  19169. for (const module of this.orderedModules) {
  19170. if (module.needsExportShim) {
  19171. this.needsExportsShim = true;
  19172. break;
  19173. }
  19174. }
  19175. const usedNames = new Set(['Object', 'Promise']);
  19176. if (this.needsExportsShim) {
  19177. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  19178. }
  19179. if (symbols) {
  19180. usedNames.add('Symbol');
  19181. }
  19182. switch (format) {
  19183. case 'system': {
  19184. usedNames.add('module').add('exports');
  19185. break;
  19186. }
  19187. case 'es': {
  19188. break;
  19189. }
  19190. case 'cjs': {
  19191. usedNames.add('module').add('require').add('__filename').add('__dirname');
  19192. }
  19193. // fallthrough
  19194. default: {
  19195. usedNames.add('exports');
  19196. for (const helper of HELPER_NAMES) {
  19197. usedNames.add(helper);
  19198. }
  19199. }
  19200. }
  19201. 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);
  19202. }
  19203. setImportMetaResolutions(fileName) {
  19204. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  19205. for (const module of orderedModules) {
  19206. for (const importMeta of module.importMetas) {
  19207. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  19208. }
  19209. if (includedNamespaces.has(module)) {
  19210. module.namespace.prepare(accessedGlobalsByScope);
  19211. }
  19212. }
  19213. }
  19214. setUpChunkImportsAndExportsForModule(module) {
  19215. const moduleImports = new Set(module.includedImports);
  19216. // when we are not preserving modules, we need to make all namespace variables available for
  19217. // rendering the namespace object
  19218. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  19219. const memberVariables = module.namespace.getMemberVariables();
  19220. for (const variable of Object.values(memberVariables)) {
  19221. if (variable.included) {
  19222. moduleImports.add(variable);
  19223. }
  19224. }
  19225. }
  19226. for (let variable of moduleImports) {
  19227. if (variable instanceof ExportDefaultVariable) {
  19228. variable = variable.getOriginalVariable();
  19229. }
  19230. if (variable instanceof SyntheticNamedExportVariable) {
  19231. variable = variable.getBaseVariable();
  19232. }
  19233. const chunk = this.chunkByModule.get(variable.module);
  19234. if (chunk !== this) {
  19235. this.imports.add(variable);
  19236. if (variable.module instanceof Module) {
  19237. this.checkCircularDependencyImport(variable, module);
  19238. // When preserving modules, we do not create namespace objects but directly
  19239. // use the actual namespaces, which would be broken by this logic.
  19240. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  19241. chunk.exports.add(variable);
  19242. }
  19243. }
  19244. }
  19245. }
  19246. if (this.includedNamespaces.has(module) ||
  19247. (module.info.isEntry && module.preserveSignature !== false) ||
  19248. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  19249. this.ensureReexportsAreAvailableForModule(module);
  19250. }
  19251. for (const { node, resolution } of module.dynamicImports) {
  19252. if (node.included &&
  19253. resolution instanceof Module &&
  19254. this.chunkByModule.get(resolution) === this &&
  19255. !this.includedNamespaces.has(resolution)) {
  19256. this.includedNamespaces.add(resolution);
  19257. this.ensureReexportsAreAvailableForModule(resolution);
  19258. }
  19259. }
  19260. }
  19261. }
  19262. function getChunkNameFromModule(module) {
  19263. return getPredefinedChunkNameFromModule(module) ?? parseAst_js.getAliasName(module.id);
  19264. }
  19265. function getPredefinedChunkNameFromModule(module) {
  19266. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  19267. }
  19268. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  19269. const importedBindingsPerDependency = {};
  19270. for (const [dependency, declaration] of renderedDependencies) {
  19271. const specifiers = new Set();
  19272. if (declaration.imports) {
  19273. for (const { imported } of declaration.imports) {
  19274. specifiers.add(imported);
  19275. }
  19276. }
  19277. if (declaration.reexports) {
  19278. for (const { imported } of declaration.reexports) {
  19279. specifiers.add(imported);
  19280. }
  19281. }
  19282. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  19283. }
  19284. return importedBindingsPerDependency;
  19285. }
  19286. const QUERY_HASH_REGEX = /[#?]/;
  19287. const resolveFileName = (dependency) => dependency.getFileName();
  19288. /**
  19289. * Concatenate a number of iterables to a new iterable without fully evaluating
  19290. * their iterators. Useful when e.g. working with large sets or lists and when
  19291. * there is a chance that the iterators will not be fully exhausted.
  19292. */
  19293. function* concatLazy(iterables) {
  19294. for (const iterable of iterables) {
  19295. yield* iterable;
  19296. }
  19297. }
  19298. /**
  19299. * At its core, the algorithm first starts from each static or dynamic entry
  19300. * point and then assigns that entry point to all modules than can be reached
  19301. * via static imports. We call this the *dependent entry points* of that
  19302. * module.
  19303. *
  19304. * Then we group all modules with the same dependent entry points into chunks
  19305. * as those modules will always be loaded together.
  19306. *
  19307. * One non-trivial optimization we can apply is that dynamic entries are
  19308. * different from static entries in so far as when a dynamic import occurs,
  19309. * some modules are already in memory. If some of these modules are also
  19310. * dependencies of the dynamic entry, then it does not make sense to create a
  19311. * separate chunk for them. Instead, the dynamic import target can load them
  19312. * from the importing chunk.
  19313. *
  19314. * With regard to chunking, if B is implicitly loaded after A, then this can be
  19315. * handled the same way as if there was a dynamic import A => B.
  19316. *
  19317. * Example:
  19318. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  19319. * Then the initial algorithm would assign A into the A chunk, C into the C
  19320. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  19321. * points A and C.
  19322. * However we know that C can only be loaded from A, so A and its dependency B
  19323. * must already be in memory when C is loaded. So it is enough to create only
  19324. * two chunks A containing [AB] and C containing [C].
  19325. *
  19326. * So we do not assign the dynamic entry C as dependent entry point to modules
  19327. * that are already loaded.
  19328. *
  19329. * In a more complex example, let us assume that we have entry points X and Y.
  19330. * Further, let us assume
  19331. * X -> A, X -> B, X -> C,
  19332. * Y -> A, Y -> B,
  19333. * A => D,
  19334. * D -> B, D -> C
  19335. * So without dynamic import optimization, the dependent entry points are
  19336. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  19337. * chunks.
  19338. *
  19339. * Now D is loaded only after A is loaded. But A is loaded if either X is
  19340. * loaded or Y is loaded. So the modules that are already in memory when D is
  19341. * loaded are the intersection of all modules that X depends on with all
  19342. * modules that Y depends on, which in this case are the modules A and B.
  19343. * We could also say they are all modules that have both X and Y as dependent
  19344. * entry points.
  19345. *
  19346. * So we can remove D as dependent entry point from A and B, which means they
  19347. * both now have only XY as dependent entry points and can be merged into the
  19348. * same chunk.
  19349. *
  19350. * Now let us extend this to the most general case where we have several
  19351. * dynamic importers for one dynamic entry point.
  19352. *
  19353. * In the most general form, it works like this:
  19354. * For each dynamic entry point, we have a number of dynamic importers, which
  19355. * are the modules importing it. Using the previous ideas, we can determine
  19356. * the modules already in memory for each dynamic importer by looking for all
  19357. * modules that have all the dependent entry points of the dynamic importer as
  19358. * dependent entry points.
  19359. * So the modules that are guaranteed to be in memory when the dynamic entry
  19360. * point is loaded are the intersection of the modules already in memory for
  19361. * each dynamic importer.
  19362. *
  19363. * Assuming that A => D and B => D and A has dependent entry points XY and B
  19364. * has dependent entry points YZ, then the modules guaranteed to be in memory
  19365. * are all modules that have at least XYZ as dependent entry points.
  19366. * We call XYZ the *dynamically dependent entry points* of D.
  19367. *
  19368. * Now there is one last case to consider: If one of the dynamically dependent
  19369. * entries is itself a dynamic entry, then any module is in memory that either
  19370. * is a dependency of that dynamic entry or again has the dynamic dependent
  19371. * entries of that dynamic entry as dependent entry points.
  19372. *
  19373. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  19374. * complexity with regard to dynamic entries that blew up for very large
  19375. * projects.
  19376. *
  19377. * If we have an efficient way to do Set operations, an alternative approach
  19378. * would be to instead collect already loaded modules per dynamic entry. And as
  19379. * all chunks from the initial grouping would behave the same, we can instead
  19380. * collect already loaded chunks for a performance improvement.
  19381. *
  19382. * To do that efficiently, need
  19383. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  19384. * imports that can be triggered by a dynamic entry
  19385. * - a Map of static dependencies per entry
  19386. * - a Map of already loaded chunks per entry that we initially populate with
  19387. * empty Sets for static entries and Sets containing all entries for dynamic
  19388. * entries
  19389. *
  19390. * For efficient operations, we assign each entry a numerical index and
  19391. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  19392. * bit index. Then the last two maps can be represented as arrays of BigInt
  19393. * values.
  19394. *
  19395. * Then we iterate through each dynamic entry. We set the already loaded modules
  19396. * to the intersection of the previously already loaded modules with the union
  19397. * of the already loaded modules of that chunk with its static dependencies.
  19398. *
  19399. * If the already loaded modules changed, then we use the Map of dynamic imports
  19400. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  19401. * them back into the iteration. As an additional optimization, we note for
  19402. * each dynamic entry which dynamic dependent entries have changed and only
  19403. * intersect those entries again on subsequent interations.
  19404. *
  19405. * Then we remove the dynamic entries from the list of dependent entries for
  19406. * those chunks that are already loaded for that dynamic entry and create
  19407. * another round of chunks.
  19408. */
  19409. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  19410. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  19411. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  19412. // Each chunk is identified by its position in this array
  19413. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  19414. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  19415. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19416. // If we no longer want this, we should make a copy here.
  19417. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  19418. // This mutates the dependentEntries in chunkAtoms
  19419. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry);
  19420. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  19421. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  19422. alias: null,
  19423. modules
  19424. })));
  19425. return chunkDefinitions;
  19426. }
  19427. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  19428. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  19429. const manualChunkModulesByAlias = Object.create(null);
  19430. for (const [entry, alias] of manualChunkAliasByEntry) {
  19431. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  19432. }
  19433. const manualChunks = Object.entries(manualChunkModulesByAlias);
  19434. const chunkDefinitions = new Array(manualChunks.length);
  19435. let index = 0;
  19436. for (const [alias, modules] of manualChunks) {
  19437. chunkDefinitions[index++] = { alias, modules };
  19438. }
  19439. return { chunkDefinitions, modulesInManualChunks };
  19440. }
  19441. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  19442. const modulesToHandle = new Set([entry]);
  19443. for (const module of modulesToHandle) {
  19444. modulesInManualChunks.add(module);
  19445. manualChunkModules.push(module);
  19446. for (const dependency of module.dependencies) {
  19447. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  19448. modulesToHandle.add(dependency);
  19449. }
  19450. }
  19451. }
  19452. }
  19453. function analyzeModuleGraph(entries) {
  19454. const dynamicEntryModules = new Set();
  19455. const dependentEntriesByModule = new Map();
  19456. const allEntriesSet = new Set(entries);
  19457. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  19458. let entryIndex = 0;
  19459. for (const currentEntry of allEntriesSet) {
  19460. const dynamicImportsForCurrentEntry = new Set();
  19461. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  19462. const modulesToHandle = new Set([currentEntry]);
  19463. for (const module of modulesToHandle) {
  19464. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  19465. for (const dependency of module.getDependenciesToBeIncluded()) {
  19466. if (!(dependency instanceof ExternalModule)) {
  19467. modulesToHandle.add(dependency);
  19468. }
  19469. }
  19470. for (const { resolution } of module.dynamicImports) {
  19471. if (resolution instanceof Module &&
  19472. resolution.includedDynamicImporters.length > 0 &&
  19473. !allEntriesSet.has(resolution)) {
  19474. dynamicEntryModules.add(resolution);
  19475. allEntriesSet.add(resolution);
  19476. dynamicImportsForCurrentEntry.add(resolution);
  19477. }
  19478. }
  19479. for (const dependency of module.implicitlyLoadedBefore) {
  19480. if (!allEntriesSet.has(dependency)) {
  19481. dynamicEntryModules.add(dependency);
  19482. allEntriesSet.add(dependency);
  19483. }
  19484. }
  19485. }
  19486. entryIndex++;
  19487. }
  19488. const allEntries = [...allEntriesSet];
  19489. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  19490. return {
  19491. allEntries,
  19492. dependentEntriesByModule,
  19493. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  19494. dynamicImportsByEntry
  19495. };
  19496. }
  19497. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  19498. const entryIndexByModule = new Map();
  19499. const dynamicEntries = new Set();
  19500. for (const [entryIndex, entry] of allEntries.entries()) {
  19501. entryIndexByModule.set(entry, entryIndex);
  19502. if (dynamicEntryModules.has(entry)) {
  19503. dynamicEntries.add(entryIndex);
  19504. }
  19505. }
  19506. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  19507. let index = 0;
  19508. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  19509. const dynamicImports = new Set();
  19510. for (const dynamicEntry of dynamicImportModules) {
  19511. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  19512. }
  19513. dynamicImportsByEntry[index++] = dynamicImports;
  19514. }
  19515. return { dynamicEntries, dynamicImportsByEntry };
  19516. }
  19517. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  19518. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  19519. for (const dynamicEntryIndex of dynamicEntries) {
  19520. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  19521. const dynamicEntry = allEntries[dynamicEntryIndex];
  19522. for (const importer of concatLazy([
  19523. dynamicEntry.includedDynamicImporters,
  19524. dynamicEntry.implicitlyLoadedAfter
  19525. ])) {
  19526. for (const entry of dependentEntriesByModule.get(importer)) {
  19527. dynamicallyDependentEntries.add(entry);
  19528. }
  19529. }
  19530. }
  19531. return dynamicallyDependentEntriesByDynamicEntry;
  19532. }
  19533. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  19534. const chunkModules = Object.create(null);
  19535. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  19536. let chunkSignature = 0n;
  19537. for (const entryIndex of dependentEntries) {
  19538. chunkSignature |= 1n << BigInt(entryIndex);
  19539. }
  19540. (chunkModules[String(chunkSignature)] ||= {
  19541. dependentEntries: new Set(dependentEntries),
  19542. modules: []
  19543. }).modules.push(...modules);
  19544. }
  19545. return Object.values(chunkModules);
  19546. }
  19547. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  19548. for (const [module, dependentEntries] of dependentEntriesByModule) {
  19549. if (!modulesInManualChunks.has(module)) {
  19550. yield { dependentEntries, modules: [module] };
  19551. }
  19552. }
  19553. }
  19554. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  19555. // The indices correspond to the indices in allEntries. The atoms correspond
  19556. // to bits in the bigint values where chunk 0 is the lowest bit.
  19557. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  19558. // This toggles the bits for each atom that is a dependency of an entry
  19559. let atomMask = 1n;
  19560. for (const { dependentEntries } of chunkAtoms) {
  19561. for (const entryIndex of dependentEntries) {
  19562. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  19563. }
  19564. atomMask <<= 1n;
  19565. }
  19566. return staticDependencyAtomsByEntry;
  19567. }
  19568. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19569. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  19570. // Dynamic entries have all atoms as already loaded initially because we then
  19571. // intersect with the static dependency atoms of all dynamic importers.
  19572. // Static entries cannot have already loaded atoms.
  19573. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  19574. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  19575. // We delete here so that they can be added again if necessary to be handled
  19576. // again by the loop
  19577. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  19578. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  19579. let updatedLoadedAtoms = knownLoadedAtoms;
  19580. for (const entryIndex of dynamicallyDependentEntries) {
  19581. updatedLoadedAtoms &=
  19582. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  19583. }
  19584. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  19585. // updated again
  19586. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  19587. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  19588. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  19589. // If this adds an entry that was deleted before, it will be handled
  19590. // again. This is the reason why we delete every entry from this map
  19591. // that we processed.
  19592. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  19593. }
  19594. }
  19595. }
  19596. return alreadyLoadedAtomsByEntry;
  19597. }
  19598. /**
  19599. * This removes all unnecessary dynamic entries from the dependentEntries in its
  19600. * first argument if a chunk is already loaded without that entry.
  19601. */
  19602. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry) {
  19603. // Remove entries from dependent entries if a chunk is already loaded without
  19604. // that entry.
  19605. let chunkMask = 1n;
  19606. for (const { dependentEntries } of chunkAtoms) {
  19607. for (const entryIndex of dependentEntries) {
  19608. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask) {
  19609. dependentEntries.delete(entryIndex);
  19610. }
  19611. }
  19612. chunkMask <<= 1n;
  19613. }
  19614. }
  19615. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  19616. const chunksBySignature = Object.create(null);
  19617. const chunkByModule = new Map();
  19618. const sizeByAtom = new Array(chunkAtoms.length);
  19619. let sideEffectAtoms = 0n;
  19620. let atomMask = 1n;
  19621. let index = 0;
  19622. for (const { dependentEntries, modules } of chunkAtoms) {
  19623. let chunkSignature = 0n;
  19624. let correlatedAtoms = -1n;
  19625. for (const entryIndex of dependentEntries) {
  19626. chunkSignature |= 1n << BigInt(entryIndex);
  19627. // Correlated atoms are the atoms that are guaranteed to be loaded as
  19628. // well when a given atom is loaded. It is the intersection of the already
  19629. // loaded modules of each chunk merged with its static dependencies.
  19630. correlatedAtoms &=
  19631. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  19632. }
  19633. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  19634. containedAtoms: 0n,
  19635. correlatedAtoms,
  19636. dependencies: new Set(),
  19637. dependentChunks: new Set(),
  19638. dependentEntries: new Set(dependentEntries),
  19639. modules: [],
  19640. pure: true,
  19641. size: 0
  19642. });
  19643. let atomSize = 0;
  19644. let pure = true;
  19645. for (const module of modules) {
  19646. chunkByModule.set(module, chunk);
  19647. // Unfortunately, we cannot take tree-shaking into account here because
  19648. // rendering did not happen yet, but we can detect empty modules
  19649. if (module.isIncluded()) {
  19650. pure &&= !module.hasEffects();
  19651. // we use a trivial size for the default minChunkSize to improve
  19652. // performance
  19653. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  19654. }
  19655. }
  19656. if (!pure) {
  19657. sideEffectAtoms |= atomMask;
  19658. }
  19659. sizeByAtom[index++] = atomSize;
  19660. chunk.containedAtoms |= atomMask;
  19661. chunk.modules.push(...modules);
  19662. chunk.pure &&= pure;
  19663. chunk.size += atomSize;
  19664. atomMask <<= 1n;
  19665. }
  19666. const chunks = Object.values(chunksBySignature);
  19667. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  19668. return { chunks, sideEffectAtoms, sizeByAtom };
  19669. }
  19670. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  19671. const signatureByExternalModule = new Map();
  19672. let externalSideEffectAtoms = 0n;
  19673. for (const chunk of chunks) {
  19674. const { dependencies, modules } = chunk;
  19675. for (const module of modules) {
  19676. for (const dependency of module.getDependenciesToBeIncluded()) {
  19677. if (dependency instanceof ExternalModule) {
  19678. if (dependency.info.moduleSideEffects) {
  19679. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  19680. const signature = nextAvailableAtomMask;
  19681. nextAvailableAtomMask <<= 1n;
  19682. externalSideEffectAtoms |= signature;
  19683. return signature;
  19684. });
  19685. chunk.containedAtoms |= signature;
  19686. chunk.correlatedAtoms |= signature;
  19687. }
  19688. }
  19689. else {
  19690. const dependencyChunk = chunkByModule.get(dependency);
  19691. if (dependencyChunk && dependencyChunk !== chunk) {
  19692. dependencies.add(dependencyChunk);
  19693. dependencyChunk.dependentChunks.add(chunk);
  19694. }
  19695. }
  19696. }
  19697. }
  19698. }
  19699. return externalSideEffectAtoms;
  19700. }
  19701. /**
  19702. * This function tries to get rid of small chunks by merging them with other
  19703. * chunks.
  19704. *
  19705. * We can only merge chunks safely if after the merge, loading any entry point
  19706. * in any allowed order will not trigger side effects that should not have been
  19707. * triggered. While side effects are usually things like global function calls,
  19708. * global variable mutations or potentially thrown errors, details do not
  19709. * matter here, and we just discern chunks without side effects (pure chunks)
  19710. * from other chunks.
  19711. *
  19712. * As a first step, we assign each pre-generated chunk with side effects a
  19713. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  19714. *
  19715. * Now to determine the side effects of loading a chunk, one also has to take
  19716. * the side effects of its dependencies into account. So if A depends on B
  19717. * (A -> B) and both have side effects, loading A triggers effects AB.
  19718. *
  19719. * Now from the previous step we know that each chunk is uniquely determine by
  19720. * the entry points that depend on it and cause it to load, which we will call
  19721. * its dependent entry points.
  19722. *
  19723. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  19724. * Starting from that idea, we can determine a set of chunks—and thus a set
  19725. * of side effects—that must have been triggered if a certain chunk has been
  19726. * loaded. Basically, it is the intersection of all chunks loaded by the
  19727. * dependent entry points of a given chunk. We call the corresponding side
  19728. * effects the correlated side effects of that chunk.
  19729. *
  19730. * Example:
  19731. * X -> ABC, Y -> ADE, A-> F, B -> D
  19732. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  19733. * The intersection is ADF. So we know that when A is loaded, D and F must also
  19734. * be in memory even though neither D nor A is a dependency of the other.
  19735. * If all have side effects, we call ADF the correlated side effects of A. The
  19736. * correlated side effects need to remain constant when merging chunks.
  19737. *
  19738. * In contrast, we have the dependency side effects of A, which represents
  19739. * the side effects we trigger if we directly load A. In this example, the
  19740. * dependency side effects are AF.
  19741. * For entry chunks, dependency and correlated side effects are the same.
  19742. *
  19743. * With these concepts, merging chunks is allowed if the correlated side
  19744. * effects of each entry do not change. Thus, we are allowed to merge two
  19745. * chunks if
  19746. *
  19747. * a) the dependency side effects of each chunk are a subset of the correlated
  19748. * side effects of the other chunk, so no additional side effects are
  19749. * triggered for any entry, or
  19750. * b) The dependent entry points of chunk A are a subset of the dependent entry
  19751. * points of chunk B while the dependency side effects of A are a subset of
  19752. * the correlated side effects of B. Because in that scenario, whenever A is
  19753. * loaded, B is loaded as well. But there are cases when B is loaded where A
  19754. * is not loaded. So if we merge the chunks, all dependency side effects of
  19755. * A will be added to the correlated side effects of B, and as the latter is
  19756. * not allowed to change, the former need to be a subset of the latter.
  19757. *
  19758. * Another consideration when merging small chunks into other chunks is to
  19759. * avoid
  19760. * that too much additional code is loaded. This is achieved when the dependent
  19761. * entries of the small chunk are a subset of the dependent entries of the
  19762. * other
  19763. * chunk. Because then when the small chunk is loaded, the other chunk was
  19764. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  19765. * additional size of the small chunk is loaded unnecessarily.
  19766. *
  19767. * So the algorithm performs merges in two passes:
  19768. *
  19769. * 1. First we try to merge small chunks A only into other chunks B if the
  19770. * dependent entries of A are a subset of the dependent entries of B and the
  19771. * dependency side effects of A are a subset of the correlated side effects
  19772. * of B.
  19773. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  19774. * following the rule (a), starting with the smallest chunks to look for
  19775. * possible merge targets.
  19776. */
  19777. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  19778. timeStart('optimize chunks', 3);
  19779. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  19780. if (!chunkPartition) {
  19781. timeEnd('optimize chunks', 3);
  19782. return chunks; // the actual modules
  19783. }
  19784. if (minChunkSize > 1) {
  19785. log('info', parseAst_js.logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  19786. }
  19787. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  19788. if (minChunkSize > 1) {
  19789. log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  19790. }
  19791. timeEnd('optimize chunks', 3);
  19792. return [...chunkPartition.small, ...chunkPartition.big];
  19793. }
  19794. function getPartitionedChunks(chunks, minChunkSize) {
  19795. const smallChunks = [];
  19796. const bigChunks = [];
  19797. for (const chunk of chunks) {
  19798. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  19799. }
  19800. if (smallChunks.length === 0) {
  19801. return null;
  19802. }
  19803. smallChunks.sort(compareChunkSize);
  19804. bigChunks.sort(compareChunkSize);
  19805. return {
  19806. big: new Set(bigChunks),
  19807. small: new Set(smallChunks)
  19808. };
  19809. }
  19810. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  19811. return sizeA - sizeB;
  19812. }
  19813. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  19814. const { small } = chunkPartition;
  19815. for (const mergedChunk of small) {
  19816. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  19817. // In the default case, we do not accept size increases
  19818. minChunkSize <= 1 ? 1 : Infinity);
  19819. if (bestTargetChunk) {
  19820. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  19821. small.delete(mergedChunk);
  19822. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  19823. bestTargetChunk.modules.push(...modules);
  19824. bestTargetChunk.size += size;
  19825. bestTargetChunk.pure &&= pure;
  19826. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  19827. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  19828. bestTargetChunk.containedAtoms |= containedAtoms;
  19829. for (const entry of mergedChunk.dependentEntries) {
  19830. dependentEntries.add(entry);
  19831. }
  19832. for (const dependency of mergedChunk.dependencies) {
  19833. dependencies.add(dependency);
  19834. dependency.dependentChunks.delete(mergedChunk);
  19835. dependency.dependentChunks.add(bestTargetChunk);
  19836. }
  19837. for (const dependentChunk of mergedChunk.dependentChunks) {
  19838. dependentChunks.add(dependentChunk);
  19839. dependentChunk.dependencies.delete(mergedChunk);
  19840. dependentChunk.dependencies.add(bestTargetChunk);
  19841. }
  19842. dependencies.delete(bestTargetChunk);
  19843. dependentChunks.delete(bestTargetChunk);
  19844. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  19845. }
  19846. }
  19847. }
  19848. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  19849. let bestTargetChunk = null;
  19850. // In the default case, we do not accept size increases
  19851. for (const targetChunk of concatLazy([small, big])) {
  19852. if (mergedChunk === targetChunk)
  19853. continue;
  19854. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  19855. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  19856. bestTargetChunk = targetChunk;
  19857. if (additionalSizeAfterMerge === 0)
  19858. break;
  19859. smallestAdditionalSize = additionalSizeAfterMerge;
  19860. }
  19861. }
  19862. return bestTargetChunk;
  19863. }
  19864. /**
  19865. * Determine the additional unused code size that would be added by merging the
  19866. * two chunks. This is not an exact measurement but rather an upper bound. If
  19867. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  19868. * is returned.
  19869. * Merging will not produce cycles if none of the direct non-merged
  19870. * dependencies of a chunk have the other chunk as a transitive dependency.
  19871. */
  19872. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  19873. // The maximum additional unused code size allowed to be added by the merge,
  19874. // taking dependencies into account, needs to be below this number
  19875. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  19876. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  19877. return firstSize < currentAdditionalSize
  19878. ? firstSize +
  19879. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  19880. : Infinity;
  19881. }
  19882. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  19883. const { correlatedAtoms } = dependencyChunk;
  19884. let dependencyAtoms = dependentChunk.containedAtoms;
  19885. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  19886. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  19887. return Infinity;
  19888. }
  19889. const chunksToCheck = new Set(dependentChunk.dependencies);
  19890. for (const { dependencies, containedAtoms } of chunksToCheck) {
  19891. dependencyAtoms |= containedAtoms;
  19892. const containedSideEffects = containedAtoms & sideEffectAtoms;
  19893. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  19894. return Infinity;
  19895. }
  19896. for (const dependency of dependencies) {
  19897. if (dependency === dependencyChunk) {
  19898. return Infinity;
  19899. }
  19900. chunksToCheck.add(dependency);
  19901. }
  19902. }
  19903. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  19904. }
  19905. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  19906. let size = 0;
  19907. let atomIndex = 0;
  19908. let atomSignature = 1n;
  19909. const { length } = sizeByAtom;
  19910. for (; atomIndex < length; atomIndex++) {
  19911. if ((atoms & atomSignature) === atomSignature) {
  19912. size += sizeByAtom[atomIndex];
  19913. }
  19914. atomSignature <<= 1n;
  19915. if (size >= currentAdditionalSize) {
  19916. return Infinity;
  19917. }
  19918. }
  19919. return size;
  19920. }
  19921. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  19922. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  19923. }
  19924. // ported from https://github.com/substack/node-commondir
  19925. function commondir(files) {
  19926. if (files.length === 0)
  19927. return '/';
  19928. if (files.length === 1)
  19929. return path.dirname(files[0]);
  19930. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  19931. const pathSegments = file.split(/\/+|\\+/);
  19932. let index;
  19933. for (index = 0; commonSegments[index] === pathSegments[index] &&
  19934. index < Math.min(commonSegments.length, pathSegments.length); index++)
  19935. ;
  19936. return commonSegments.slice(0, index);
  19937. }, files[0].split(/\/+|\\+/));
  19938. // Windows correctly handles paths with forward-slashes
  19939. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  19940. }
  19941. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  19942. function sortByExecutionOrder(units) {
  19943. units.sort(compareExecIndex);
  19944. }
  19945. // This process is currently faulty in so far as it only takes the first entry
  19946. // module into account and assumes that dynamic imports are imported in a
  19947. // certain order.
  19948. // A better algorithm would follow every possible execution path and mark which
  19949. // modules are executed before or after which other modules. THen the chunking
  19950. // would need to take care that in each chunk, all modules are always executed
  19951. // in the same sequence.
  19952. function analyseModuleExecution(entryModules) {
  19953. let nextExecIndex = 0;
  19954. const cyclePaths = [];
  19955. const analysedModules = new Set();
  19956. const dynamicImports = new Set();
  19957. const parents = new Map();
  19958. const orderedModules = [];
  19959. const analyseModule = (module) => {
  19960. if (module instanceof Module) {
  19961. for (const dependency of module.dependencies) {
  19962. if (parents.has(dependency)) {
  19963. if (!analysedModules.has(dependency)) {
  19964. cyclePaths.push(getCyclePath(dependency, module, parents));
  19965. }
  19966. continue;
  19967. }
  19968. parents.set(dependency, module);
  19969. analyseModule(dependency);
  19970. }
  19971. for (const dependency of module.implicitlyLoadedBefore) {
  19972. dynamicImports.add(dependency);
  19973. }
  19974. for (const { resolution } of module.dynamicImports) {
  19975. if (resolution instanceof Module) {
  19976. dynamicImports.add(resolution);
  19977. }
  19978. }
  19979. orderedModules.push(module);
  19980. }
  19981. module.execIndex = nextExecIndex++;
  19982. analysedModules.add(module);
  19983. };
  19984. for (const currentEntry of entryModules) {
  19985. if (!parents.has(currentEntry)) {
  19986. parents.set(currentEntry, null);
  19987. analyseModule(currentEntry);
  19988. }
  19989. }
  19990. for (const currentEntry of dynamicImports) {
  19991. if (!parents.has(currentEntry)) {
  19992. parents.set(currentEntry, null);
  19993. analyseModule(currentEntry);
  19994. }
  19995. }
  19996. return { cyclePaths, orderedModules };
  19997. }
  19998. function getCyclePath(module, parent, parents) {
  19999. const cycleSymbol = Symbol(module.id);
  20000. const path = [module.id];
  20001. let nextModule = parent;
  20002. module.cycles.add(cycleSymbol);
  20003. while (nextModule !== module) {
  20004. nextModule.cycles.add(cycleSymbol);
  20005. path.push(nextModule.id);
  20006. nextModule = parents.get(nextModule);
  20007. }
  20008. path.push(path[0]);
  20009. path.reverse();
  20010. return path;
  20011. }
  20012. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  20013. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  20014. const cnst = constBindings ? 'const' : 'var';
  20015. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  20016. const getFunctionIntro = arrowFunctions
  20017. ? (parameters, { isAsync, name }) => {
  20018. const singleParameter = parameters.length === 1;
  20019. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  20020. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  20021. }
  20022. : getNonArrowFunctionIntro;
  20023. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  20024. `${getFunctionIntro(parameters, {
  20025. isAsync: false,
  20026. name
  20027. })}${arrowFunctions
  20028. ? lineBreakIndent
  20029. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  20030. : ''
  20031. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  20032. arrowFunctions
  20033. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  20034. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  20035. ];
  20036. const isValidPropertyName = reservedNamesAsProps
  20037. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  20038. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  20039. return {
  20040. _,
  20041. cnst,
  20042. getDirectReturnFunction,
  20043. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  20044. const [left, right] = getDirectReturnFunction(parameters, {
  20045. functionReturn: true,
  20046. lineBreakIndent: null,
  20047. name: null
  20048. });
  20049. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  20050. },
  20051. getFunctionIntro,
  20052. getNonArrowFunctionIntro,
  20053. getObject(fields, { lineBreakIndent }) {
  20054. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  20055. return `{${fields
  20056. .map(([key, value]) => {
  20057. if (key === null)
  20058. return `${prefix}${value}`;
  20059. const keyInObject = stringifyObjectKeyIfNeeded(key);
  20060. return key === value && objectShorthand && key === keyInObject
  20061. ? prefix + key
  20062. : `${prefix}${keyInObject}:${_}${value}`;
  20063. })
  20064. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  20065. },
  20066. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  20067. n,
  20068. s
  20069. };
  20070. }
  20071. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  20072. class Source {
  20073. constructor(filename, content) {
  20074. this.isOriginal = true;
  20075. this.filename = filename;
  20076. this.content = content;
  20077. }
  20078. traceSegment(line, column, name) {
  20079. return { column, line, name, source: this };
  20080. }
  20081. }
  20082. class Link {
  20083. constructor(map, sources) {
  20084. this.sources = sources;
  20085. this.names = map.names;
  20086. this.mappings = map.mappings;
  20087. }
  20088. traceMappings() {
  20089. const sources = [];
  20090. const sourceIndexMap = new Map();
  20091. const sourcesContent = [];
  20092. const names = [];
  20093. const nameIndexMap = new Map();
  20094. const mappings = [];
  20095. for (const line of this.mappings) {
  20096. const tracedLine = [];
  20097. for (const segment of line) {
  20098. if (segment.length === 1)
  20099. continue;
  20100. const source = this.sources[segment[1]];
  20101. if (!source)
  20102. continue;
  20103. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  20104. if (traced) {
  20105. const { column, line, name, source: { content, filename } } = traced;
  20106. let sourceIndex = sourceIndexMap.get(filename);
  20107. if (sourceIndex === undefined) {
  20108. sourceIndex = sources.length;
  20109. sources.push(filename);
  20110. sourceIndexMap.set(filename, sourceIndex);
  20111. sourcesContent[sourceIndex] = content;
  20112. }
  20113. else if (sourcesContent[sourceIndex] == null) {
  20114. sourcesContent[sourceIndex] = content;
  20115. }
  20116. else if (content != null && sourcesContent[sourceIndex] !== content) {
  20117. return parseAst_js.error(parseAst_js.logConflictingSourcemapSources(filename));
  20118. }
  20119. const tracedSegment = [segment[0], sourceIndex, line, column];
  20120. if (name) {
  20121. let nameIndex = nameIndexMap.get(name);
  20122. if (nameIndex === undefined) {
  20123. nameIndex = names.length;
  20124. names.push(name);
  20125. nameIndexMap.set(name, nameIndex);
  20126. }
  20127. tracedSegment[4] = nameIndex;
  20128. }
  20129. tracedLine.push(tracedSegment);
  20130. }
  20131. }
  20132. mappings.push(tracedLine);
  20133. }
  20134. return { mappings, names, sources, sourcesContent };
  20135. }
  20136. traceSegment(line, column, name) {
  20137. const segments = this.mappings[line];
  20138. if (!segments)
  20139. return null;
  20140. // binary search through segments for the given column
  20141. let searchStart = 0;
  20142. let searchEnd = segments.length - 1;
  20143. while (searchStart <= searchEnd) {
  20144. const m = (searchStart + searchEnd) >> 1;
  20145. const segment = segments[m];
  20146. // If a sourcemap does not have sufficient resolution to contain a
  20147. // necessary mapping, e.g. because it only contains line information, we
  20148. // use the best approximation we could find
  20149. if (segment[0] === column || searchStart === searchEnd) {
  20150. if (segment.length == 1)
  20151. return null;
  20152. const source = this.sources[segment[1]];
  20153. if (!source)
  20154. return null;
  20155. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  20156. }
  20157. if (segment[0] > column) {
  20158. searchEnd = m - 1;
  20159. }
  20160. else {
  20161. searchStart = m + 1;
  20162. }
  20163. }
  20164. return null;
  20165. }
  20166. }
  20167. function getLinkMap(log) {
  20168. return function linkMap(source, map) {
  20169. if (!map.missing) {
  20170. return new Link(map, [source]);
  20171. }
  20172. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logSourcemapBroken(map.plugin));
  20173. return new Link({
  20174. mappings: [],
  20175. names: []
  20176. }, [source]);
  20177. };
  20178. }
  20179. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  20180. let source;
  20181. if (originalSourcemap) {
  20182. const sources = originalSourcemap.sources;
  20183. const sourcesContent = originalSourcemap.sourcesContent || [];
  20184. const directory = path.dirname(id) || '.';
  20185. const sourceRoot = originalSourcemap.sourceRoot || '.';
  20186. const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  20187. source = new Link(originalSourcemap, baseSources);
  20188. }
  20189. else {
  20190. source = new Source(id, originalCode);
  20191. }
  20192. return sourcemapChain.reduce(linkMap, source);
  20193. }
  20194. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  20195. const linkMap = getLinkMap(log);
  20196. const moduleSources = modules
  20197. .filter(module => !module.excludeFromSourcemap)
  20198. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  20199. const link = new Link(map, moduleSources);
  20200. const source = bundleSourcemapChain.reduce(linkMap, link);
  20201. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  20202. if (file) {
  20203. const directory = path.dirname(file);
  20204. sources = sources.map((source) => path.relative(directory, source));
  20205. file = path.basename(file);
  20206. }
  20207. sourcesContent = (excludeContent ? null : sourcesContent);
  20208. for (const module of modules) {
  20209. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  20210. }
  20211. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  20212. }
  20213. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  20214. if (sourcemapChain.length === 0) {
  20215. return originalSourcemap;
  20216. }
  20217. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  20218. const map = source.traceMappings();
  20219. return decodedSourcemap({ version: 3, ...map });
  20220. }
  20221. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  20222. // this for an actual sourceMappingURL
  20223. let SOURCEMAPPING_URL = 'sourceMa';
  20224. SOURCEMAPPING_URL += 'ppingURL';
  20225. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  20226. timeStart('render chunks', 2);
  20227. reserveEntryChunksInBundle(chunks);
  20228. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  20229. timeEnd('render chunks', 2);
  20230. timeStart('transform chunks', 2);
  20231. const getHash = hasherByType[outputOptions.hashCharacters];
  20232. const chunkGraph = getChunkGraph(chunks);
  20233. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  20234. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  20235. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  20236. timeEnd('transform chunks', 2);
  20237. }
  20238. function reserveEntryChunksInBundle(chunks) {
  20239. for (const chunk of chunks) {
  20240. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  20241. // reserves name in bundle as side effect if it does not contain a hash
  20242. chunk.getPreliminaryFileName();
  20243. }
  20244. }
  20245. }
  20246. function getChunkGraph(chunks) {
  20247. return Object.fromEntries(chunks.map(chunk => {
  20248. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  20249. return [renderedChunkInfo.fileName, renderedChunkInfo];
  20250. }));
  20251. }
  20252. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  20253. let map = null;
  20254. const sourcemapChain = [];
  20255. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  20256. if (result == null)
  20257. return code;
  20258. if (typeof result === 'string')
  20259. result = {
  20260. code: result,
  20261. map: undefined
  20262. };
  20263. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  20264. if (result.map !== null) {
  20265. const map = decodedSourcemap(result.map);
  20266. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  20267. }
  20268. return result.code;
  20269. });
  20270. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  20271. if (!compact && code[code.length - 1] !== '\n')
  20272. code += '\n';
  20273. if (sourcemap) {
  20274. timeStart('sourcemaps', 3);
  20275. let resultingFile;
  20276. if (file)
  20277. resultingFile = path.resolve(sourcemapFile || file);
  20278. else if (dir)
  20279. resultingFile = path.resolve(dir, fileName);
  20280. else
  20281. resultingFile = path.resolve(fileName);
  20282. const decodedMap = magicString.generateDecodedMap({});
  20283. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  20284. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  20285. let sourcePath = map.sources[sourcesIndex];
  20286. const sourcemapPath = `${resultingFile}.map`;
  20287. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  20288. if (typeof ignoreList !== 'boolean') {
  20289. parseAst_js.error(parseAst_js.logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  20290. }
  20291. if (ignoreList) {
  20292. if (map.x_google_ignoreList === undefined) {
  20293. map.x_google_ignoreList = [];
  20294. }
  20295. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  20296. map.x_google_ignoreList.push(sourcesIndex);
  20297. }
  20298. }
  20299. if (sourcemapPathTransform) {
  20300. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  20301. if (typeof sourcePath !== 'string') {
  20302. parseAst_js.error(parseAst_js.logFailedValidation(`sourcemapPathTransform function must return a string.`));
  20303. }
  20304. }
  20305. map.sources[sourcesIndex] = parseAst_js.normalize(sourcePath);
  20306. }
  20307. timeEnd('sourcemaps', 3);
  20308. }
  20309. return {
  20310. code,
  20311. map
  20312. };
  20313. }
  20314. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  20315. const nonHashedChunksWithPlaceholders = [];
  20316. const renderedChunksByPlaceholder = new Map();
  20317. const hashDependenciesByPlaceholder = new Map();
  20318. const initialHashesByPlaceholder = new Map();
  20319. const placeholders = new Set();
  20320. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  20321. if (hashPlaceholder)
  20322. placeholders.add(hashPlaceholder);
  20323. }
  20324. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  20325. const transformedChunk = {
  20326. chunk,
  20327. fileName,
  20328. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  20329. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  20330. };
  20331. const { code, map } = transformedChunk;
  20332. if (hashPlaceholder) {
  20333. // To create a reproducible content-only hash, all placeholders are
  20334. // replaced with the same value before hashing
  20335. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  20336. let contentToHash = transformedCode;
  20337. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  20338. if (pluginHash) {
  20339. augmentation += pluginHash;
  20340. }
  20341. return augmentation;
  20342. });
  20343. if (hashAugmentation) {
  20344. contentToHash += hashAugmentation;
  20345. }
  20346. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  20347. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  20348. containedPlaceholders,
  20349. contentHash: getHash(contentToHash)
  20350. });
  20351. }
  20352. else {
  20353. nonHashedChunksWithPlaceholders.push(transformedChunk);
  20354. }
  20355. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  20356. if (map && sourcemapHashPlaceholder) {
  20357. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  20358. }
  20359. }));
  20360. return {
  20361. hashDependenciesByPlaceholder,
  20362. initialHashesByPlaceholder,
  20363. nonHashedChunksWithPlaceholders,
  20364. placeholders,
  20365. renderedChunksByPlaceholder
  20366. };
  20367. }
  20368. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  20369. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  20370. for (const placeholder of placeholders) {
  20371. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  20372. let contentToHash = '';
  20373. const hashDependencyPlaceholders = new Set([placeholder]);
  20374. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  20375. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  20376. contentToHash += contentHash;
  20377. for (const containedPlaceholder of containedPlaceholders) {
  20378. // When looping over a map, setting an entry only causes a new iteration if the key is new
  20379. hashDependencyPlaceholders.add(containedPlaceholder);
  20380. }
  20381. }
  20382. let finalFileName;
  20383. let finalHash;
  20384. do {
  20385. // In case of a hash collision, create a hash of the hash
  20386. if (finalHash) {
  20387. contentToHash = finalHash;
  20388. }
  20389. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  20390. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  20391. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  20392. bundle[finalFileName] = FILE_PLACEHOLDER;
  20393. hashesByPlaceholder.set(placeholder, finalHash);
  20394. }
  20395. return hashesByPlaceholder;
  20396. }
  20397. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  20398. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  20399. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  20400. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  20401. let finalSourcemapFileName = null;
  20402. if (map) {
  20403. if (options.sourcemapDebugIds) {
  20404. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20405. }
  20406. finalSourcemapFileName = sourcemapFileName
  20407. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20408. : `${finalFileName}.map`;
  20409. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  20410. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20411. }
  20412. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  20413. }
  20414. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  20415. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  20416. let finalSourcemapFileName = null;
  20417. if (map) {
  20418. if (options.sourcemapDebugIds) {
  20419. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  20420. }
  20421. finalSourcemapFileName = sourcemapFileName
  20422. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  20423. : `${fileName}.map`;
  20424. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  20425. }
  20426. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  20427. }
  20428. }
  20429. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  20430. let url;
  20431. if (sourcemap === 'inline') {
  20432. url = map.toUrl();
  20433. }
  20434. else {
  20435. const sourcemapFileName = path.basename(fileName);
  20436. url = sourcemapBaseUrl
  20437. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  20438. : sourcemapFileName;
  20439. pluginDriver.emitFile({
  20440. fileName,
  20441. originalFileName: null,
  20442. source: map.toString(),
  20443. type: 'asset'
  20444. });
  20445. }
  20446. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  20447. }
  20448. function calculateDebugIdAndGetComment(code, map) {
  20449. const hash = hasherByType.hex(code);
  20450. const debugId = [
  20451. hash.slice(0, 8),
  20452. hash.slice(8, 12),
  20453. '4' + hash.slice(12, 15),
  20454. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  20455. hash.slice(20, 32)
  20456. ].join('-');
  20457. map.debugId = debugId;
  20458. return '//# debugId=' + debugId + '\n';
  20459. }
  20460. class Bundle {
  20461. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  20462. this.outputOptions = outputOptions;
  20463. this.unsetOptions = unsetOptions;
  20464. this.inputOptions = inputOptions;
  20465. this.pluginDriver = pluginDriver;
  20466. this.graph = graph;
  20467. this.facadeChunkByModule = new Map();
  20468. this.includedNamespaces = new Set();
  20469. }
  20470. async generate(isWrite) {
  20471. timeStart('GENERATE', 1);
  20472. const outputBundleBase = Object.create(null);
  20473. const outputBundle = getOutputBundle(outputBundleBase);
  20474. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  20475. try {
  20476. timeStart('initialize render', 2);
  20477. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  20478. timeEnd('initialize render', 2);
  20479. timeStart('generate chunks', 2);
  20480. const getHashPlaceholder = getHashPlaceholderGenerator();
  20481. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  20482. if (chunks.length > 1) {
  20483. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  20484. }
  20485. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  20486. for (const chunk of chunks) {
  20487. chunk.generateExports();
  20488. }
  20489. timeEnd('generate chunks', 2);
  20490. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  20491. }
  20492. catch (error_) {
  20493. await this.pluginDriver.hookParallel('renderError', [error_]);
  20494. throw error_;
  20495. }
  20496. removeUnreferencedAssets(outputBundle);
  20497. timeStart('generate bundle', 2);
  20498. await this.pluginDriver.hookSeq('generateBundle', [
  20499. this.outputOptions,
  20500. outputBundle,
  20501. isWrite
  20502. ]);
  20503. this.finaliseAssets(outputBundle);
  20504. timeEnd('generate bundle', 2);
  20505. timeEnd('GENERATE', 1);
  20506. return outputBundleBase;
  20507. }
  20508. async addManualChunks(manualChunks) {
  20509. const manualChunkAliasByEntry = new Map();
  20510. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  20511. alias,
  20512. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  20513. })));
  20514. for (const { alias, entries } of chunkEntries) {
  20515. for (const entry of entries) {
  20516. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  20517. }
  20518. }
  20519. return manualChunkAliasByEntry;
  20520. }
  20521. assignManualChunks(getManualChunk) {
  20522. const manualChunkAliasesWithEntry = [];
  20523. const manualChunksApi = {
  20524. getModuleIds: () => this.graph.modulesById.keys(),
  20525. getModuleInfo: this.graph.getModuleInfo
  20526. };
  20527. for (const module of this.graph.modulesById.values()) {
  20528. if (module instanceof Module) {
  20529. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  20530. if (typeof manualChunkAlias === 'string') {
  20531. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  20532. }
  20533. }
  20534. }
  20535. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  20536. const manualChunkAliasByEntry = new Map();
  20537. for (const [alias, module] of manualChunkAliasesWithEntry) {
  20538. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  20539. }
  20540. return manualChunkAliasByEntry;
  20541. }
  20542. finaliseAssets(bundle) {
  20543. if (this.outputOptions.validate) {
  20544. for (const file of Object.values(bundle)) {
  20545. if ('code' in file) {
  20546. try {
  20547. parseAst_js.parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  20548. }
  20549. catch (error_) {
  20550. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logChunkInvalid(file, error_));
  20551. }
  20552. }
  20553. }
  20554. }
  20555. this.pluginDriver.finaliseAssets();
  20556. }
  20557. async generateChunks(bundle, getHashPlaceholder) {
  20558. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  20559. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  20560. ? await this.addManualChunks(manualChunks)
  20561. : this.assignManualChunks(manualChunks);
  20562. const snippets = getGenerateCodeSnippets(this.outputOptions);
  20563. const includedModules = getIncludedModules(this.graph.modulesById);
  20564. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  20565. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  20566. const executableModule = inlineDynamicImports
  20567. ? [{ alias: null, modules: includedModules }]
  20568. : preserveModules
  20569. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  20570. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog);
  20571. const chunks = new Array(executableModule.length);
  20572. const chunkByModule = new Map();
  20573. let index = 0;
  20574. for (const { alias, modules } of executableModule) {
  20575. sortByExecutionOrder(modules);
  20576. 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);
  20577. chunks[index++] = chunk;
  20578. }
  20579. for (const chunk of chunks) {
  20580. chunk.link();
  20581. }
  20582. const facades = [];
  20583. for (const chunk of chunks) {
  20584. facades.push(...chunk.generateFacades());
  20585. }
  20586. return [...chunks, ...facades];
  20587. }
  20588. }
  20589. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  20590. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  20591. 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));
  20592. if (typeof outputOptions.file === 'string')
  20593. 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'));
  20594. if (outputOptions.sourcemapFile)
  20595. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapFile', parseAst_js.URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  20596. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  20597. 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'));
  20598. }
  20599. function getIncludedModules(modulesById) {
  20600. const includedModules = [];
  20601. for (const module of modulesById.values()) {
  20602. if (module instanceof Module &&
  20603. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  20604. includedModules.push(module);
  20605. }
  20606. }
  20607. return includedModules;
  20608. }
  20609. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  20610. const absoluteEntryModulePaths = [];
  20611. for (const module of includedModules) {
  20612. if ((module.info.isEntry || preserveModules) && parseAst_js.isAbsolute(module.id)) {
  20613. absoluteEntryModulePaths.push(module.id);
  20614. }
  20615. }
  20616. return absoluteEntryModulePaths;
  20617. }
  20618. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  20619. const externalChunkByModule = new Map();
  20620. for (const module of modulesById.values()) {
  20621. if (module instanceof ExternalModule) {
  20622. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  20623. }
  20624. }
  20625. return externalChunkByModule;
  20626. }
  20627. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  20628. const existingAlias = manualChunkAliasByEntry.get(module);
  20629. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  20630. return parseAst_js.error(parseAst_js.logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  20631. }
  20632. manualChunkAliasByEntry.set(module, alias);
  20633. }
  20634. function flru (max) {
  20635. var num, curr, prev;
  20636. var limit = max;
  20637. function keep(key, value) {
  20638. if (++num > limit) {
  20639. prev = curr;
  20640. reset(1);
  20641. ++num;
  20642. }
  20643. curr[key] = value;
  20644. }
  20645. function reset(isPartial) {
  20646. num = 0;
  20647. curr = Object.create(null);
  20648. isPartial || (prev=Object.create(null));
  20649. }
  20650. reset();
  20651. return {
  20652. clear: reset,
  20653. has: function (key) {
  20654. return curr[key] !== void 0 || prev[key] !== void 0;
  20655. },
  20656. get: function (key) {
  20657. var val = curr[key];
  20658. if (val !== void 0) return val;
  20659. if ((val=prev[key]) !== void 0) {
  20660. keep(key, val);
  20661. return val;
  20662. }
  20663. },
  20664. set: function (key, value) {
  20665. if (curr[key] !== void 0) {
  20666. curr[key] = value;
  20667. } else {
  20668. keep(key, value);
  20669. }
  20670. }
  20671. };
  20672. }
  20673. class GlobalScope extends Scope {
  20674. constructor() {
  20675. super();
  20676. this.parent = null;
  20677. this.variables.set('undefined', new UndefinedVariable());
  20678. }
  20679. findVariable(name) {
  20680. let variable = this.variables.get(name);
  20681. if (!variable) {
  20682. variable = new GlobalVariable(name);
  20683. this.variables.set(name, variable);
  20684. }
  20685. return variable;
  20686. }
  20687. }
  20688. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  20689. let skipped = null;
  20690. let replaceContext = null;
  20691. if (skip) {
  20692. skipped = new Set();
  20693. for (const skippedCall of skip) {
  20694. if (source === skippedCall.source && importer === skippedCall.importer) {
  20695. skipped.add(skippedCall.plugin);
  20696. }
  20697. }
  20698. replaceContext = (pluginContext, plugin) => ({
  20699. ...pluginContext,
  20700. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) => {
  20701. skipSelf ??= true;
  20702. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20703. }
  20704. });
  20705. }
  20706. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  20707. }
  20708. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  20709. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  20710. if (pluginResult != null) {
  20711. const [resolveIdResult, plugin] = pluginResult;
  20712. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  20713. return {
  20714. ...resolveIdResult,
  20715. resolvedBy: plugin.name
  20716. };
  20717. }
  20718. if (typeof resolveIdResult === 'string') {
  20719. return {
  20720. id: resolveIdResult,
  20721. resolvedBy: plugin.name
  20722. };
  20723. }
  20724. return resolveIdResult;
  20725. }
  20726. // external modules (non-entry modules that start with neither '.' or '/')
  20727. // are skipped at this stage.
  20728. if (importer !== undefined && !parseAst_js.isAbsolute(source) && source[0] !== '.')
  20729. return null;
  20730. // `resolve` processes paths from right to left, prepending them until an
  20731. // absolute path is created. Absolute importees therefore shortcircuit the
  20732. // resolve call and require no special handing on our part.
  20733. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20734. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
  20735. }
  20736. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20737. return ((await findFile(file, preserveSymlinks)) ??
  20738. (await findFile(file + '.mjs', preserveSymlinks)) ??
  20739. (await findFile(file + '.js', preserveSymlinks)));
  20740. }
  20741. async function findFile(file, preserveSymlinks) {
  20742. try {
  20743. const stats = await promises.lstat(file);
  20744. if (!preserveSymlinks && stats.isSymbolicLink())
  20745. return await findFile(await promises.realpath(file), preserveSymlinks);
  20746. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20747. // check case
  20748. const name = path.basename(file);
  20749. const files = await promises.readdir(path.dirname(file));
  20750. if (files.includes(name))
  20751. return file;
  20752. }
  20753. }
  20754. catch {
  20755. // suppress
  20756. }
  20757. }
  20758. function stripBom(content) {
  20759. if (content.charCodeAt(0) === 0xfe_ff) {
  20760. return stripBom(content.slice(1));
  20761. }
  20762. return content;
  20763. }
  20764. async function transform(source, module, pluginDriver, log) {
  20765. const id = module.id;
  20766. const sourcemapChain = [];
  20767. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20768. const originalCode = source.code;
  20769. let ast = source.ast;
  20770. const transformDependencies = [];
  20771. const emittedFiles = [];
  20772. let customTransformCache = false;
  20773. const useCustomTransformCache = () => (customTransformCache = true);
  20774. let pluginName = '';
  20775. let currentSource = source.code;
  20776. function transformReducer(previousCode, result, plugin) {
  20777. let code;
  20778. let map;
  20779. if (typeof result === 'string') {
  20780. code = result;
  20781. }
  20782. else if (result && typeof result === 'object') {
  20783. module.updateOptions(result);
  20784. if (result.code == null) {
  20785. if (result.map || result.ast) {
  20786. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNoTransformMapOrAstWithoutCode(plugin.name));
  20787. }
  20788. return previousCode;
  20789. }
  20790. ({ code, map, ast } = result);
  20791. }
  20792. else {
  20793. return previousCode;
  20794. }
  20795. // strict null check allows 'null' maps to not be pushed to the chain,
  20796. // while 'undefined' gets the missing map warning
  20797. if (map !== null) {
  20798. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20799. missing: true,
  20800. plugin: plugin.name
  20801. });
  20802. }
  20803. currentSource = code;
  20804. return code;
  20805. }
  20806. const getLogHandler = (handler) => (log, pos) => {
  20807. log = normalizeLog(log);
  20808. if (pos)
  20809. parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
  20810. log.id = id;
  20811. log.hook = 'transform';
  20812. handler(log);
  20813. };
  20814. let code;
  20815. try {
  20816. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  20817. pluginName = plugin.name;
  20818. return {
  20819. ...pluginContext,
  20820. addWatchFile(id) {
  20821. transformDependencies.push(id);
  20822. pluginContext.addWatchFile(id);
  20823. },
  20824. cache: customTransformCache
  20825. ? pluginContext.cache
  20826. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20827. debug: getLogHandler(pluginContext.debug),
  20828. emitFile(emittedFile) {
  20829. emittedFiles.push(emittedFile);
  20830. return pluginDriver.emitFile(emittedFile);
  20831. },
  20832. error(error_, pos) {
  20833. if (typeof error_ === 'string')
  20834. error_ = { message: error_ };
  20835. if (pos)
  20836. parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
  20837. error_.id = id;
  20838. error_.hook = 'transform';
  20839. return pluginContext.error(error_);
  20840. },
  20841. getCombinedSourcemap() {
  20842. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  20843. if (!combinedMap) {
  20844. const magicString = new MagicString(originalCode);
  20845. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20846. }
  20847. if (originalSourcemap !== combinedMap) {
  20848. originalSourcemap = combinedMap;
  20849. sourcemapChain.length = 0;
  20850. }
  20851. return new SourceMap({
  20852. ...combinedMap,
  20853. file: null,
  20854. sourcesContent: combinedMap.sourcesContent
  20855. });
  20856. },
  20857. info: getLogHandler(pluginContext.info),
  20858. setAssetSource() {
  20859. return this.error(parseAst_js.logInvalidSetAssetSourceCall());
  20860. },
  20861. warn: getLogHandler(pluginContext.warn)
  20862. };
  20863. });
  20864. }
  20865. catch (error_) {
  20866. return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
  20867. }
  20868. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  20869. emittedFiles.length > 0)
  20870. module.transformFiles = emittedFiles;
  20871. return {
  20872. ast,
  20873. code,
  20874. customTransformCache,
  20875. originalCode,
  20876. originalSourcemap,
  20877. sourcemapChain,
  20878. transformDependencies
  20879. };
  20880. }
  20881. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20882. class ModuleLoader {
  20883. constructor(graph, modulesById, options, pluginDriver) {
  20884. this.graph = graph;
  20885. this.modulesById = modulesById;
  20886. this.options = options;
  20887. this.pluginDriver = pluginDriver;
  20888. this.implicitEntryModules = new Set();
  20889. this.indexedEntryModules = [];
  20890. this.latestLoadModulesPromise = Promise.resolve();
  20891. this.moduleLoadPromises = new Map();
  20892. this.modulesWithLoadedDependencies = new Set();
  20893. this.nextChunkNamePriority = 0;
  20894. this.nextEntryModuleIndex = 0;
  20895. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20896. ? false
  20897. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  20898. this.hasModuleSideEffects = options.treeshake
  20899. ? options.treeshake.moduleSideEffects
  20900. : () => true;
  20901. }
  20902. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  20903. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  20904. await this.awaitLoadModulesPromise();
  20905. return result;
  20906. }
  20907. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20908. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20909. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20910. const firstChunkNamePriority = this.nextChunkNamePriority;
  20911. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20912. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20913. for (const [index, entryModule] of entryModules.entries()) {
  20914. entryModule.isUserDefinedEntryPoint =
  20915. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20916. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20917. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20918. if (existingIndexedModule) {
  20919. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20920. }
  20921. else {
  20922. this.indexedEntryModules.push({
  20923. index: firstEntryModuleIndex + index,
  20924. module: entryModule
  20925. });
  20926. }
  20927. }
  20928. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20929. return entryModules;
  20930. }));
  20931. await this.awaitLoadModulesPromise();
  20932. return {
  20933. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20934. implicitEntryModules: [...this.implicitEntryModules],
  20935. newEntryModules
  20936. };
  20937. }
  20938. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20939. const unresolvedModule = {
  20940. fileName: fileName || null,
  20941. id,
  20942. importer,
  20943. name: name || null
  20944. };
  20945. const module = implicitlyLoadedAfterOneOf
  20946. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20947. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20948. if (preserveSignature != null) {
  20949. module.preserveSignature = preserveSignature;
  20950. }
  20951. return module;
  20952. }
  20953. async preloadModule(resolvedId) {
  20954. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20955. return module.info;
  20956. }
  20957. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20958. const chunkNamePriority = this.nextChunkNamePriority++;
  20959. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20960. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20961. if (!entryModule.info.isEntry) {
  20962. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20963. // We need to check again if this is still an entry module as these
  20964. // changes need to be performed atomically to avoid race conditions
  20965. // if the same module is re-emitted as an entry module.
  20966. // The inverse changes happen in "handleExistingModule"
  20967. if (!entryModule.info.isEntry) {
  20968. this.implicitEntryModules.add(entryModule);
  20969. for (const module of implicitlyLoadedAfterModules) {
  20970. entryModule.implicitlyLoadedAfter.add(module);
  20971. }
  20972. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20973. dependant.implicitlyLoadedBefore.add(entryModule);
  20974. }
  20975. }
  20976. }
  20977. return entryModule;
  20978. }));
  20979. }
  20980. async addModuleSource(id, importer, module) {
  20981. let source;
  20982. try {
  20983. source = await this.graph.fileOperationQueue.run(async () => {
  20984. const content = await this.pluginDriver.hookFirst('load', [id]);
  20985. if (content !== null)
  20986. return content;
  20987. this.graph.watchFiles[id] = true;
  20988. return await promises.readFile(id, 'utf8');
  20989. });
  20990. }
  20991. catch (error_) {
  20992. let message = `Could not load ${id}`;
  20993. if (importer)
  20994. message += ` (imported by ${parseAst_js.relativeId(importer)})`;
  20995. message += `: ${error_.message}`;
  20996. error_.message = message;
  20997. throw error_;
  20998. }
  20999. const sourceDescription = typeof source === 'string'
  21000. ? { code: source }
  21001. : source != null && typeof source === 'object' && typeof source.code === 'string'
  21002. ? source
  21003. : parseAst_js.error(parseAst_js.logBadLoader(id));
  21004. sourceDescription.code = stripBom(sourceDescription.code);
  21005. const cachedModule = this.graph.cachedModules.get(id);
  21006. if (cachedModule &&
  21007. !cachedModule.customTransformCache &&
  21008. cachedModule.originalCode === sourceDescription.code &&
  21009. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  21010. {
  21011. ast: cachedModule.ast,
  21012. code: cachedModule.code,
  21013. id: cachedModule.id,
  21014. meta: cachedModule.meta,
  21015. moduleSideEffects: cachedModule.moduleSideEffects,
  21016. resolvedSources: cachedModule.resolvedIds,
  21017. syntheticNamedExports: cachedModule.syntheticNamedExports
  21018. }
  21019. ]))) {
  21020. if (cachedModule.transformFiles) {
  21021. for (const emittedFile of cachedModule.transformFiles)
  21022. this.pluginDriver.emitFile(emittedFile);
  21023. }
  21024. await module.setSource(cachedModule);
  21025. }
  21026. else {
  21027. module.updateOptions(sourceDescription);
  21028. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  21029. }
  21030. }
  21031. async awaitLoadModulesPromise() {
  21032. let startingPromise;
  21033. do {
  21034. startingPromise = this.latestLoadModulesPromise;
  21035. await startingPromise;
  21036. } while (startingPromise !== this.latestLoadModulesPromise);
  21037. }
  21038. extendLoadModulesPromise(loadNewModulesPromise) {
  21039. this.latestLoadModulesPromise = Promise.all([
  21040. loadNewModulesPromise,
  21041. this.latestLoadModulesPromise
  21042. ]);
  21043. this.latestLoadModulesPromise.catch(() => {
  21044. /* Avoid unhandled Promise rejections */
  21045. });
  21046. return loadNewModulesPromise;
  21047. }
  21048. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  21049. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  21050. if (resolvedId === null)
  21051. return null;
  21052. if (typeof resolvedId === 'string') {
  21053. dynamicImport.resolution = resolvedId;
  21054. return null;
  21055. }
  21056. return (dynamicImport.resolution = await this.fetchResolvedDependency(parseAst_js.relativeId(resolvedId.id), module.id, resolvedId));
  21057. })));
  21058. for (const dependency of dependencies) {
  21059. if (dependency) {
  21060. module.dynamicDependencies.add(dependency);
  21061. dependency.dynamicImporters.push(module.id);
  21062. }
  21063. }
  21064. }
  21065. // If this is a preload, then this method always waits for the dependencies of
  21066. // the module to be resolved.
  21067. // Otherwise, if the module does not exist, it waits for the module and all
  21068. // its dependencies to be loaded.
  21069. // Otherwise, it returns immediately.
  21070. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  21071. const existingModule = this.modulesById.get(id);
  21072. if (existingModule instanceof Module) {
  21073. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  21074. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  21075. }
  21076. await this.handleExistingModule(existingModule, isEntry, isPreload);
  21077. return existingModule;
  21078. }
  21079. if (existingModule instanceof ExternalModule) {
  21080. return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
  21081. }
  21082. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  21083. this.modulesById.set(id, module);
  21084. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  21085. this.getResolveStaticDependencyPromises(module),
  21086. this.getResolveDynamicImportPromises(module),
  21087. loadAndResolveDependenciesPromise
  21088. ]);
  21089. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  21090. loadAndResolveDependenciesPromise.catch(() => {
  21091. /* avoid unhandled promise rejections */
  21092. });
  21093. this.moduleLoadPromises.set(module, loadPromise);
  21094. const resolveDependencyPromises = await loadPromise;
  21095. if (!isPreload) {
  21096. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  21097. }
  21098. else if (isPreload === RESOLVE_DEPENDENCIES) {
  21099. await loadAndResolveDependenciesPromise;
  21100. }
  21101. return module;
  21102. }
  21103. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  21104. if (this.modulesWithLoadedDependencies.has(module)) {
  21105. return;
  21106. }
  21107. this.modulesWithLoadedDependencies.add(module);
  21108. await Promise.all([
  21109. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  21110. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  21111. ]);
  21112. module.linkImports();
  21113. // To handle errors when resolving dependencies or in moduleParsed
  21114. await loadAndResolveDependenciesPromise;
  21115. }
  21116. fetchResolvedDependency(source, importer, resolvedId) {
  21117. if (resolvedId.external) {
  21118. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  21119. let externalModule = this.modulesById.get(id);
  21120. if (!externalModule) {
  21121. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
  21122. this.modulesById.set(id, externalModule);
  21123. }
  21124. else if (!(externalModule instanceof ExternalModule)) {
  21125. return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
  21126. }
  21127. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  21128. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  21129. }
  21130. return Promise.resolve(externalModule);
  21131. }
  21132. return this.fetchModule(resolvedId, importer, false, false);
  21133. }
  21134. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  21135. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  21136. module.dependencies.add(dependency);
  21137. dependency.importers.push(module.id);
  21138. }
  21139. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  21140. for (const dependency of module.dependencies) {
  21141. if (dependency instanceof Module) {
  21142. dependency.importedFromNotTreeshaken = true;
  21143. }
  21144. }
  21145. }
  21146. }
  21147. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  21148. const { makeAbsoluteExternalsRelative } = this.options;
  21149. if (resolveIdResult) {
  21150. if (typeof resolveIdResult === 'object') {
  21151. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  21152. return {
  21153. ...resolveIdResult,
  21154. external: external &&
  21155. (external === 'relative' ||
  21156. !parseAst_js.isAbsolute(resolveIdResult.id) ||
  21157. (external === true &&
  21158. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  21159. 'absolute')
  21160. };
  21161. }
  21162. const external = this.options.external(resolveIdResult, importer, true);
  21163. return {
  21164. external: external &&
  21165. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  21166. 'absolute'),
  21167. id: external && makeAbsoluteExternalsRelative
  21168. ? normalizeRelativeExternalId(resolveIdResult, importer)
  21169. : resolveIdResult
  21170. };
  21171. }
  21172. const id = makeAbsoluteExternalsRelative
  21173. ? normalizeRelativeExternalId(source, importer)
  21174. : source;
  21175. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  21176. return null;
  21177. }
  21178. return {
  21179. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  21180. id
  21181. };
  21182. }
  21183. getResolveDynamicImportPromises(module) {
  21184. return module.dynamicImports.map(async (dynamicImport) => {
  21185. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  21186. if (resolvedId && typeof resolvedId === 'object') {
  21187. dynamicImport.id = resolvedId.id;
  21188. }
  21189. return [dynamicImport, resolvedId];
  21190. });
  21191. }
  21192. getResolveStaticDependencyPromises(module) {
  21193. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  21194. source,
  21195. (module.resolvedIds[source] =
  21196. module.resolvedIds[source] ||
  21197. this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  21198. ]);
  21199. }
  21200. getResolvedIdWithDefaults(resolvedId, attributes) {
  21201. if (!resolvedId) {
  21202. return null;
  21203. }
  21204. const external = resolvedId.external || false;
  21205. return {
  21206. attributes: resolvedId.attributes || attributes,
  21207. external,
  21208. id: resolvedId.id,
  21209. meta: resolvedId.meta || {},
  21210. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  21211. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  21212. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  21213. };
  21214. }
  21215. async handleExistingModule(module, isEntry, isPreload) {
  21216. const loadPromise = this.moduleLoadPromises.get(module);
  21217. if (isPreload) {
  21218. return isPreload === RESOLVE_DEPENDENCIES
  21219. ? waitForDependencyResolution(loadPromise)
  21220. : loadPromise;
  21221. }
  21222. if (isEntry) {
  21223. // This reverts the changes in addEntryWithImplicitDependants and needs to
  21224. // be performed atomically
  21225. module.info.isEntry = true;
  21226. this.implicitEntryModules.delete(module);
  21227. for (const dependant of module.implicitlyLoadedAfter) {
  21228. dependant.implicitlyLoadedBefore.delete(module);
  21229. }
  21230. module.implicitlyLoadedAfter.clear();
  21231. }
  21232. return this.fetchModuleDependencies(module, ...(await loadPromise));
  21233. }
  21234. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  21235. if (resolvedId === null) {
  21236. if (parseAst_js.isRelative(source)) {
  21237. return parseAst_js.error(parseAst_js.logUnresolvedImport(source, importer));
  21238. }
  21239. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnresolvedImportTreatedAsExternal(source, importer));
  21240. return {
  21241. attributes,
  21242. external: true,
  21243. id: source,
  21244. meta: {},
  21245. moduleSideEffects: this.hasModuleSideEffects(source, true),
  21246. resolvedBy: 'rollup',
  21247. syntheticNamedExports: false
  21248. };
  21249. }
  21250. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  21251. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logExternalSyntheticExports(source, importer));
  21252. }
  21253. return resolvedId;
  21254. }
  21255. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  21256. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT);
  21257. if (resolveIdResult == null) {
  21258. return parseAst_js.error(implicitlyLoadedBefore === null
  21259. ? parseAst_js.logUnresolvedEntry(unresolvedId)
  21260. : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  21261. }
  21262. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  21263. if (resolveIdResult === false || isExternalModules) {
  21264. return parseAst_js.error(implicitlyLoadedBefore === null
  21265. ? isExternalModules && isLoadForManualChunks
  21266. ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  21267. : parseAst_js.logEntryCannotBeExternal(unresolvedId)
  21268. : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  21269. }
  21270. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  21271. ? resolveIdResult
  21272. : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
  21273. }
  21274. async resolveDynamicImport(module, specifier, importer, attributes) {
  21275. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  21276. specifier,
  21277. importer,
  21278. { attributes }
  21279. ]);
  21280. if (typeof specifier !== 'string') {
  21281. if (typeof resolution === 'string') {
  21282. return resolution;
  21283. }
  21284. if (!resolution) {
  21285. return null;
  21286. }
  21287. return this.getResolvedIdWithDefaults(resolution, attributes);
  21288. }
  21289. if (resolution == null) {
  21290. const existingResolution = module.resolvedIds[specifier];
  21291. if (existingResolution) {
  21292. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  21293. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  21294. }
  21295. return existingResolution;
  21296. }
  21297. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  21298. }
  21299. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  21300. }
  21301. }
  21302. function normalizeRelativeExternalId(source, importer) {
  21303. return parseAst_js.isRelative(source)
  21304. ? importer
  21305. ? path.resolve(importer, '..', source)
  21306. : path.resolve(source)
  21307. : source;
  21308. }
  21309. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  21310. if (fileName !== null) {
  21311. module.chunkFileNames.add(fileName);
  21312. }
  21313. else if (name !== null) {
  21314. // Always keep chunkNames sorted by priority
  21315. let namePosition = 0;
  21316. while (module.chunkNames[namePosition]?.priority < priority)
  21317. namePosition++;
  21318. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  21319. }
  21320. }
  21321. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  21322. return (makeAbsoluteExternalsRelative === true ||
  21323. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && parseAst_js.isRelative(source)) ||
  21324. !parseAst_js.isAbsolute(id));
  21325. }
  21326. async function waitForDependencyResolution(loadPromise) {
  21327. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  21328. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  21329. }
  21330. class Queue {
  21331. constructor(maxParallel) {
  21332. this.maxParallel = maxParallel;
  21333. this.queue = [];
  21334. this.workerCount = 0;
  21335. }
  21336. run(task) {
  21337. return new Promise((resolve, reject) => {
  21338. this.queue.push({ reject, resolve, task });
  21339. this.work();
  21340. });
  21341. }
  21342. async work() {
  21343. if (this.workerCount >= this.maxParallel)
  21344. return;
  21345. this.workerCount++;
  21346. let entry;
  21347. while ((entry = this.queue.shift())) {
  21348. const { reject, resolve, task } = entry;
  21349. try {
  21350. const result = await task();
  21351. resolve(result);
  21352. }
  21353. catch (error) {
  21354. reject(error);
  21355. }
  21356. }
  21357. this.workerCount--;
  21358. }
  21359. }
  21360. function normalizeEntryModules(entryModules) {
  21361. if (Array.isArray(entryModules)) {
  21362. return entryModules.map(id => ({
  21363. fileName: null,
  21364. id,
  21365. implicitlyLoadedAfter: [],
  21366. importer: undefined,
  21367. name: null
  21368. }));
  21369. }
  21370. return Object.entries(entryModules).map(([name, id]) => ({
  21371. fileName: null,
  21372. id,
  21373. implicitlyLoadedAfter: [],
  21374. importer: undefined,
  21375. name
  21376. }));
  21377. }
  21378. class Graph {
  21379. constructor(options, watcher) {
  21380. this.options = options;
  21381. this.astLru = flru(5);
  21382. this.cachedModules = new Map();
  21383. this.deoptimizationTracker = new EntityPathTracker();
  21384. this.entryModules = [];
  21385. this.modulesById = new Map();
  21386. this.needsTreeshakingPass = false;
  21387. this.newlyIncludedVariableInits = new Set();
  21388. this.phase = BuildPhase.LOAD_AND_PARSE;
  21389. this.scope = new GlobalScope();
  21390. this.watchFiles = Object.create(null);
  21391. this.watchMode = false;
  21392. this.externalModules = [];
  21393. this.implicitEntryModules = [];
  21394. this.modules = [];
  21395. this.getModuleInfo = (moduleId) => {
  21396. const foundModule = this.modulesById.get(moduleId);
  21397. if (!foundModule)
  21398. return null;
  21399. return foundModule.info;
  21400. };
  21401. if (options.cache !== false) {
  21402. if (options.cache?.modules) {
  21403. for (const module of options.cache.modules)
  21404. this.cachedModules.set(module.id, module);
  21405. }
  21406. this.pluginCache = options.cache?.plugins || Object.create(null);
  21407. // increment access counter
  21408. for (const name in this.pluginCache) {
  21409. const cache = this.pluginCache[name];
  21410. for (const value of Object.values(cache))
  21411. value[0]++;
  21412. }
  21413. }
  21414. if (watcher) {
  21415. this.watchMode = true;
  21416. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  21417. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21418. watcher.onCurrentRun('change', handleChange);
  21419. watcher.onCurrentRun('close', handleClose);
  21420. }
  21421. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21422. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21423. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21424. this.pureFunctions = getPureFunctions(options);
  21425. }
  21426. async build() {
  21427. timeStart('generate module graph', 2);
  21428. await this.generateModuleGraph();
  21429. timeEnd('generate module graph', 2);
  21430. timeStart('sort and bind modules', 2);
  21431. this.phase = BuildPhase.ANALYSE;
  21432. this.sortModules();
  21433. timeEnd('sort and bind modules', 2);
  21434. timeStart('mark included statements', 2);
  21435. this.includeStatements();
  21436. timeEnd('mark included statements', 2);
  21437. this.phase = BuildPhase.GENERATE;
  21438. }
  21439. getCache() {
  21440. // handle plugin cache eviction
  21441. for (const name in this.pluginCache) {
  21442. const cache = this.pluginCache[name];
  21443. let allDeleted = true;
  21444. for (const [key, value] of Object.entries(cache)) {
  21445. if (value[0] >= this.options.experimentalCacheExpiry)
  21446. delete cache[key];
  21447. else
  21448. allDeleted = false;
  21449. }
  21450. if (allDeleted)
  21451. delete this.pluginCache[name];
  21452. }
  21453. return {
  21454. modules: this.modules.map(module => module.toJSON()),
  21455. plugins: this.pluginCache
  21456. };
  21457. }
  21458. async generateModuleGraph() {
  21459. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21460. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21461. if (this.entryModules.length === 0) {
  21462. throw new Error('You must supply options.input to rollup');
  21463. }
  21464. for (const module of this.modulesById.values()) {
  21465. module.cacheInfoGetters();
  21466. if (module instanceof Module) {
  21467. this.modules.push(module);
  21468. }
  21469. else {
  21470. this.externalModules.push(module);
  21471. }
  21472. }
  21473. }
  21474. includeStatements() {
  21475. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  21476. for (const module of entryModules) {
  21477. markModuleAndImpureDependenciesAsExecuted(module);
  21478. }
  21479. if (this.options.treeshake) {
  21480. let treeshakingPass = 1;
  21481. this.newlyIncludedVariableInits.clear();
  21482. do {
  21483. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21484. this.needsTreeshakingPass = false;
  21485. for (const module of this.modules) {
  21486. if (module.isExecuted) {
  21487. module.hasTreeShakingPassStarted = true;
  21488. if (module.info.moduleSideEffects === 'no-treeshake') {
  21489. module.includeAllInBundle();
  21490. }
  21491. else {
  21492. module.include();
  21493. }
  21494. for (const entity of this.newlyIncludedVariableInits) {
  21495. this.newlyIncludedVariableInits.delete(entity);
  21496. entity.include(createInclusionContext(), false);
  21497. }
  21498. }
  21499. }
  21500. if (treeshakingPass === 1) {
  21501. // We only include exports after the first pass to avoid issues with
  21502. // the TDZ detection logic
  21503. for (const module of entryModules) {
  21504. if (module.preserveSignature !== false) {
  21505. module.includeAllExports(false);
  21506. this.needsTreeshakingPass = true;
  21507. }
  21508. }
  21509. }
  21510. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21511. } while (this.needsTreeshakingPass);
  21512. }
  21513. else {
  21514. for (const module of this.modules)
  21515. module.includeAllInBundle();
  21516. }
  21517. for (const externalModule of this.externalModules)
  21518. externalModule.warnUnusedImports();
  21519. for (const module of this.implicitEntryModules) {
  21520. for (const dependant of module.implicitlyLoadedAfter) {
  21521. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21522. parseAst_js.error(parseAst_js.logImplicitDependantIsNotIncluded(dependant));
  21523. }
  21524. }
  21525. }
  21526. }
  21527. sortModules() {
  21528. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21529. for (const cyclePath of cyclePaths) {
  21530. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularDependency(cyclePath));
  21531. }
  21532. this.modules = orderedModules;
  21533. for (const module of this.modules) {
  21534. module.bindReferences();
  21535. }
  21536. this.warnForMissingExports();
  21537. }
  21538. warnForMissingExports() {
  21539. for (const module of this.modules) {
  21540. for (const importDescription of module.importDescriptions.values()) {
  21541. if (importDescription.name !== '*' &&
  21542. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21543. module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  21544. }
  21545. }
  21546. }
  21547. }
  21548. }
  21549. function formatAction([pluginName, hookName, parameters]) {
  21550. const action = `(${pluginName}) ${hookName}`;
  21551. const s = JSON.stringify;
  21552. switch (hookName) {
  21553. case 'resolveId': {
  21554. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  21555. }
  21556. case 'load': {
  21557. return `${action} ${s(parameters[0])}`;
  21558. }
  21559. case 'transform': {
  21560. return `${action} ${s(parameters[1])}`;
  21561. }
  21562. case 'shouldTransformCachedModule': {
  21563. return `${action} ${s(parameters[0].id)}`;
  21564. }
  21565. case 'moduleParsed': {
  21566. return `${action} ${s(parameters[0].id)}`;
  21567. }
  21568. }
  21569. return action;
  21570. }
  21571. let handleBeforeExit = null;
  21572. const rejectByPluginDriver = new Map();
  21573. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21574. const emptyEventLoopPromise = new Promise((_, reject) => {
  21575. rejectByPluginDriver.set(pluginDriver, reject);
  21576. if (!handleBeforeExit) {
  21577. // We only ever create a single event listener to avoid max listener and
  21578. // other issues
  21579. handleBeforeExit = () => {
  21580. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  21581. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21582. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21583. [...unfulfilledActions].map(formatAction).join('\n')));
  21584. }
  21585. };
  21586. process$1.once('beforeExit', handleBeforeExit);
  21587. }
  21588. });
  21589. try {
  21590. return await Promise.race([callback(), emptyEventLoopPromise]);
  21591. }
  21592. finally {
  21593. rejectByPluginDriver.delete(pluginDriver);
  21594. if (rejectByPluginDriver.size === 0) {
  21595. process$1.off('beforeExit', handleBeforeExit);
  21596. handleBeforeExit = null;
  21597. }
  21598. }
  21599. }
  21600. async function initWasm() { }
  21601. async function normalizeInputOptions(config, watchMode) {
  21602. // These are options that may trigger special warnings or behaviour later
  21603. // if the user did not select an explicit value
  21604. const unsetOptions = new Set();
  21605. const context = config.context ?? 'undefined';
  21606. const plugins = await normalizePluginOption(config.plugins);
  21607. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  21608. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  21609. const strictDeprecations = config.strictDeprecations || false;
  21610. const maxParallelFileOps = getMaxParallelFileOps(config);
  21611. const options = {
  21612. cache: getCache(config),
  21613. context,
  21614. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  21615. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  21616. external: getIdMatcher(config.external),
  21617. input: getInput(config),
  21618. jsx: getJsx(config),
  21619. logLevel,
  21620. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  21621. maxParallelFileOps,
  21622. moduleContext: getModuleContext(config, context),
  21623. onLog,
  21624. perf: config.perf || false,
  21625. plugins,
  21626. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  21627. preserveSymlinks: config.preserveSymlinks || false,
  21628. shimMissingExports: config.shimMissingExports || false,
  21629. strictDeprecations,
  21630. treeshake: getTreeshake(config)
  21631. };
  21632. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  21633. return { options, unsetOptions };
  21634. }
  21635. const getCache = (config) => config.cache === true // `true` is the default
  21636. ? undefined
  21637. : config.cache?.cache || config.cache;
  21638. const getIdMatcher = (option) => {
  21639. if (option === true) {
  21640. return () => true;
  21641. }
  21642. if (typeof option === 'function') {
  21643. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  21644. }
  21645. if (option) {
  21646. const ids = new Set();
  21647. const matchers = [];
  21648. for (const value of ensureArray$1(option)) {
  21649. if (value instanceof RegExp) {
  21650. matchers.push(value);
  21651. }
  21652. else {
  21653. ids.add(value);
  21654. }
  21655. }
  21656. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21657. }
  21658. return () => false;
  21659. };
  21660. const getInput = (config) => {
  21661. const configInput = config.input;
  21662. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21663. };
  21664. const getJsx = (config) => {
  21665. const configJsx = config.jsx;
  21666. if (!configJsx)
  21667. return false;
  21668. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ');
  21669. const { factory, importSource, mode } = configWithPreset;
  21670. switch (mode) {
  21671. case 'automatic': {
  21672. return {
  21673. factory: factory || 'React.createElement',
  21674. importSource: importSource || 'react',
  21675. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  21676. mode: 'automatic'
  21677. };
  21678. }
  21679. case 'preserve': {
  21680. if (importSource && !(factory || configWithPreset.fragment)) {
  21681. 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'));
  21682. }
  21683. return {
  21684. factory: factory || null,
  21685. fragment: configWithPreset.fragment || null,
  21686. importSource: importSource || null,
  21687. mode: 'preserve'
  21688. };
  21689. }
  21690. // case 'classic':
  21691. default: {
  21692. if (mode && mode !== 'classic') {
  21693. parseAst_js.error(parseAst_js.logInvalidOption('jsx.mode', parseAst_js.URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  21694. }
  21695. return {
  21696. factory: factory || 'React.createElement',
  21697. fragment: configWithPreset.fragment || 'React.Fragment',
  21698. importSource: importSource || null,
  21699. mode: 'classic'
  21700. };
  21701. }
  21702. }
  21703. };
  21704. const getMaxParallelFileOps = (config) => {
  21705. const maxParallelFileOps = config.maxParallelFileOps;
  21706. if (typeof maxParallelFileOps === 'number') {
  21707. if (maxParallelFileOps <= 0)
  21708. return Infinity;
  21709. return maxParallelFileOps;
  21710. }
  21711. return 20;
  21712. };
  21713. const getModuleContext = (config, context) => {
  21714. const configModuleContext = config.moduleContext;
  21715. if (typeof configModuleContext === 'function') {
  21716. return id => configModuleContext(id) ?? context;
  21717. }
  21718. if (configModuleContext) {
  21719. const contextByModuleId = Object.create(null);
  21720. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21721. contextByModuleId[path.resolve(key)] = moduleContext;
  21722. }
  21723. return id => contextByModuleId[id] ?? context;
  21724. }
  21725. return () => context;
  21726. };
  21727. const getTreeshake = (config) => {
  21728. const configTreeshake = config.treeshake;
  21729. if (configTreeshake === false) {
  21730. return false;
  21731. }
  21732. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ');
  21733. return {
  21734. annotations: configWithPreset.annotations !== false,
  21735. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21736. manualPureFunctions: configWithPreset.manualPureFunctions ?? parseAst_js.EMPTY_ARRAY,
  21737. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  21738. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21739. ? 'always'
  21740. : configWithPreset.propertyReadSideEffects !== false,
  21741. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21742. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21743. };
  21744. };
  21745. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  21746. if (typeof moduleSideEffectsOption === 'boolean') {
  21747. return () => moduleSideEffectsOption;
  21748. }
  21749. if (moduleSideEffectsOption === 'no-external') {
  21750. return (_id, external) => !external;
  21751. }
  21752. if (typeof moduleSideEffectsOption === 'function') {
  21753. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  21754. }
  21755. if (Array.isArray(moduleSideEffectsOption)) {
  21756. const ids = new Set(moduleSideEffectsOption);
  21757. return id => ids.has(id);
  21758. }
  21759. if (moduleSideEffectsOption) {
  21760. 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'));
  21761. }
  21762. return () => true;
  21763. };
  21764. // https://datatracker.ietf.org/doc/html/rfc2396
  21765. // eslint-disable-next-line no-control-regex
  21766. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  21767. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21768. function sanitizeFileName(name) {
  21769. const match = DRIVE_LETTER_REGEX.exec(name);
  21770. const driveLetter = match ? match[0] : '';
  21771. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21772. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21773. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21774. }
  21775. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21776. // These are options that may trigger special warnings or behaviour later
  21777. // if the user did not select an explicit value
  21778. const unsetOptions = new Set(unsetInputOptions);
  21779. const compact = config.compact || false;
  21780. const format = getFormat(config);
  21781. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21782. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21783. const file = getFile(config, preserveModules, inputOptions);
  21784. const generatedCode = getGeneratedCode(config);
  21785. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  21786. const outputOptions = {
  21787. amd: getAmd(config),
  21788. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  21789. banner: getAddon(config, 'banner'),
  21790. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  21791. compact,
  21792. dir: getDir(config, file),
  21793. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  21794. entryFileNames: getEntryFileNames(config, unsetOptions),
  21795. esModule: config.esModule ?? 'if-default-prop',
  21796. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  21797. exports: getExports(config, unsetOptions),
  21798. extend: config.extend || false,
  21799. externalImportAssertions: externalImportAttributes,
  21800. externalImportAttributes,
  21801. externalLiveBindings: config.externalLiveBindings ?? true,
  21802. file,
  21803. footer: getAddon(config, 'footer'),
  21804. format,
  21805. freeze: config.freeze ?? true,
  21806. generatedCode,
  21807. globals: config.globals || {},
  21808. hashCharacters: config.hashCharacters ?? 'base64',
  21809. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  21810. importAttributesKey: config.importAttributesKey ?? 'assert',
  21811. indent: getIndent(config, compact),
  21812. inlineDynamicImports,
  21813. interop: getInterop(config),
  21814. intro: getAddon(config, 'intro'),
  21815. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  21816. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21817. name: config.name,
  21818. noConflict: config.noConflict || false,
  21819. outro: getAddon(config, 'outro'),
  21820. paths: config.paths || {},
  21821. plugins: await normalizePluginOption(config.plugins),
  21822. preserveModules,
  21823. preserveModulesRoot: getPreserveModulesRoot(config),
  21824. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  21825. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21826. ? config.sanitizeFileName
  21827. : config.sanitizeFileName === false
  21828. ? id => id
  21829. : sanitizeFileName,
  21830. sourcemap: config.sourcemap || false,
  21831. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21832. sourcemapDebugIds: config.sourcemapDebugIds || false,
  21833. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21834. sourcemapFile: config.sourcemapFile,
  21835. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  21836. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  21837. ? config.sourcemapIgnoreList
  21838. : config.sourcemapIgnoreList === false
  21839. ? () => false
  21840. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  21841. sourcemapPathTransform: config.sourcemapPathTransform,
  21842. strict: config.strict ?? true,
  21843. systemNullSetters: config.systemNullSetters ?? true,
  21844. validate: config.validate || false,
  21845. virtualDirname: config.virtualDirname || '_virtual'
  21846. };
  21847. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  21848. return { options: outputOptions, unsetOptions };
  21849. }
  21850. const getFile = (config, preserveModules, inputOptions) => {
  21851. const { file } = config;
  21852. if (typeof file === 'string') {
  21853. if (preserveModules) {
  21854. 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'));
  21855. }
  21856. if (!Array.isArray(inputOptions.input))
  21857. 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'));
  21858. }
  21859. return file;
  21860. };
  21861. const getFormat = (config) => {
  21862. const configFormat = config.format;
  21863. switch (configFormat) {
  21864. case undefined:
  21865. case 'es':
  21866. case 'esm':
  21867. case 'module': {
  21868. return 'es';
  21869. }
  21870. case 'cjs':
  21871. case 'commonjs': {
  21872. return 'cjs';
  21873. }
  21874. case 'system':
  21875. case 'systemjs': {
  21876. return 'system';
  21877. }
  21878. case 'amd':
  21879. case 'iife':
  21880. case 'umd': {
  21881. return configFormat;
  21882. }
  21883. default: {
  21884. 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));
  21885. }
  21886. }
  21887. };
  21888. const getInlineDynamicImports = (config, inputOptions) => {
  21889. const inlineDynamicImports = config.inlineDynamicImports || false;
  21890. const { input } = inputOptions;
  21891. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21892. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21893. }
  21894. return inlineDynamicImports;
  21895. };
  21896. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21897. const preserveModules = config.preserveModules || false;
  21898. if (preserveModules) {
  21899. if (inlineDynamicImports) {
  21900. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  21901. }
  21902. if (inputOptions.preserveEntrySignatures === false) {
  21903. return parseAst_js.error(parseAst_js.logInvalidOption('preserveEntrySignatures', parseAst_js.URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  21904. }
  21905. }
  21906. return preserveModules;
  21907. };
  21908. const getPreserveModulesRoot = (config) => {
  21909. const { preserveModulesRoot } = config;
  21910. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21911. return undefined;
  21912. }
  21913. return path.resolve(preserveModulesRoot);
  21914. };
  21915. const getAmd = (config) => {
  21916. const mergedOption = {
  21917. autoId: false,
  21918. basePath: '',
  21919. define: 'define',
  21920. forceJsExtensionForImports: false,
  21921. ...config.amd
  21922. };
  21923. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  21924. 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"'));
  21925. }
  21926. if (mergedOption.basePath && !mergedOption.autoId) {
  21927. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.basePath', parseAst_js.URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  21928. }
  21929. return mergedOption.autoId
  21930. ? {
  21931. autoId: true,
  21932. basePath: mergedOption.basePath,
  21933. define: mergedOption.define,
  21934. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  21935. }
  21936. : {
  21937. autoId: false,
  21938. define: mergedOption.define,
  21939. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  21940. id: mergedOption.id
  21941. };
  21942. };
  21943. const getAddon = (config, name) => {
  21944. const configAddon = config[name];
  21945. if (typeof configAddon === 'function') {
  21946. return configAddon;
  21947. }
  21948. return () => configAddon || '';
  21949. };
  21950. const getDir = (config, file) => {
  21951. const { dir } = config;
  21952. if (typeof dir === 'string' && typeof file === 'string') {
  21953. 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'));
  21954. }
  21955. return dir;
  21956. };
  21957. const getEntryFileNames = (config, unsetOptions) => {
  21958. const configEntryFileNames = config.entryFileNames;
  21959. if (configEntryFileNames == null) {
  21960. unsetOptions.add('entryFileNames');
  21961. }
  21962. return configEntryFileNames ?? '[name].js';
  21963. };
  21964. function getExports(config, unsetOptions) {
  21965. const configExports = config.exports;
  21966. if (configExports == null) {
  21967. unsetOptions.add('exports');
  21968. }
  21969. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  21970. return parseAst_js.error(parseAst_js.logInvalidExportOptionValue(configExports));
  21971. }
  21972. return configExports || 'auto';
  21973. }
  21974. const getExternalImportAttributes = (config, inputOptions) => {
  21975. if (config.externalImportAssertions != undefined) {
  21976. parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  21977. }
  21978. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  21979. };
  21980. const getGeneratedCode = (config) => {
  21981. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
  21982. return {
  21983. arrowFunctions: configWithPreset.arrowFunctions === true,
  21984. constBindings: configWithPreset.constBindings === true,
  21985. objectShorthand: configWithPreset.objectShorthand === true,
  21986. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  21987. symbols: configWithPreset.symbols === true
  21988. };
  21989. };
  21990. const getIndent = (config, compact) => {
  21991. if (compact) {
  21992. return '';
  21993. }
  21994. const configIndent = config.indent;
  21995. return configIndent === false ? '' : (configIndent ?? true);
  21996. };
  21997. const ALLOWED_INTEROP_TYPES = new Set([
  21998. 'compat',
  21999. 'auto',
  22000. 'esModule',
  22001. 'default',
  22002. 'defaultOnly'
  22003. ]);
  22004. const getInterop = (config) => {
  22005. const configInterop = config.interop;
  22006. if (typeof configInterop === 'function') {
  22007. const interopPerId = Object.create(null);
  22008. let defaultInterop = null;
  22009. return id => id === null
  22010. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22011. : id in interopPerId
  22012. ? interopPerId[id]
  22013. : validateInterop((interopPerId[id] = configInterop(id)));
  22014. }
  22015. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22016. };
  22017. const validateInterop = (interop) => {
  22018. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22019. 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));
  22020. }
  22021. return interop;
  22022. };
  22023. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22024. const configManualChunks = config.manualChunks;
  22025. if (configManualChunks) {
  22026. if (inlineDynamicImports) {
  22027. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22028. }
  22029. if (preserveModules) {
  22030. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22031. }
  22032. }
  22033. return configManualChunks || {};
  22034. };
  22035. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22036. const getSourcemapFileNames = (config, unsetOptions) => {
  22037. const configSourcemapFileNames = config.sourcemapFileNames;
  22038. if (configSourcemapFileNames == null) {
  22039. unsetOptions.add('sourcemapFileNames');
  22040. }
  22041. return configSourcemapFileNames;
  22042. };
  22043. const getSourcemapBaseUrl = (config) => {
  22044. const { sourcemapBaseUrl } = config;
  22045. if (sourcemapBaseUrl) {
  22046. if (parseAst_js.isValidUrl(sourcemapBaseUrl)) {
  22047. return parseAst_js.addTrailingSlashIfMissed(sourcemapBaseUrl);
  22048. }
  22049. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapBaseUrl', parseAst_js.URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22050. }
  22051. };
  22052. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22053. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22054. function rollup(rawInputOptions) {
  22055. return rollupInternal(rawInputOptions, null);
  22056. }
  22057. async function rollupInternal(rawInputOptions, watcher) {
  22058. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22059. initialiseTimers(inputOptions);
  22060. await initWasm();
  22061. const graph = new Graph(inputOptions, watcher);
  22062. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22063. const useCache = rawInputOptions.cache !== false;
  22064. if (rawInputOptions.cache) {
  22065. inputOptions.cache = undefined;
  22066. rawInputOptions.cache = undefined;
  22067. }
  22068. timeStart('BUILD', 1);
  22069. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22070. try {
  22071. timeStart('initialize', 2);
  22072. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22073. timeEnd('initialize', 2);
  22074. await graph.build();
  22075. }
  22076. catch (error_) {
  22077. const watchFiles = Object.keys(graph.watchFiles);
  22078. if (watchFiles.length > 0) {
  22079. error_.watchFiles = watchFiles;
  22080. }
  22081. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22082. await graph.pluginDriver.hookParallel('closeBundle', []);
  22083. throw error_;
  22084. }
  22085. await graph.pluginDriver.hookParallel('buildEnd', []);
  22086. });
  22087. timeEnd('BUILD', 1);
  22088. const result = {
  22089. cache: useCache ? graph.getCache() : undefined,
  22090. async close() {
  22091. if (result.closed)
  22092. return;
  22093. result.closed = true;
  22094. await graph.pluginDriver.hookParallel('closeBundle', []);
  22095. },
  22096. closed: false,
  22097. async [Symbol.asyncDispose]() {
  22098. await this.close();
  22099. },
  22100. async generate(rawOutputOptions) {
  22101. if (result.closed)
  22102. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22103. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22104. },
  22105. get watchFiles() {
  22106. return Object.keys(graph.watchFiles);
  22107. },
  22108. async write(rawOutputOptions) {
  22109. if (result.closed)
  22110. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  22111. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22112. }
  22113. };
  22114. if (inputOptions.perf)
  22115. result.getTimings = getTimings;
  22116. return result;
  22117. }
  22118. async function getInputOptions(initialInputOptions, watchMode) {
  22119. if (!initialInputOptions) {
  22120. throw new Error('You must supply an options object to rollup');
  22121. }
  22122. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22123. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22124. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22125. return { options, unsetOptions };
  22126. }
  22127. async function getProcessedInputOptions(inputOptions, watchMode) {
  22128. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22129. const logLevel = inputOptions.logLevel || parseAst_js.LOGLEVEL_INFO;
  22130. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22131. for (const plugin of plugins) {
  22132. const { name, options } = plugin;
  22133. const handler = 'handler' in options ? options.handler : options;
  22134. const processedOptions = await handler.call({
  22135. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22136. error: (error_) => parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22137. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22138. meta: { rollupVersion: version, watchMode },
  22139. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22140. }, inputOptions);
  22141. if (processedOptions) {
  22142. inputOptions = processedOptions;
  22143. }
  22144. }
  22145. return inputOptions;
  22146. }
  22147. function normalizePlugins(plugins, anonymousPrefix) {
  22148. for (const [index, plugin] of plugins.entries()) {
  22149. if (!plugin.name) {
  22150. plugin.name = `${anonymousPrefix}${index + 1}`;
  22151. }
  22152. }
  22153. }
  22154. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22155. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22156. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22157. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22158. const generated = await bundle.generate(isWrite);
  22159. if (isWrite) {
  22160. timeStart('WRITE', 1);
  22161. if (!outputOptions.dir && !outputOptions.file) {
  22162. return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
  22163. }
  22164. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22165. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22166. timeEnd('WRITE', 1);
  22167. }
  22168. return createOutput(generated);
  22169. });
  22170. }
  22171. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22172. if (!rawOutputOptions) {
  22173. throw new Error('You must supply an options object');
  22174. }
  22175. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22176. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22177. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22178. return {
  22179. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22180. outputPluginDriver
  22181. };
  22182. }
  22183. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22184. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22185. const emitError = () => pluginContext.error(parseAst_js.logCannotEmitFromOptionsHook());
  22186. return {
  22187. ...pluginContext,
  22188. emitFile: emitError,
  22189. setAssetSource: emitError
  22190. };
  22191. }), inputOptions, unsetInputOptions);
  22192. }
  22193. function createOutput(outputBundle) {
  22194. return {
  22195. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22196. };
  22197. }
  22198. var SortingFileType;
  22199. (function (SortingFileType) {
  22200. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22201. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22202. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22203. })(SortingFileType || (SortingFileType = {}));
  22204. function getSortingFileType(file) {
  22205. if (file.type === 'asset') {
  22206. return SortingFileType.ASSET;
  22207. }
  22208. if (file.isEntry) {
  22209. return SortingFileType.ENTRY_CHUNK;
  22210. }
  22211. return SortingFileType.SECONDARY_CHUNK;
  22212. }
  22213. async function writeOutputFile(outputFile, outputOptions) {
  22214. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  22215. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22216. await promises.mkdir(path.dirname(fileName), { recursive: true });
  22217. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22218. }
  22219. /**
  22220. * Auxiliary function for defining rollup configuration
  22221. * Mainly to facilitate IDE code prompts, after all, export default does not
  22222. * prompt, even if you add @type annotations, it is not accurate
  22223. * @param options
  22224. */
  22225. function defineConfig(options) {
  22226. return options;
  22227. }
  22228. exports.bold = bold;
  22229. exports.commandAliases = commandAliases;
  22230. exports.createFilter = createFilter;
  22231. exports.cyan = cyan;
  22232. exports.defineConfig = defineConfig;
  22233. exports.ensureArray = ensureArray$1;
  22234. exports.getAugmentedNamespace = getAugmentedNamespace;
  22235. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  22236. exports.getNewArray = getNewArray;
  22237. exports.getOrCreate = getOrCreate;
  22238. exports.gray = gray;
  22239. exports.green = green;
  22240. exports.handleError = handleError;
  22241. exports.isWatchEnabled = isWatchEnabled;
  22242. exports.mergeOptions = mergeOptions;
  22243. exports.normalizePluginOption = normalizePluginOption;
  22244. exports.pc = pc;
  22245. exports.rollup = rollup;
  22246. exports.rollupInternal = rollupInternal;
  22247. exports.stderr = stderr;
  22248. exports.underline = underline;
  22249. exports.version = version;
  22250. exports.yellow = yellow;
  22251. //# sourceMappingURL=rollup.js.map