rollup.js 829 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195
  1. /*
  2. @license
  3. Rollup.js v4.24.2
  4. Sun, 27 Oct 2024 15:39:37 GMT - commit 32d0e7dae85121ac0850ec28576a10a6302f84a9
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const parseAst_js = require('./parseAst.js');
  10. const process$1 = require('node:process');
  11. const tty = require('tty');
  12. const path = require('node:path');
  13. const require$$0 = require('path');
  14. const native_js = require('../native.js');
  15. const node_perf_hooks = require('node:perf_hooks');
  16. const promises = require('node:fs/promises');
  17. function _interopNamespaceDefault(e) {
  18. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  19. if (e) {
  20. for (const k in e) {
  21. n[k] = e[k];
  22. }
  23. }
  24. n.default = e;
  25. return n;
  26. }
  27. const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
  28. var version = "4.24.2";
  29. function ensureArray$1(items) {
  30. if (Array.isArray(items)) {
  31. return items.filter(Boolean);
  32. }
  33. if (items) {
  34. return [items];
  35. }
  36. return [];
  37. }
  38. var BuildPhase;
  39. (function (BuildPhase) {
  40. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  41. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  42. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  43. })(BuildPhase || (BuildPhase = {}));
  44. let textEncoder;
  45. const getHash64 = input => native_js.xxhashBase64Url(ensureBuffer(input));
  46. const getHash36 = input => native_js.xxhashBase36(ensureBuffer(input));
  47. const getHash16 = input => native_js.xxhashBase16(ensureBuffer(input));
  48. const hasherByType = {
  49. base36: getHash36,
  50. base64: getHash64,
  51. hex: getHash16
  52. };
  53. function ensureBuffer(input) {
  54. if (typeof input === 'string') {
  55. if (typeof Buffer === 'undefined') {
  56. textEncoder ??= new TextEncoder();
  57. return textEncoder.encode(input);
  58. }
  59. return Buffer.from(input);
  60. }
  61. return input;
  62. }
  63. function getOrCreate(map, key, init) {
  64. const existing = map.get(key);
  65. if (existing !== undefined) {
  66. return existing;
  67. }
  68. const value = init();
  69. map.set(key, value);
  70. return value;
  71. }
  72. function getNewSet() {
  73. return new Set();
  74. }
  75. function getNewArray() {
  76. return [];
  77. }
  78. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  79. const base = 64;
  80. function toBase64(value) {
  81. let outString = '';
  82. do {
  83. const currentDigit = value % base;
  84. value = (value / base) | 0;
  85. outString = chars$1[currentDigit] + outString;
  86. } while (value !== 0);
  87. return outString;
  88. }
  89. // Four random characters from the private use area to minimize risk of
  90. // conflicts
  91. const hashPlaceholderLeft = '!~{';
  92. const hashPlaceholderRight = '}~';
  93. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  94. // This is the size of a 128-bits xxhash with base64url encoding
  95. const MAX_HASH_SIZE = 22;
  96. const DEFAULT_HASH_SIZE = 8;
  97. const getHashPlaceholderGenerator = () => {
  98. let nextIndex = 0;
  99. return (optionName, hashSize) => {
  100. if (hashSize > MAX_HASH_SIZE) {
  101. return parseAst_js.error(parseAst_js.logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  102. }
  103. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  104. if (placeholder.length > hashSize) {
  105. 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.`));
  106. }
  107. return placeholder;
  108. };
  109. };
  110. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  111. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  112. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  113. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  114. const containedPlaceholders = new Set();
  115. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  116. if (placeholders.has(placeholder)) {
  117. containedPlaceholders.add(placeholder);
  118. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  119. }
  120. return placeholder;
  121. });
  122. return { containedPlaceholders, transformedCode };
  123. };
  124. const lowercaseBundleKeys = Symbol('bundleKeys');
  125. const FILE_PLACEHOLDER = {
  126. type: 'placeholder'
  127. };
  128. const getOutputBundle = (outputBundleBase) => {
  129. const reservedLowercaseBundleKeys = new Set();
  130. return new Proxy(outputBundleBase, {
  131. deleteProperty(target, key) {
  132. if (typeof key === 'string') {
  133. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  134. }
  135. return Reflect.deleteProperty(target, key);
  136. },
  137. get(target, key) {
  138. if (key === lowercaseBundleKeys) {
  139. return reservedLowercaseBundleKeys;
  140. }
  141. return Reflect.get(target, key);
  142. },
  143. set(target, key, value) {
  144. if (typeof key === 'string') {
  145. reservedLowercaseBundleKeys.add(key.toLowerCase());
  146. }
  147. return Reflect.set(target, key, value);
  148. }
  149. });
  150. };
  151. const removeUnreferencedAssets = (outputBundle) => {
  152. const unreferencedAssets = new Set();
  153. const bundleEntries = Object.values(outputBundle);
  154. for (const asset of bundleEntries) {
  155. if (asset.type === 'asset' && asset.needsCodeReference) {
  156. unreferencedAssets.add(asset.fileName);
  157. }
  158. }
  159. for (const chunk of bundleEntries) {
  160. if (chunk.type === 'chunk') {
  161. for (const referencedFile of chunk.referencedFiles) {
  162. if (unreferencedAssets.has(referencedFile)) {
  163. unreferencedAssets.delete(referencedFile);
  164. }
  165. }
  166. }
  167. }
  168. for (const file of unreferencedAssets) {
  169. delete outputBundle[file];
  170. }
  171. };
  172. function renderNamePattern(pattern, patternName, replacements) {
  173. if (parseAst_js.isPathFragment(pattern))
  174. 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.`));
  175. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  176. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  177. return parseAst_js.error(parseAst_js.logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  178. }
  179. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  180. if (parseAst_js.isPathFragment(replacement))
  181. return parseAst_js.error(parseAst_js.logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  182. return replacement;
  183. });
  184. }
  185. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  186. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  187. return name;
  188. const extension = path.extname(name);
  189. name = name.slice(0, Math.max(0, name.length - extension.length));
  190. let uniqueName, uniqueIndex = 1;
  191. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  192. ;
  193. return uniqueName;
  194. }
  195. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  196. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  197. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  198. ? outputOptions.assetFileNames({
  199. // Additionally, this should be non-enumerable in the next major
  200. get name() {
  201. 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);
  202. return name;
  203. },
  204. names,
  205. // Additionally, this should be non-enumerable in the next major
  206. get originalFileName() {
  207. 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);
  208. return originalFileName;
  209. },
  210. originalFileNames,
  211. source,
  212. type: 'asset'
  213. })
  214. : outputOptions.assetFileNames, 'output.assetFileNames', {
  215. ext: () => path.extname(emittedName).slice(1),
  216. extname: () => path.extname(emittedName),
  217. hash: size => sourceHash.slice(0, Math.max(0, size || DEFAULT_HASH_SIZE)),
  218. name: () => emittedName.slice(0, Math.max(0, emittedName.length - path.extname(emittedName).length))
  219. }), bundle);
  220. }
  221. function reserveFileNameInBundle(fileName, { bundle }, log) {
  222. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  223. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logFileNameConflict(fileName));
  224. }
  225. else {
  226. bundle[fileName] = FILE_PLACEHOLDER;
  227. }
  228. }
  229. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  230. function hasValidType(emittedFile) {
  231. return Boolean(emittedFile &&
  232. emittedFileTypes.has(emittedFile.type));
  233. }
  234. function hasValidName(emittedFile) {
  235. const validatedName = emittedFile.fileName || emittedFile.name;
  236. return !validatedName || (typeof validatedName === 'string' && !parseAst_js.isPathFragment(validatedName));
  237. }
  238. function getValidSource(source, emittedFile, fileReferenceId) {
  239. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  240. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  241. 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.`));
  242. }
  243. return source;
  244. }
  245. function getAssetFileName(file, referenceId) {
  246. if (typeof file.fileName !== 'string') {
  247. return parseAst_js.error(parseAst_js.logAssetNotFinalisedForFileName(file.name || referenceId));
  248. }
  249. return file.fileName;
  250. }
  251. function getChunkFileName(file, facadeChunkByModule) {
  252. if (file.fileName) {
  253. return file.fileName;
  254. }
  255. if (facadeChunkByModule) {
  256. return facadeChunkByModule.get(file.module).getFileName();
  257. }
  258. return parseAst_js.error(parseAst_js.logChunkNotGeneratedForFileName(file.fileName || file.name));
  259. }
  260. class FileEmitter {
  261. constructor(graph, options, baseFileEmitter) {
  262. this.graph = graph;
  263. this.options = options;
  264. this.facadeChunkByModule = null;
  265. this.nextIdBase = 1;
  266. this.output = null;
  267. this.outputFileEmitters = [];
  268. this.emitFile = (emittedFile) => {
  269. if (!hasValidType(emittedFile)) {
  270. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  271. }
  272. if (emittedFile.type === 'prebuilt-chunk') {
  273. return this.emitPrebuiltChunk(emittedFile);
  274. }
  275. if (!hasValidName(emittedFile)) {
  276. 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}".`));
  277. }
  278. if (emittedFile.type === 'chunk') {
  279. return this.emitChunk(emittedFile);
  280. }
  281. return this.emitAsset(emittedFile);
  282. };
  283. this.finaliseAssets = () => {
  284. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  285. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  286. return parseAst_js.error(parseAst_js.logNoAssetSourceSet(emittedFile.name || referenceId));
  287. }
  288. };
  289. this.getFileName = (fileReferenceId) => {
  290. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  291. if (!emittedFile)
  292. return parseAst_js.error(parseAst_js.logFileReferenceIdNotFoundForFilename(fileReferenceId));
  293. if (emittedFile.type === 'chunk') {
  294. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  295. }
  296. if (emittedFile.type === 'prebuilt-chunk') {
  297. return emittedFile.fileName;
  298. }
  299. return getAssetFileName(emittedFile, fileReferenceId);
  300. };
  301. this.setAssetSource = (referenceId, requestedSource) => {
  302. const consumedFile = this.filesByReferenceId.get(referenceId);
  303. if (!consumedFile)
  304. return parseAst_js.error(parseAst_js.logAssetReferenceIdNotFoundForSetSource(referenceId));
  305. if (consumedFile.type !== 'asset') {
  306. return parseAst_js.error(parseAst_js.logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  307. }
  308. if (consumedFile.source !== undefined) {
  309. return parseAst_js.error(parseAst_js.logAssetSourceAlreadySet(consumedFile.name || referenceId));
  310. }
  311. const source = getValidSource(requestedSource, consumedFile, referenceId);
  312. if (this.output) {
  313. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  314. }
  315. else {
  316. consumedFile.source = source;
  317. for (const emitter of this.outputFileEmitters) {
  318. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  319. }
  320. }
  321. };
  322. this.setChunkInformation = (facadeChunkByModule) => {
  323. this.facadeChunkByModule = facadeChunkByModule;
  324. };
  325. this.setOutputBundle = (bundle, outputOptions) => {
  326. const getHash = hasherByType[outputOptions.hashCharacters];
  327. const output = (this.output = {
  328. bundle,
  329. fileNamesBySourceHash: new Map(),
  330. getHash,
  331. outputOptions
  332. });
  333. for (const emittedFile of this.filesByReferenceId.values()) {
  334. if (emittedFile.fileName) {
  335. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  336. }
  337. }
  338. const consumedAssetsByHash = new Map();
  339. for (const consumedFile of this.filesByReferenceId.values()) {
  340. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  341. if (consumedFile.fileName) {
  342. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  343. }
  344. else {
  345. const sourceHash = getHash(consumedFile.source);
  346. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  347. }
  348. }
  349. else if (consumedFile.type === 'prebuilt-chunk') {
  350. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  351. }
  352. }
  353. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  354. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  355. }
  356. };
  357. this.filesByReferenceId = baseFileEmitter
  358. ? new Map(baseFileEmitter.filesByReferenceId)
  359. : new Map();
  360. baseFileEmitter?.addOutputFileEmitter(this);
  361. }
  362. addOutputFileEmitter(outputFileEmitter) {
  363. this.outputFileEmitters.push(outputFileEmitter);
  364. }
  365. assignReferenceId(file, idBase) {
  366. let referenceId = idBase;
  367. do {
  368. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  369. } while (this.filesByReferenceId.has(referenceId) ||
  370. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  371. file.referenceId = referenceId;
  372. this.filesByReferenceId.set(referenceId, file);
  373. for (const { filesByReferenceId } of this.outputFileEmitters) {
  374. filesByReferenceId.set(referenceId, file);
  375. }
  376. return referenceId;
  377. }
  378. createPrebuiltChunk(prebuiltChunk) {
  379. return {
  380. code: prebuiltChunk.code,
  381. dynamicImports: [],
  382. exports: prebuiltChunk.exports || [],
  383. facadeModuleId: null,
  384. fileName: prebuiltChunk.fileName,
  385. implicitlyLoadedBefore: [],
  386. importedBindings: {},
  387. imports: [],
  388. isDynamicEntry: false,
  389. isEntry: false,
  390. isImplicitEntry: false,
  391. map: prebuiltChunk.map || null,
  392. moduleIds: [],
  393. modules: {},
  394. name: prebuiltChunk.fileName,
  395. preliminaryFileName: prebuiltChunk.fileName,
  396. referencedFiles: [],
  397. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  398. type: 'chunk'
  399. };
  400. }
  401. emitAsset(emittedAsset) {
  402. const source = emittedAsset.source === undefined
  403. ? undefined
  404. : getValidSource(emittedAsset.source, emittedAsset, null);
  405. const originalFileName = emittedAsset.originalFileName || null;
  406. if (typeof originalFileName === 'string') {
  407. this.graph.watchFiles[originalFileName] = true;
  408. }
  409. const consumedAsset = {
  410. fileName: emittedAsset.fileName,
  411. name: emittedAsset.name,
  412. needsCodeReference: !!emittedAsset.needsCodeReference,
  413. originalFileName,
  414. referenceId: '',
  415. source,
  416. type: 'asset'
  417. };
  418. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  419. if (this.output) {
  420. this.emitAssetWithReferenceId(consumedAsset, this.output);
  421. }
  422. else {
  423. for (const fileEmitter of this.outputFileEmitters) {
  424. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  425. }
  426. }
  427. return referenceId;
  428. }
  429. emitAssetWithReferenceId(consumedAsset, output) {
  430. const { fileName, source } = consumedAsset;
  431. if (fileName) {
  432. reserveFileNameInBundle(fileName, output, this.options.onLog);
  433. }
  434. if (source !== undefined) {
  435. this.finalizeAdditionalAsset(consumedAsset, source, output);
  436. }
  437. }
  438. emitChunk(emittedChunk) {
  439. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  440. return parseAst_js.error(parseAst_js.logInvalidRollupPhaseForChunkEmission());
  441. }
  442. if (typeof emittedChunk.id !== 'string') {
  443. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  444. }
  445. const consumedChunk = {
  446. fileName: emittedChunk.fileName,
  447. module: null,
  448. name: emittedChunk.name || emittedChunk.id,
  449. referenceId: '',
  450. type: 'chunk'
  451. };
  452. this.graph.moduleLoader
  453. .emitChunk(emittedChunk)
  454. .then(module => (consumedChunk.module = module))
  455. .catch(() => {
  456. // Avoid unhandled Promise rejection as the error will be thrown later
  457. // once module loading has finished
  458. });
  459. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  460. }
  461. emitPrebuiltChunk(emitPrebuiltChunk) {
  462. if (typeof emitPrebuiltChunk.code !== 'string') {
  463. return parseAst_js.error(parseAst_js.logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  464. }
  465. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  466. parseAst_js.isPathFragment(emitPrebuiltChunk.fileName)) {
  467. 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}".`));
  468. }
  469. const consumedPrebuiltChunk = {
  470. code: emitPrebuiltChunk.code,
  471. exports: emitPrebuiltChunk.exports,
  472. fileName: emitPrebuiltChunk.fileName,
  473. map: emitPrebuiltChunk.map,
  474. referenceId: '',
  475. type: 'prebuilt-chunk'
  476. };
  477. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  478. if (this.output) {
  479. this.output.bundle[consumedPrebuiltChunk.fileName] =
  480. this.createPrebuiltChunk(consumedPrebuiltChunk);
  481. }
  482. return referenceId;
  483. }
  484. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  485. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  486. // Deduplicate assets if an explicit fileName is not provided
  487. if (!fileName) {
  488. const sourceHash = getHash(source);
  489. fileName = fileNamesBySourceHash.get(sourceHash);
  490. if (!fileName) {
  491. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  492. fileNamesBySourceHash.set(sourceHash, fileName);
  493. }
  494. }
  495. // We must not modify the original assets to avoid interaction between outputs
  496. const assetWithFileName = { ...consumedFile, fileName, source };
  497. this.filesByReferenceId.set(referenceId, assetWithFileName);
  498. const existingAsset = bundle[fileName];
  499. if (existingAsset?.type === 'asset') {
  500. existingAsset.needsCodeReference &&= needsCodeReference;
  501. if (name) {
  502. existingAsset.names.push(name);
  503. }
  504. if (originalFileName) {
  505. existingAsset.originalFileNames.push(originalFileName);
  506. }
  507. }
  508. else {
  509. const { options } = this;
  510. bundle[fileName] = {
  511. fileName,
  512. get name() {
  513. // Additionally, this should be non-enumerable in the next major
  514. 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);
  515. return name;
  516. },
  517. names: name ? [name] : [],
  518. needsCodeReference,
  519. get originalFileName() {
  520. // Additionally, this should be non-enumerable in the next major
  521. 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);
  522. return originalFileName;
  523. },
  524. originalFileNames: originalFileName ? [originalFileName] : [],
  525. source,
  526. type: 'asset'
  527. };
  528. }
  529. }
  530. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  531. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  532. let fileName = '';
  533. let usedConsumedFile;
  534. let needsCodeReference = true;
  535. for (const consumedFile of consumedFiles) {
  536. needsCodeReference &&= consumedFile.needsCodeReference;
  537. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  538. if (!fileName ||
  539. assetFileName.length < fileName.length ||
  540. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  541. fileName = assetFileName;
  542. usedConsumedFile = consumedFile;
  543. }
  544. }
  545. fileNamesBySourceHash.set(sourceHash, fileName);
  546. for (const consumedFile of consumedFiles) {
  547. // We must not modify the original assets to avoid interaction between outputs
  548. const assetWithFileName = { ...consumedFile, fileName };
  549. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  550. }
  551. const { options } = this;
  552. bundle[fileName] = {
  553. fileName,
  554. get name() {
  555. // Additionally, this should be non-enumerable in the next major
  556. 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);
  557. return usedConsumedFile.name;
  558. },
  559. names,
  560. needsCodeReference,
  561. get originalFileName() {
  562. // Additionally, this should be non-enumerable in the next major
  563. 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);
  564. return usedConsumedFile.originalFileName;
  565. },
  566. originalFileNames,
  567. source: usedConsumedFile.source,
  568. type: 'asset'
  569. };
  570. }
  571. }
  572. function getNamesFromAssets(consumedFiles) {
  573. const names = [];
  574. const originalFileNames = [];
  575. for (const { name, originalFileName } of consumedFiles) {
  576. if (typeof name === 'string') {
  577. names.push(name);
  578. }
  579. if (originalFileName) {
  580. originalFileNames.push(originalFileName);
  581. }
  582. }
  583. originalFileNames.sort();
  584. // Sort by length first and then alphabetically so that the order is stable
  585. // and the shortest names come first
  586. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  587. return { names, originalFileNames };
  588. }
  589. const doNothing = () => { };
  590. async function asyncFlatten(array) {
  591. do {
  592. array = (await Promise.all(array)).flat(Infinity);
  593. } while (array.some((v) => v?.then));
  594. return array;
  595. }
  596. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  597. const { onwarn, onLog } = config;
  598. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  599. if (onLog) {
  600. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  601. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  602. if (level === parseAst_js.LOGLEVEL_ERROR) {
  603. return parseAst_js.error(normalizeLog(handledLog));
  604. }
  605. if (parseAst_js.logLevelPriority[level] >= minimalPriority) {
  606. defaultOnLog(level, normalizeLog(handledLog));
  607. }
  608. });
  609. }
  610. return defaultOnLog;
  611. };
  612. const getDefaultOnLog = (printLog, onwarn) => onwarn
  613. ? (level, log) => {
  614. if (level === parseAst_js.LOGLEVEL_WARN) {
  615. onwarn(addLogToString(log), warning => printLog(parseAst_js.LOGLEVEL_WARN, normalizeLog(warning)));
  616. }
  617. else {
  618. printLog(level, log);
  619. }
  620. }
  621. : printLog;
  622. const addLogToString = (log) => {
  623. Object.defineProperty(log, 'toString', {
  624. value: () => log.message,
  625. writable: true
  626. });
  627. return log;
  628. };
  629. const normalizeLog = (log) => typeof log === 'string'
  630. ? { message: log }
  631. : typeof log === 'function'
  632. ? normalizeLog(log())
  633. : log;
  634. const defaultPrintLog = (level, { message }) => {
  635. switch (level) {
  636. case parseAst_js.LOGLEVEL_WARN: {
  637. return console.warn(message);
  638. }
  639. case parseAst_js.LOGLEVEL_DEBUG: {
  640. return console.debug(message);
  641. }
  642. default: {
  643. return console.info(message);
  644. }
  645. }
  646. };
  647. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  648. const validOptionSet = new Set(validOptions);
  649. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  650. if (unknownOptions.length > 0) {
  651. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  652. }
  653. }
  654. const treeshakePresets = {
  655. recommended: {
  656. annotations: true,
  657. correctVarValueBeforeDeclaration: false,
  658. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  659. moduleSideEffects: () => true,
  660. propertyReadSideEffects: true,
  661. tryCatchDeoptimization: true,
  662. unknownGlobalSideEffects: false
  663. },
  664. safest: {
  665. annotations: true,
  666. correctVarValueBeforeDeclaration: true,
  667. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  668. moduleSideEffects: () => true,
  669. propertyReadSideEffects: true,
  670. tryCatchDeoptimization: true,
  671. unknownGlobalSideEffects: true
  672. },
  673. smallest: {
  674. annotations: true,
  675. correctVarValueBeforeDeclaration: false,
  676. manualPureFunctions: parseAst_js.EMPTY_ARRAY,
  677. moduleSideEffects: () => false,
  678. propertyReadSideEffects: false,
  679. tryCatchDeoptimization: false,
  680. unknownGlobalSideEffects: false
  681. }
  682. };
  683. const jsxPresets = {
  684. preserve: {
  685. factory: null,
  686. fragment: null,
  687. importSource: null,
  688. mode: 'preserve'
  689. },
  690. 'preserve-react': {
  691. factory: 'React.createElement',
  692. fragment: 'React.Fragment',
  693. importSource: 'react',
  694. mode: 'preserve'
  695. },
  696. react: {
  697. factory: 'React.createElement',
  698. fragment: 'React.Fragment',
  699. importSource: 'react',
  700. mode: 'classic'
  701. },
  702. 'react-jsx': {
  703. factory: 'React.createElement',
  704. importSource: 'react',
  705. jsxImportSource: 'react/jsx-runtime',
  706. mode: 'automatic'
  707. }
  708. };
  709. const generatedCodePresets = {
  710. es2015: {
  711. arrowFunctions: true,
  712. constBindings: true,
  713. objectShorthand: true,
  714. reservedNamesAsProps: true,
  715. symbols: true
  716. },
  717. es5: {
  718. arrowFunctions: false,
  719. constBindings: false,
  720. objectShorthand: false,
  721. reservedNamesAsProps: true,
  722. symbols: false
  723. }
  724. };
  725. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  726. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  727. if (typeof value === 'string') {
  728. const preset = presets[value];
  729. if (preset) {
  730. return preset;
  731. }
  732. 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));
  733. }
  734. return objectifyOption(value);
  735. };
  736. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  737. const presetName = value?.preset;
  738. if (presetName) {
  739. const preset = presets[presetName];
  740. if (preset) {
  741. return { ...preset, ...value };
  742. }
  743. else {
  744. parseAst_js.error(parseAst_js.logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${parseAst_js.printQuotedStringList(Object.keys(presets))}`, presetName));
  745. }
  746. }
  747. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  748. };
  749. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  750. function getLogHandler(level, code, logger, pluginName, logLevel) {
  751. if (parseAst_js.logLevelPriority[level] < parseAst_js.logLevelPriority[logLevel]) {
  752. return doNothing;
  753. }
  754. return (log, pos) => {
  755. if (pos != null) {
  756. logger(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidLogPosition(pluginName));
  757. }
  758. log = normalizeLog(log);
  759. if (log.code && !log.pluginCode) {
  760. log.pluginCode = log.code;
  761. }
  762. log.code = code;
  763. log.plugin = pluginName;
  764. logger(level, log);
  765. };
  766. }
  767. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  768. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  769. function createPluginCache(cache) {
  770. return {
  771. delete(id) {
  772. return delete cache[id];
  773. },
  774. get(id) {
  775. const item = cache[id];
  776. if (!item)
  777. return;
  778. item[0] = 0;
  779. return item[1];
  780. },
  781. has(id) {
  782. const item = cache[id];
  783. if (!item)
  784. return false;
  785. item[0] = 0;
  786. return true;
  787. },
  788. set(id, value) {
  789. cache[id] = [0, value];
  790. }
  791. };
  792. }
  793. function getTrackedPluginCache(pluginCache, onUse) {
  794. return {
  795. delete(id) {
  796. onUse();
  797. return pluginCache.delete(id);
  798. },
  799. get(id) {
  800. onUse();
  801. return pluginCache.get(id);
  802. },
  803. has(id) {
  804. onUse();
  805. return pluginCache.has(id);
  806. },
  807. set(id, value) {
  808. onUse();
  809. return pluginCache.set(id, value);
  810. }
  811. };
  812. }
  813. const NO_CACHE = {
  814. delete() {
  815. return false;
  816. },
  817. get() {
  818. return undefined;
  819. },
  820. has() {
  821. return false;
  822. },
  823. set() { }
  824. };
  825. function uncacheablePluginError(pluginName) {
  826. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  827. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  828. return parseAst_js.error(parseAst_js.logAnonymousPluginCache());
  829. }
  830. return parseAst_js.error(parseAst_js.logDuplicatePluginName(pluginName));
  831. }
  832. function getCacheForUncacheablePlugin(pluginName) {
  833. return {
  834. delete() {
  835. return uncacheablePluginError(pluginName);
  836. },
  837. get() {
  838. return uncacheablePluginError(pluginName);
  839. },
  840. has() {
  841. return uncacheablePluginError(pluginName);
  842. },
  843. set() {
  844. return uncacheablePluginError(pluginName);
  845. }
  846. };
  847. }
  848. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  849. const { logLevel, onLog } = options;
  850. let cacheable = true;
  851. if (typeof plugin.cacheKey !== 'string') {
  852. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  853. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  854. existingPluginNames.has(plugin.name)) {
  855. cacheable = false;
  856. }
  857. else {
  858. existingPluginNames.add(plugin.name);
  859. }
  860. }
  861. let cacheInstance;
  862. if (!pluginCache) {
  863. cacheInstance = NO_CACHE;
  864. }
  865. else if (cacheable) {
  866. const cacheKey = plugin.cacheKey || plugin.name;
  867. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  868. }
  869. else {
  870. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  871. }
  872. return {
  873. addWatchFile(id) {
  874. graph.watchFiles[id] = true;
  875. },
  876. cache: cacheInstance,
  877. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  878. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  879. error(error_) {
  880. return parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), plugin.name));
  881. },
  882. getFileName: fileEmitter.getFileName,
  883. getModuleIds: () => graph.modulesById.keys(),
  884. getModuleInfo: graph.getModuleInfo,
  885. getWatchFiles: () => Object.keys(graph.watchFiles),
  886. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  887. load(resolvedId) {
  888. return graph.moduleLoader.preloadModule(resolvedId);
  889. },
  890. meta: {
  891. rollupVersion: version,
  892. watchMode: graph.watchMode
  893. },
  894. parse: parseAst_js.parseAst,
  895. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) {
  896. skipSelf ??= true;
  897. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  898. },
  899. setAssetSource: fileEmitter.setAssetSource,
  900. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  901. };
  902. }
  903. // This will make sure no input hook is omitted
  904. const inputHookNames = {
  905. buildEnd: 1,
  906. buildStart: 1,
  907. closeBundle: 1,
  908. closeWatcher: 1,
  909. load: 1,
  910. moduleParsed: 1,
  911. onLog: 1,
  912. options: 1,
  913. resolveDynamicImport: 1,
  914. resolveId: 1,
  915. shouldTransformCachedModule: 1,
  916. transform: 1,
  917. watchChange: 1
  918. };
  919. const inputHooks = Object.keys(inputHookNames);
  920. class PluginDriver {
  921. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  922. this.graph = graph;
  923. this.options = options;
  924. this.pluginCache = pluginCache;
  925. this.sortedPlugins = new Map();
  926. this.unfulfilledActions = new Set();
  927. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  928. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  929. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  930. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  931. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  932. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  933. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  934. const existingPluginNames = new Set();
  935. this.pluginContexts = new Map(this.plugins.map(plugin => [
  936. plugin,
  937. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  938. ]));
  939. if (basePluginDriver) {
  940. for (const plugin of userPlugins) {
  941. for (const hook of inputHooks) {
  942. if (hook in plugin) {
  943. options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInputHookInOutputPlugin(plugin.name, hook));
  944. }
  945. }
  946. }
  947. }
  948. }
  949. createOutputPluginDriver(plugins) {
  950. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  951. }
  952. getUnfulfilledHookActions() {
  953. return this.unfulfilledActions;
  954. }
  955. // chains, first non-null result stops and returns
  956. hookFirst(hookName, parameters, replaceContext, skipped) {
  957. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  958. }
  959. // chains, first non-null result stops and returns result and last plugin
  960. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  961. for (const plugin of this.getSortedPlugins(hookName)) {
  962. if (skipped?.has(plugin))
  963. continue;
  964. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  965. if (result != null)
  966. return [result, plugin];
  967. }
  968. return null;
  969. }
  970. // chains synchronously, first non-null result stops and returns
  971. hookFirstSync(hookName, parameters, replaceContext) {
  972. for (const plugin of this.getSortedPlugins(hookName)) {
  973. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  974. if (result != null)
  975. return result;
  976. }
  977. return null;
  978. }
  979. // parallel, ignores returns
  980. async hookParallel(hookName, parameters, replaceContext) {
  981. const parallelPromises = [];
  982. for (const plugin of this.getSortedPlugins(hookName)) {
  983. if (plugin[hookName].sequential) {
  984. await Promise.all(parallelPromises);
  985. parallelPromises.length = 0;
  986. await this.runHook(hookName, parameters, plugin, replaceContext);
  987. }
  988. else {
  989. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  990. }
  991. }
  992. await Promise.all(parallelPromises);
  993. }
  994. // chains, reduces returned value, handling the reduced value as the first hook argument
  995. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  996. let promise = Promise.resolve(argument0);
  997. for (const plugin of this.getSortedPlugins(hookName)) {
  998. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  999. }
  1000. return promise;
  1001. }
  1002. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  1003. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  1004. for (const plugin of this.getSortedPlugins(hookName)) {
  1005. const parameters = [argument0, ...rest];
  1006. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1007. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  1008. }
  1009. return argument0;
  1010. }
  1011. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  1012. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  1013. const results = [];
  1014. const parallelResults = [];
  1015. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  1016. if (plugin[hookName].sequential) {
  1017. results.push(...(await Promise.all(parallelResults)));
  1018. parallelResults.length = 0;
  1019. results.push(await this.runHook(hookName, parameters, plugin));
  1020. }
  1021. else {
  1022. parallelResults.push(this.runHook(hookName, parameters, plugin));
  1023. }
  1024. }
  1025. results.push(...(await Promise.all(parallelResults)));
  1026. return results.reduce(reducer, await initialValue);
  1027. }
  1028. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  1029. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  1030. let accumulator = initialValue;
  1031. for (const plugin of this.getSortedPlugins(hookName)) {
  1032. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1033. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  1034. }
  1035. return accumulator;
  1036. }
  1037. // chains, ignores returns
  1038. hookSeq(hookName, parameters, replaceContext) {
  1039. let promise = Promise.resolve();
  1040. for (const plugin of this.getSortedPlugins(hookName)) {
  1041. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  1042. }
  1043. return promise.then(noReturn);
  1044. }
  1045. getSortedPlugins(hookName, validateHandler) {
  1046. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  1047. }
  1048. // Implementation signature
  1049. runHook(hookName, parameters, plugin, replaceContext) {
  1050. // We always filter for plugins that support the hook before running it
  1051. const hook = plugin[hookName];
  1052. const handler = typeof hook === 'object' ? hook.handler : hook;
  1053. let context = this.pluginContexts.get(plugin);
  1054. if (replaceContext) {
  1055. context = replaceContext(context, plugin);
  1056. }
  1057. let action = null;
  1058. return Promise.resolve()
  1059. .then(() => {
  1060. if (typeof handler !== 'function') {
  1061. return handler;
  1062. }
  1063. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  1064. const hookResult = handler.apply(context, parameters);
  1065. if (!hookResult?.then) {
  1066. // short circuit for non-thenables and non-Promises
  1067. return hookResult;
  1068. }
  1069. // Track pending hook actions to properly error out when
  1070. // unfulfilled promises cause rollup to abruptly and confusingly
  1071. // exit with a successful 0 return code but without producing any
  1072. // output, errors or warnings.
  1073. action = [plugin.name, hookName, parameters];
  1074. this.unfulfilledActions.add(action);
  1075. // Although it would be more elegant to just return hookResult here
  1076. // and put the .then() handler just above the .catch() handler below,
  1077. // doing so would subtly change the defacto async event dispatch order
  1078. // which at least one test and some plugins in the wild may depend on.
  1079. return Promise.resolve(hookResult).then(result => {
  1080. // action was fulfilled
  1081. this.unfulfilledActions.delete(action);
  1082. return result;
  1083. });
  1084. })
  1085. .catch(error_ => {
  1086. if (action !== null) {
  1087. // action considered to be fulfilled since error being handled
  1088. this.unfulfilledActions.delete(action);
  1089. }
  1090. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  1091. });
  1092. }
  1093. /**
  1094. * Run a sync plugin hook and return the result.
  1095. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  1096. * @param args Arguments passed to the plugin hook.
  1097. * @param plugin The acutal plugin
  1098. * @param replaceContext When passed, the plugin context can be overridden.
  1099. */
  1100. runHookSync(hookName, parameters, plugin, replaceContext) {
  1101. const hook = plugin[hookName];
  1102. const handler = typeof hook === 'object' ? hook.handler : hook;
  1103. let context = this.pluginContexts.get(plugin);
  1104. if (replaceContext) {
  1105. context = replaceContext(context, plugin);
  1106. }
  1107. try {
  1108. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  1109. return handler.apply(context, parameters);
  1110. }
  1111. catch (error_) {
  1112. return parseAst_js.error(parseAst_js.logPluginError(error_, plugin.name, { hook: hookName }));
  1113. }
  1114. }
  1115. }
  1116. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  1117. const pre = [];
  1118. const normal = [];
  1119. const post = [];
  1120. for (const plugin of plugins) {
  1121. const hook = plugin[hookName];
  1122. if (hook) {
  1123. if (typeof hook === 'object') {
  1124. validateHandler(hook.handler, hookName, plugin);
  1125. if (hook.order === 'pre') {
  1126. pre.push(plugin);
  1127. continue;
  1128. }
  1129. if (hook.order === 'post') {
  1130. post.push(plugin);
  1131. continue;
  1132. }
  1133. }
  1134. else {
  1135. validateHandler(hook, hookName, plugin);
  1136. }
  1137. normal.push(plugin);
  1138. }
  1139. }
  1140. return [...pre, ...normal, ...post];
  1141. }
  1142. function validateFunctionPluginHandler(handler, hookName, plugin) {
  1143. if (typeof handler !== 'function') {
  1144. parseAst_js.error(parseAst_js.logInvalidFunctionPluginHook(hookName, plugin.name));
  1145. }
  1146. }
  1147. function validateAddonPluginHandler(handler, hookName, plugin) {
  1148. if (typeof handler !== 'string' && typeof handler !== 'function') {
  1149. return parseAst_js.error(parseAst_js.logInvalidAddonPluginHook(hookName, plugin.name));
  1150. }
  1151. }
  1152. function noReturn() { }
  1153. function getLogger(plugins, onLog, watchMode, logLevel) {
  1154. plugins = getSortedValidatedPlugins('onLog', plugins);
  1155. const minimalPriority = parseAst_js.logLevelPriority[logLevel];
  1156. const logger = (level, log, skipped = parseAst_js.EMPTY_SET) => {
  1157. parseAst_js.augmentLogMessage(log);
  1158. const logPriority = parseAst_js.logLevelPriority[level];
  1159. if (logPriority < minimalPriority) {
  1160. return;
  1161. }
  1162. for (const plugin of plugins) {
  1163. if (skipped.has(plugin))
  1164. continue;
  1165. const { onLog: pluginOnLog } = plugin;
  1166. const getLogHandler = (level) => {
  1167. if (parseAst_js.logLevelPriority[level] < minimalPriority) {
  1168. return doNothing;
  1169. }
  1170. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  1171. };
  1172. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  1173. if (handler.call({
  1174. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG),
  1175. error: (log) => parseAst_js.error(normalizeLog(log)),
  1176. info: getLogHandler(parseAst_js.LOGLEVEL_INFO),
  1177. meta: { rollupVersion: version, watchMode },
  1178. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN)
  1179. }, level, log) === false) {
  1180. return;
  1181. }
  1182. }
  1183. onLog(level, log);
  1184. };
  1185. return logger;
  1186. }
  1187. const commandAliases = {
  1188. c: 'config',
  1189. d: 'dir',
  1190. e: 'external',
  1191. f: 'format',
  1192. g: 'globals',
  1193. h: 'help',
  1194. i: 'input',
  1195. m: 'sourcemap',
  1196. n: 'name',
  1197. o: 'file',
  1198. p: 'plugin',
  1199. v: 'version',
  1200. w: 'watch'
  1201. };
  1202. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  1203. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  1204. const command = getCommandOptions(rawCommandOptions);
  1205. const plugins = await normalizePluginOption(config.plugins);
  1206. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  1207. const onLog = getOnLog(config, logLevel, printLog);
  1208. const log = getLogger(plugins, onLog, watchMode, logLevel);
  1209. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  1210. if (command.output) {
  1211. Object.assign(command, command.output);
  1212. }
  1213. const outputOptionsArray = ensureArray$1(config.output);
  1214. if (outputOptionsArray.length === 0)
  1215. outputOptionsArray.push({});
  1216. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  1217. warnUnknownOptions(command, [
  1218. ...Object.keys(inputOptions),
  1219. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  1220. ...Object.keys(commandAliases),
  1221. 'bundleConfigAsCjs',
  1222. 'config',
  1223. 'configPlugin',
  1224. 'environment',
  1225. 'failAfterWarnings',
  1226. 'filterLogs',
  1227. 'forceExit',
  1228. 'plugin',
  1229. 'silent',
  1230. 'stdin',
  1231. 'waitForBundleInput'
  1232. ], 'CLI flags', log, /^_$|output$|config/);
  1233. inputOptions.output = outputOptions;
  1234. return inputOptions;
  1235. }
  1236. function getCommandOptions(rawCommandOptions) {
  1237. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  1238. ? rawCommandOptions.external.split(',')
  1239. : [];
  1240. return {
  1241. ...rawCommandOptions,
  1242. external,
  1243. globals: typeof rawCommandOptions.globals === 'string'
  1244. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  1245. const [id, variableName] = globalDefinition.split(':');
  1246. globals[id] = variableName;
  1247. if (!external.includes(id)) {
  1248. external.push(id);
  1249. }
  1250. return globals;
  1251. }, Object.create(null))
  1252. : undefined
  1253. };
  1254. }
  1255. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  1256. const getOption = (name) => overrides[name] ?? config[name];
  1257. const inputOptions = {
  1258. cache: config.cache,
  1259. context: getOption('context'),
  1260. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  1261. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  1262. external: getExternal(config, overrides),
  1263. input: getOption('input') || [],
  1264. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ')),
  1265. logLevel: getOption('logLevel'),
  1266. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  1267. maxParallelFileOps: getOption('maxParallelFileOps'),
  1268. moduleContext: getOption('moduleContext'),
  1269. onLog,
  1270. onwarn: undefined,
  1271. perf: getOption('perf'),
  1272. plugins,
  1273. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  1274. preserveSymlinks: getOption('preserveSymlinks'),
  1275. shimMissingExports: getOption('shimMissingExports'),
  1276. strictDeprecations: getOption('strictDeprecations'),
  1277. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ')),
  1278. watch: getWatch(config, overrides)
  1279. };
  1280. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  1281. return inputOptions;
  1282. }
  1283. const getExternal = (config, overrides) => {
  1284. const configExternal = config.external;
  1285. return typeof configExternal === 'function'
  1286. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  1287. : [...ensureArray$1(configExternal), ...overrides.external];
  1288. };
  1289. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  1290. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  1291. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  1292. if (commandOption !== undefined) {
  1293. return commandOption && { ...configOption, ...commandOption };
  1294. }
  1295. return configOption;
  1296. };
  1297. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  1298. const isWatchEnabled = (optionValue) => {
  1299. if (Array.isArray(optionValue)) {
  1300. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  1301. }
  1302. return optionValue === true;
  1303. };
  1304. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  1305. if (!optionValue) {
  1306. return optionValue;
  1307. }
  1308. if (Array.isArray(optionValue)) {
  1309. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  1310. }
  1311. return objectifyValue(optionValue);
  1312. };
  1313. async function mergeOutputOptions(config, overrides, log) {
  1314. const getOption = (name) => overrides[name] ?? config[name];
  1315. const outputOptions = {
  1316. amd: getObjectOption(config, overrides, 'amd'),
  1317. assetFileNames: getOption('assetFileNames'),
  1318. banner: getOption('banner'),
  1319. chunkFileNames: getOption('chunkFileNames'),
  1320. compact: getOption('compact'),
  1321. dir: getOption('dir'),
  1322. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  1323. entryFileNames: getOption('entryFileNames'),
  1324. esModule: getOption('esModule'),
  1325. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  1326. exports: getOption('exports'),
  1327. extend: getOption('extend'),
  1328. externalImportAssertions: getOption('externalImportAssertions'),
  1329. externalImportAttributes: getOption('externalImportAttributes'),
  1330. externalLiveBindings: getOption('externalLiveBindings'),
  1331. file: getOption('file'),
  1332. footer: getOption('footer'),
  1333. format: getOption('format'),
  1334. freeze: getOption('freeze'),
  1335. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '')),
  1336. globals: getOption('globals'),
  1337. hashCharacters: getOption('hashCharacters'),
  1338. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  1339. importAttributesKey: getOption('importAttributesKey'),
  1340. indent: getOption('indent'),
  1341. inlineDynamicImports: getOption('inlineDynamicImports'),
  1342. interop: getOption('interop'),
  1343. intro: getOption('intro'),
  1344. manualChunks: getOption('manualChunks'),
  1345. minifyInternalExports: getOption('minifyInternalExports'),
  1346. name: getOption('name'),
  1347. noConflict: getOption('noConflict'),
  1348. outro: getOption('outro'),
  1349. paths: getOption('paths'),
  1350. plugins: await normalizePluginOption(config.plugins),
  1351. preserveModules: getOption('preserveModules'),
  1352. preserveModulesRoot: getOption('preserveModulesRoot'),
  1353. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  1354. sanitizeFileName: getOption('sanitizeFileName'),
  1355. sourcemap: getOption('sourcemap'),
  1356. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  1357. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  1358. sourcemapFile: getOption('sourcemapFile'),
  1359. sourcemapFileNames: getOption('sourcemapFileNames'),
  1360. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  1361. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  1362. strict: getOption('strict'),
  1363. systemNullSetters: getOption('systemNullSetters'),
  1364. validate: getOption('validate'),
  1365. virtualDirname: getOption('virtualDirname')
  1366. };
  1367. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  1368. return outputOptions;
  1369. }
  1370. const {
  1371. env = {},
  1372. argv = [],
  1373. platform = "",
  1374. } = typeof process === "undefined" ? {} : process;
  1375. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  1376. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  1377. const isWindows = platform === "win32";
  1378. const isDumbTerminal = env.TERM === "dumb";
  1379. const isCompatibleTerminal =
  1380. tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
  1381. const isCI =
  1382. "CI" in env &&
  1383. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  1384. const isColorSupported =
  1385. !isDisabled &&
  1386. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  1387. const replaceClose = (
  1388. index,
  1389. string,
  1390. close,
  1391. replace,
  1392. head = string.substring(0, index) + replace,
  1393. tail = string.substring(index + close.length),
  1394. next = tail.indexOf(close)
  1395. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  1396. const clearBleed = (index, string, open, close, replace) =>
  1397. index < 0
  1398. ? open + string + close
  1399. : open + replaceClose(index, string, close, replace) + close;
  1400. const filterEmpty =
  1401. (open, close, replace = open, at = open.length + 1) =>
  1402. (string) =>
  1403. string || !(string === "" || string === undefined)
  1404. ? clearBleed(
  1405. ("" + string).indexOf(close, at),
  1406. string,
  1407. open,
  1408. close,
  1409. replace
  1410. )
  1411. : "";
  1412. const init = (open, close, replace) =>
  1413. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  1414. const colors = {
  1415. reset: init(0, 0),
  1416. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  1417. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  1418. italic: init(3, 23),
  1419. underline: init(4, 24),
  1420. inverse: init(7, 27),
  1421. hidden: init(8, 28),
  1422. strikethrough: init(9, 29),
  1423. black: init(30, 39),
  1424. red: init(31, 39),
  1425. green: init(32, 39),
  1426. yellow: init(33, 39),
  1427. blue: init(34, 39),
  1428. magenta: init(35, 39),
  1429. cyan: init(36, 39),
  1430. white: init(37, 39),
  1431. gray: init(90, 39),
  1432. bgBlack: init(40, 49),
  1433. bgRed: init(41, 49),
  1434. bgGreen: init(42, 49),
  1435. bgYellow: init(43, 49),
  1436. bgBlue: init(44, 49),
  1437. bgMagenta: init(45, 49),
  1438. bgCyan: init(46, 49),
  1439. bgWhite: init(47, 49),
  1440. blackBright: init(90, 39),
  1441. redBright: init(91, 39),
  1442. greenBright: init(92, 39),
  1443. yellowBright: init(93, 39),
  1444. blueBright: init(94, 39),
  1445. magentaBright: init(95, 39),
  1446. cyanBright: init(96, 39),
  1447. whiteBright: init(97, 39),
  1448. bgBlackBright: init(100, 49),
  1449. bgRedBright: init(101, 49),
  1450. bgGreenBright: init(102, 49),
  1451. bgYellowBright: init(103, 49),
  1452. bgBlueBright: init(104, 49),
  1453. bgMagentaBright: init(105, 49),
  1454. bgCyanBright: init(106, 49),
  1455. bgWhiteBright: init(107, 49),
  1456. };
  1457. const createColors = ({ useColor = isColorSupported } = {}) =>
  1458. useColor
  1459. ? colors
  1460. : Object.keys(colors).reduce(
  1461. (colors, key) => ({ ...colors, [key]: String }),
  1462. {}
  1463. );
  1464. const {
  1465. reset,
  1466. bold: bold$1,
  1467. dim: dim$1,
  1468. italic,
  1469. underline: underline$1,
  1470. inverse,
  1471. hidden,
  1472. strikethrough,
  1473. black,
  1474. red: red$1,
  1475. green: green$1,
  1476. yellow: yellow$1,
  1477. blue,
  1478. magenta,
  1479. cyan: cyan$1,
  1480. white,
  1481. gray: gray$1,
  1482. bgBlack,
  1483. bgRed,
  1484. bgGreen,
  1485. bgYellow,
  1486. bgBlue,
  1487. bgMagenta,
  1488. bgCyan,
  1489. bgWhite,
  1490. blackBright,
  1491. redBright,
  1492. greenBright,
  1493. yellowBright,
  1494. blueBright,
  1495. magentaBright,
  1496. cyanBright,
  1497. whiteBright,
  1498. bgBlackBright,
  1499. bgRedBright,
  1500. bgGreenBright,
  1501. bgYellowBright,
  1502. bgBlueBright,
  1503. bgMagentaBright,
  1504. bgCyanBright,
  1505. bgWhiteBright,
  1506. } = createColors();
  1507. // @see https://no-color.org
  1508. // @see https://www.npmjs.com/package/chalk
  1509. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  1510. useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
  1511. });
  1512. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  1513. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  1514. function handleError(error, recover = false) {
  1515. const name = error.name || error.cause?.name;
  1516. const nameSection = name ? `${name}: ` : '';
  1517. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  1518. const message = `${pluginSection}${nameSection}${error.message}`;
  1519. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  1520. if (error.url) {
  1521. outputLines.push(cyan(error.url));
  1522. }
  1523. if (error.loc) {
  1524. outputLines.push(`${parseAst_js.relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  1525. }
  1526. else if (error.id) {
  1527. outputLines.push(parseAst_js.relativeId(error.id));
  1528. }
  1529. if (error.frame) {
  1530. outputLines.push(dim(error.frame));
  1531. }
  1532. if (error.stack) {
  1533. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  1534. }
  1535. // ES2022: Error.prototype.cause is optional
  1536. if (error.cause) {
  1537. let cause = error.cause;
  1538. const causeErrorLines = [];
  1539. let indent = '';
  1540. while (cause) {
  1541. indent += ' ';
  1542. const message = cause.stack || cause;
  1543. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  1544. cause = cause.cause;
  1545. }
  1546. outputLines.push(dim(causeErrorLines.join('\n')));
  1547. }
  1548. outputLines.push('', '');
  1549. stderr(outputLines.join('\n'));
  1550. if (!recover)
  1551. process$1.exit(1);
  1552. }
  1553. const comma = ','.charCodeAt(0);
  1554. const semicolon = ';'.charCodeAt(0);
  1555. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  1556. const intToChar = new Uint8Array(64); // 64 possible chars.
  1557. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  1558. for (let i = 0; i < chars.length; i++) {
  1559. const c = chars.charCodeAt(i);
  1560. intToChar[i] = c;
  1561. charToInt[c] = i;
  1562. }
  1563. function decodeInteger(reader, relative) {
  1564. let value = 0;
  1565. let shift = 0;
  1566. let integer = 0;
  1567. do {
  1568. const c = reader.next();
  1569. integer = charToInt[c];
  1570. value |= (integer & 31) << shift;
  1571. shift += 5;
  1572. } while (integer & 32);
  1573. const shouldNegate = value & 1;
  1574. value >>>= 1;
  1575. if (shouldNegate) {
  1576. value = -0x80000000 | -value;
  1577. }
  1578. return relative + value;
  1579. }
  1580. function encodeInteger(builder, num, relative) {
  1581. let delta = num - relative;
  1582. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  1583. do {
  1584. let clamped = delta & 0b011111;
  1585. delta >>>= 5;
  1586. if (delta > 0)
  1587. clamped |= 0b100000;
  1588. builder.write(intToChar[clamped]);
  1589. } while (delta > 0);
  1590. return num;
  1591. }
  1592. function hasMoreVlq(reader, max) {
  1593. if (reader.pos >= max)
  1594. return false;
  1595. return reader.peek() !== comma;
  1596. }
  1597. const bufLength = 1024 * 16;
  1598. // Provide a fallback for older environments.
  1599. const td = typeof TextDecoder !== 'undefined'
  1600. ? /* #__PURE__ */ new TextDecoder()
  1601. : typeof Buffer !== 'undefined'
  1602. ? {
  1603. decode(buf) {
  1604. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  1605. return out.toString();
  1606. },
  1607. }
  1608. : {
  1609. decode(buf) {
  1610. let out = '';
  1611. for (let i = 0; i < buf.length; i++) {
  1612. out += String.fromCharCode(buf[i]);
  1613. }
  1614. return out;
  1615. },
  1616. };
  1617. class StringWriter {
  1618. constructor() {
  1619. this.pos = 0;
  1620. this.out = '';
  1621. this.buffer = new Uint8Array(bufLength);
  1622. }
  1623. write(v) {
  1624. const { buffer } = this;
  1625. buffer[this.pos++] = v;
  1626. if (this.pos === bufLength) {
  1627. this.out += td.decode(buffer);
  1628. this.pos = 0;
  1629. }
  1630. }
  1631. flush() {
  1632. const { buffer, out, pos } = this;
  1633. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  1634. }
  1635. }
  1636. class StringReader {
  1637. constructor(buffer) {
  1638. this.pos = 0;
  1639. this.buffer = buffer;
  1640. }
  1641. next() {
  1642. return this.buffer.charCodeAt(this.pos++);
  1643. }
  1644. peek() {
  1645. return this.buffer.charCodeAt(this.pos);
  1646. }
  1647. indexOf(char) {
  1648. const { buffer, pos } = this;
  1649. const idx = buffer.indexOf(char, pos);
  1650. return idx === -1 ? buffer.length : idx;
  1651. }
  1652. }
  1653. function decode(mappings) {
  1654. const { length } = mappings;
  1655. const reader = new StringReader(mappings);
  1656. const decoded = [];
  1657. let genColumn = 0;
  1658. let sourcesIndex = 0;
  1659. let sourceLine = 0;
  1660. let sourceColumn = 0;
  1661. let namesIndex = 0;
  1662. do {
  1663. const semi = reader.indexOf(';');
  1664. const line = [];
  1665. let sorted = true;
  1666. let lastCol = 0;
  1667. genColumn = 0;
  1668. while (reader.pos < semi) {
  1669. let seg;
  1670. genColumn = decodeInteger(reader, genColumn);
  1671. if (genColumn < lastCol)
  1672. sorted = false;
  1673. lastCol = genColumn;
  1674. if (hasMoreVlq(reader, semi)) {
  1675. sourcesIndex = decodeInteger(reader, sourcesIndex);
  1676. sourceLine = decodeInteger(reader, sourceLine);
  1677. sourceColumn = decodeInteger(reader, sourceColumn);
  1678. if (hasMoreVlq(reader, semi)) {
  1679. namesIndex = decodeInteger(reader, namesIndex);
  1680. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  1681. }
  1682. else {
  1683. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  1684. }
  1685. }
  1686. else {
  1687. seg = [genColumn];
  1688. }
  1689. line.push(seg);
  1690. reader.pos++;
  1691. }
  1692. if (!sorted)
  1693. sort(line);
  1694. decoded.push(line);
  1695. reader.pos = semi + 1;
  1696. } while (reader.pos <= length);
  1697. return decoded;
  1698. }
  1699. function sort(line) {
  1700. line.sort(sortComparator);
  1701. }
  1702. function sortComparator(a, b) {
  1703. return a[0] - b[0];
  1704. }
  1705. function encode(decoded) {
  1706. const writer = new StringWriter();
  1707. let sourcesIndex = 0;
  1708. let sourceLine = 0;
  1709. let sourceColumn = 0;
  1710. let namesIndex = 0;
  1711. for (let i = 0; i < decoded.length; i++) {
  1712. const line = decoded[i];
  1713. if (i > 0)
  1714. writer.write(semicolon);
  1715. if (line.length === 0)
  1716. continue;
  1717. let genColumn = 0;
  1718. for (let j = 0; j < line.length; j++) {
  1719. const segment = line[j];
  1720. if (j > 0)
  1721. writer.write(comma);
  1722. genColumn = encodeInteger(writer, segment[0], genColumn);
  1723. if (segment.length === 1)
  1724. continue;
  1725. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  1726. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  1727. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  1728. if (segment.length === 4)
  1729. continue;
  1730. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  1731. }
  1732. }
  1733. return writer.flush();
  1734. }
  1735. class BitSet {
  1736. constructor(arg) {
  1737. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  1738. }
  1739. add(n) {
  1740. this.bits[n >> 5] |= 1 << (n & 31);
  1741. }
  1742. has(n) {
  1743. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  1744. }
  1745. }
  1746. let Chunk$1 = class Chunk {
  1747. constructor(start, end, content) {
  1748. this.start = start;
  1749. this.end = end;
  1750. this.original = content;
  1751. this.intro = '';
  1752. this.outro = '';
  1753. this.content = content;
  1754. this.storeName = false;
  1755. this.edited = false;
  1756. {
  1757. this.previous = null;
  1758. this.next = null;
  1759. }
  1760. }
  1761. appendLeft(content) {
  1762. this.outro += content;
  1763. }
  1764. appendRight(content) {
  1765. this.intro = this.intro + content;
  1766. }
  1767. clone() {
  1768. const chunk = new Chunk(this.start, this.end, this.original);
  1769. chunk.intro = this.intro;
  1770. chunk.outro = this.outro;
  1771. chunk.content = this.content;
  1772. chunk.storeName = this.storeName;
  1773. chunk.edited = this.edited;
  1774. return chunk;
  1775. }
  1776. contains(index) {
  1777. return this.start < index && index < this.end;
  1778. }
  1779. eachNext(fn) {
  1780. let chunk = this;
  1781. while (chunk) {
  1782. fn(chunk);
  1783. chunk = chunk.next;
  1784. }
  1785. }
  1786. eachPrevious(fn) {
  1787. let chunk = this;
  1788. while (chunk) {
  1789. fn(chunk);
  1790. chunk = chunk.previous;
  1791. }
  1792. }
  1793. edit(content, storeName, contentOnly) {
  1794. this.content = content;
  1795. if (!contentOnly) {
  1796. this.intro = '';
  1797. this.outro = '';
  1798. }
  1799. this.storeName = storeName;
  1800. this.edited = true;
  1801. return this;
  1802. }
  1803. prependLeft(content) {
  1804. this.outro = content + this.outro;
  1805. }
  1806. prependRight(content) {
  1807. this.intro = content + this.intro;
  1808. }
  1809. reset() {
  1810. this.intro = '';
  1811. this.outro = '';
  1812. if (this.edited) {
  1813. this.content = this.original;
  1814. this.storeName = false;
  1815. this.edited = false;
  1816. }
  1817. }
  1818. split(index) {
  1819. const sliceIndex = index - this.start;
  1820. const originalBefore = this.original.slice(0, sliceIndex);
  1821. const originalAfter = this.original.slice(sliceIndex);
  1822. this.original = originalBefore;
  1823. const newChunk = new Chunk(index, this.end, originalAfter);
  1824. newChunk.outro = this.outro;
  1825. this.outro = '';
  1826. this.end = index;
  1827. if (this.edited) {
  1828. // after split we should save the edit content record into the correct chunk
  1829. // to make sure sourcemap correct
  1830. // For example:
  1831. // ' test'.trim()
  1832. // split -> ' ' + 'test'
  1833. // ✔️ edit -> '' + 'test'
  1834. // ✖️ edit -> 'test' + ''
  1835. // TODO is this block necessary?...
  1836. newChunk.edit('', false);
  1837. this.content = '';
  1838. } else {
  1839. this.content = originalBefore;
  1840. }
  1841. newChunk.next = this.next;
  1842. if (newChunk.next) newChunk.next.previous = newChunk;
  1843. newChunk.previous = this;
  1844. this.next = newChunk;
  1845. return newChunk;
  1846. }
  1847. toString() {
  1848. return this.intro + this.content + this.outro;
  1849. }
  1850. trimEnd(rx) {
  1851. this.outro = this.outro.replace(rx, '');
  1852. if (this.outro.length) return true;
  1853. const trimmed = this.content.replace(rx, '');
  1854. if (trimmed.length) {
  1855. if (trimmed !== this.content) {
  1856. this.split(this.start + trimmed.length).edit('', undefined, true);
  1857. if (this.edited) {
  1858. // save the change, if it has been edited
  1859. this.edit(trimmed, this.storeName, true);
  1860. }
  1861. }
  1862. return true;
  1863. } else {
  1864. this.edit('', undefined, true);
  1865. this.intro = this.intro.replace(rx, '');
  1866. if (this.intro.length) return true;
  1867. }
  1868. }
  1869. trimStart(rx) {
  1870. this.intro = this.intro.replace(rx, '');
  1871. if (this.intro.length) return true;
  1872. const trimmed = this.content.replace(rx, '');
  1873. if (trimmed.length) {
  1874. if (trimmed !== this.content) {
  1875. const newChunk = this.split(this.end - trimmed.length);
  1876. if (this.edited) {
  1877. // save the change, if it has been edited
  1878. newChunk.edit(trimmed, this.storeName, true);
  1879. }
  1880. this.edit('', undefined, true);
  1881. }
  1882. return true;
  1883. } else {
  1884. this.edit('', undefined, true);
  1885. this.outro = this.outro.replace(rx, '');
  1886. if (this.outro.length) return true;
  1887. }
  1888. }
  1889. };
  1890. function getBtoa() {
  1891. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  1892. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  1893. } else if (typeof Buffer === 'function') {
  1894. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  1895. } else {
  1896. return () => {
  1897. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  1898. };
  1899. }
  1900. }
  1901. const btoa = /*#__PURE__*/ getBtoa();
  1902. class SourceMap {
  1903. constructor(properties) {
  1904. this.version = 3;
  1905. this.file = properties.file;
  1906. this.sources = properties.sources;
  1907. this.sourcesContent = properties.sourcesContent;
  1908. this.names = properties.names;
  1909. this.mappings = encode(properties.mappings);
  1910. if (typeof properties.x_google_ignoreList !== 'undefined') {
  1911. this.x_google_ignoreList = properties.x_google_ignoreList;
  1912. }
  1913. }
  1914. toString() {
  1915. return JSON.stringify(this);
  1916. }
  1917. toUrl() {
  1918. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  1919. }
  1920. }
  1921. function guessIndent(code) {
  1922. const lines = code.split('\n');
  1923. const tabbed = lines.filter((line) => /^\t+/.test(line));
  1924. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  1925. if (tabbed.length === 0 && spaced.length === 0) {
  1926. return null;
  1927. }
  1928. // More lines tabbed than spaced? Assume tabs, and
  1929. // default to tabs in the case of a tie (or nothing
  1930. // to go on)
  1931. if (tabbed.length >= spaced.length) {
  1932. return '\t';
  1933. }
  1934. // Otherwise, we need to guess the multiple
  1935. const min = spaced.reduce((previous, current) => {
  1936. const numSpaces = /^ +/.exec(current)[0].length;
  1937. return Math.min(numSpaces, previous);
  1938. }, Infinity);
  1939. return new Array(min + 1).join(' ');
  1940. }
  1941. function getRelativePath(from, to) {
  1942. const fromParts = from.split(/[/\\]/);
  1943. const toParts = to.split(/[/\\]/);
  1944. fromParts.pop(); // get dirname
  1945. while (fromParts[0] === toParts[0]) {
  1946. fromParts.shift();
  1947. toParts.shift();
  1948. }
  1949. if (fromParts.length) {
  1950. let i = fromParts.length;
  1951. while (i--) fromParts[i] = '..';
  1952. }
  1953. return fromParts.concat(toParts).join('/');
  1954. }
  1955. const toString = Object.prototype.toString;
  1956. function isObject(thing) {
  1957. return toString.call(thing) === '[object Object]';
  1958. }
  1959. function getLocator(source) {
  1960. const originalLines = source.split('\n');
  1961. const lineOffsets = [];
  1962. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  1963. lineOffsets.push(pos);
  1964. pos += originalLines[i].length + 1;
  1965. }
  1966. return function locate(index) {
  1967. let i = 0;
  1968. let j = lineOffsets.length;
  1969. while (i < j) {
  1970. const m = (i + j) >> 1;
  1971. if (index < lineOffsets[m]) {
  1972. j = m;
  1973. } else {
  1974. i = m + 1;
  1975. }
  1976. }
  1977. const line = i - 1;
  1978. const column = index - lineOffsets[line];
  1979. return { line, column };
  1980. };
  1981. }
  1982. const wordRegex = /\w/;
  1983. class Mappings {
  1984. constructor(hires) {
  1985. this.hires = hires;
  1986. this.generatedCodeLine = 0;
  1987. this.generatedCodeColumn = 0;
  1988. this.raw = [];
  1989. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1990. this.pending = null;
  1991. }
  1992. addEdit(sourceIndex, content, loc, nameIndex) {
  1993. if (content.length) {
  1994. const contentLengthMinusOne = content.length - 1;
  1995. let contentLineEnd = content.indexOf('\n', 0);
  1996. let previousContentLineEnd = -1;
  1997. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  1998. // else code afterwards would fill one line too many
  1999. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  2000. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2001. if (nameIndex >= 0) {
  2002. segment.push(nameIndex);
  2003. }
  2004. this.rawSegments.push(segment);
  2005. this.generatedCodeLine += 1;
  2006. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2007. this.generatedCodeColumn = 0;
  2008. previousContentLineEnd = contentLineEnd;
  2009. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  2010. }
  2011. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2012. if (nameIndex >= 0) {
  2013. segment.push(nameIndex);
  2014. }
  2015. this.rawSegments.push(segment);
  2016. this.advance(content.slice(previousContentLineEnd + 1));
  2017. } else if (this.pending) {
  2018. this.rawSegments.push(this.pending);
  2019. this.advance(content);
  2020. }
  2021. this.pending = null;
  2022. }
  2023. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  2024. let originalCharIndex = chunk.start;
  2025. let first = true;
  2026. // when iterating each char, check if it's in a word boundary
  2027. let charInHiresBoundary = false;
  2028. while (originalCharIndex < chunk.end) {
  2029. if (original[originalCharIndex] === '\n') {
  2030. loc.line += 1;
  2031. loc.column = 0;
  2032. this.generatedCodeLine += 1;
  2033. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2034. this.generatedCodeColumn = 0;
  2035. first = true;
  2036. } else {
  2037. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  2038. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2039. if (this.hires === 'boundary') {
  2040. // in hires "boundary", group segments per word boundary than per char
  2041. if (wordRegex.test(original[originalCharIndex])) {
  2042. // for first char in the boundary found, start the boundary by pushing a segment
  2043. if (!charInHiresBoundary) {
  2044. this.rawSegments.push(segment);
  2045. charInHiresBoundary = true;
  2046. }
  2047. } else {
  2048. // for non-word char, end the boundary by pushing a segment
  2049. this.rawSegments.push(segment);
  2050. charInHiresBoundary = false;
  2051. }
  2052. } else {
  2053. this.rawSegments.push(segment);
  2054. }
  2055. }
  2056. loc.column += 1;
  2057. this.generatedCodeColumn += 1;
  2058. first = false;
  2059. }
  2060. originalCharIndex += 1;
  2061. }
  2062. this.pending = null;
  2063. }
  2064. advance(str) {
  2065. if (!str) return;
  2066. const lines = str.split('\n');
  2067. if (lines.length > 1) {
  2068. for (let i = 0; i < lines.length - 1; i++) {
  2069. this.generatedCodeLine++;
  2070. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2071. }
  2072. this.generatedCodeColumn = 0;
  2073. }
  2074. this.generatedCodeColumn += lines[lines.length - 1].length;
  2075. }
  2076. }
  2077. const n = '\n';
  2078. const warned = {
  2079. insertLeft: false,
  2080. insertRight: false,
  2081. storeName: false,
  2082. };
  2083. class MagicString {
  2084. constructor(string, options = {}) {
  2085. const chunk = new Chunk$1(0, string.length, string);
  2086. Object.defineProperties(this, {
  2087. original: { writable: true, value: string },
  2088. outro: { writable: true, value: '' },
  2089. intro: { writable: true, value: '' },
  2090. firstChunk: { writable: true, value: chunk },
  2091. lastChunk: { writable: true, value: chunk },
  2092. lastSearchedChunk: { writable: true, value: chunk },
  2093. byStart: { writable: true, value: {} },
  2094. byEnd: { writable: true, value: {} },
  2095. filename: { writable: true, value: options.filename },
  2096. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  2097. sourcemapLocations: { writable: true, value: new BitSet() },
  2098. storedNames: { writable: true, value: {} },
  2099. indentStr: { writable: true, value: undefined },
  2100. ignoreList: { writable: true, value: options.ignoreList },
  2101. });
  2102. this.byStart[0] = chunk;
  2103. this.byEnd[string.length] = chunk;
  2104. }
  2105. addSourcemapLocation(char) {
  2106. this.sourcemapLocations.add(char);
  2107. }
  2108. append(content) {
  2109. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2110. this.outro += content;
  2111. return this;
  2112. }
  2113. appendLeft(index, content) {
  2114. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2115. this._split(index);
  2116. const chunk = this.byEnd[index];
  2117. if (chunk) {
  2118. chunk.appendLeft(content);
  2119. } else {
  2120. this.intro += content;
  2121. }
  2122. return this;
  2123. }
  2124. appendRight(index, content) {
  2125. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2126. this._split(index);
  2127. const chunk = this.byStart[index];
  2128. if (chunk) {
  2129. chunk.appendRight(content);
  2130. } else {
  2131. this.outro += content;
  2132. }
  2133. return this;
  2134. }
  2135. clone() {
  2136. const cloned = new MagicString(this.original, { filename: this.filename });
  2137. let originalChunk = this.firstChunk;
  2138. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  2139. while (originalChunk) {
  2140. cloned.byStart[clonedChunk.start] = clonedChunk;
  2141. cloned.byEnd[clonedChunk.end] = clonedChunk;
  2142. const nextOriginalChunk = originalChunk.next;
  2143. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  2144. if (nextClonedChunk) {
  2145. clonedChunk.next = nextClonedChunk;
  2146. nextClonedChunk.previous = clonedChunk;
  2147. clonedChunk = nextClonedChunk;
  2148. }
  2149. originalChunk = nextOriginalChunk;
  2150. }
  2151. cloned.lastChunk = clonedChunk;
  2152. if (this.indentExclusionRanges) {
  2153. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  2154. }
  2155. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  2156. cloned.intro = this.intro;
  2157. cloned.outro = this.outro;
  2158. return cloned;
  2159. }
  2160. generateDecodedMap(options) {
  2161. options = options || {};
  2162. const sourceIndex = 0;
  2163. const names = Object.keys(this.storedNames);
  2164. const mappings = new Mappings(options.hires);
  2165. const locate = getLocator(this.original);
  2166. if (this.intro) {
  2167. mappings.advance(this.intro);
  2168. }
  2169. this.firstChunk.eachNext((chunk) => {
  2170. const loc = locate(chunk.start);
  2171. if (chunk.intro.length) mappings.advance(chunk.intro);
  2172. if (chunk.edited) {
  2173. mappings.addEdit(
  2174. sourceIndex,
  2175. chunk.content,
  2176. loc,
  2177. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2178. );
  2179. } else {
  2180. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  2181. }
  2182. if (chunk.outro.length) mappings.advance(chunk.outro);
  2183. });
  2184. return {
  2185. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2186. sources: [
  2187. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  2188. ],
  2189. sourcesContent: options.includeContent ? [this.original] : undefined,
  2190. names,
  2191. mappings: mappings.raw,
  2192. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  2193. };
  2194. }
  2195. generateMap(options) {
  2196. return new SourceMap(this.generateDecodedMap(options));
  2197. }
  2198. _ensureindentStr() {
  2199. if (this.indentStr === undefined) {
  2200. this.indentStr = guessIndent(this.original);
  2201. }
  2202. }
  2203. _getRawIndentString() {
  2204. this._ensureindentStr();
  2205. return this.indentStr;
  2206. }
  2207. getIndentString() {
  2208. this._ensureindentStr();
  2209. return this.indentStr === null ? '\t' : this.indentStr;
  2210. }
  2211. indent(indentStr, options) {
  2212. const pattern = /^[^\r\n]/gm;
  2213. if (isObject(indentStr)) {
  2214. options = indentStr;
  2215. indentStr = undefined;
  2216. }
  2217. if (indentStr === undefined) {
  2218. this._ensureindentStr();
  2219. indentStr = this.indentStr || '\t';
  2220. }
  2221. if (indentStr === '') return this; // noop
  2222. options = options || {};
  2223. // Process exclusion ranges
  2224. const isExcluded = {};
  2225. if (options.exclude) {
  2226. const exclusions =
  2227. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  2228. exclusions.forEach((exclusion) => {
  2229. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  2230. isExcluded[i] = true;
  2231. }
  2232. });
  2233. }
  2234. let shouldIndentNextCharacter = options.indentStart !== false;
  2235. const replacer = (match) => {
  2236. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  2237. shouldIndentNextCharacter = true;
  2238. return match;
  2239. };
  2240. this.intro = this.intro.replace(pattern, replacer);
  2241. let charIndex = 0;
  2242. let chunk = this.firstChunk;
  2243. while (chunk) {
  2244. const end = chunk.end;
  2245. if (chunk.edited) {
  2246. if (!isExcluded[charIndex]) {
  2247. chunk.content = chunk.content.replace(pattern, replacer);
  2248. if (chunk.content.length) {
  2249. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  2250. }
  2251. }
  2252. } else {
  2253. charIndex = chunk.start;
  2254. while (charIndex < end) {
  2255. if (!isExcluded[charIndex]) {
  2256. const char = this.original[charIndex];
  2257. if (char === '\n') {
  2258. shouldIndentNextCharacter = true;
  2259. } else if (char !== '\r' && shouldIndentNextCharacter) {
  2260. shouldIndentNextCharacter = false;
  2261. if (charIndex === chunk.start) {
  2262. chunk.prependRight(indentStr);
  2263. } else {
  2264. this._splitChunk(chunk, charIndex);
  2265. chunk = chunk.next;
  2266. chunk.prependRight(indentStr);
  2267. }
  2268. }
  2269. }
  2270. charIndex += 1;
  2271. }
  2272. }
  2273. charIndex = chunk.end;
  2274. chunk = chunk.next;
  2275. }
  2276. this.outro = this.outro.replace(pattern, replacer);
  2277. return this;
  2278. }
  2279. insert() {
  2280. throw new Error(
  2281. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  2282. );
  2283. }
  2284. insertLeft(index, content) {
  2285. if (!warned.insertLeft) {
  2286. console.warn(
  2287. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  2288. ); // eslint-disable-line no-console
  2289. warned.insertLeft = true;
  2290. }
  2291. return this.appendLeft(index, content);
  2292. }
  2293. insertRight(index, content) {
  2294. if (!warned.insertRight) {
  2295. console.warn(
  2296. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  2297. ); // eslint-disable-line no-console
  2298. warned.insertRight = true;
  2299. }
  2300. return this.prependRight(index, content);
  2301. }
  2302. move(start, end, index) {
  2303. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  2304. this._split(start);
  2305. this._split(end);
  2306. this._split(index);
  2307. const first = this.byStart[start];
  2308. const last = this.byEnd[end];
  2309. const oldLeft = first.previous;
  2310. const oldRight = last.next;
  2311. const newRight = this.byStart[index];
  2312. if (!newRight && last === this.lastChunk) return this;
  2313. const newLeft = newRight ? newRight.previous : this.lastChunk;
  2314. if (oldLeft) oldLeft.next = oldRight;
  2315. if (oldRight) oldRight.previous = oldLeft;
  2316. if (newLeft) newLeft.next = first;
  2317. if (newRight) newRight.previous = last;
  2318. if (!first.previous) this.firstChunk = last.next;
  2319. if (!last.next) {
  2320. this.lastChunk = first.previous;
  2321. this.lastChunk.next = null;
  2322. }
  2323. first.previous = newLeft;
  2324. last.next = newRight || null;
  2325. if (!newLeft) this.firstChunk = first;
  2326. if (!newRight) this.lastChunk = last;
  2327. return this;
  2328. }
  2329. overwrite(start, end, content, options) {
  2330. options = options || {};
  2331. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  2332. }
  2333. update(start, end, content, options) {
  2334. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  2335. if (this.original.length !== 0) {
  2336. while (start < 0) start += this.original.length;
  2337. while (end < 0) end += this.original.length;
  2338. }
  2339. if (end > this.original.length) throw new Error('end is out of bounds');
  2340. if (start === end)
  2341. throw new Error(
  2342. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  2343. );
  2344. this._split(start);
  2345. this._split(end);
  2346. if (options === true) {
  2347. if (!warned.storeName) {
  2348. console.warn(
  2349. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  2350. ); // eslint-disable-line no-console
  2351. warned.storeName = true;
  2352. }
  2353. options = { storeName: true };
  2354. }
  2355. const storeName = options !== undefined ? options.storeName : false;
  2356. const overwrite = options !== undefined ? options.overwrite : false;
  2357. if (storeName) {
  2358. const original = this.original.slice(start, end);
  2359. Object.defineProperty(this.storedNames, original, {
  2360. writable: true,
  2361. value: true,
  2362. enumerable: true,
  2363. });
  2364. }
  2365. const first = this.byStart[start];
  2366. const last = this.byEnd[end];
  2367. if (first) {
  2368. let chunk = first;
  2369. while (chunk !== last) {
  2370. if (chunk.next !== this.byStart[chunk.end]) {
  2371. throw new Error('Cannot overwrite across a split point');
  2372. }
  2373. chunk = chunk.next;
  2374. chunk.edit('', false);
  2375. }
  2376. first.edit(content, storeName, !overwrite);
  2377. } else {
  2378. // must be inserting at the end
  2379. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  2380. // TODO last chunk in the array may not be the last chunk, if it's moved...
  2381. last.next = newChunk;
  2382. newChunk.previous = last;
  2383. }
  2384. return this;
  2385. }
  2386. prepend(content) {
  2387. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2388. this.intro = content + this.intro;
  2389. return this;
  2390. }
  2391. prependLeft(index, content) {
  2392. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2393. this._split(index);
  2394. const chunk = this.byEnd[index];
  2395. if (chunk) {
  2396. chunk.prependLeft(content);
  2397. } else {
  2398. this.intro = content + this.intro;
  2399. }
  2400. return this;
  2401. }
  2402. prependRight(index, content) {
  2403. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2404. this._split(index);
  2405. const chunk = this.byStart[index];
  2406. if (chunk) {
  2407. chunk.prependRight(content);
  2408. } else {
  2409. this.outro = content + this.outro;
  2410. }
  2411. return this;
  2412. }
  2413. remove(start, end) {
  2414. if (this.original.length !== 0) {
  2415. while (start < 0) start += this.original.length;
  2416. while (end < 0) end += this.original.length;
  2417. }
  2418. if (start === end) return this;
  2419. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2420. if (start > end) throw new Error('end must be greater than start');
  2421. this._split(start);
  2422. this._split(end);
  2423. let chunk = this.byStart[start];
  2424. while (chunk) {
  2425. chunk.intro = '';
  2426. chunk.outro = '';
  2427. chunk.edit('');
  2428. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2429. }
  2430. return this;
  2431. }
  2432. reset(start, end) {
  2433. if (this.original.length !== 0) {
  2434. while (start < 0) start += this.original.length;
  2435. while (end < 0) end += this.original.length;
  2436. }
  2437. if (start === end) return this;
  2438. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  2439. if (start > end) throw new Error('end must be greater than start');
  2440. this._split(start);
  2441. this._split(end);
  2442. let chunk = this.byStart[start];
  2443. while (chunk) {
  2444. chunk.reset();
  2445. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  2446. }
  2447. return this;
  2448. }
  2449. lastChar() {
  2450. if (this.outro.length) return this.outro[this.outro.length - 1];
  2451. let chunk = this.lastChunk;
  2452. do {
  2453. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  2454. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  2455. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  2456. } while ((chunk = chunk.previous));
  2457. if (this.intro.length) return this.intro[this.intro.length - 1];
  2458. return '';
  2459. }
  2460. lastLine() {
  2461. let lineIndex = this.outro.lastIndexOf(n);
  2462. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  2463. let lineStr = this.outro;
  2464. let chunk = this.lastChunk;
  2465. do {
  2466. if (chunk.outro.length > 0) {
  2467. lineIndex = chunk.outro.lastIndexOf(n);
  2468. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  2469. lineStr = chunk.outro + lineStr;
  2470. }
  2471. if (chunk.content.length > 0) {
  2472. lineIndex = chunk.content.lastIndexOf(n);
  2473. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  2474. lineStr = chunk.content + lineStr;
  2475. }
  2476. if (chunk.intro.length > 0) {
  2477. lineIndex = chunk.intro.lastIndexOf(n);
  2478. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  2479. lineStr = chunk.intro + lineStr;
  2480. }
  2481. } while ((chunk = chunk.previous));
  2482. lineIndex = this.intro.lastIndexOf(n);
  2483. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  2484. return this.intro + lineStr;
  2485. }
  2486. slice(start = 0, end = this.original.length) {
  2487. if (this.original.length !== 0) {
  2488. while (start < 0) start += this.original.length;
  2489. while (end < 0) end += this.original.length;
  2490. }
  2491. let result = '';
  2492. // find start chunk
  2493. let chunk = this.firstChunk;
  2494. while (chunk && (chunk.start > start || chunk.end <= start)) {
  2495. // found end chunk before start
  2496. if (chunk.start < end && chunk.end >= end) {
  2497. return result;
  2498. }
  2499. chunk = chunk.next;
  2500. }
  2501. if (chunk && chunk.edited && chunk.start !== start)
  2502. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  2503. const startChunk = chunk;
  2504. while (chunk) {
  2505. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  2506. result += chunk.intro;
  2507. }
  2508. const containsEnd = chunk.start < end && chunk.end >= end;
  2509. if (containsEnd && chunk.edited && chunk.end !== end)
  2510. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  2511. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  2512. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  2513. result += chunk.content.slice(sliceStart, sliceEnd);
  2514. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  2515. result += chunk.outro;
  2516. }
  2517. if (containsEnd) {
  2518. break;
  2519. }
  2520. chunk = chunk.next;
  2521. }
  2522. return result;
  2523. }
  2524. // TODO deprecate this? not really very useful
  2525. snip(start, end) {
  2526. const clone = this.clone();
  2527. clone.remove(0, start);
  2528. clone.remove(end, clone.original.length);
  2529. return clone;
  2530. }
  2531. _split(index) {
  2532. if (this.byStart[index] || this.byEnd[index]) return;
  2533. let chunk = this.lastSearchedChunk;
  2534. const searchForward = index > chunk.end;
  2535. while (chunk) {
  2536. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  2537. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  2538. }
  2539. }
  2540. _splitChunk(chunk, index) {
  2541. if (chunk.edited && chunk.content.length) {
  2542. // zero-length edited chunks are a special case (overlapping replacements)
  2543. const loc = getLocator(this.original)(index);
  2544. throw new Error(
  2545. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  2546. );
  2547. }
  2548. const newChunk = chunk.split(index);
  2549. this.byEnd[index] = chunk;
  2550. this.byStart[index] = newChunk;
  2551. this.byEnd[newChunk.end] = newChunk;
  2552. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  2553. this.lastSearchedChunk = chunk;
  2554. return true;
  2555. }
  2556. toString() {
  2557. let str = this.intro;
  2558. let chunk = this.firstChunk;
  2559. while (chunk) {
  2560. str += chunk.toString();
  2561. chunk = chunk.next;
  2562. }
  2563. return str + this.outro;
  2564. }
  2565. isEmpty() {
  2566. let chunk = this.firstChunk;
  2567. do {
  2568. if (
  2569. (chunk.intro.length && chunk.intro.trim()) ||
  2570. (chunk.content.length && chunk.content.trim()) ||
  2571. (chunk.outro.length && chunk.outro.trim())
  2572. )
  2573. return false;
  2574. } while ((chunk = chunk.next));
  2575. return true;
  2576. }
  2577. length() {
  2578. let chunk = this.firstChunk;
  2579. let length = 0;
  2580. do {
  2581. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  2582. } while ((chunk = chunk.next));
  2583. return length;
  2584. }
  2585. trimLines() {
  2586. return this.trim('[\\r\\n]');
  2587. }
  2588. trim(charType) {
  2589. return this.trimStart(charType).trimEnd(charType);
  2590. }
  2591. trimEndAborted(charType) {
  2592. const rx = new RegExp((charType || '\\s') + '+$');
  2593. this.outro = this.outro.replace(rx, '');
  2594. if (this.outro.length) return true;
  2595. let chunk = this.lastChunk;
  2596. do {
  2597. const end = chunk.end;
  2598. const aborted = chunk.trimEnd(rx);
  2599. // if chunk was trimmed, we have a new lastChunk
  2600. if (chunk.end !== end) {
  2601. if (this.lastChunk === chunk) {
  2602. this.lastChunk = chunk.next;
  2603. }
  2604. this.byEnd[chunk.end] = chunk;
  2605. this.byStart[chunk.next.start] = chunk.next;
  2606. this.byEnd[chunk.next.end] = chunk.next;
  2607. }
  2608. if (aborted) return true;
  2609. chunk = chunk.previous;
  2610. } while (chunk);
  2611. return false;
  2612. }
  2613. trimEnd(charType) {
  2614. this.trimEndAborted(charType);
  2615. return this;
  2616. }
  2617. trimStartAborted(charType) {
  2618. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2619. this.intro = this.intro.replace(rx, '');
  2620. if (this.intro.length) return true;
  2621. let chunk = this.firstChunk;
  2622. do {
  2623. const end = chunk.end;
  2624. const aborted = chunk.trimStart(rx);
  2625. if (chunk.end !== end) {
  2626. // special case...
  2627. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  2628. this.byEnd[chunk.end] = chunk;
  2629. this.byStart[chunk.next.start] = chunk.next;
  2630. this.byEnd[chunk.next.end] = chunk.next;
  2631. }
  2632. if (aborted) return true;
  2633. chunk = chunk.next;
  2634. } while (chunk);
  2635. return false;
  2636. }
  2637. trimStart(charType) {
  2638. this.trimStartAborted(charType);
  2639. return this;
  2640. }
  2641. hasChanged() {
  2642. return this.original !== this.toString();
  2643. }
  2644. _replaceRegexp(searchValue, replacement) {
  2645. function getReplacement(match, str) {
  2646. if (typeof replacement === 'string') {
  2647. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  2648. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  2649. if (i === '$') return '$';
  2650. if (i === '&') return match[0];
  2651. const num = +i;
  2652. if (num < match.length) return match[+i];
  2653. return `$${i}`;
  2654. });
  2655. } else {
  2656. return replacement(...match, match.index, str, match.groups);
  2657. }
  2658. }
  2659. function matchAll(re, str) {
  2660. let match;
  2661. const matches = [];
  2662. while ((match = re.exec(str))) {
  2663. matches.push(match);
  2664. }
  2665. return matches;
  2666. }
  2667. if (searchValue.global) {
  2668. const matches = matchAll(searchValue, this.original);
  2669. matches.forEach((match) => {
  2670. if (match.index != null) {
  2671. const replacement = getReplacement(match, this.original);
  2672. if (replacement !== match[0]) {
  2673. this.overwrite(
  2674. match.index,
  2675. match.index + match[0].length,
  2676. replacement
  2677. );
  2678. }
  2679. }
  2680. });
  2681. } else {
  2682. const match = this.original.match(searchValue);
  2683. if (match && match.index != null) {
  2684. const replacement = getReplacement(match, this.original);
  2685. if (replacement !== match[0]) {
  2686. this.overwrite(
  2687. match.index,
  2688. match.index + match[0].length,
  2689. replacement
  2690. );
  2691. }
  2692. }
  2693. }
  2694. return this;
  2695. }
  2696. _replaceString(string, replacement) {
  2697. const { original } = this;
  2698. const index = original.indexOf(string);
  2699. if (index !== -1) {
  2700. this.overwrite(index, index + string.length, replacement);
  2701. }
  2702. return this;
  2703. }
  2704. replace(searchValue, replacement) {
  2705. if (typeof searchValue === 'string') {
  2706. return this._replaceString(searchValue, replacement);
  2707. }
  2708. return this._replaceRegexp(searchValue, replacement);
  2709. }
  2710. _replaceAllString(string, replacement) {
  2711. const { original } = this;
  2712. const stringLength = string.length;
  2713. for (
  2714. let index = original.indexOf(string);
  2715. index !== -1;
  2716. index = original.indexOf(string, index + stringLength)
  2717. ) {
  2718. const previous = original.slice(index, index + stringLength);
  2719. if (previous !== replacement)
  2720. this.overwrite(index, index + stringLength, replacement);
  2721. }
  2722. return this;
  2723. }
  2724. replaceAll(searchValue, replacement) {
  2725. if (typeof searchValue === 'string') {
  2726. return this._replaceAllString(searchValue, replacement);
  2727. }
  2728. if (!searchValue.global) {
  2729. throw new TypeError(
  2730. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  2731. );
  2732. }
  2733. return this._replaceRegexp(searchValue, replacement);
  2734. }
  2735. }
  2736. const hasOwnProp = Object.prototype.hasOwnProperty;
  2737. let Bundle$1 = class Bundle {
  2738. constructor(options = {}) {
  2739. this.intro = options.intro || '';
  2740. this.separator = options.separator !== undefined ? options.separator : '\n';
  2741. this.sources = [];
  2742. this.uniqueSources = [];
  2743. this.uniqueSourceIndexByFilename = {};
  2744. }
  2745. addSource(source) {
  2746. if (source instanceof MagicString) {
  2747. return this.addSource({
  2748. content: source,
  2749. filename: source.filename,
  2750. separator: this.separator,
  2751. });
  2752. }
  2753. if (!isObject(source) || !source.content) {
  2754. throw new Error(
  2755. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  2756. );
  2757. }
  2758. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  2759. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  2760. });
  2761. if (source.separator === undefined) {
  2762. // TODO there's a bunch of this sort of thing, needs cleaning up
  2763. source.separator = this.separator;
  2764. }
  2765. if (source.filename) {
  2766. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  2767. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  2768. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  2769. } else {
  2770. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  2771. if (source.content.original !== uniqueSource.content) {
  2772. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  2773. }
  2774. }
  2775. }
  2776. this.sources.push(source);
  2777. return this;
  2778. }
  2779. append(str, options) {
  2780. this.addSource({
  2781. content: new MagicString(str),
  2782. separator: (options && options.separator) || '',
  2783. });
  2784. return this;
  2785. }
  2786. clone() {
  2787. const bundle = new Bundle({
  2788. intro: this.intro,
  2789. separator: this.separator,
  2790. });
  2791. this.sources.forEach((source) => {
  2792. bundle.addSource({
  2793. filename: source.filename,
  2794. content: source.content.clone(),
  2795. separator: source.separator,
  2796. });
  2797. });
  2798. return bundle;
  2799. }
  2800. generateDecodedMap(options = {}) {
  2801. const names = [];
  2802. let x_google_ignoreList = undefined;
  2803. this.sources.forEach((source) => {
  2804. Object.keys(source.content.storedNames).forEach((name) => {
  2805. if (!~names.indexOf(name)) names.push(name);
  2806. });
  2807. });
  2808. const mappings = new Mappings(options.hires);
  2809. if (this.intro) {
  2810. mappings.advance(this.intro);
  2811. }
  2812. this.sources.forEach((source, i) => {
  2813. if (i > 0) {
  2814. mappings.advance(this.separator);
  2815. }
  2816. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  2817. const magicString = source.content;
  2818. const locate = getLocator(magicString.original);
  2819. if (magicString.intro) {
  2820. mappings.advance(magicString.intro);
  2821. }
  2822. magicString.firstChunk.eachNext((chunk) => {
  2823. const loc = locate(chunk.start);
  2824. if (chunk.intro.length) mappings.advance(chunk.intro);
  2825. if (source.filename) {
  2826. if (chunk.edited) {
  2827. mappings.addEdit(
  2828. sourceIndex,
  2829. chunk.content,
  2830. loc,
  2831. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2832. );
  2833. } else {
  2834. mappings.addUneditedChunk(
  2835. sourceIndex,
  2836. chunk,
  2837. magicString.original,
  2838. loc,
  2839. magicString.sourcemapLocations,
  2840. );
  2841. }
  2842. } else {
  2843. mappings.advance(chunk.content);
  2844. }
  2845. if (chunk.outro.length) mappings.advance(chunk.outro);
  2846. });
  2847. if (magicString.outro) {
  2848. mappings.advance(magicString.outro);
  2849. }
  2850. if (source.ignoreList && sourceIndex !== -1) {
  2851. if (x_google_ignoreList === undefined) {
  2852. x_google_ignoreList = [];
  2853. }
  2854. x_google_ignoreList.push(sourceIndex);
  2855. }
  2856. });
  2857. return {
  2858. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2859. sources: this.uniqueSources.map((source) => {
  2860. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  2861. }),
  2862. sourcesContent: this.uniqueSources.map((source) => {
  2863. return options.includeContent ? source.content : null;
  2864. }),
  2865. names,
  2866. mappings: mappings.raw,
  2867. x_google_ignoreList,
  2868. };
  2869. }
  2870. generateMap(options) {
  2871. return new SourceMap(this.generateDecodedMap(options));
  2872. }
  2873. getIndentString() {
  2874. const indentStringCounts = {};
  2875. this.sources.forEach((source) => {
  2876. const indentStr = source.content._getRawIndentString();
  2877. if (indentStr === null) return;
  2878. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  2879. indentStringCounts[indentStr] += 1;
  2880. });
  2881. return (
  2882. Object.keys(indentStringCounts).sort((a, b) => {
  2883. return indentStringCounts[a] - indentStringCounts[b];
  2884. })[0] || '\t'
  2885. );
  2886. }
  2887. indent(indentStr) {
  2888. if (!arguments.length) {
  2889. indentStr = this.getIndentString();
  2890. }
  2891. if (indentStr === '') return this; // noop
  2892. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  2893. this.sources.forEach((source, i) => {
  2894. const separator = source.separator !== undefined ? source.separator : this.separator;
  2895. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  2896. source.content.indent(indentStr, {
  2897. exclude: source.indentExclusionRanges,
  2898. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  2899. });
  2900. trailingNewline = source.content.lastChar() === '\n';
  2901. });
  2902. if (this.intro) {
  2903. this.intro =
  2904. indentStr +
  2905. this.intro.replace(/^[^\n]/gm, (match, index) => {
  2906. return index > 0 ? indentStr + match : match;
  2907. });
  2908. }
  2909. return this;
  2910. }
  2911. prepend(str) {
  2912. this.intro = str + this.intro;
  2913. return this;
  2914. }
  2915. toString() {
  2916. const body = this.sources
  2917. .map((source, i) => {
  2918. const separator = source.separator !== undefined ? source.separator : this.separator;
  2919. const str = (i > 0 ? separator : '') + source.content.toString();
  2920. return str;
  2921. })
  2922. .join('');
  2923. return this.intro + body;
  2924. }
  2925. isEmpty() {
  2926. if (this.intro.length && this.intro.trim()) return false;
  2927. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  2928. return true;
  2929. }
  2930. length() {
  2931. return this.sources.reduce(
  2932. (length, source) => length + source.content.length(),
  2933. this.intro.length,
  2934. );
  2935. }
  2936. trimLines() {
  2937. return this.trim('[\\r\\n]');
  2938. }
  2939. trim(charType) {
  2940. return this.trimStart(charType).trimEnd(charType);
  2941. }
  2942. trimStart(charType) {
  2943. const rx = new RegExp('^' + (charType || '\\s') + '+');
  2944. this.intro = this.intro.replace(rx, '');
  2945. if (!this.intro) {
  2946. let source;
  2947. let i = 0;
  2948. do {
  2949. source = this.sources[i++];
  2950. if (!source) {
  2951. break;
  2952. }
  2953. } while (!source.content.trimStartAborted(charType));
  2954. }
  2955. return this;
  2956. }
  2957. trimEnd(charType) {
  2958. const rx = new RegExp((charType || '\\s') + '+$');
  2959. let source;
  2960. let i = this.sources.length - 1;
  2961. do {
  2962. source = this.sources[i--];
  2963. if (!source) {
  2964. this.intro = this.intro.replace(rx, '');
  2965. break;
  2966. }
  2967. } while (!source.content.trimEndAborted(charType));
  2968. return this;
  2969. }
  2970. };
  2971. function treeshakeNode(node, code, start, end) {
  2972. code.remove(start, end);
  2973. node.removeAnnotations(code);
  2974. }
  2975. const NO_SEMICOLON = { isNoStatement: true };
  2976. // This assumes there are only white-space and comments between start and the string we are looking for
  2977. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  2978. let searchPos, charCodeAfterSlash;
  2979. searchPos = code.indexOf(searchString, start);
  2980. while (true) {
  2981. start = code.indexOf('/', start);
  2982. if (start === -1 || start >= searchPos)
  2983. return searchPos;
  2984. charCodeAfterSlash = code.charCodeAt(++start);
  2985. ++start;
  2986. // With our assumption, '/' always starts a comment. Determine comment type:
  2987. start =
  2988. charCodeAfterSlash === 47 /*"/"*/
  2989. ? code.indexOf('\n', start) + 1
  2990. : code.indexOf('*/', start) + 2;
  2991. if (start > searchPos) {
  2992. searchPos = code.indexOf(searchString, start);
  2993. }
  2994. }
  2995. }
  2996. const NON_WHITESPACE = /\S/g;
  2997. function findNonWhiteSpace(code, index) {
  2998. NON_WHITESPACE.lastIndex = index;
  2999. const result = NON_WHITESPACE.exec(code);
  3000. return result.index;
  3001. }
  3002. const WHITESPACE = /\s/;
  3003. function findLastWhiteSpaceReverse(code, start, end) {
  3004. while (true) {
  3005. if (start >= end) {
  3006. return end;
  3007. }
  3008. if (WHITESPACE.test(code[end - 1])) {
  3009. end--;
  3010. }
  3011. else {
  3012. return end;
  3013. }
  3014. }
  3015. }
  3016. // This assumes "code" only contains white-space and comments
  3017. // Returns position of line-comment if applicable
  3018. function findFirstLineBreakOutsideComment(code) {
  3019. let lineBreakPos, charCodeAfterSlash, start = 0;
  3020. lineBreakPos = code.indexOf('\n', start);
  3021. while (true) {
  3022. start = code.indexOf('/', start);
  3023. if (start === -1 || start > lineBreakPos)
  3024. return [lineBreakPos, lineBreakPos + 1];
  3025. // With our assumption, '/' always starts a comment. Determine comment type:
  3026. charCodeAfterSlash = code.charCodeAt(start + 1);
  3027. if (charCodeAfterSlash === 47 /*"/"*/)
  3028. return [start, lineBreakPos + 1];
  3029. start = code.indexOf('*/', start + 2) + 2;
  3030. if (start > lineBreakPos) {
  3031. lineBreakPos = code.indexOf('\n', start);
  3032. }
  3033. }
  3034. }
  3035. function renderStatementList(statements, code, start, end, options) {
  3036. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  3037. let nextNode = statements[0];
  3038. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  3039. if (nextNodeNeedsBoundaries) {
  3040. nextNodeStart =
  3041. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  3042. }
  3043. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  3044. currentNode = nextNode;
  3045. currentNodeStart = nextNodeStart;
  3046. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  3047. nextNode = statements[nextIndex];
  3048. nextNodeNeedsBoundaries =
  3049. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  3050. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  3051. nextNodeStart =
  3052. currentNode.end +
  3053. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  3054. if (currentNode.included) {
  3055. if (currentNodeNeedsBoundaries) {
  3056. currentNode.render(code, options, {
  3057. end: nextNodeStart,
  3058. start: currentNodeStart
  3059. });
  3060. }
  3061. else {
  3062. currentNode.render(code, options);
  3063. }
  3064. }
  3065. else {
  3066. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  3067. }
  3068. }
  3069. else {
  3070. currentNode.render(code, options);
  3071. }
  3072. }
  3073. }
  3074. // This assumes that the first character is not part of the first node
  3075. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  3076. const splitUpNodes = [];
  3077. let node, nextNodeStart, contentEnd, char;
  3078. let separator = start - 1;
  3079. for (const nextNode of nodes) {
  3080. if (node !== undefined) {
  3081. separator =
  3082. node.end +
  3083. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  3084. }
  3085. nextNodeStart = contentEnd =
  3086. separator +
  3087. 1 +
  3088. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  3089. while (((char = code.original.charCodeAt(nextNodeStart)),
  3090. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  3091. nextNodeStart++;
  3092. if (node !== undefined) {
  3093. splitUpNodes.push({
  3094. contentEnd,
  3095. end: nextNodeStart,
  3096. node,
  3097. separator,
  3098. start
  3099. });
  3100. }
  3101. node = nextNode;
  3102. start = nextNodeStart;
  3103. }
  3104. splitUpNodes.push({
  3105. contentEnd: end,
  3106. end,
  3107. node: node,
  3108. separator: null,
  3109. start
  3110. });
  3111. return splitUpNodes;
  3112. }
  3113. // This assumes there are only white-space and comments between start and end
  3114. function removeLineBreaks(code, start, end) {
  3115. while (true) {
  3116. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  3117. if (removeStart === -1) {
  3118. break;
  3119. }
  3120. code.remove(start + removeStart, (start += removeEnd));
  3121. }
  3122. }
  3123. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  3124. if (exportedVariables.length === 1 &&
  3125. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  3126. const variable = exportedVariables[0];
  3127. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  3128. }
  3129. else {
  3130. const fields = [];
  3131. for (const variable of exportedVariables) {
  3132. for (const exportName of exportNamesByVariable.get(variable)) {
  3133. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  3134. }
  3135. }
  3136. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  3137. }
  3138. }
  3139. // This is only invoked if there is exactly one export name
  3140. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  3141. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  3142. code.appendLeft(expressionEnd, ')');
  3143. }
  3144. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  3145. const { _, getDirectReturnIifeLeft } = options.snippets;
  3146. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  3147. code.appendLeft(expressionEnd, ')');
  3148. }
  3149. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  3150. const { _, getPropertyAccess } = options.snippets;
  3151. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  3152. if (needsParens) {
  3153. code.prependRight(expressionStart, '(');
  3154. code.appendLeft(expressionEnd, ')');
  3155. }
  3156. }
  3157. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  3158. const { _ } = options.snippets;
  3159. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  3160. if (needsParens) {
  3161. code.prependRight(expressionStart, '(');
  3162. code.appendLeft(expressionEnd, ')');
  3163. }
  3164. }
  3165. /** @typedef { import('estree').Node} Node */
  3166. /** @typedef {Node | {
  3167. * type: 'PropertyDefinition';
  3168. * computed: boolean;
  3169. * value: Node
  3170. * }} NodeWithPropertyDefinition */
  3171. /**
  3172. *
  3173. * @param {NodeWithPropertyDefinition} node
  3174. * @param {NodeWithPropertyDefinition} parent
  3175. * @returns {boolean}
  3176. */
  3177. function is_reference (node, parent) {
  3178. if (node.type === 'MemberExpression') {
  3179. return !node.computed && is_reference(node.object, node);
  3180. }
  3181. if (node.type === 'Identifier') {
  3182. if (!parent) return true;
  3183. switch (parent.type) {
  3184. // disregard `bar` in `foo.bar`
  3185. case 'MemberExpression': return parent.computed || node === parent.object;
  3186. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  3187. case 'MethodDefinition': return parent.computed;
  3188. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  3189. case 'PropertyDefinition': return parent.computed || node === parent.value;
  3190. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  3191. case 'Property': return parent.computed || node === parent.value;
  3192. // disregard the `bar` in `export { foo as bar }` or
  3193. // the foo in `import { foo as bar }`
  3194. case 'ExportSpecifier':
  3195. case 'ImportSpecifier': return node === parent.local;
  3196. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  3197. case 'LabeledStatement':
  3198. case 'BreakStatement':
  3199. case 'ContinueStatement': return false;
  3200. default: return true;
  3201. }
  3202. }
  3203. return false;
  3204. }
  3205. const PureFunctionKey = Symbol('PureFunction');
  3206. const getPureFunctions = ({ treeshake }) => {
  3207. const pureFunctions = Object.create(null);
  3208. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  3209. let currentFunctions = pureFunctions;
  3210. for (const pathSegment of functionName.split('.')) {
  3211. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  3212. }
  3213. currentFunctions[PureFunctionKey] = true;
  3214. }
  3215. return pureFunctions;
  3216. };
  3217. const UnknownKey = Symbol('Unknown Key');
  3218. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  3219. const UnknownInteger = Symbol('Unknown Integer');
  3220. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  3221. const EMPTY_PATH = [];
  3222. const UNKNOWN_PATH = [UnknownKey];
  3223. // For deoptimizations, this means we are modifying an unknown property but did
  3224. // not lose track of the object or are creating a setter/getter;
  3225. // For assignment effects it means we do not check for setter/getter effects
  3226. // but only if something is mutated that is included, which is relevant for
  3227. // Object.defineProperty
  3228. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  3229. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  3230. const EntitiesKey = Symbol('Entities');
  3231. class PathTracker {
  3232. constructor() {
  3233. this.entityPaths = Object.create(null, {
  3234. [EntitiesKey]: { value: new Set() }
  3235. });
  3236. }
  3237. trackEntityAtPathAndGetIfTracked(path, entity) {
  3238. const trackedEntities = this.getEntities(path);
  3239. if (trackedEntities.has(entity))
  3240. return true;
  3241. trackedEntities.add(entity);
  3242. return false;
  3243. }
  3244. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  3245. const trackedEntities = this.getEntities(path);
  3246. if (trackedEntities.has(entity))
  3247. return returnIfTracked;
  3248. trackedEntities.add(entity);
  3249. const result = onUntracked();
  3250. trackedEntities.delete(entity);
  3251. return result;
  3252. }
  3253. getEntities(path) {
  3254. let currentPaths = this.entityPaths;
  3255. for (const pathSegment of path) {
  3256. currentPaths = currentPaths[pathSegment] =
  3257. currentPaths[pathSegment] ||
  3258. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  3259. }
  3260. return currentPaths[EntitiesKey];
  3261. }
  3262. }
  3263. const SHARED_RECURSION_TRACKER = new PathTracker();
  3264. class DiscriminatedPathTracker {
  3265. constructor() {
  3266. this.entityPaths = Object.create(null, {
  3267. [EntitiesKey]: { value: new Map() }
  3268. });
  3269. }
  3270. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  3271. let currentPaths = this.entityPaths;
  3272. for (const pathSegment of path) {
  3273. currentPaths = currentPaths[pathSegment] =
  3274. currentPaths[pathSegment] ||
  3275. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  3276. }
  3277. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  3278. if (trackedEntities.has(entity))
  3279. return true;
  3280. trackedEntities.add(entity);
  3281. return false;
  3282. }
  3283. }
  3284. function isFlagSet(flags, flag) {
  3285. return (flags & flag) !== 0;
  3286. }
  3287. function setFlag(flags, flag, value) {
  3288. return (flags & ~flag) | (-value & flag);
  3289. }
  3290. const UnknownValue = Symbol('Unknown Value');
  3291. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  3292. class ExpressionEntity {
  3293. constructor() {
  3294. this.flags = 0;
  3295. }
  3296. get included() {
  3297. return isFlagSet(this.flags, 1 /* Flag.included */);
  3298. }
  3299. set included(value) {
  3300. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  3301. }
  3302. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  3303. deoptimizeInteraction(interaction);
  3304. }
  3305. deoptimizePath(_path) { }
  3306. /**
  3307. * If possible it returns a stringifyable literal value for this node that
  3308. * can be used for inlining or comparing values. Otherwise, it should return
  3309. * UnknownValue.
  3310. */
  3311. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  3312. return UnknownValue;
  3313. }
  3314. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  3315. return UNKNOWN_RETURN_EXPRESSION;
  3316. }
  3317. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  3318. return true;
  3319. }
  3320. include(_context, _includeChildrenRecursively, _options) {
  3321. this.included = true;
  3322. }
  3323. includeCallArguments(context, parameters) {
  3324. for (const argument of parameters) {
  3325. argument.include(context, false);
  3326. }
  3327. }
  3328. shouldBeIncluded(_context) {
  3329. return true;
  3330. }
  3331. }
  3332. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  3333. })();
  3334. const UNKNOWN_RETURN_EXPRESSION = [
  3335. UNKNOWN_EXPRESSION,
  3336. false
  3337. ];
  3338. const deoptimizeInteraction = (interaction) => {
  3339. for (const argument of interaction.args) {
  3340. argument?.deoptimizePath(UNKNOWN_PATH);
  3341. }
  3342. };
  3343. const INTERACTION_ACCESSED = 0;
  3344. const INTERACTION_ASSIGNED = 1;
  3345. const INTERACTION_CALLED = 2;
  3346. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  3347. args: [null],
  3348. type: INTERACTION_ACCESSED
  3349. };
  3350. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  3351. args: [null, UNKNOWN_EXPRESSION],
  3352. type: INTERACTION_ASSIGNED
  3353. };
  3354. // While this is technically a call without arguments, we can compare against
  3355. // this reference in places where precise values or this argument would make a
  3356. // difference
  3357. const NODE_INTERACTION_UNKNOWN_CALL = {
  3358. args: [null],
  3359. type: INTERACTION_CALLED,
  3360. withNew: false
  3361. };
  3362. class Variable extends ExpressionEntity {
  3363. markReassigned() {
  3364. this.isReassigned = true;
  3365. }
  3366. constructor(name) {
  3367. super();
  3368. this.name = name;
  3369. this.alwaysRendered = false;
  3370. this.forbiddenNames = null;
  3371. this.globalName = null;
  3372. this.initReached = false;
  3373. this.isId = false;
  3374. this.kind = null;
  3375. this.renderBaseName = null;
  3376. this.renderName = null;
  3377. this.isReassigned = false;
  3378. this.onlyFunctionCallUsed = true;
  3379. }
  3380. /**
  3381. * Binds identifiers that reference this variable to this variable.
  3382. * Necessary to be able to change variable names.
  3383. */
  3384. addReference(_identifier) { }
  3385. /**
  3386. * Check if the identifier variable is only used as function call
  3387. * @returns true if the variable is only used as function call
  3388. */
  3389. getOnlyFunctionCallUsed() {
  3390. return this.onlyFunctionCallUsed;
  3391. }
  3392. /**
  3393. * Collect the places where the identifier variable is used
  3394. * @param usedPlace Where the variable is used
  3395. */
  3396. addUsedPlace(usedPlace) {
  3397. const isFunctionCall = usedPlace.parent.type === parseAst_js.CallExpression &&
  3398. usedPlace.parent.callee === usedPlace;
  3399. if (!isFunctionCall && usedPlace.parent.type !== parseAst_js.ExportDefaultDeclaration) {
  3400. this.onlyFunctionCallUsed = false;
  3401. }
  3402. }
  3403. /**
  3404. * Prevent this variable from being renamed to this name to avoid name
  3405. * collisions
  3406. */
  3407. forbidName(name) {
  3408. (this.forbiddenNames ||= new Set()).add(name);
  3409. }
  3410. getBaseVariableName() {
  3411. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  3412. this.renderBaseName ||
  3413. this.renderName ||
  3414. this.name);
  3415. }
  3416. getName(getPropertyAccess, useOriginalName) {
  3417. if (this.globalName) {
  3418. return this.globalName;
  3419. }
  3420. if (useOriginalName?.(this)) {
  3421. return this.name;
  3422. }
  3423. if (this.renderedLikeHoisted) {
  3424. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  3425. }
  3426. const name = this.renderName || this.name;
  3427. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  3428. }
  3429. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  3430. return type !== INTERACTION_ACCESSED || path.length > 0;
  3431. }
  3432. /**
  3433. * Marks this variable as being part of the bundle, which is usually the case
  3434. * when one of its identifiers becomes part of the bundle. Returns true if it
  3435. * has not been included previously. Once a variable is included, it should
  3436. * take care all its declarations are included.
  3437. */
  3438. include() {
  3439. this.included = true;
  3440. this.renderedLikeHoisted?.include();
  3441. }
  3442. /**
  3443. * Links the rendered name of this variable to another variable and includes
  3444. * this variable if the other variable is included.
  3445. */
  3446. renderLikeHoisted(variable) {
  3447. this.renderedLikeHoisted = variable;
  3448. }
  3449. markCalledFromTryStatement() { }
  3450. setRenderNames(baseName, name) {
  3451. this.renderBaseName = baseName;
  3452. this.renderName = name;
  3453. }
  3454. }
  3455. class ExternalVariable extends Variable {
  3456. constructor(module, name) {
  3457. super(name);
  3458. this.referenced = false;
  3459. this.module = module;
  3460. this.isNamespace = name === '*';
  3461. }
  3462. addReference(identifier) {
  3463. this.referenced = true;
  3464. if (this.name === 'default' || this.name === '*') {
  3465. this.module.suggestName(identifier.name);
  3466. }
  3467. }
  3468. hasEffectsOnInteractionAtPath(path, { type }) {
  3469. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  3470. }
  3471. include() {
  3472. super.include();
  3473. this.module.used = true;
  3474. }
  3475. }
  3476. function cacheObjectGetters(object, getterProperties) {
  3477. for (const property of getterProperties) {
  3478. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  3479. Object.defineProperty(object, property, {
  3480. get() {
  3481. const value = propertyGetter.call(object);
  3482. // This replaces the getter with a fixed value for subsequent calls
  3483. Object.defineProperty(object, property, { value });
  3484. return value;
  3485. }
  3486. });
  3487. }
  3488. }
  3489. const RESERVED_NAMES = new Set([
  3490. 'await',
  3491. 'break',
  3492. 'case',
  3493. 'catch',
  3494. 'class',
  3495. 'const',
  3496. 'continue',
  3497. 'debugger',
  3498. 'default',
  3499. 'delete',
  3500. 'do',
  3501. 'else',
  3502. 'enum',
  3503. 'eval',
  3504. 'export',
  3505. 'extends',
  3506. 'false',
  3507. 'finally',
  3508. 'for',
  3509. 'function',
  3510. 'if',
  3511. 'implements',
  3512. 'import',
  3513. 'in',
  3514. 'instanceof',
  3515. 'interface',
  3516. 'let',
  3517. 'NaN',
  3518. 'new',
  3519. 'null',
  3520. 'package',
  3521. 'private',
  3522. 'protected',
  3523. 'public',
  3524. 'return',
  3525. 'static',
  3526. 'super',
  3527. 'switch',
  3528. 'this',
  3529. 'throw',
  3530. 'true',
  3531. 'try',
  3532. 'typeof',
  3533. 'undefined',
  3534. 'var',
  3535. 'void',
  3536. 'while',
  3537. 'with',
  3538. 'yield'
  3539. ]);
  3540. const illegalCharacters = /[^\w$]/g;
  3541. const startsWithDigit = (value) => /\d/.test(value[0]);
  3542. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  3543. function isLegal(value) {
  3544. if (needsEscape(value)) {
  3545. return false;
  3546. }
  3547. return !illegalCharacters.test(value);
  3548. }
  3549. function makeLegal(value) {
  3550. value = value
  3551. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  3552. .replace(illegalCharacters, '_');
  3553. if (needsEscape(value))
  3554. value = `_${value}`;
  3555. return value || '_';
  3556. }
  3557. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  3558. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  3559. function stringifyObjectKeyIfNeeded(key) {
  3560. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  3561. return key === '__proto__' ? '["__proto__"]' : key;
  3562. }
  3563. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  3564. return key;
  3565. }
  3566. return JSON.stringify(key);
  3567. }
  3568. function stringifyIdentifierIfNeeded(key) {
  3569. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  3570. return key;
  3571. }
  3572. return JSON.stringify(key);
  3573. }
  3574. class ExternalModule {
  3575. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  3576. this.options = options;
  3577. this.id = id;
  3578. this.renormalizeRenderPath = renormalizeRenderPath;
  3579. this.dynamicImporters = [];
  3580. this.execIndex = Infinity;
  3581. this.exportedVariables = new Map();
  3582. this.importers = [];
  3583. this.reexported = false;
  3584. this.used = false;
  3585. this.declarations = new Map();
  3586. this.mostCommonSuggestion = 0;
  3587. this.nameSuggestions = new Map();
  3588. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  3589. const { importers, dynamicImporters } = this;
  3590. this.info = {
  3591. ast: null,
  3592. attributes,
  3593. code: null,
  3594. dynamicallyImportedIdResolutions: parseAst_js.EMPTY_ARRAY,
  3595. dynamicallyImportedIds: parseAst_js.EMPTY_ARRAY,
  3596. get dynamicImporters() {
  3597. return dynamicImporters.sort();
  3598. },
  3599. exportedBindings: null,
  3600. exports: null,
  3601. hasDefaultExport: null,
  3602. id,
  3603. implicitlyLoadedAfterOneOf: parseAst_js.EMPTY_ARRAY,
  3604. implicitlyLoadedBefore: parseAst_js.EMPTY_ARRAY,
  3605. importedIdResolutions: parseAst_js.EMPTY_ARRAY,
  3606. importedIds: parseAst_js.EMPTY_ARRAY,
  3607. get importers() {
  3608. return importers.sort();
  3609. },
  3610. isEntry: false,
  3611. isExternal: true,
  3612. isIncluded: null,
  3613. meta,
  3614. moduleSideEffects,
  3615. syntheticNamedExports: false
  3616. };
  3617. }
  3618. cacheInfoGetters() {
  3619. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  3620. }
  3621. getVariableForExportName(name) {
  3622. const declaration = this.declarations.get(name);
  3623. if (declaration)
  3624. return [declaration];
  3625. const externalVariable = new ExternalVariable(this, name);
  3626. this.declarations.set(name, externalVariable);
  3627. this.exportedVariables.set(externalVariable, name);
  3628. return [externalVariable];
  3629. }
  3630. suggestName(name) {
  3631. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  3632. this.nameSuggestions.set(name, value);
  3633. if (value > this.mostCommonSuggestion) {
  3634. this.mostCommonSuggestion = value;
  3635. this.suggestedVariableName = name;
  3636. }
  3637. }
  3638. warnUnusedImports() {
  3639. const unused = [...this.declarations]
  3640. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  3641. .map(([name]) => name);
  3642. if (unused.length === 0)
  3643. return;
  3644. const importersSet = new Set();
  3645. for (const name of unused) {
  3646. for (const importer of this.declarations.get(name).module.importers) {
  3647. importersSet.add(importer);
  3648. }
  3649. }
  3650. const importersArray = [...importersSet];
  3651. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnusedExternalImports(this.id, unused, importersArray));
  3652. }
  3653. }
  3654. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  3655. baseModule.isExecuted = true;
  3656. const modules = [baseModule];
  3657. const visitedModules = new Set();
  3658. for (const module of modules) {
  3659. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  3660. if (!(dependency instanceof ExternalModule) &&
  3661. !dependency.isExecuted &&
  3662. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  3663. !visitedModules.has(dependency.id)) {
  3664. dependency.isExecuted = true;
  3665. visitedModules.add(dependency.id);
  3666. modules.push(dependency);
  3667. }
  3668. }
  3669. }
  3670. }
  3671. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  3672. return Object.create(inheritedDescriptions, memberDescriptions);
  3673. }
  3674. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  3675. getLiteralValueAtPath() {
  3676. return undefined;
  3677. }
  3678. })();
  3679. const returnsUnknown = {
  3680. value: {
  3681. hasEffectsWhenCalled: null,
  3682. returns: UNKNOWN_EXPRESSION
  3683. }
  3684. };
  3685. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  3686. getReturnExpressionWhenCalledAtPath(path) {
  3687. if (path.length === 1) {
  3688. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  3689. }
  3690. return UNKNOWN_RETURN_EXPRESSION;
  3691. }
  3692. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3693. if (interaction.type === INTERACTION_ACCESSED) {
  3694. return path.length > 1;
  3695. }
  3696. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3697. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  3698. }
  3699. return true;
  3700. }
  3701. })();
  3702. const returnsBoolean = {
  3703. value: {
  3704. hasEffectsWhenCalled: null,
  3705. returns: UNKNOWN_LITERAL_BOOLEAN
  3706. }
  3707. };
  3708. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  3709. getReturnExpressionWhenCalledAtPath(path) {
  3710. if (path.length === 1) {
  3711. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  3712. }
  3713. return UNKNOWN_RETURN_EXPRESSION;
  3714. }
  3715. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3716. if (interaction.type === INTERACTION_ACCESSED) {
  3717. return path.length > 1;
  3718. }
  3719. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3720. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  3721. }
  3722. return true;
  3723. }
  3724. })();
  3725. const returnsNumber = {
  3726. value: {
  3727. hasEffectsWhenCalled: null,
  3728. returns: UNKNOWN_LITERAL_NUMBER
  3729. }
  3730. };
  3731. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  3732. getReturnExpressionWhenCalledAtPath(path) {
  3733. if (path.length === 1) {
  3734. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  3735. }
  3736. return UNKNOWN_RETURN_EXPRESSION;
  3737. }
  3738. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3739. if (interaction.type === INTERACTION_ACCESSED) {
  3740. return path.length > 1;
  3741. }
  3742. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3743. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  3744. }
  3745. return true;
  3746. }
  3747. })();
  3748. const returnsString = {
  3749. value: {
  3750. hasEffectsWhenCalled: null,
  3751. returns: UNKNOWN_LITERAL_STRING
  3752. }
  3753. };
  3754. const stringReplace = {
  3755. value: {
  3756. hasEffectsWhenCalled({ args }, context) {
  3757. const argument1 = args[2];
  3758. return (args.length < 3 ||
  3759. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  3760. deoptimizeCache() { }
  3761. }) === 'symbol' &&
  3762. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  3763. },
  3764. returns: UNKNOWN_LITERAL_STRING
  3765. }
  3766. };
  3767. const objectMembers = assembleMemberDescriptions({
  3768. hasOwnProperty: returnsBoolean,
  3769. isPrototypeOf: returnsBoolean,
  3770. propertyIsEnumerable: returnsBoolean,
  3771. toLocaleString: returnsString,
  3772. toString: returnsString,
  3773. valueOf: returnsUnknown
  3774. });
  3775. const literalBooleanMembers = assembleMemberDescriptions({
  3776. valueOf: returnsBoolean
  3777. }, objectMembers);
  3778. const literalNumberMembers = assembleMemberDescriptions({
  3779. toExponential: returnsString,
  3780. toFixed: returnsString,
  3781. toLocaleString: returnsString,
  3782. toPrecision: returnsString,
  3783. valueOf: returnsNumber
  3784. }, objectMembers);
  3785. /**
  3786. * RegExp are stateful when they have the global or sticky flags set.
  3787. * But if we actually don't use them, the side effect does not matter.
  3788. * the check logic in `hasEffectsOnInteractionAtPath`.
  3789. */
  3790. const literalRegExpMembers = assembleMemberDescriptions({
  3791. exec: returnsUnknown,
  3792. test: returnsBoolean
  3793. }, objectMembers);
  3794. const literalStringMembers = assembleMemberDescriptions({
  3795. anchor: returnsString,
  3796. at: returnsUnknown,
  3797. big: returnsString,
  3798. blink: returnsString,
  3799. bold: returnsString,
  3800. charAt: returnsString,
  3801. charCodeAt: returnsNumber,
  3802. codePointAt: returnsUnknown,
  3803. concat: returnsString,
  3804. endsWith: returnsBoolean,
  3805. fixed: returnsString,
  3806. fontcolor: returnsString,
  3807. fontsize: returnsString,
  3808. includes: returnsBoolean,
  3809. indexOf: returnsNumber,
  3810. italics: returnsString,
  3811. lastIndexOf: returnsNumber,
  3812. link: returnsString,
  3813. localeCompare: returnsNumber,
  3814. match: returnsUnknown,
  3815. matchAll: returnsUnknown,
  3816. normalize: returnsString,
  3817. padEnd: returnsString,
  3818. padStart: returnsString,
  3819. repeat: returnsString,
  3820. replace: stringReplace,
  3821. replaceAll: stringReplace,
  3822. search: returnsNumber,
  3823. slice: returnsString,
  3824. small: returnsString,
  3825. split: returnsUnknown,
  3826. startsWith: returnsBoolean,
  3827. strike: returnsString,
  3828. sub: returnsString,
  3829. substr: returnsString,
  3830. substring: returnsString,
  3831. sup: returnsString,
  3832. toLocaleLowerCase: returnsString,
  3833. toLocaleUpperCase: returnsString,
  3834. toLowerCase: returnsString,
  3835. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  3836. toUpperCase: returnsString,
  3837. trim: returnsString,
  3838. trimEnd: returnsString,
  3839. trimLeft: returnsString,
  3840. trimRight: returnsString,
  3841. trimStart: returnsString,
  3842. valueOf: returnsString
  3843. }, objectMembers);
  3844. function getLiteralMembersForValue(value) {
  3845. if (value instanceof RegExp) {
  3846. return literalRegExpMembers;
  3847. }
  3848. switch (typeof value) {
  3849. case 'boolean': {
  3850. return literalBooleanMembers;
  3851. }
  3852. case 'number': {
  3853. return literalNumberMembers;
  3854. }
  3855. case 'string': {
  3856. return literalStringMembers;
  3857. }
  3858. }
  3859. return Object.create(null);
  3860. }
  3861. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  3862. if (typeof memberName !== 'string' || !members[memberName]) {
  3863. return true;
  3864. }
  3865. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  3866. }
  3867. function getMemberReturnExpressionWhenCalled(members, memberName) {
  3868. if (typeof memberName !== 'string' || !members[memberName])
  3869. return UNKNOWN_RETURN_EXPRESSION;
  3870. return [members[memberName].returns, false];
  3871. }
  3872. // This file is generated by scripts/generate-child-node-keys.js.
  3873. // Do not edit this file directly.
  3874. const childNodeKeys = {
  3875. ArrayExpression: ['elements'],
  3876. ArrayPattern: ['elements'],
  3877. ArrowFunctionExpression: ['params', 'body'],
  3878. AssignmentExpression: ['left', 'right'],
  3879. AssignmentPattern: ['left', 'right'],
  3880. AwaitExpression: ['argument'],
  3881. BinaryExpression: ['left', 'right'],
  3882. BlockStatement: ['body'],
  3883. BreakStatement: ['label'],
  3884. CallExpression: ['callee', 'arguments'],
  3885. CatchClause: ['param', 'body'],
  3886. ChainExpression: ['expression'],
  3887. ClassBody: ['body'],
  3888. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  3889. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  3890. ConditionalExpression: ['test', 'consequent', 'alternate'],
  3891. ContinueStatement: ['label'],
  3892. DebuggerStatement: [],
  3893. Decorator: ['expression'],
  3894. DoWhileStatement: ['body', 'test'],
  3895. EmptyStatement: [],
  3896. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  3897. ExportDefaultDeclaration: ['declaration'],
  3898. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  3899. ExportSpecifier: ['local', 'exported'],
  3900. ExpressionStatement: ['expression'],
  3901. ForInStatement: ['left', 'right', 'body'],
  3902. ForOfStatement: ['left', 'right', 'body'],
  3903. ForStatement: ['init', 'test', 'update', 'body'],
  3904. FunctionDeclaration: ['id', 'params', 'body'],
  3905. FunctionExpression: ['id', 'params', 'body'],
  3906. Identifier: [],
  3907. IfStatement: ['test', 'consequent', 'alternate'],
  3908. ImportAttribute: ['key', 'value'],
  3909. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  3910. ImportDefaultSpecifier: ['local'],
  3911. ImportExpression: ['source', 'options'],
  3912. ImportNamespaceSpecifier: ['local'],
  3913. ImportSpecifier: ['imported', 'local'],
  3914. JSXAttribute: ['name', 'value'],
  3915. JSXClosingElement: ['name'],
  3916. JSXClosingFragment: [],
  3917. JSXElement: ['openingElement', 'children', 'closingElement'],
  3918. JSXEmptyExpression: [],
  3919. JSXExpressionContainer: ['expression'],
  3920. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  3921. JSXIdentifier: [],
  3922. JSXMemberExpression: ['object', 'property'],
  3923. JSXNamespacedName: ['namespace', 'name'],
  3924. JSXOpeningElement: ['name', 'attributes'],
  3925. JSXOpeningFragment: [],
  3926. JSXSpreadAttribute: ['argument'],
  3927. JSXSpreadChild: ['expression'],
  3928. JSXText: [],
  3929. LabeledStatement: ['label', 'body'],
  3930. Literal: [],
  3931. LogicalExpression: ['left', 'right'],
  3932. MemberExpression: ['object', 'property'],
  3933. MetaProperty: ['meta', 'property'],
  3934. MethodDefinition: ['decorators', 'key', 'value'],
  3935. NewExpression: ['callee', 'arguments'],
  3936. ObjectExpression: ['properties'],
  3937. ObjectPattern: ['properties'],
  3938. PanicError: [],
  3939. ParseError: [],
  3940. PrivateIdentifier: [],
  3941. Program: ['body'],
  3942. Property: ['key', 'value'],
  3943. PropertyDefinition: ['decorators', 'key', 'value'],
  3944. RestElement: ['argument'],
  3945. ReturnStatement: ['argument'],
  3946. SequenceExpression: ['expressions'],
  3947. SpreadElement: ['argument'],
  3948. StaticBlock: ['body'],
  3949. Super: [],
  3950. SwitchCase: ['test', 'consequent'],
  3951. SwitchStatement: ['discriminant', 'cases'],
  3952. TaggedTemplateExpression: ['tag', 'quasi'],
  3953. TemplateElement: [],
  3954. TemplateLiteral: ['quasis', 'expressions'],
  3955. ThisExpression: [],
  3956. ThrowStatement: ['argument'],
  3957. TryStatement: ['block', 'handler', 'finalizer'],
  3958. UnaryExpression: ['argument'],
  3959. UpdateExpression: ['argument'],
  3960. VariableDeclaration: ['declarations'],
  3961. VariableDeclarator: ['id', 'init'],
  3962. WhileStatement: ['test', 'body'],
  3963. YieldExpression: ['argument']
  3964. };
  3965. function createInclusionContext() {
  3966. return {
  3967. brokenFlow: false,
  3968. hasBreak: false,
  3969. hasContinue: false,
  3970. includedCallArguments: new Set(),
  3971. includedLabels: new Set()
  3972. };
  3973. }
  3974. function createHasEffectsContext() {
  3975. return {
  3976. accessed: new PathTracker(),
  3977. assigned: new PathTracker(),
  3978. brokenFlow: false,
  3979. called: new DiscriminatedPathTracker(),
  3980. hasBreak: false,
  3981. hasContinue: false,
  3982. ignore: {
  3983. breaks: false,
  3984. continues: false,
  3985. labels: new Set(),
  3986. returnYield: false,
  3987. this: false
  3988. },
  3989. includedLabels: new Set(),
  3990. instantiated: new DiscriminatedPathTracker(),
  3991. replacedVariableInits: new Map()
  3992. };
  3993. }
  3994. const INCLUDE_PARAMETERS = 'variables';
  3995. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  3996. class NodeBase extends ExpressionEntity {
  3997. /**
  3998. * Nodes can apply custom deoptimizations once they become part of the
  3999. * executed code. To do this, they must initialize this as false, implement
  4000. * applyDeoptimizations and call this from include and hasEffects if they have
  4001. * custom handlers
  4002. */
  4003. get deoptimized() {
  4004. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  4005. }
  4006. set deoptimized(value) {
  4007. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  4008. }
  4009. constructor(parent, parentScope) {
  4010. super();
  4011. this.parent = parent;
  4012. this.scope = parentScope;
  4013. this.createScope(parentScope);
  4014. }
  4015. addExportedVariables(_variables, _exportNamesByVariable) { }
  4016. /**
  4017. * Override this to bind assignments to variables and do any initialisations
  4018. * that require the scopes to be populated with variables.
  4019. */
  4020. bind() {
  4021. for (const key of childNodeKeys[this.type]) {
  4022. const value = this[key];
  4023. if (Array.isArray(value)) {
  4024. for (const child of value) {
  4025. child?.bind();
  4026. }
  4027. }
  4028. else if (value) {
  4029. value.bind();
  4030. }
  4031. }
  4032. }
  4033. /**
  4034. * Override if this node should receive a different scope than the parent
  4035. * scope.
  4036. */
  4037. createScope(parentScope) {
  4038. this.scope = parentScope;
  4039. }
  4040. hasEffects(context) {
  4041. if (!this.deoptimized)
  4042. this.applyDeoptimizations();
  4043. for (const key of childNodeKeys[this.type]) {
  4044. const value = this[key];
  4045. if (value === null)
  4046. continue;
  4047. if (Array.isArray(value)) {
  4048. for (const child of value) {
  4049. if (child?.hasEffects(context))
  4050. return true;
  4051. }
  4052. }
  4053. else if (value.hasEffects(context))
  4054. return true;
  4055. }
  4056. return false;
  4057. }
  4058. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4059. return (this.hasEffects(context) ||
  4060. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4061. }
  4062. include(context, includeChildrenRecursively, _options) {
  4063. if (!this.deoptimized)
  4064. this.applyDeoptimizations();
  4065. this.included = true;
  4066. for (const key of childNodeKeys[this.type]) {
  4067. const value = this[key];
  4068. if (value === null)
  4069. continue;
  4070. if (Array.isArray(value)) {
  4071. for (const child of value) {
  4072. child?.include(context, includeChildrenRecursively);
  4073. }
  4074. }
  4075. else {
  4076. value.include(context, includeChildrenRecursively);
  4077. }
  4078. }
  4079. }
  4080. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4081. this.include(context, includeChildrenRecursively);
  4082. }
  4083. /**
  4084. * Override to perform special initialisation steps after the scope is
  4085. * initialised
  4086. */
  4087. initialise() {
  4088. this.scope.context.magicString.addSourcemapLocation(this.start);
  4089. this.scope.context.magicString.addSourcemapLocation(this.end);
  4090. }
  4091. parseNode(esTreeNode) {
  4092. for (const [key, value] of Object.entries(esTreeNode)) {
  4093. // Skip properties defined on the class already.
  4094. // This way, we can override this function to add custom initialisation and then call super.parseNode
  4095. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  4096. // in bitfields. Those are still assigned from the value in the esTreeNode.
  4097. if (this.hasOwnProperty(key))
  4098. continue;
  4099. if (key.charCodeAt(0) === 95 /* _ */) {
  4100. if (key === parseAst_js.ANNOTATION_KEY) {
  4101. this.annotations = value;
  4102. }
  4103. else if (key === parseAst_js.INVALID_ANNOTATION_KEY) {
  4104. this.invalidAnnotations = value;
  4105. }
  4106. }
  4107. else if (typeof value !== 'object' || value === null) {
  4108. this[key] = value;
  4109. }
  4110. else if (Array.isArray(value)) {
  4111. this[key] = [];
  4112. for (const child of value) {
  4113. this[key].push(child === null
  4114. ? null
  4115. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child));
  4116. }
  4117. }
  4118. else {
  4119. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  4120. }
  4121. }
  4122. // extend child keys for unknown node types
  4123. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  4124. this.initialise();
  4125. return this;
  4126. }
  4127. removeAnnotations(code) {
  4128. if (this.annotations) {
  4129. for (const annotation of this.annotations) {
  4130. code.remove(annotation.start, annotation.end);
  4131. }
  4132. }
  4133. }
  4134. render(code, options) {
  4135. for (const key of childNodeKeys[this.type]) {
  4136. const value = this[key];
  4137. if (value === null)
  4138. continue;
  4139. if (Array.isArray(value)) {
  4140. for (const child of value) {
  4141. child?.render(code, options);
  4142. }
  4143. }
  4144. else {
  4145. value.render(code, options);
  4146. }
  4147. }
  4148. }
  4149. setAssignedValue(value) {
  4150. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  4151. }
  4152. shouldBeIncluded(context) {
  4153. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4154. }
  4155. /**
  4156. * Just deoptimize everything by default so that when e.g. we do not track
  4157. * something properly, it is deoptimized.
  4158. * @protected
  4159. */
  4160. applyDeoptimizations() {
  4161. this.deoptimized = true;
  4162. for (const key of childNodeKeys[this.type]) {
  4163. const value = this[key];
  4164. if (value === null)
  4165. continue;
  4166. if (Array.isArray(value)) {
  4167. for (const child of value) {
  4168. child?.deoptimizePath(UNKNOWN_PATH);
  4169. }
  4170. }
  4171. else {
  4172. value.deoptimizePath(UNKNOWN_PATH);
  4173. }
  4174. }
  4175. this.scope.context.requestTreeshakingPass();
  4176. }
  4177. }
  4178. function createChildNodeKeysForNode(esTreeNode) {
  4179. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4180. }
  4181. class SpreadElement extends NodeBase {
  4182. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4183. if (path.length > 0) {
  4184. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4185. }
  4186. }
  4187. hasEffects(context) {
  4188. if (!this.deoptimized)
  4189. this.applyDeoptimizations();
  4190. const { propertyReadSideEffects } = this.scope.context.options
  4191. .treeshake;
  4192. return (this.argument.hasEffects(context) ||
  4193. (propertyReadSideEffects &&
  4194. (propertyReadSideEffects === 'always' ||
  4195. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4196. }
  4197. applyDeoptimizations() {
  4198. this.deoptimized = true;
  4199. // Only properties of properties of the argument could become subject to reassignment
  4200. // This will also reassign the return values of iterators
  4201. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4202. this.scope.context.requestTreeshakingPass();
  4203. }
  4204. }
  4205. class Method extends ExpressionEntity {
  4206. constructor(description) {
  4207. super();
  4208. this.description = description;
  4209. }
  4210. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  4211. if (type === INTERACTION_CALLED && path.length === 0) {
  4212. if (this.description.mutatesSelfAsArray) {
  4213. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4214. }
  4215. if (this.description.mutatesArgs) {
  4216. for (let index = 1; index < args.length; index++) {
  4217. args[index].deoptimizePath(UNKNOWN_PATH);
  4218. }
  4219. }
  4220. }
  4221. }
  4222. getReturnExpressionWhenCalledAtPath(path, { args }) {
  4223. if (path.length > 0) {
  4224. return UNKNOWN_RETURN_EXPRESSION;
  4225. }
  4226. return [
  4227. this.description.returnsPrimitive ||
  4228. (this.description.returns === 'self'
  4229. ? args[0] || UNKNOWN_EXPRESSION
  4230. : this.description.returns()),
  4231. false
  4232. ];
  4233. }
  4234. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4235. const { type } = interaction;
  4236. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4237. return true;
  4238. }
  4239. if (type === INTERACTION_CALLED) {
  4240. const { args } = interaction;
  4241. if (this.description.mutatesSelfAsArray === true &&
  4242. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  4243. return true;
  4244. }
  4245. if (this.description.callsArgs) {
  4246. for (const argumentIndex of this.description.callsArgs) {
  4247. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4248. return true;
  4249. }
  4250. }
  4251. }
  4252. }
  4253. return false;
  4254. }
  4255. }
  4256. const METHOD_RETURNS_BOOLEAN = [
  4257. new Method({
  4258. callsArgs: null,
  4259. mutatesArgs: false,
  4260. mutatesSelfAsArray: false,
  4261. returns: null,
  4262. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4263. })
  4264. ];
  4265. const METHOD_RETURNS_STRING = [
  4266. new Method({
  4267. callsArgs: null,
  4268. mutatesArgs: false,
  4269. mutatesSelfAsArray: false,
  4270. returns: null,
  4271. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4272. })
  4273. ];
  4274. const METHOD_RETURNS_NUMBER = [
  4275. new Method({
  4276. callsArgs: null,
  4277. mutatesArgs: false,
  4278. mutatesSelfAsArray: false,
  4279. returns: null,
  4280. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4281. })
  4282. ];
  4283. const METHOD_RETURNS_UNKNOWN = [
  4284. new Method({
  4285. callsArgs: null,
  4286. mutatesArgs: false,
  4287. mutatesSelfAsArray: false,
  4288. returns: null,
  4289. returnsPrimitive: UNKNOWN_EXPRESSION
  4290. })
  4291. ];
  4292. const INTEGER_REG_EXP = /^\d+$/;
  4293. class ObjectEntity extends ExpressionEntity {
  4294. get hasLostTrack() {
  4295. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  4296. }
  4297. set hasLostTrack(value) {
  4298. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  4299. }
  4300. get hasUnknownDeoptimizedInteger() {
  4301. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  4302. }
  4303. set hasUnknownDeoptimizedInteger(value) {
  4304. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  4305. }
  4306. get hasUnknownDeoptimizedProperty() {
  4307. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  4308. }
  4309. set hasUnknownDeoptimizedProperty(value) {
  4310. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  4311. }
  4312. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4313. // and we assume there are no setters or getters
  4314. constructor(properties, prototypeExpression, immutable = false) {
  4315. super();
  4316. this.prototypeExpression = prototypeExpression;
  4317. this.immutable = immutable;
  4318. this.additionalExpressionsToBeDeoptimized = new Set();
  4319. this.allProperties = [];
  4320. this.deoptimizedPaths = Object.create(null);
  4321. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4322. this.gettersByKey = Object.create(null);
  4323. this.propertiesAndGettersByKey = Object.create(null);
  4324. this.propertiesAndSettersByKey = Object.create(null);
  4325. this.settersByKey = Object.create(null);
  4326. this.unknownIntegerProps = [];
  4327. this.unmatchableGetters = [];
  4328. this.unmatchablePropertiesAndGetters = [];
  4329. this.unmatchableSetters = [];
  4330. if (Array.isArray(properties)) {
  4331. this.buildPropertyMaps(properties);
  4332. }
  4333. else {
  4334. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4335. for (const propertiesForKey of Object.values(properties)) {
  4336. this.allProperties.push(...propertiesForKey);
  4337. }
  4338. }
  4339. }
  4340. deoptimizeAllProperties(noAccessors) {
  4341. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4342. if (noAccessors) {
  4343. this.hasUnknownDeoptimizedProperty = true;
  4344. }
  4345. else {
  4346. this.hasLostTrack = true;
  4347. }
  4348. if (isDeoptimized) {
  4349. return;
  4350. }
  4351. for (const properties of [
  4352. ...Object.values(this.propertiesAndGettersByKey),
  4353. ...Object.values(this.settersByKey)
  4354. ]) {
  4355. for (const property of properties) {
  4356. property.deoptimizePath(UNKNOWN_PATH);
  4357. }
  4358. }
  4359. // While the prototype itself cannot be mutated, each property can
  4360. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  4361. this.deoptimizeCachedEntities();
  4362. }
  4363. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4364. const [key, ...subPath] = path;
  4365. const { args, type } = interaction;
  4366. if (this.hasLostTrack ||
  4367. // single paths that are deoptimized will not become getters or setters
  4368. ((type === INTERACTION_CALLED || path.length > 1) &&
  4369. (this.hasUnknownDeoptimizedProperty ||
  4370. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4371. deoptimizeInteraction(interaction);
  4372. return;
  4373. }
  4374. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  4375. ? [
  4376. this.propertiesAndGettersByKey,
  4377. this.propertiesAndGettersByKey,
  4378. this.unmatchablePropertiesAndGetters
  4379. ]
  4380. : type === INTERACTION_ACCESSED
  4381. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4382. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4383. if (typeof key === 'string') {
  4384. if (propertiesForExactMatchByKey[key]) {
  4385. const properties = relevantPropertiesByKey[key];
  4386. if (properties) {
  4387. for (const property of properties) {
  4388. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4389. }
  4390. }
  4391. if (!this.immutable) {
  4392. for (const argument of args) {
  4393. if (argument) {
  4394. this.additionalExpressionsToBeDeoptimized.add(argument);
  4395. }
  4396. }
  4397. }
  4398. return;
  4399. }
  4400. for (const property of relevantUnmatchableProperties) {
  4401. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4402. }
  4403. if (INTEGER_REG_EXP.test(key)) {
  4404. for (const property of this.unknownIntegerProps) {
  4405. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4406. }
  4407. }
  4408. }
  4409. else {
  4410. for (const properties of [
  4411. ...Object.values(relevantPropertiesByKey),
  4412. relevantUnmatchableProperties
  4413. ]) {
  4414. for (const property of properties) {
  4415. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4416. }
  4417. }
  4418. for (const property of this.unknownIntegerProps) {
  4419. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  4420. }
  4421. }
  4422. if (!this.immutable) {
  4423. for (const argument of args) {
  4424. if (argument) {
  4425. this.additionalExpressionsToBeDeoptimized.add(argument);
  4426. }
  4427. }
  4428. }
  4429. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4430. }
  4431. deoptimizeIntegerProperties() {
  4432. if (this.hasLostTrack ||
  4433. this.hasUnknownDeoptimizedProperty ||
  4434. this.hasUnknownDeoptimizedInteger) {
  4435. return;
  4436. }
  4437. this.hasUnknownDeoptimizedInteger = true;
  4438. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4439. if (INTEGER_REG_EXP.test(key)) {
  4440. for (const property of propertiesAndGetters) {
  4441. property.deoptimizePath(UNKNOWN_PATH);
  4442. }
  4443. }
  4444. }
  4445. this.deoptimizeCachedIntegerEntities();
  4446. }
  4447. // Assumption: If only a specific path is deoptimized, no accessors are created
  4448. deoptimizePath(path) {
  4449. if (this.hasLostTrack || this.immutable) {
  4450. return;
  4451. }
  4452. const key = path[0];
  4453. if (path.length === 1) {
  4454. if (key === UnknownInteger) {
  4455. return this.deoptimizeIntegerProperties();
  4456. }
  4457. else if (typeof key !== 'string') {
  4458. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4459. }
  4460. if (!this.deoptimizedPaths[key]) {
  4461. this.deoptimizedPaths[key] = true;
  4462. // we only deoptimizeCache exact matches as in all other cases,
  4463. // we do not return a literal value or return expression
  4464. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4465. if (expressionsToBeDeoptimized) {
  4466. for (const expression of expressionsToBeDeoptimized) {
  4467. expression.deoptimizeCache();
  4468. }
  4469. }
  4470. }
  4471. }
  4472. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4473. for (const property of typeof key === 'string'
  4474. ? [
  4475. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  4476. ...(this.settersByKey[key] || this.unmatchableSetters)
  4477. ]
  4478. : this.allProperties) {
  4479. property.deoptimizePath(subPath);
  4480. }
  4481. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  4482. }
  4483. getLiteralValueAtPath(path, recursionTracker, origin) {
  4484. if (path.length === 0) {
  4485. return UnknownTruthyValue;
  4486. }
  4487. const key = path[0];
  4488. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4489. if (expressionAtPath) {
  4490. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4491. }
  4492. if (this.prototypeExpression) {
  4493. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4494. }
  4495. if (path.length === 1) {
  4496. return undefined;
  4497. }
  4498. return UnknownValue;
  4499. }
  4500. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4501. if (path.length === 0) {
  4502. return UNKNOWN_RETURN_EXPRESSION;
  4503. }
  4504. const [key, ...subPath] = path;
  4505. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4506. if (expressionAtPath) {
  4507. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4508. }
  4509. if (this.prototypeExpression) {
  4510. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4511. }
  4512. return UNKNOWN_RETURN_EXPRESSION;
  4513. }
  4514. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4515. const [key, ...subPath] = path;
  4516. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  4517. const expressionAtPath = this.getMemberExpression(key);
  4518. if (expressionAtPath) {
  4519. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  4520. }
  4521. if (this.prototypeExpression) {
  4522. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4523. }
  4524. return true;
  4525. }
  4526. if (key === UnknownNonAccessorKey)
  4527. return false;
  4528. if (this.hasLostTrack)
  4529. return true;
  4530. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  4531. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4532. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4533. if (typeof key === 'string') {
  4534. if (propertiesAndAccessorsByKey[key]) {
  4535. const accessors = accessorsByKey[key];
  4536. if (accessors) {
  4537. for (const accessor of accessors) {
  4538. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4539. return true;
  4540. }
  4541. }
  4542. return false;
  4543. }
  4544. for (const accessor of unmatchableAccessors) {
  4545. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  4546. return true;
  4547. }
  4548. }
  4549. }
  4550. else {
  4551. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  4552. for (const accessor of accessors) {
  4553. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  4554. return true;
  4555. }
  4556. }
  4557. }
  4558. if (this.prototypeExpression) {
  4559. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4560. }
  4561. return false;
  4562. }
  4563. buildPropertyMaps(properties) {
  4564. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  4565. const unmatchablePropertiesAndSetters = [];
  4566. for (let index = properties.length - 1; index >= 0; index--) {
  4567. const { key, kind, property } = properties[index];
  4568. allProperties.push(property);
  4569. if (typeof key === 'string') {
  4570. if (kind === 'set') {
  4571. if (!propertiesAndSettersByKey[key]) {
  4572. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4573. settersByKey[key] = [property, ...unmatchableSetters];
  4574. }
  4575. }
  4576. else if (kind === 'get') {
  4577. if (!propertiesAndGettersByKey[key]) {
  4578. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4579. gettersByKey[key] = [property, ...unmatchableGetters];
  4580. }
  4581. }
  4582. else {
  4583. if (!propertiesAndSettersByKey[key]) {
  4584. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4585. }
  4586. if (!propertiesAndGettersByKey[key]) {
  4587. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4588. }
  4589. }
  4590. }
  4591. else {
  4592. if (key === UnknownInteger) {
  4593. unknownIntegerProps.push(property);
  4594. continue;
  4595. }
  4596. if (kind === 'set')
  4597. unmatchableSetters.push(property);
  4598. if (kind === 'get')
  4599. unmatchableGetters.push(property);
  4600. if (kind !== 'get')
  4601. unmatchablePropertiesAndSetters.push(property);
  4602. if (kind !== 'set')
  4603. unmatchablePropertiesAndGetters.push(property);
  4604. }
  4605. }
  4606. }
  4607. deoptimizeCachedEntities() {
  4608. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  4609. for (const expression of expressionsToBeDeoptimized) {
  4610. expression.deoptimizeCache();
  4611. }
  4612. }
  4613. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4614. expression.deoptimizePath(UNKNOWN_PATH);
  4615. }
  4616. }
  4617. deoptimizeCachedIntegerEntities() {
  4618. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  4619. if (INTEGER_REG_EXP.test(key)) {
  4620. for (const expression of expressionsToBeDeoptimized) {
  4621. expression.deoptimizeCache();
  4622. }
  4623. }
  4624. }
  4625. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  4626. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4627. }
  4628. }
  4629. getMemberExpression(key) {
  4630. if (this.hasLostTrack ||
  4631. this.hasUnknownDeoptimizedProperty ||
  4632. typeof key !== 'string' ||
  4633. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  4634. this.deoptimizedPaths[key]) {
  4635. return UNKNOWN_EXPRESSION;
  4636. }
  4637. const properties = this.propertiesAndGettersByKey[key];
  4638. if (properties?.length === 1) {
  4639. return properties[0];
  4640. }
  4641. if (properties ||
  4642. this.unmatchablePropertiesAndGetters.length > 0 ||
  4643. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  4644. return UNKNOWN_EXPRESSION;
  4645. }
  4646. return null;
  4647. }
  4648. getMemberExpressionAndTrackDeopt(key, origin) {
  4649. if (typeof key !== 'string') {
  4650. return UNKNOWN_EXPRESSION;
  4651. }
  4652. const expression = this.getMemberExpression(key);
  4653. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  4654. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  4655. this.expressionsToBeDeoptimizedByKey[key] || []);
  4656. expressionsToBeDeoptimized.push(origin);
  4657. }
  4658. return expression;
  4659. }
  4660. }
  4661. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  4662. // This makes sure unknown properties are not handled as "undefined" but as
  4663. // "unknown" but without access side effects. An exception is done for numeric
  4664. // properties as we do not expect new builtin properties to be numbers, this
  4665. // will improve tree-shaking for out-of-bounds array properties
  4666. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  4667. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  4668. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  4669. deoptimizeInteraction(interaction);
  4670. }
  4671. }
  4672. getLiteralValueAtPath(path) {
  4673. // We ignore number properties as we do not expect new properties to be
  4674. // numbers and also want to keep handling out-of-bound array elements as
  4675. // "undefined"
  4676. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  4677. }
  4678. hasEffectsOnInteractionAtPath(path, { type }) {
  4679. return path.length > 1 || type === INTERACTION_CALLED;
  4680. }
  4681. })();
  4682. const OBJECT_PROTOTYPE = new ObjectEntity({
  4683. __proto__: null,
  4684. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  4685. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  4686. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  4687. toLocaleString: METHOD_RETURNS_STRING,
  4688. toString: METHOD_RETURNS_STRING,
  4689. valueOf: METHOD_RETURNS_UNKNOWN
  4690. }, OBJECT_PROTOTYPE_FALLBACK, true);
  4691. const NEW_ARRAY_PROPERTIES = [
  4692. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  4693. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  4694. ];
  4695. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  4696. new Method({
  4697. callsArgs: [0],
  4698. mutatesArgs: false,
  4699. mutatesSelfAsArray: 'deopt-only',
  4700. returns: null,
  4701. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4702. })
  4703. ];
  4704. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  4705. new Method({
  4706. callsArgs: [0],
  4707. mutatesArgs: false,
  4708. mutatesSelfAsArray: 'deopt-only',
  4709. returns: null,
  4710. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4711. })
  4712. ];
  4713. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  4714. new Method({
  4715. callsArgs: null,
  4716. mutatesArgs: false,
  4717. mutatesSelfAsArray: true,
  4718. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4719. returnsPrimitive: null
  4720. })
  4721. ];
  4722. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4723. new Method({
  4724. callsArgs: null,
  4725. mutatesArgs: false,
  4726. mutatesSelfAsArray: 'deopt-only',
  4727. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4728. returnsPrimitive: null
  4729. })
  4730. ];
  4731. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  4732. new Method({
  4733. callsArgs: [0],
  4734. mutatesArgs: false,
  4735. mutatesSelfAsArray: 'deopt-only',
  4736. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  4737. returnsPrimitive: null
  4738. })
  4739. ];
  4740. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  4741. new Method({
  4742. callsArgs: null,
  4743. mutatesArgs: true,
  4744. mutatesSelfAsArray: true,
  4745. returns: null,
  4746. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4747. })
  4748. ];
  4749. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  4750. new Method({
  4751. callsArgs: null,
  4752. mutatesArgs: false,
  4753. mutatesSelfAsArray: true,
  4754. returns: null,
  4755. returnsPrimitive: UNKNOWN_EXPRESSION
  4756. })
  4757. ];
  4758. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4759. new Method({
  4760. callsArgs: null,
  4761. mutatesArgs: false,
  4762. mutatesSelfAsArray: 'deopt-only',
  4763. returns: null,
  4764. returnsPrimitive: UNKNOWN_EXPRESSION
  4765. })
  4766. ];
  4767. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  4768. new Method({
  4769. callsArgs: [0],
  4770. mutatesArgs: false,
  4771. mutatesSelfAsArray: 'deopt-only',
  4772. returns: null,
  4773. returnsPrimitive: UNKNOWN_EXPRESSION
  4774. })
  4775. ];
  4776. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  4777. new Method({
  4778. callsArgs: null,
  4779. mutatesArgs: false,
  4780. mutatesSelfAsArray: true,
  4781. returns: 'self',
  4782. returnsPrimitive: null
  4783. })
  4784. ];
  4785. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  4786. new Method({
  4787. callsArgs: [0],
  4788. mutatesArgs: false,
  4789. mutatesSelfAsArray: true,
  4790. returns: 'self',
  4791. returnsPrimitive: null
  4792. })
  4793. ];
  4794. const ARRAY_PROTOTYPE = new ObjectEntity({
  4795. __proto__: null,
  4796. // We assume that accessors have effects as we do not track the accessed value afterwards
  4797. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  4798. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4799. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  4800. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4801. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4802. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  4803. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4804. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4805. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4806. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4807. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  4808. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4809. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4810. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4811. includes: METHOD_RETURNS_BOOLEAN,
  4812. indexOf: METHOD_RETURNS_NUMBER,
  4813. join: METHOD_RETURNS_STRING,
  4814. keys: METHOD_RETURNS_UNKNOWN,
  4815. lastIndexOf: METHOD_RETURNS_NUMBER,
  4816. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4817. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4818. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4819. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4820. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  4821. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  4822. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  4823. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  4824. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  4825. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  4826. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  4827. toLocaleString: METHOD_RETURNS_STRING,
  4828. toString: METHOD_RETURNS_STRING,
  4829. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  4830. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  4831. }, OBJECT_PROTOTYPE, true);
  4832. class ArrayExpression extends NodeBase {
  4833. constructor() {
  4834. super(...arguments);
  4835. this.objectEntity = null;
  4836. }
  4837. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4838. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4839. }
  4840. deoptimizePath(path) {
  4841. this.getObjectEntity().deoptimizePath(path);
  4842. }
  4843. getLiteralValueAtPath(path, recursionTracker, origin) {
  4844. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  4845. }
  4846. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4847. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4848. }
  4849. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4850. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  4851. }
  4852. applyDeoptimizations() {
  4853. this.deoptimized = true;
  4854. let hasSpread = false;
  4855. for (let index = 0; index < this.elements.length; index++) {
  4856. const element = this.elements[index];
  4857. if (element && (hasSpread || element instanceof SpreadElement)) {
  4858. hasSpread = true;
  4859. element.deoptimizePath(UNKNOWN_PATH);
  4860. }
  4861. }
  4862. this.scope.context.requestTreeshakingPass();
  4863. }
  4864. getObjectEntity() {
  4865. if (this.objectEntity !== null) {
  4866. return this.objectEntity;
  4867. }
  4868. const properties = [
  4869. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  4870. ];
  4871. let hasSpread = false;
  4872. for (let index = 0; index < this.elements.length; index++) {
  4873. const element = this.elements[index];
  4874. if (hasSpread || element instanceof SpreadElement) {
  4875. if (element) {
  4876. hasSpread = true;
  4877. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  4878. }
  4879. }
  4880. else if (element) {
  4881. properties.push({ key: String(index), kind: 'init', property: element });
  4882. }
  4883. else {
  4884. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  4885. }
  4886. }
  4887. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  4888. }
  4889. }
  4890. /* eslint sort-keys: "off" */
  4891. const ValueProperties = Symbol('Value Properties');
  4892. const getTruthyLiteralValue = () => UnknownTruthyValue;
  4893. const returnFalse = () => false;
  4894. const returnTrue = () => true;
  4895. const PURE = {
  4896. deoptimizeArgumentsOnCall: doNothing,
  4897. getLiteralValue: getTruthyLiteralValue,
  4898. hasEffectsWhenCalled: returnFalse
  4899. };
  4900. const IMPURE = {
  4901. deoptimizeArgumentsOnCall: doNothing,
  4902. getLiteralValue: getTruthyLiteralValue,
  4903. hasEffectsWhenCalled: returnTrue
  4904. };
  4905. const PURE_WITH_ARRAY = {
  4906. deoptimizeArgumentsOnCall: doNothing,
  4907. getLiteralValue: getTruthyLiteralValue,
  4908. hasEffectsWhenCalled({ args }) {
  4909. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  4910. }
  4911. };
  4912. const GETTER_ACCESS = {
  4913. deoptimizeArgumentsOnCall: doNothing,
  4914. getLiteralValue: getTruthyLiteralValue,
  4915. hasEffectsWhenCalled({ args }, context) {
  4916. const [_thisArgument, firstArgument] = args;
  4917. return (!(firstArgument instanceof ExpressionEntity) ||
  4918. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4919. }
  4920. };
  4921. // We use shortened variables to reduce file size here
  4922. /* OBJECT */
  4923. const O = {
  4924. __proto__: null,
  4925. [ValueProperties]: IMPURE
  4926. };
  4927. /* PURE FUNCTION */
  4928. const PF = {
  4929. __proto__: null,
  4930. [ValueProperties]: PURE
  4931. };
  4932. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  4933. const PF_NO_GETTER = {
  4934. __proto__: null,
  4935. [ValueProperties]: GETTER_ACCESS
  4936. };
  4937. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  4938. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  4939. __proto__: null,
  4940. [ValueProperties]: {
  4941. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  4942. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  4943. },
  4944. getLiteralValue: getTruthyLiteralValue,
  4945. hasEffectsWhenCalled({ args }, context) {
  4946. return (args.length <= 1 ||
  4947. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  4948. }
  4949. }
  4950. };
  4951. /* CONSTRUCTOR */
  4952. const C = {
  4953. __proto__: null,
  4954. [ValueProperties]: IMPURE,
  4955. prototype: O
  4956. };
  4957. /* PURE CONSTRUCTOR */
  4958. const PC = {
  4959. __proto__: null,
  4960. [ValueProperties]: PURE,
  4961. prototype: O
  4962. };
  4963. const PC_WITH_ARRAY = {
  4964. __proto__: null,
  4965. [ValueProperties]: PURE_WITH_ARRAY,
  4966. prototype: O
  4967. };
  4968. const ARRAY_TYPE = {
  4969. __proto__: null,
  4970. [ValueProperties]: PURE,
  4971. from: O,
  4972. of: PF,
  4973. prototype: O
  4974. };
  4975. const INTL_MEMBER = {
  4976. __proto__: null,
  4977. [ValueProperties]: PURE,
  4978. supportedLocalesOf: PC
  4979. };
  4980. const knownGlobals = {
  4981. // Placeholders for global objects to avoid shape mutations
  4982. global: O,
  4983. globalThis: O,
  4984. self: O,
  4985. window: O,
  4986. // Common globals
  4987. __proto__: null,
  4988. [ValueProperties]: IMPURE,
  4989. Array: {
  4990. __proto__: null,
  4991. [ValueProperties]: IMPURE,
  4992. from: O,
  4993. isArray: PF,
  4994. of: PF,
  4995. prototype: O
  4996. },
  4997. ArrayBuffer: {
  4998. __proto__: null,
  4999. [ValueProperties]: PURE,
  5000. isView: PF,
  5001. prototype: O
  5002. },
  5003. AggregateError: PC_WITH_ARRAY,
  5004. Atomics: O,
  5005. BigInt: C,
  5006. BigInt64Array: C,
  5007. BigUint64Array: C,
  5008. Boolean: PC,
  5009. constructor: C,
  5010. DataView: PC,
  5011. Date: {
  5012. __proto__: null,
  5013. [ValueProperties]: PURE,
  5014. now: PF,
  5015. parse: PF,
  5016. prototype: O,
  5017. UTC: PF
  5018. },
  5019. decodeURI: PF,
  5020. decodeURIComponent: PF,
  5021. encodeURI: PF,
  5022. encodeURIComponent: PF,
  5023. Error: PC,
  5024. escape: PF,
  5025. eval: O,
  5026. EvalError: PC,
  5027. FinalizationRegistry: C,
  5028. Float32Array: ARRAY_TYPE,
  5029. Float64Array: ARRAY_TYPE,
  5030. Function: C,
  5031. hasOwnProperty: O,
  5032. Infinity: O,
  5033. Int16Array: ARRAY_TYPE,
  5034. Int32Array: ARRAY_TYPE,
  5035. Int8Array: ARRAY_TYPE,
  5036. isFinite: PF,
  5037. isNaN: PF,
  5038. isPrototypeOf: O,
  5039. JSON: O,
  5040. Map: PC_WITH_ARRAY,
  5041. Math: {
  5042. __proto__: null,
  5043. [ValueProperties]: IMPURE,
  5044. abs: PF,
  5045. acos: PF,
  5046. acosh: PF,
  5047. asin: PF,
  5048. asinh: PF,
  5049. atan: PF,
  5050. atan2: PF,
  5051. atanh: PF,
  5052. cbrt: PF,
  5053. ceil: PF,
  5054. clz32: PF,
  5055. cos: PF,
  5056. cosh: PF,
  5057. exp: PF,
  5058. expm1: PF,
  5059. floor: PF,
  5060. fround: PF,
  5061. hypot: PF,
  5062. imul: PF,
  5063. log: PF,
  5064. log10: PF,
  5065. log1p: PF,
  5066. log2: PF,
  5067. max: PF,
  5068. min: PF,
  5069. pow: PF,
  5070. random: PF,
  5071. round: PF,
  5072. sign: PF,
  5073. sin: PF,
  5074. sinh: PF,
  5075. sqrt: PF,
  5076. tan: PF,
  5077. tanh: PF,
  5078. trunc: PF
  5079. },
  5080. NaN: O,
  5081. Number: {
  5082. __proto__: null,
  5083. [ValueProperties]: PURE,
  5084. isFinite: PF,
  5085. isInteger: PF,
  5086. isNaN: PF,
  5087. isSafeInteger: PF,
  5088. parseFloat: PF,
  5089. parseInt: PF,
  5090. prototype: O
  5091. },
  5092. Object: {
  5093. __proto__: null,
  5094. [ValueProperties]: PURE,
  5095. create: PF,
  5096. // Technically those can throw in certain situations, but we ignore this as
  5097. // code that relies on this will hopefully wrap this in a try-catch, which
  5098. // deoptimizes everything anyway
  5099. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5100. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5101. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  5102. getOwnPropertyDescriptor: PF,
  5103. getOwnPropertyDescriptors: PF,
  5104. getOwnPropertyNames: PF,
  5105. getOwnPropertySymbols: PF,
  5106. getPrototypeOf: PF,
  5107. hasOwn: PF,
  5108. is: PF,
  5109. isExtensible: PF,
  5110. isFrozen: PF,
  5111. isSealed: PF,
  5112. keys: PF,
  5113. fromEntries: O,
  5114. entries: PF_NO_GETTER,
  5115. values: PF_NO_GETTER,
  5116. prototype: O
  5117. },
  5118. parseFloat: PF,
  5119. parseInt: PF,
  5120. Promise: {
  5121. __proto__: null,
  5122. [ValueProperties]: IMPURE,
  5123. all: O,
  5124. allSettled: O,
  5125. any: O,
  5126. prototype: O,
  5127. race: O,
  5128. reject: O,
  5129. resolve: O
  5130. },
  5131. propertyIsEnumerable: O,
  5132. Proxy: O,
  5133. RangeError: PC,
  5134. ReferenceError: PC,
  5135. Reflect: O,
  5136. RegExp: PC,
  5137. Set: PC_WITH_ARRAY,
  5138. SharedArrayBuffer: C,
  5139. String: {
  5140. __proto__: null,
  5141. [ValueProperties]: PURE,
  5142. fromCharCode: PF,
  5143. fromCodePoint: PF,
  5144. prototype: O,
  5145. raw: PF
  5146. },
  5147. Symbol: {
  5148. __proto__: null,
  5149. [ValueProperties]: PURE,
  5150. for: PF,
  5151. keyFor: PF,
  5152. prototype: O,
  5153. toStringTag: {
  5154. __proto__: null,
  5155. [ValueProperties]: {
  5156. deoptimizeArgumentsOnCall: doNothing,
  5157. getLiteralValue() {
  5158. return SymbolToStringTag;
  5159. },
  5160. hasEffectsWhenCalled: returnTrue
  5161. }
  5162. }
  5163. },
  5164. SyntaxError: PC,
  5165. toLocaleString: O,
  5166. toString: O,
  5167. TypeError: PC,
  5168. Uint16Array: ARRAY_TYPE,
  5169. Uint32Array: ARRAY_TYPE,
  5170. Uint8Array: ARRAY_TYPE,
  5171. Uint8ClampedArray: ARRAY_TYPE,
  5172. // Technically, this is a global, but it needs special handling
  5173. // undefined: ?,
  5174. unescape: PF,
  5175. URIError: PC,
  5176. valueOf: O,
  5177. WeakMap: PC_WITH_ARRAY,
  5178. WeakRef: C,
  5179. WeakSet: PC_WITH_ARRAY,
  5180. // Additional globals shared by Node and Browser that are not strictly part of the language
  5181. clearInterval: C,
  5182. clearTimeout: C,
  5183. console: {
  5184. __proto__: null,
  5185. [ValueProperties]: IMPURE,
  5186. assert: C,
  5187. clear: C,
  5188. count: C,
  5189. countReset: C,
  5190. debug: C,
  5191. dir: C,
  5192. dirxml: C,
  5193. error: C,
  5194. exception: C,
  5195. group: C,
  5196. groupCollapsed: C,
  5197. groupEnd: C,
  5198. info: C,
  5199. log: C,
  5200. table: C,
  5201. time: C,
  5202. timeEnd: C,
  5203. timeLog: C,
  5204. trace: C,
  5205. warn: C
  5206. },
  5207. Intl: {
  5208. __proto__: null,
  5209. [ValueProperties]: IMPURE,
  5210. Collator: INTL_MEMBER,
  5211. DateTimeFormat: INTL_MEMBER,
  5212. DisplayNames: INTL_MEMBER,
  5213. ListFormat: INTL_MEMBER,
  5214. Locale: INTL_MEMBER,
  5215. NumberFormat: INTL_MEMBER,
  5216. PluralRules: INTL_MEMBER,
  5217. RelativeTimeFormat: INTL_MEMBER,
  5218. Segmenter: INTL_MEMBER
  5219. },
  5220. setInterval: C,
  5221. setTimeout: C,
  5222. TextDecoder: C,
  5223. TextEncoder: C,
  5224. URL: {
  5225. __proto__: null,
  5226. [ValueProperties]: IMPURE,
  5227. prototype: O,
  5228. canParse: PF
  5229. },
  5230. URLSearchParams: C,
  5231. // Browser specific globals
  5232. AbortController: C,
  5233. AbortSignal: C,
  5234. addEventListener: O,
  5235. alert: O,
  5236. AnalyserNode: C,
  5237. Animation: C,
  5238. AnimationEvent: C,
  5239. applicationCache: O,
  5240. ApplicationCache: C,
  5241. ApplicationCacheErrorEvent: C,
  5242. atob: O,
  5243. Attr: C,
  5244. Audio: C,
  5245. AudioBuffer: C,
  5246. AudioBufferSourceNode: C,
  5247. AudioContext: C,
  5248. AudioDestinationNode: C,
  5249. AudioListener: C,
  5250. AudioNode: C,
  5251. AudioParam: C,
  5252. AudioProcessingEvent: C,
  5253. AudioScheduledSourceNode: C,
  5254. AudioWorkletNode: C,
  5255. BarProp: C,
  5256. BaseAudioContext: C,
  5257. BatteryManager: C,
  5258. BeforeUnloadEvent: C,
  5259. BiquadFilterNode: C,
  5260. Blob: C,
  5261. BlobEvent: C,
  5262. blur: O,
  5263. BroadcastChannel: C,
  5264. btoa: O,
  5265. ByteLengthQueuingStrategy: C,
  5266. Cache: C,
  5267. caches: O,
  5268. CacheStorage: C,
  5269. cancelAnimationFrame: O,
  5270. cancelIdleCallback: O,
  5271. CanvasCaptureMediaStreamTrack: C,
  5272. CanvasGradient: C,
  5273. CanvasPattern: C,
  5274. CanvasRenderingContext2D: C,
  5275. ChannelMergerNode: C,
  5276. ChannelSplitterNode: C,
  5277. CharacterData: C,
  5278. clientInformation: O,
  5279. ClipboardEvent: C,
  5280. close: O,
  5281. closed: O,
  5282. CloseEvent: C,
  5283. Comment: C,
  5284. CompositionEvent: C,
  5285. confirm: O,
  5286. ConstantSourceNode: C,
  5287. ConvolverNode: C,
  5288. CountQueuingStrategy: C,
  5289. createImageBitmap: O,
  5290. Credential: C,
  5291. CredentialsContainer: C,
  5292. crypto: O,
  5293. Crypto: C,
  5294. CryptoKey: C,
  5295. CSS: C,
  5296. CSSConditionRule: C,
  5297. CSSFontFaceRule: C,
  5298. CSSGroupingRule: C,
  5299. CSSImportRule: C,
  5300. CSSKeyframeRule: C,
  5301. CSSKeyframesRule: C,
  5302. CSSMediaRule: C,
  5303. CSSNamespaceRule: C,
  5304. CSSPageRule: C,
  5305. CSSRule: C,
  5306. CSSRuleList: C,
  5307. CSSStyleDeclaration: C,
  5308. CSSStyleRule: C,
  5309. CSSStyleSheet: C,
  5310. CSSSupportsRule: C,
  5311. CustomElementRegistry: C,
  5312. customElements: O,
  5313. CustomEvent: {
  5314. __proto__: null,
  5315. [ValueProperties]: {
  5316. deoptimizeArgumentsOnCall({ args }) {
  5317. args[2]?.deoptimizePath(['detail']);
  5318. },
  5319. getLiteralValue: getTruthyLiteralValue,
  5320. hasEffectsWhenCalled: returnFalse
  5321. },
  5322. prototype: O
  5323. },
  5324. DataTransfer: C,
  5325. DataTransferItem: C,
  5326. DataTransferItemList: C,
  5327. defaultstatus: O,
  5328. defaultStatus: O,
  5329. DelayNode: C,
  5330. DeviceMotionEvent: C,
  5331. DeviceOrientationEvent: C,
  5332. devicePixelRatio: O,
  5333. dispatchEvent: O,
  5334. document: O,
  5335. Document: C,
  5336. DocumentFragment: C,
  5337. DocumentType: C,
  5338. DOMError: C,
  5339. DOMException: C,
  5340. DOMImplementation: C,
  5341. DOMMatrix: C,
  5342. DOMMatrixReadOnly: C,
  5343. DOMParser: C,
  5344. DOMPoint: C,
  5345. DOMPointReadOnly: C,
  5346. DOMQuad: C,
  5347. DOMRect: C,
  5348. DOMRectReadOnly: C,
  5349. DOMStringList: C,
  5350. DOMStringMap: C,
  5351. DOMTokenList: C,
  5352. DragEvent: C,
  5353. DynamicsCompressorNode: C,
  5354. Element: C,
  5355. ErrorEvent: C,
  5356. Event: C,
  5357. EventSource: C,
  5358. EventTarget: C,
  5359. external: O,
  5360. fetch: O,
  5361. File: C,
  5362. FileList: C,
  5363. FileReader: C,
  5364. find: O,
  5365. focus: O,
  5366. FocusEvent: C,
  5367. FontFace: C,
  5368. FontFaceSetLoadEvent: C,
  5369. FormData: C,
  5370. frames: O,
  5371. GainNode: C,
  5372. Gamepad: C,
  5373. GamepadButton: C,
  5374. GamepadEvent: C,
  5375. getComputedStyle: O,
  5376. getSelection: O,
  5377. HashChangeEvent: C,
  5378. Headers: C,
  5379. history: O,
  5380. History: C,
  5381. HTMLAllCollection: C,
  5382. HTMLAnchorElement: C,
  5383. HTMLAreaElement: C,
  5384. HTMLAudioElement: C,
  5385. HTMLBaseElement: C,
  5386. HTMLBodyElement: C,
  5387. HTMLBRElement: C,
  5388. HTMLButtonElement: C,
  5389. HTMLCanvasElement: C,
  5390. HTMLCollection: C,
  5391. HTMLContentElement: C,
  5392. HTMLDataElement: C,
  5393. HTMLDataListElement: C,
  5394. HTMLDetailsElement: C,
  5395. HTMLDialogElement: C,
  5396. HTMLDirectoryElement: C,
  5397. HTMLDivElement: C,
  5398. HTMLDListElement: C,
  5399. HTMLDocument: C,
  5400. HTMLElement: C,
  5401. HTMLEmbedElement: C,
  5402. HTMLFieldSetElement: C,
  5403. HTMLFontElement: C,
  5404. HTMLFormControlsCollection: C,
  5405. HTMLFormElement: C,
  5406. HTMLFrameElement: C,
  5407. HTMLFrameSetElement: C,
  5408. HTMLHeadElement: C,
  5409. HTMLHeadingElement: C,
  5410. HTMLHRElement: C,
  5411. HTMLHtmlElement: C,
  5412. HTMLIFrameElement: C,
  5413. HTMLImageElement: C,
  5414. HTMLInputElement: C,
  5415. HTMLLabelElement: C,
  5416. HTMLLegendElement: C,
  5417. HTMLLIElement: C,
  5418. HTMLLinkElement: C,
  5419. HTMLMapElement: C,
  5420. HTMLMarqueeElement: C,
  5421. HTMLMediaElement: C,
  5422. HTMLMenuElement: C,
  5423. HTMLMetaElement: C,
  5424. HTMLMeterElement: C,
  5425. HTMLModElement: C,
  5426. HTMLObjectElement: C,
  5427. HTMLOListElement: C,
  5428. HTMLOptGroupElement: C,
  5429. HTMLOptionElement: C,
  5430. HTMLOptionsCollection: C,
  5431. HTMLOutputElement: C,
  5432. HTMLParagraphElement: C,
  5433. HTMLParamElement: C,
  5434. HTMLPictureElement: C,
  5435. HTMLPreElement: C,
  5436. HTMLProgressElement: C,
  5437. HTMLQuoteElement: C,
  5438. HTMLScriptElement: C,
  5439. HTMLSelectElement: C,
  5440. HTMLShadowElement: C,
  5441. HTMLSlotElement: C,
  5442. HTMLSourceElement: C,
  5443. HTMLSpanElement: C,
  5444. HTMLStyleElement: C,
  5445. HTMLTableCaptionElement: C,
  5446. HTMLTableCellElement: C,
  5447. HTMLTableColElement: C,
  5448. HTMLTableElement: C,
  5449. HTMLTableRowElement: C,
  5450. HTMLTableSectionElement: C,
  5451. HTMLTemplateElement: C,
  5452. HTMLTextAreaElement: C,
  5453. HTMLTimeElement: C,
  5454. HTMLTitleElement: C,
  5455. HTMLTrackElement: C,
  5456. HTMLUListElement: C,
  5457. HTMLUnknownElement: C,
  5458. HTMLVideoElement: C,
  5459. IDBCursor: C,
  5460. IDBCursorWithValue: C,
  5461. IDBDatabase: C,
  5462. IDBFactory: C,
  5463. IDBIndex: C,
  5464. IDBKeyRange: C,
  5465. IDBObjectStore: C,
  5466. IDBOpenDBRequest: C,
  5467. IDBRequest: C,
  5468. IDBTransaction: C,
  5469. IDBVersionChangeEvent: C,
  5470. IdleDeadline: C,
  5471. IIRFilterNode: C,
  5472. Image: C,
  5473. ImageBitmap: C,
  5474. ImageBitmapRenderingContext: C,
  5475. ImageCapture: C,
  5476. ImageData: C,
  5477. indexedDB: O,
  5478. innerHeight: O,
  5479. innerWidth: O,
  5480. InputEvent: C,
  5481. IntersectionObserver: C,
  5482. IntersectionObserverEntry: C,
  5483. isSecureContext: O,
  5484. KeyboardEvent: C,
  5485. KeyframeEffect: C,
  5486. length: O,
  5487. localStorage: O,
  5488. location: O,
  5489. Location: C,
  5490. locationbar: O,
  5491. matchMedia: O,
  5492. MediaDeviceInfo: C,
  5493. MediaDevices: C,
  5494. MediaElementAudioSourceNode: C,
  5495. MediaEncryptedEvent: C,
  5496. MediaError: C,
  5497. MediaKeyMessageEvent: C,
  5498. MediaKeySession: C,
  5499. MediaKeyStatusMap: C,
  5500. MediaKeySystemAccess: C,
  5501. MediaList: C,
  5502. MediaQueryList: C,
  5503. MediaQueryListEvent: C,
  5504. MediaRecorder: C,
  5505. MediaSettingsRange: C,
  5506. MediaSource: C,
  5507. MediaStream: C,
  5508. MediaStreamAudioDestinationNode: C,
  5509. MediaStreamAudioSourceNode: C,
  5510. MediaStreamEvent: C,
  5511. MediaStreamTrack: C,
  5512. MediaStreamTrackEvent: C,
  5513. menubar: O,
  5514. MessageChannel: C,
  5515. MessageEvent: C,
  5516. MessagePort: C,
  5517. MIDIAccess: C,
  5518. MIDIConnectionEvent: C,
  5519. MIDIInput: C,
  5520. MIDIInputMap: C,
  5521. MIDIMessageEvent: C,
  5522. MIDIOutput: C,
  5523. MIDIOutputMap: C,
  5524. MIDIPort: C,
  5525. MimeType: C,
  5526. MimeTypeArray: C,
  5527. MouseEvent: C,
  5528. moveBy: O,
  5529. moveTo: O,
  5530. MutationEvent: C,
  5531. MutationObserver: C,
  5532. MutationRecord: C,
  5533. name: O,
  5534. NamedNodeMap: C,
  5535. NavigationPreloadManager: C,
  5536. navigator: O,
  5537. Navigator: C,
  5538. NetworkInformation: C,
  5539. Node: C,
  5540. NodeFilter: O,
  5541. NodeIterator: C,
  5542. NodeList: C,
  5543. Notification: C,
  5544. OfflineAudioCompletionEvent: C,
  5545. OfflineAudioContext: C,
  5546. offscreenBuffering: O,
  5547. OffscreenCanvas: C,
  5548. open: O,
  5549. openDatabase: O,
  5550. Option: C,
  5551. origin: O,
  5552. OscillatorNode: C,
  5553. outerHeight: O,
  5554. outerWidth: O,
  5555. PageTransitionEvent: C,
  5556. pageXOffset: O,
  5557. pageYOffset: O,
  5558. PannerNode: C,
  5559. parent: O,
  5560. Path2D: C,
  5561. PaymentAddress: C,
  5562. PaymentRequest: C,
  5563. PaymentRequestUpdateEvent: C,
  5564. PaymentResponse: C,
  5565. performance: O,
  5566. Performance: C,
  5567. PerformanceEntry: C,
  5568. PerformanceLongTaskTiming: C,
  5569. PerformanceMark: C,
  5570. PerformanceMeasure: C,
  5571. PerformanceNavigation: C,
  5572. PerformanceNavigationTiming: C,
  5573. PerformanceObserver: C,
  5574. PerformanceObserverEntryList: C,
  5575. PerformancePaintTiming: C,
  5576. PerformanceResourceTiming: C,
  5577. PerformanceTiming: C,
  5578. PeriodicWave: C,
  5579. Permissions: C,
  5580. PermissionStatus: C,
  5581. personalbar: O,
  5582. PhotoCapabilities: C,
  5583. Plugin: C,
  5584. PluginArray: C,
  5585. PointerEvent: C,
  5586. PopStateEvent: C,
  5587. postMessage: O,
  5588. Presentation: C,
  5589. PresentationAvailability: C,
  5590. PresentationConnection: C,
  5591. PresentationConnectionAvailableEvent: C,
  5592. PresentationConnectionCloseEvent: C,
  5593. PresentationConnectionList: C,
  5594. PresentationReceiver: C,
  5595. PresentationRequest: C,
  5596. print: O,
  5597. ProcessingInstruction: C,
  5598. ProgressEvent: C,
  5599. PromiseRejectionEvent: C,
  5600. prompt: O,
  5601. PushManager: C,
  5602. PushSubscription: C,
  5603. PushSubscriptionOptions: C,
  5604. queueMicrotask: O,
  5605. RadioNodeList: C,
  5606. Range: C,
  5607. ReadableStream: C,
  5608. RemotePlayback: C,
  5609. removeEventListener: O,
  5610. Request: C,
  5611. requestAnimationFrame: O,
  5612. requestIdleCallback: O,
  5613. resizeBy: O,
  5614. ResizeObserver: C,
  5615. ResizeObserverEntry: C,
  5616. resizeTo: O,
  5617. Response: C,
  5618. RTCCertificate: C,
  5619. RTCDataChannel: C,
  5620. RTCDataChannelEvent: C,
  5621. RTCDtlsTransport: C,
  5622. RTCIceCandidate: C,
  5623. RTCIceTransport: C,
  5624. RTCPeerConnection: C,
  5625. RTCPeerConnectionIceEvent: C,
  5626. RTCRtpReceiver: C,
  5627. RTCRtpSender: C,
  5628. RTCSctpTransport: C,
  5629. RTCSessionDescription: C,
  5630. RTCStatsReport: C,
  5631. RTCTrackEvent: C,
  5632. screen: O,
  5633. Screen: C,
  5634. screenLeft: O,
  5635. ScreenOrientation: C,
  5636. screenTop: O,
  5637. screenX: O,
  5638. screenY: O,
  5639. ScriptProcessorNode: C,
  5640. scroll: O,
  5641. scrollbars: O,
  5642. scrollBy: O,
  5643. scrollTo: O,
  5644. scrollX: O,
  5645. scrollY: O,
  5646. SecurityPolicyViolationEvent: C,
  5647. Selection: C,
  5648. ServiceWorker: C,
  5649. ServiceWorkerContainer: C,
  5650. ServiceWorkerRegistration: C,
  5651. sessionStorage: O,
  5652. ShadowRoot: C,
  5653. SharedWorker: C,
  5654. SourceBuffer: C,
  5655. SourceBufferList: C,
  5656. speechSynthesis: O,
  5657. SpeechSynthesisEvent: C,
  5658. SpeechSynthesisUtterance: C,
  5659. StaticRange: C,
  5660. status: O,
  5661. statusbar: O,
  5662. StereoPannerNode: C,
  5663. stop: O,
  5664. Storage: C,
  5665. StorageEvent: C,
  5666. StorageManager: C,
  5667. styleMedia: O,
  5668. StyleSheet: C,
  5669. StyleSheetList: C,
  5670. SubtleCrypto: C,
  5671. SVGAElement: C,
  5672. SVGAngle: C,
  5673. SVGAnimatedAngle: C,
  5674. SVGAnimatedBoolean: C,
  5675. SVGAnimatedEnumeration: C,
  5676. SVGAnimatedInteger: C,
  5677. SVGAnimatedLength: C,
  5678. SVGAnimatedLengthList: C,
  5679. SVGAnimatedNumber: C,
  5680. SVGAnimatedNumberList: C,
  5681. SVGAnimatedPreserveAspectRatio: C,
  5682. SVGAnimatedRect: C,
  5683. SVGAnimatedString: C,
  5684. SVGAnimatedTransformList: C,
  5685. SVGAnimateElement: C,
  5686. SVGAnimateMotionElement: C,
  5687. SVGAnimateTransformElement: C,
  5688. SVGAnimationElement: C,
  5689. SVGCircleElement: C,
  5690. SVGClipPathElement: C,
  5691. SVGComponentTransferFunctionElement: C,
  5692. SVGDefsElement: C,
  5693. SVGDescElement: C,
  5694. SVGDiscardElement: C,
  5695. SVGElement: C,
  5696. SVGEllipseElement: C,
  5697. SVGFEBlendElement: C,
  5698. SVGFEColorMatrixElement: C,
  5699. SVGFEComponentTransferElement: C,
  5700. SVGFECompositeElement: C,
  5701. SVGFEConvolveMatrixElement: C,
  5702. SVGFEDiffuseLightingElement: C,
  5703. SVGFEDisplacementMapElement: C,
  5704. SVGFEDistantLightElement: C,
  5705. SVGFEDropShadowElement: C,
  5706. SVGFEFloodElement: C,
  5707. SVGFEFuncAElement: C,
  5708. SVGFEFuncBElement: C,
  5709. SVGFEFuncGElement: C,
  5710. SVGFEFuncRElement: C,
  5711. SVGFEGaussianBlurElement: C,
  5712. SVGFEImageElement: C,
  5713. SVGFEMergeElement: C,
  5714. SVGFEMergeNodeElement: C,
  5715. SVGFEMorphologyElement: C,
  5716. SVGFEOffsetElement: C,
  5717. SVGFEPointLightElement: C,
  5718. SVGFESpecularLightingElement: C,
  5719. SVGFESpotLightElement: C,
  5720. SVGFETileElement: C,
  5721. SVGFETurbulenceElement: C,
  5722. SVGFilterElement: C,
  5723. SVGForeignObjectElement: C,
  5724. SVGGElement: C,
  5725. SVGGeometryElement: C,
  5726. SVGGradientElement: C,
  5727. SVGGraphicsElement: C,
  5728. SVGImageElement: C,
  5729. SVGLength: C,
  5730. SVGLengthList: C,
  5731. SVGLinearGradientElement: C,
  5732. SVGLineElement: C,
  5733. SVGMarkerElement: C,
  5734. SVGMaskElement: C,
  5735. SVGMatrix: C,
  5736. SVGMetadataElement: C,
  5737. SVGMPathElement: C,
  5738. SVGNumber: C,
  5739. SVGNumberList: C,
  5740. SVGPathElement: C,
  5741. SVGPatternElement: C,
  5742. SVGPoint: C,
  5743. SVGPointList: C,
  5744. SVGPolygonElement: C,
  5745. SVGPolylineElement: C,
  5746. SVGPreserveAspectRatio: C,
  5747. SVGRadialGradientElement: C,
  5748. SVGRect: C,
  5749. SVGRectElement: C,
  5750. SVGScriptElement: C,
  5751. SVGSetElement: C,
  5752. SVGStopElement: C,
  5753. SVGStringList: C,
  5754. SVGStyleElement: C,
  5755. SVGSVGElement: C,
  5756. SVGSwitchElement: C,
  5757. SVGSymbolElement: C,
  5758. SVGTextContentElement: C,
  5759. SVGTextElement: C,
  5760. SVGTextPathElement: C,
  5761. SVGTextPositioningElement: C,
  5762. SVGTitleElement: C,
  5763. SVGTransform: C,
  5764. SVGTransformList: C,
  5765. SVGTSpanElement: C,
  5766. SVGUnitTypes: C,
  5767. SVGUseElement: C,
  5768. SVGViewElement: C,
  5769. TaskAttributionTiming: C,
  5770. Text: C,
  5771. TextEvent: C,
  5772. TextMetrics: C,
  5773. TextTrack: C,
  5774. TextTrackCue: C,
  5775. TextTrackCueList: C,
  5776. TextTrackList: C,
  5777. TimeRanges: C,
  5778. toolbar: O,
  5779. top: O,
  5780. Touch: C,
  5781. TouchEvent: C,
  5782. TouchList: C,
  5783. TrackEvent: C,
  5784. TransitionEvent: C,
  5785. TreeWalker: C,
  5786. UIEvent: C,
  5787. ValidityState: C,
  5788. visualViewport: O,
  5789. VisualViewport: C,
  5790. VTTCue: C,
  5791. WaveShaperNode: C,
  5792. WebAssembly: O,
  5793. WebGL2RenderingContext: C,
  5794. WebGLActiveInfo: C,
  5795. WebGLBuffer: C,
  5796. WebGLContextEvent: C,
  5797. WebGLFramebuffer: C,
  5798. WebGLProgram: C,
  5799. WebGLQuery: C,
  5800. WebGLRenderbuffer: C,
  5801. WebGLRenderingContext: C,
  5802. WebGLSampler: C,
  5803. WebGLShader: C,
  5804. WebGLShaderPrecisionFormat: C,
  5805. WebGLSync: C,
  5806. WebGLTexture: C,
  5807. WebGLTransformFeedback: C,
  5808. WebGLUniformLocation: C,
  5809. WebGLVertexArrayObject: C,
  5810. WebSocket: C,
  5811. WheelEvent: C,
  5812. Window: C,
  5813. Worker: C,
  5814. WritableStream: C,
  5815. XMLDocument: C,
  5816. XMLHttpRequest: C,
  5817. XMLHttpRequestEventTarget: C,
  5818. XMLHttpRequestUpload: C,
  5819. XMLSerializer: C,
  5820. XPathEvaluator: C,
  5821. XPathExpression: C,
  5822. XPathResult: C,
  5823. XSLTProcessor: C
  5824. };
  5825. for (const global of ['window', 'global', 'self', 'globalThis']) {
  5826. knownGlobals[global] = knownGlobals;
  5827. }
  5828. function getGlobalAtPath(path) {
  5829. let currentGlobal = knownGlobals;
  5830. for (const pathSegment of path) {
  5831. if (typeof pathSegment !== 'string') {
  5832. return null;
  5833. }
  5834. currentGlobal = currentGlobal[pathSegment];
  5835. if (!currentGlobal) {
  5836. return null;
  5837. }
  5838. }
  5839. return currentGlobal[ValueProperties];
  5840. }
  5841. class GlobalVariable extends Variable {
  5842. constructor(name) {
  5843. super(name);
  5844. // Ensure we use live-bindings for globals as we do not know if they have
  5845. // been reassigned
  5846. this.markReassigned();
  5847. }
  5848. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5849. switch (interaction.type) {
  5850. // While there is no point in testing these cases as at the moment, they
  5851. // are also covered via other means, we keep them for completeness
  5852. case INTERACTION_ACCESSED:
  5853. case INTERACTION_ASSIGNED: {
  5854. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  5855. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5856. }
  5857. return;
  5858. }
  5859. case INTERACTION_CALLED: {
  5860. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  5861. if (globalAtPath) {
  5862. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  5863. }
  5864. else {
  5865. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5866. }
  5867. return;
  5868. }
  5869. }
  5870. }
  5871. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  5872. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  5873. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  5874. }
  5875. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5876. switch (interaction.type) {
  5877. case INTERACTION_ACCESSED: {
  5878. if (path.length === 0) {
  5879. // Technically, "undefined" is a global variable of sorts
  5880. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  5881. }
  5882. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  5883. }
  5884. case INTERACTION_ASSIGNED: {
  5885. return true;
  5886. }
  5887. case INTERACTION_CALLED: {
  5888. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  5889. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  5890. }
  5891. }
  5892. }
  5893. }
  5894. class LocalVariable extends Variable {
  5895. constructor(name, declarator, init, context, kind) {
  5896. super(name);
  5897. this.init = init;
  5898. this.calledFromTryStatement = false;
  5899. this.additionalInitializers = null;
  5900. this.expressionsToBeDeoptimized = [];
  5901. this.declarations = declarator ? [declarator] : [];
  5902. this.deoptimizationTracker = context.deoptimizationTracker;
  5903. this.module = context.module;
  5904. this.kind = kind;
  5905. }
  5906. addDeclaration(identifier, init) {
  5907. this.declarations.push(identifier);
  5908. this.markInitializersForDeoptimization().push(init);
  5909. }
  5910. consolidateInitializers() {
  5911. if (this.additionalInitializers) {
  5912. for (const initializer of this.additionalInitializers) {
  5913. initializer.deoptimizePath(UNKNOWN_PATH);
  5914. }
  5915. this.additionalInitializers = null;
  5916. }
  5917. }
  5918. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5919. if (this.isReassigned) {
  5920. deoptimizeInteraction(interaction);
  5921. return;
  5922. }
  5923. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5924. }
  5925. deoptimizePath(path) {
  5926. if (this.isReassigned ||
  5927. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5928. return;
  5929. }
  5930. if (path.length === 0) {
  5931. this.markReassigned();
  5932. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5933. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  5934. for (const expression of expressionsToBeDeoptimized) {
  5935. expression.deoptimizeCache();
  5936. }
  5937. this.init.deoptimizePath(UNKNOWN_PATH);
  5938. }
  5939. else {
  5940. this.init.deoptimizePath(path);
  5941. }
  5942. }
  5943. getLiteralValueAtPath(path, recursionTracker, origin) {
  5944. if (this.isReassigned) {
  5945. return UnknownValue;
  5946. }
  5947. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5948. this.expressionsToBeDeoptimized.push(origin);
  5949. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5950. }, UnknownValue);
  5951. }
  5952. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5953. if (this.isReassigned) {
  5954. return UNKNOWN_RETURN_EXPRESSION;
  5955. }
  5956. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5957. this.expressionsToBeDeoptimized.push(origin);
  5958. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5959. }, UNKNOWN_RETURN_EXPRESSION);
  5960. }
  5961. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5962. switch (interaction.type) {
  5963. case INTERACTION_ACCESSED: {
  5964. if (this.isReassigned)
  5965. return true;
  5966. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5967. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5968. }
  5969. case INTERACTION_ASSIGNED: {
  5970. if (this.included)
  5971. return true;
  5972. if (path.length === 0)
  5973. return false;
  5974. if (this.isReassigned)
  5975. return true;
  5976. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5977. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5978. }
  5979. case INTERACTION_CALLED: {
  5980. if (this.isReassigned)
  5981. return true;
  5982. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5983. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5984. }
  5985. }
  5986. }
  5987. include() {
  5988. if (!this.included) {
  5989. super.include();
  5990. for (const declaration of this.declarations) {
  5991. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5992. if (!declaration.included)
  5993. declaration.include(createInclusionContext(), false);
  5994. let node = declaration.parent;
  5995. while (!node.included) {
  5996. // We do not want to properly include parents in case they are part of a dead branch
  5997. // in which case .include() might pull in more dead code
  5998. node.included = true;
  5999. if (node.type === parseAst_js.Program)
  6000. break;
  6001. node = node.parent;
  6002. }
  6003. }
  6004. }
  6005. }
  6006. includeCallArguments(context, parameters) {
  6007. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  6008. for (const argument of parameters) {
  6009. argument.include(context, false);
  6010. }
  6011. }
  6012. else {
  6013. context.includedCallArguments.add(this.init);
  6014. this.init.includeCallArguments(context, parameters);
  6015. context.includedCallArguments.delete(this.init);
  6016. }
  6017. }
  6018. markCalledFromTryStatement() {
  6019. this.calledFromTryStatement = true;
  6020. }
  6021. markInitializersForDeoptimization() {
  6022. if (this.additionalInitializers === null) {
  6023. this.additionalInitializers = [this.init];
  6024. this.init = UNKNOWN_EXPRESSION;
  6025. this.markReassigned();
  6026. }
  6027. return this.additionalInitializers;
  6028. }
  6029. }
  6030. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  6031. class IdentifierBase extends NodeBase {
  6032. constructor() {
  6033. super(...arguments);
  6034. this.variable = null;
  6035. this.isVariableReference = false;
  6036. }
  6037. get isTDZAccess() {
  6038. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  6039. return null;
  6040. }
  6041. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  6042. }
  6043. set isTDZAccess(value) {
  6044. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  6045. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  6046. }
  6047. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6048. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6049. }
  6050. deoptimizePath(path) {
  6051. if (path.length === 0 && !this.scope.contains(this.name)) {
  6052. this.disallowImportReassignment();
  6053. }
  6054. // We keep conditional chaining because an unknown Node could have an
  6055. // Identifier as property that might be deoptimized by default
  6056. this.variable?.deoptimizePath(path);
  6057. }
  6058. getLiteralValueAtPath(path, recursionTracker, origin) {
  6059. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6060. }
  6061. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6062. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6063. return [expression, isPure || this.isPureFunction(path)];
  6064. }
  6065. hasEffects(context) {
  6066. if (!this.deoptimized)
  6067. this.applyDeoptimizations();
  6068. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6069. return true;
  6070. }
  6071. return (this.scope.context.options.treeshake
  6072. .unknownGlobalSideEffects &&
  6073. this.variable instanceof GlobalVariable &&
  6074. !this.isPureFunction(EMPTY_PATH) &&
  6075. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6076. }
  6077. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6078. switch (interaction.type) {
  6079. case INTERACTION_ACCESSED: {
  6080. return (this.variable !== null &&
  6081. !this.isPureFunction(path) &&
  6082. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6083. }
  6084. case INTERACTION_ASSIGNED: {
  6085. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6086. }
  6087. case INTERACTION_CALLED: {
  6088. return (!this.isPureFunction(path) &&
  6089. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6090. }
  6091. }
  6092. }
  6093. include() {
  6094. if (!this.deoptimized)
  6095. this.applyDeoptimizations();
  6096. if (!this.included) {
  6097. this.included = true;
  6098. if (this.variable !== null) {
  6099. this.scope.context.includeVariableInModule(this.variable);
  6100. }
  6101. }
  6102. }
  6103. includeCallArguments(context, parameters) {
  6104. this.variable.includeCallArguments(context, parameters);
  6105. }
  6106. isPossibleTDZ() {
  6107. // return cached value to avoid issues with the next tree-shaking pass
  6108. const cachedTdzAccess = this.isTDZAccess;
  6109. if (cachedTdzAccess !== null)
  6110. return cachedTdzAccess;
  6111. if (!(this.variable instanceof LocalVariable &&
  6112. this.variable.kind &&
  6113. tdzVariableKinds.has(this.variable.kind) &&
  6114. // We ignore modules that did not receive a treeshaking pass yet as that
  6115. // causes many false positives due to circular dependencies or disabled
  6116. // moduleSideEffects.
  6117. this.variable.module.hasTreeShakingPassStarted)) {
  6118. return (this.isTDZAccess = false);
  6119. }
  6120. let decl_id;
  6121. if (this.variable.declarations &&
  6122. this.variable.declarations.length === 1 &&
  6123. (decl_id = this.variable.declarations[0]) &&
  6124. this.start < decl_id.start &&
  6125. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6126. // a variable accessed before its declaration
  6127. // in the same function or at top level of module
  6128. return (this.isTDZAccess = true);
  6129. }
  6130. if (!this.variable.initReached) {
  6131. // Either a const/let TDZ violation or
  6132. // var use before declaration was encountered.
  6133. return (this.isTDZAccess = true);
  6134. }
  6135. return (this.isTDZAccess = false);
  6136. }
  6137. applyDeoptimizations() {
  6138. this.deoptimized = true;
  6139. if (this.variable instanceof LocalVariable) {
  6140. // When accessing a variable from a module without side effects, this
  6141. // means we use an export of that module and therefore need to potentially
  6142. // include it in the bundle.
  6143. if (!this.variable.module.isExecuted) {
  6144. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  6145. }
  6146. this.variable.consolidateInitializers();
  6147. this.scope.context.requestTreeshakingPass();
  6148. }
  6149. if (this.isVariableReference) {
  6150. this.variable.addUsedPlace(this);
  6151. this.scope.context.requestTreeshakingPass();
  6152. }
  6153. }
  6154. disallowImportReassignment() {
  6155. return this.scope.context.error(parseAst_js.logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  6156. }
  6157. getVariableRespectingTDZ() {
  6158. if (this.isPossibleTDZ()) {
  6159. return UNKNOWN_EXPRESSION;
  6160. }
  6161. return this.variable;
  6162. }
  6163. isPureFunction(path) {
  6164. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  6165. for (const segment of path) {
  6166. if (currentPureFunction) {
  6167. if (currentPureFunction[PureFunctionKey]) {
  6168. return true;
  6169. }
  6170. currentPureFunction = currentPureFunction[segment];
  6171. }
  6172. else {
  6173. return false;
  6174. }
  6175. }
  6176. return currentPureFunction?.[PureFunctionKey];
  6177. }
  6178. }
  6179. function closestParentFunctionOrProgram(node) {
  6180. while (node && !/^Program|Function/.test(node.type)) {
  6181. node = node.parent;
  6182. }
  6183. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6184. return node;
  6185. }
  6186. class Identifier extends IdentifierBase {
  6187. constructor() {
  6188. super(...arguments);
  6189. this.variable = null;
  6190. }
  6191. addExportedVariables(variables, exportNamesByVariable) {
  6192. if (exportNamesByVariable.has(this.variable)) {
  6193. variables.push(this.variable);
  6194. }
  6195. }
  6196. bind() {
  6197. if (!this.variable && is_reference(this, this.parent)) {
  6198. this.variable = this.scope.findVariable(this.name);
  6199. this.variable.addReference(this);
  6200. this.isVariableReference = true;
  6201. }
  6202. }
  6203. declare(kind, init) {
  6204. let variable;
  6205. const { treeshake } = this.scope.context.options;
  6206. switch (kind) {
  6207. case 'var': {
  6208. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6209. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6210. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6211. variable.markInitializersForDeoptimization();
  6212. }
  6213. break;
  6214. }
  6215. case 'function': {
  6216. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6217. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6218. break;
  6219. }
  6220. case 'let':
  6221. case 'const':
  6222. case 'using':
  6223. case 'await using':
  6224. case 'class': {
  6225. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  6226. break;
  6227. }
  6228. case 'parameter': {
  6229. variable = this.scope.addParameterDeclaration(this);
  6230. break;
  6231. }
  6232. /* istanbul ignore next */
  6233. default: {
  6234. /* istanbul ignore next */
  6235. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6236. }
  6237. }
  6238. return [(this.variable = variable)];
  6239. }
  6240. markDeclarationReached() {
  6241. this.variable.initReached = true;
  6242. }
  6243. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = parseAst_js.BLANK) {
  6244. if (this.variable) {
  6245. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  6246. if (name !== this.name) {
  6247. code.overwrite(this.start, this.end, name, {
  6248. contentOnly: true,
  6249. storeName: true
  6250. });
  6251. if (isShorthandProperty) {
  6252. code.prependRight(this.start, `${this.name}: `);
  6253. }
  6254. }
  6255. // In strict mode, any variable named "eval" must be the actual "eval" function
  6256. if (name === 'eval' &&
  6257. renderedParentType === parseAst_js.CallExpression &&
  6258. isCalleeOfRenderedParent) {
  6259. code.appendRight(this.start, '0, ');
  6260. }
  6261. }
  6262. }
  6263. }
  6264. function getSafeName(baseName, usedNames, forbiddenNames) {
  6265. let safeName = baseName;
  6266. let count = 1;
  6267. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  6268. safeName = `${baseName}$${toBase64(count++)}`;
  6269. }
  6270. usedNames.add(safeName);
  6271. return safeName;
  6272. }
  6273. class Scope {
  6274. constructor() {
  6275. this.children = [];
  6276. this.variables = new Map();
  6277. }
  6278. /*
  6279. Redeclaration rules:
  6280. - var can redeclare var
  6281. - in function scopes, function and var can redeclare function and var
  6282. - var is hoisted across scopes, function remains in the scope it is declared
  6283. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  6284. - function cannot redeclare catch scope parameters
  6285. - var can redeclare catch scope parameters in a way
  6286. - if the parameter is an identifier and not a pattern
  6287. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  6288. - const, let, class, and function except in the cases above cannot redeclare anything
  6289. */
  6290. addDeclaration(identifier, context, init, kind) {
  6291. const name = identifier.name;
  6292. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6293. if (existingVariable) {
  6294. const existingKind = existingVariable.kind;
  6295. if (kind === 'var' && existingKind === 'var') {
  6296. existingVariable.addDeclaration(identifier, init);
  6297. return existingVariable;
  6298. }
  6299. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  6300. }
  6301. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  6302. this.variables.set(name, newVariable);
  6303. return newVariable;
  6304. }
  6305. addHoistedVariable(name, variable) {
  6306. (this.hoistedVariables ||= new Map()).set(name, variable);
  6307. }
  6308. contains(name) {
  6309. return this.variables.has(name);
  6310. }
  6311. findVariable(_name) {
  6312. /* istanbul ignore next */
  6313. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  6314. }
  6315. }
  6316. class ChildScope extends Scope {
  6317. constructor(parent, context) {
  6318. super();
  6319. this.parent = parent;
  6320. this.context = context;
  6321. this.accessedOutsideVariables = new Map();
  6322. parent.children.push(this);
  6323. }
  6324. addAccessedDynamicImport(importExpression) {
  6325. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  6326. if (this.parent instanceof ChildScope) {
  6327. this.parent.addAccessedDynamicImport(importExpression);
  6328. }
  6329. }
  6330. addAccessedGlobals(globals, accessedGlobalsByScope) {
  6331. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  6332. for (const name of globals) {
  6333. accessedGlobals.add(name);
  6334. }
  6335. accessedGlobalsByScope.set(this, accessedGlobals);
  6336. if (this.parent instanceof ChildScope) {
  6337. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  6338. }
  6339. }
  6340. addNamespaceMemberAccess(name, variable) {
  6341. this.accessedOutsideVariables.set(name, variable);
  6342. this.parent.addNamespaceMemberAccess(name, variable);
  6343. }
  6344. addReturnExpression(expression) {
  6345. if (this.parent instanceof ChildScope) {
  6346. this.parent.addReturnExpression(expression);
  6347. }
  6348. }
  6349. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  6350. for (const variable of this.accessedOutsideVariables.values()) {
  6351. if (variable.included) {
  6352. usedNames.add(variable.getBaseVariableName());
  6353. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6354. usedNames.add('exports');
  6355. }
  6356. }
  6357. }
  6358. const accessedGlobals = accessedGlobalsByScope.get(this);
  6359. if (accessedGlobals) {
  6360. for (const name of accessedGlobals) {
  6361. usedNames.add(name);
  6362. }
  6363. }
  6364. }
  6365. contains(name) {
  6366. return this.variables.has(name) || this.parent.contains(name);
  6367. }
  6368. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  6369. const usedNames = new Set();
  6370. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  6371. if (this.accessedDynamicImports) {
  6372. for (const importExpression of this.accessedDynamicImports) {
  6373. if (importExpression.inlineNamespace) {
  6374. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  6375. }
  6376. }
  6377. }
  6378. for (const [name, variable] of this.variables) {
  6379. if (variable.included || variable.alwaysRendered) {
  6380. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  6381. }
  6382. }
  6383. for (const scope of this.children) {
  6384. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  6385. }
  6386. }
  6387. findLexicalBoundary() {
  6388. return this.parent.findLexicalBoundary();
  6389. }
  6390. findGlobal(name) {
  6391. const variable = this.parent.findVariable(name);
  6392. this.accessedOutsideVariables.set(name, variable);
  6393. return variable;
  6394. }
  6395. findVariable(name) {
  6396. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  6397. if (knownVariable) {
  6398. return knownVariable;
  6399. }
  6400. const variable = this.parent.findVariable(name);
  6401. this.accessedOutsideVariables.set(name, variable);
  6402. return variable;
  6403. }
  6404. }
  6405. function checkEffectForNodes(nodes, context) {
  6406. for (const node of nodes) {
  6407. if (node.hasEffects(context)) {
  6408. return true;
  6409. }
  6410. }
  6411. return false;
  6412. }
  6413. class MethodBase extends NodeBase {
  6414. constructor() {
  6415. super(...arguments);
  6416. this.accessedValue = null;
  6417. }
  6418. get computed() {
  6419. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6420. }
  6421. set computed(value) {
  6422. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6423. }
  6424. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6425. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  6426. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  6427. args: interaction.args,
  6428. type: INTERACTION_CALLED,
  6429. withNew: false
  6430. }, EMPTY_PATH, recursionTracker);
  6431. }
  6432. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  6433. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  6434. args: interaction.args,
  6435. type: INTERACTION_CALLED,
  6436. withNew: false
  6437. }, EMPTY_PATH, recursionTracker);
  6438. }
  6439. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6440. }
  6441. // As getter properties directly receive their values from fixed function
  6442. // expressions, there is no known situation where a getter is deoptimized.
  6443. deoptimizeCache() { }
  6444. deoptimizePath(path) {
  6445. this.getAccessedValue()[0].deoptimizePath(path);
  6446. }
  6447. getLiteralValueAtPath(path, recursionTracker, origin) {
  6448. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  6449. }
  6450. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6451. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6452. }
  6453. hasEffects(context) {
  6454. return this.key.hasEffects(context);
  6455. }
  6456. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6457. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  6458. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  6459. args: interaction.args,
  6460. type: INTERACTION_CALLED,
  6461. withNew: false
  6462. }, context);
  6463. }
  6464. // setters are only called for empty paths
  6465. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  6466. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  6467. args: interaction.args,
  6468. type: INTERACTION_CALLED,
  6469. withNew: false
  6470. }, context);
  6471. }
  6472. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  6473. }
  6474. applyDeoptimizations() { }
  6475. getAccessedValue() {
  6476. if (this.accessedValue === null) {
  6477. if (this.kind === 'get') {
  6478. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  6479. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  6480. }
  6481. else {
  6482. return (this.accessedValue = [this.value, false]);
  6483. }
  6484. }
  6485. return this.accessedValue;
  6486. }
  6487. }
  6488. class MethodDefinition extends MethodBase {
  6489. hasEffects(context) {
  6490. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  6491. }
  6492. applyDeoptimizations() { }
  6493. }
  6494. class BlockScope extends ChildScope {
  6495. constructor(parent) {
  6496. super(parent, parent.context);
  6497. }
  6498. addDeclaration(identifier, context, init, kind) {
  6499. if (kind === 'var') {
  6500. const name = identifier.name;
  6501. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6502. if (existingVariable) {
  6503. if (existingVariable.kind === 'var' ||
  6504. (kind === 'var' && existingVariable.kind === 'parameter')) {
  6505. existingVariable.addDeclaration(identifier, init);
  6506. return existingVariable;
  6507. }
  6508. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  6509. }
  6510. const declaredVariable = this.parent.addDeclaration(identifier, context, init, kind);
  6511. // Necessary to make sure the init is deoptimized for conditional declarations.
  6512. // We cannot call deoptimizePath here.
  6513. declaredVariable.markInitializersForDeoptimization();
  6514. // We add the variable to this and all parent scopes to reliably detect conflicts
  6515. this.addHoistedVariable(name, declaredVariable);
  6516. return declaredVariable;
  6517. }
  6518. return super.addDeclaration(identifier, context, init, kind);
  6519. }
  6520. }
  6521. class StaticBlock extends NodeBase {
  6522. createScope(parentScope) {
  6523. this.scope = new BlockScope(parentScope);
  6524. }
  6525. hasEffects(context) {
  6526. for (const node of this.body) {
  6527. if (node.hasEffects(context))
  6528. return true;
  6529. }
  6530. return false;
  6531. }
  6532. include(context, includeChildrenRecursively) {
  6533. this.included = true;
  6534. for (const node of this.body) {
  6535. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6536. node.include(context, includeChildrenRecursively);
  6537. }
  6538. }
  6539. render(code, options) {
  6540. if (this.body.length > 0) {
  6541. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  6542. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  6543. }
  6544. else {
  6545. super.render(code, options);
  6546. }
  6547. }
  6548. }
  6549. function isStaticBlock(statement) {
  6550. return statement.type === parseAst_js.StaticBlock;
  6551. }
  6552. class ObjectMember extends ExpressionEntity {
  6553. constructor(object, key) {
  6554. super();
  6555. this.object = object;
  6556. this.key = key;
  6557. }
  6558. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6559. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  6560. }
  6561. deoptimizePath(path) {
  6562. this.object.deoptimizePath([this.key, ...path]);
  6563. }
  6564. getLiteralValueAtPath(path, recursionTracker, origin) {
  6565. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  6566. }
  6567. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6568. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  6569. }
  6570. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6571. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  6572. }
  6573. }
  6574. class ClassNode extends NodeBase {
  6575. constructor() {
  6576. super(...arguments);
  6577. this.objectEntity = null;
  6578. }
  6579. createScope(parentScope) {
  6580. this.scope = new ChildScope(parentScope, parentScope.context);
  6581. }
  6582. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6583. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6584. }
  6585. deoptimizeCache() {
  6586. this.getObjectEntity().deoptimizeAllProperties();
  6587. }
  6588. deoptimizePath(path) {
  6589. this.getObjectEntity().deoptimizePath(path);
  6590. }
  6591. getLiteralValueAtPath(path, recursionTracker, origin) {
  6592. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6593. }
  6594. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6595. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6596. }
  6597. hasEffects(context) {
  6598. if (!this.deoptimized)
  6599. this.applyDeoptimizations();
  6600. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  6601. this.id?.markDeclarationReached();
  6602. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  6603. }
  6604. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6605. return interaction.type === INTERACTION_CALLED && path.length === 0
  6606. ? !interaction.withNew ||
  6607. (this.classConstructor === null
  6608. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  6609. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  6610. false
  6611. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6612. }
  6613. include(context, includeChildrenRecursively) {
  6614. if (!this.deoptimized)
  6615. this.applyDeoptimizations();
  6616. this.included = true;
  6617. this.superClass?.include(context, includeChildrenRecursively);
  6618. this.body.include(context, includeChildrenRecursively);
  6619. for (const decorator of this.decorators)
  6620. decorator.include(context, includeChildrenRecursively);
  6621. if (this.id) {
  6622. this.id.markDeclarationReached();
  6623. this.id.include();
  6624. }
  6625. }
  6626. initialise() {
  6627. super.initialise();
  6628. this.id?.declare('class', this);
  6629. for (const method of this.body.body) {
  6630. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  6631. this.classConstructor = method;
  6632. return;
  6633. }
  6634. }
  6635. this.classConstructor = null;
  6636. }
  6637. applyDeoptimizations() {
  6638. this.deoptimized = true;
  6639. for (const definition of this.body.body) {
  6640. if (!isStaticBlock(definition) &&
  6641. !(definition.static ||
  6642. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  6643. // Calls to methods are not tracked, ensure that the return value is deoptimized
  6644. definition.deoptimizePath(UNKNOWN_PATH);
  6645. }
  6646. }
  6647. this.scope.context.requestTreeshakingPass();
  6648. }
  6649. getObjectEntity() {
  6650. if (this.objectEntity !== null) {
  6651. return this.objectEntity;
  6652. }
  6653. const staticProperties = [];
  6654. const dynamicMethods = [];
  6655. for (const definition of this.body.body) {
  6656. if (isStaticBlock(definition))
  6657. continue;
  6658. const properties = definition.static ? staticProperties : dynamicMethods;
  6659. const definitionKind = definition.kind;
  6660. // Note that class fields do not end up on the prototype
  6661. if (properties === dynamicMethods && !definitionKind)
  6662. continue;
  6663. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  6664. let key;
  6665. if (definition.computed) {
  6666. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6667. if (typeof keyValue === 'symbol') {
  6668. properties.push({ key: UnknownKey, kind, property: definition });
  6669. continue;
  6670. }
  6671. else {
  6672. key = String(keyValue);
  6673. }
  6674. }
  6675. else {
  6676. key =
  6677. definition.key instanceof Identifier
  6678. ? definition.key.name
  6679. : String(definition.key.value);
  6680. }
  6681. properties.push({ key, kind, property: definition });
  6682. }
  6683. staticProperties.unshift({
  6684. key: 'prototype',
  6685. kind: 'init',
  6686. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  6687. });
  6688. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  6689. }
  6690. }
  6691. class ClassDeclaration extends ClassNode {
  6692. initialise() {
  6693. super.initialise();
  6694. if (this.id !== null) {
  6695. this.id.variable.isId = true;
  6696. }
  6697. }
  6698. parseNode(esTreeNode) {
  6699. if (esTreeNode.id !== null) {
  6700. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6701. }
  6702. return super.parseNode(esTreeNode);
  6703. }
  6704. render(code, options) {
  6705. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  6706. if (this.id) {
  6707. const { variable, name } = this.id;
  6708. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6709. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  6710. }
  6711. const renderedVariable = variable.getName(getPropertyAccess);
  6712. if (renderedVariable !== name) {
  6713. this.decorators.map(decorator => decorator.render(code, options));
  6714. this.superClass?.render(code, options);
  6715. this.body.render(code, {
  6716. ...options,
  6717. useOriginalName: (_variable) => _variable === variable
  6718. });
  6719. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  6720. code.prependLeft(this.end, ';');
  6721. return;
  6722. }
  6723. }
  6724. super.render(code, options);
  6725. }
  6726. applyDeoptimizations() {
  6727. super.applyDeoptimizations();
  6728. const { id, scope } = this;
  6729. if (id) {
  6730. const { name, variable } = id;
  6731. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  6732. if (accessedVariable !== variable) {
  6733. accessedVariable.forbidName(name);
  6734. }
  6735. }
  6736. }
  6737. }
  6738. }
  6739. class ArgumentsVariable extends LocalVariable {
  6740. constructor(context) {
  6741. super('arguments', null, UNKNOWN_EXPRESSION, context, 'other');
  6742. this.deoptimizedArguments = [];
  6743. }
  6744. addArgumentToBeDeoptimized(argument) {
  6745. if (this.included) {
  6746. argument.deoptimizePath(UNKNOWN_PATH);
  6747. }
  6748. else {
  6749. this.deoptimizedArguments.push(argument);
  6750. }
  6751. }
  6752. hasEffectsOnInteractionAtPath(path, { type }) {
  6753. return type !== INTERACTION_ACCESSED || path.length > 1;
  6754. }
  6755. include() {
  6756. super.include();
  6757. for (const argument of this.deoptimizedArguments) {
  6758. argument.deoptimizePath(UNKNOWN_PATH);
  6759. }
  6760. this.deoptimizedArguments.length = 0;
  6761. }
  6762. }
  6763. const MAX_TRACKED_INTERACTIONS = 20;
  6764. const NO_INTERACTIONS = parseAst_js.EMPTY_ARRAY;
  6765. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  6766. const EMPTY_PATH_TRACKER = new PathTracker();
  6767. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  6768. class ParameterVariable extends LocalVariable {
  6769. constructor(name, declarator, context) {
  6770. super(name, declarator, UNKNOWN_EXPRESSION, context, 'parameter');
  6771. this.deoptimizationInteractions = [];
  6772. this.deoptimizations = new PathTracker();
  6773. this.deoptimizedFields = new Set();
  6774. this.entitiesToBeDeoptimized = new Set();
  6775. this.expressionsUseTheKnownValue = [];
  6776. this.knownValue = null;
  6777. this.knownValueLiteral = UnknownValue;
  6778. this.frozenValue = null;
  6779. }
  6780. addEntityToBeDeoptimized(entity) {
  6781. if (entity === UNKNOWN_EXPRESSION) {
  6782. // As unknown expressions fully deoptimize all interactions, we can clear
  6783. // the interaction cache at this point provided we keep this optimization
  6784. // in mind when adding new interactions
  6785. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6786. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  6787. for (const { interaction } of this.deoptimizationInteractions) {
  6788. deoptimizeInteraction(interaction);
  6789. }
  6790. this.deoptimizationInteractions = NO_INTERACTIONS;
  6791. }
  6792. }
  6793. else if (this.deoptimizedFields.has(UnknownKey)) {
  6794. // This means that we already deoptimized all interactions and no longer
  6795. // track them
  6796. entity.deoptimizePath(UNKNOWN_PATH);
  6797. }
  6798. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  6799. this.entitiesToBeDeoptimized.add(entity);
  6800. for (const field of this.deoptimizedFields) {
  6801. entity.deoptimizePath([field]);
  6802. }
  6803. for (const { interaction, path } of this.deoptimizationInteractions) {
  6804. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6805. }
  6806. }
  6807. }
  6808. markReassigned() {
  6809. if (this.isReassigned) {
  6810. return;
  6811. }
  6812. super.markReassigned();
  6813. for (const expression of this.expressionsUseTheKnownValue) {
  6814. expression.deoptimizeCache();
  6815. }
  6816. this.expressionsUseTheKnownValue = parseAst_js.EMPTY_ARRAY;
  6817. }
  6818. deoptimizeCache() {
  6819. this.markReassigned();
  6820. }
  6821. /**
  6822. * Update the known value of the parameter variable.
  6823. * Must be called for every function call, so it can track all the arguments,
  6824. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  6825. * @param argument The argument of the function call
  6826. */
  6827. updateKnownValue(argument) {
  6828. if (this.isReassigned) {
  6829. return;
  6830. }
  6831. if (this.knownValue === null) {
  6832. this.knownValue = argument;
  6833. this.knownValueLiteral = argument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6834. return;
  6835. }
  6836. // the same literal or identifier, do nothing
  6837. if (this.knownValue === argument ||
  6838. (this.knownValue instanceof Identifier &&
  6839. argument instanceof Identifier &&
  6840. this.knownValue.variable === argument.variable)) {
  6841. return;
  6842. }
  6843. const oldValue = this.knownValueLiteral;
  6844. if (typeof oldValue === 'symbol') {
  6845. this.markReassigned();
  6846. return;
  6847. }
  6848. // add tracking for the new argument
  6849. const newValue = argument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6850. if (newValue !== oldValue) {
  6851. this.markReassigned();
  6852. }
  6853. }
  6854. /**
  6855. * This function freezes the known value of the parameter variable,
  6856. * so the optimization starts with a certain ExpressionEntity.
  6857. * The optimization can be undone by calling `markReassigned`.
  6858. * @returns the frozen value
  6859. */
  6860. getKnownValue() {
  6861. if (this.frozenValue === null) {
  6862. this.frozenValue = this.knownValue || UNKNOWN_EXPRESSION;
  6863. }
  6864. return this.frozenValue;
  6865. }
  6866. getLiteralValueAtPath(path, recursionTracker, origin) {
  6867. if (this.isReassigned) {
  6868. return UnknownValue;
  6869. }
  6870. const knownValue = this.getKnownValue();
  6871. this.expressionsUseTheKnownValue.push(origin);
  6872. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath(path, recursionTracker, origin), UnknownValue);
  6873. }
  6874. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6875. if (this.isReassigned || interaction.type === INTERACTION_ASSIGNED) {
  6876. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  6877. }
  6878. const knownValue = this.getKnownValue();
  6879. return knownValue.hasEffectsOnInteractionAtPath(path, interaction, context);
  6880. }
  6881. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6882. // For performance reasons, we fully deoptimize all deeper interactions
  6883. if (path.length >= 2 ||
  6884. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  6885. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  6886. (path.length === 1 &&
  6887. (this.deoptimizedFields.has(UnknownKey) ||
  6888. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  6889. deoptimizeInteraction(interaction);
  6890. return;
  6891. }
  6892. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  6893. for (const entity of this.entitiesToBeDeoptimized) {
  6894. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6895. }
  6896. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6897. this.deoptimizationInteractions.push({
  6898. interaction,
  6899. path
  6900. });
  6901. }
  6902. }
  6903. }
  6904. deoptimizePath(path) {
  6905. if (path.length === 0) {
  6906. this.markReassigned();
  6907. return;
  6908. }
  6909. if (this.deoptimizedFields.has(UnknownKey)) {
  6910. return;
  6911. }
  6912. const key = path[0];
  6913. if (this.deoptimizedFields.has(key)) {
  6914. return;
  6915. }
  6916. this.deoptimizedFields.add(key);
  6917. for (const entity of this.entitiesToBeDeoptimized) {
  6918. // We do not need a recursion tracker here as we already track whether
  6919. // this field is deoptimized
  6920. entity.deoptimizePath([key]);
  6921. }
  6922. if (key === UnknownKey) {
  6923. // save some memory
  6924. this.deoptimizationInteractions = NO_INTERACTIONS;
  6925. this.deoptimizations = EMPTY_PATH_TRACKER;
  6926. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  6927. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  6928. }
  6929. }
  6930. getReturnExpressionWhenCalledAtPath(path) {
  6931. // We deoptimize everything that is called as that will trivially deoptimize
  6932. // the corresponding return expressions as well and avoid badly performing
  6933. // and complicated alternatives
  6934. if (path.length === 0) {
  6935. this.deoptimizePath(UNKNOWN_PATH);
  6936. }
  6937. else if (!this.deoptimizedFields.has(path[0])) {
  6938. this.deoptimizePath([path[0]]);
  6939. }
  6940. return UNKNOWN_RETURN_EXPRESSION;
  6941. }
  6942. }
  6943. class ThisVariable extends ParameterVariable {
  6944. constructor(context) {
  6945. super('this', null, context);
  6946. }
  6947. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6948. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  6949. }
  6950. }
  6951. class CatchBodyScope extends ChildScope {
  6952. constructor(parent) {
  6953. super(parent, parent.context);
  6954. this.parent = parent;
  6955. }
  6956. addDeclaration(identifier, context, init, kind) {
  6957. if (kind === 'var') {
  6958. const name = identifier.name;
  6959. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  6960. if (existingVariable) {
  6961. const existingKind = existingVariable.kind;
  6962. if (existingKind === 'parameter' &&
  6963. // If this is a destructured parameter, it is forbidden to redeclare
  6964. existingVariable.declarations[0].parent.type === parseAst_js.CatchClause) {
  6965. // If this is a var with the same name as the catch scope parameter,
  6966. // the assignment actually goes to the parameter and the var is
  6967. // hoisted without assignment. Locally, it is shadowed by the
  6968. // parameter
  6969. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, kind);
  6970. // To avoid the need to rewrite the declaration, we link the variable
  6971. // names. If we ever implement a logic that splits initialization and
  6972. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  6973. // removed again.
  6974. // We do not need to check whether there already is a linked
  6975. // variable because then declaredVariable would be that linked
  6976. // variable.
  6977. existingVariable.renderLikeHoisted(declaredVariable);
  6978. this.addHoistedVariable(name, declaredVariable);
  6979. return declaredVariable;
  6980. }
  6981. if (existingKind === 'var') {
  6982. existingVariable.addDeclaration(identifier, init);
  6983. return existingVariable;
  6984. }
  6985. return context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  6986. }
  6987. // We only add parameters to parameter scopes
  6988. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, kind);
  6989. // Necessary to make sure the init is deoptimized for conditional declarations.
  6990. // We cannot call deoptimizePath here.
  6991. declaredVariable.markInitializersForDeoptimization();
  6992. // We add the variable to this and all parent scopes to reliably detect conflicts
  6993. this.addHoistedVariable(name, declaredVariable);
  6994. return declaredVariable;
  6995. }
  6996. return super.addDeclaration(identifier, context, init, kind);
  6997. }
  6998. }
  6999. class FunctionBodyScope extends ChildScope {
  7000. constructor(parent) {
  7001. super(parent, parent.context);
  7002. }
  7003. // There is stuff that is only allowed in function scopes, i.e. functions can
  7004. // be redeclared, functions and var can redeclare each other
  7005. addDeclaration(identifier, context, init, kind) {
  7006. const name = identifier.name;
  7007. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  7008. if (existingVariable) {
  7009. const existingKind = existingVariable.kind;
  7010. if ((kind === 'var' || kind === 'function') &&
  7011. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  7012. existingVariable.addDeclaration(identifier, init);
  7013. return existingVariable;
  7014. }
  7015. context.error(parseAst_js.logRedeclarationError(name), identifier.start);
  7016. }
  7017. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  7018. this.variables.set(name, newVariable);
  7019. return newVariable;
  7020. }
  7021. }
  7022. class ParameterScope extends ChildScope {
  7023. constructor(parent, isCatchScope) {
  7024. super(parent, parent.context);
  7025. this.parameters = [];
  7026. this.hasRest = false;
  7027. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  7028. }
  7029. /**
  7030. * Adds a parameter to this scope. Parameters must be added in the correct
  7031. * order, i.e. from left to right.
  7032. */
  7033. addParameterDeclaration(identifier) {
  7034. const { name, start } = identifier;
  7035. const existingParameter = this.variables.get(name);
  7036. if (existingParameter) {
  7037. return this.context.error(parseAst_js.logDuplicateArgumentNameError(name), start);
  7038. }
  7039. const variable = new ParameterVariable(name, identifier, this.context);
  7040. this.variables.set(name, variable);
  7041. // We also add it to the body scope to detect name conflicts with local
  7042. // variables. We still need the intermediate scope, though, as parameter
  7043. // defaults are NOT taken from the body scope but from the parameters or
  7044. // outside scope.
  7045. this.bodyScope.addHoistedVariable(name, variable);
  7046. return variable;
  7047. }
  7048. addParameterVariables(parameters, hasRest) {
  7049. this.parameters = parameters;
  7050. for (const parameterList of parameters) {
  7051. for (const parameter of parameterList) {
  7052. parameter.alwaysRendered = true;
  7053. }
  7054. }
  7055. this.hasRest = hasRest;
  7056. }
  7057. includeCallArguments(context, parameters) {
  7058. let calledFromTryStatement = false;
  7059. let argumentIncluded = false;
  7060. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  7061. for (const checkedArgument of parameters) {
  7062. if (checkedArgument instanceof SpreadElement) {
  7063. for (const argument of parameters) {
  7064. argument.include(context, false);
  7065. }
  7066. break;
  7067. }
  7068. }
  7069. for (let index = parameters.length - 1; index >= 0; index--) {
  7070. const parameterVariables = this.parameters[index] || restParameter;
  7071. const argument = parameters[index];
  7072. if (parameterVariables) {
  7073. calledFromTryStatement = false;
  7074. if (parameterVariables.length === 0) {
  7075. // handle empty destructuring
  7076. argumentIncluded = true;
  7077. }
  7078. else {
  7079. for (const variable of parameterVariables) {
  7080. if (variable.included) {
  7081. argumentIncluded = true;
  7082. }
  7083. if (variable.calledFromTryStatement) {
  7084. calledFromTryStatement = true;
  7085. }
  7086. }
  7087. }
  7088. }
  7089. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  7090. argumentIncluded = true;
  7091. }
  7092. if (argumentIncluded) {
  7093. argument.include(context, calledFromTryStatement);
  7094. }
  7095. }
  7096. }
  7097. }
  7098. class ReturnValueScope extends ParameterScope {
  7099. constructor() {
  7100. super(...arguments);
  7101. this.returnExpression = null;
  7102. this.returnExpressions = [];
  7103. }
  7104. addReturnExpression(expression) {
  7105. this.returnExpressions.push(expression);
  7106. }
  7107. getReturnExpression() {
  7108. if (this.returnExpression === null)
  7109. this.updateReturnExpression();
  7110. return this.returnExpression;
  7111. }
  7112. updateReturnExpression() {
  7113. if (this.returnExpressions.length === 1) {
  7114. this.returnExpression = this.returnExpressions[0];
  7115. }
  7116. else {
  7117. this.returnExpression = UNKNOWN_EXPRESSION;
  7118. for (const expression of this.returnExpressions) {
  7119. expression.deoptimizePath(UNKNOWN_PATH);
  7120. }
  7121. }
  7122. }
  7123. }
  7124. class FunctionScope extends ReturnValueScope {
  7125. constructor(parent) {
  7126. const { context } = parent;
  7127. super(parent, false);
  7128. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7129. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7130. }
  7131. findLexicalBoundary() {
  7132. return this;
  7133. }
  7134. includeCallArguments(context, parameters) {
  7135. super.includeCallArguments(context, parameters);
  7136. if (this.argumentsVariable.included) {
  7137. for (const argument of parameters) {
  7138. if (!argument.included) {
  7139. argument.include(context, false);
  7140. }
  7141. }
  7142. }
  7143. }
  7144. }
  7145. class ExpressionStatement extends NodeBase {
  7146. initialise() {
  7147. super.initialise();
  7148. if (this.directive &&
  7149. this.directive !== 'use strict' &&
  7150. this.parent.type === parseAst_js.Program) {
  7151. this.scope.context.log(parseAst_js.LOGLEVEL_WARN,
  7152. // This is necessary, because either way (deleting or not) can lead to errors.
  7153. parseAst_js.logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  7154. }
  7155. }
  7156. removeAnnotations(code) {
  7157. this.expression.removeAnnotations(code);
  7158. }
  7159. render(code, options) {
  7160. super.render(code, options);
  7161. if (code.original[this.end - 1] !== ';') {
  7162. code.appendLeft(this.end, ';');
  7163. }
  7164. }
  7165. shouldBeIncluded(context) {
  7166. if (this.directive && this.directive !== 'use strict')
  7167. return this.parent.type !== parseAst_js.Program;
  7168. return super.shouldBeIncluded(context);
  7169. }
  7170. applyDeoptimizations() { }
  7171. }
  7172. class BlockStatement extends NodeBase {
  7173. get deoptimizeBody() {
  7174. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  7175. }
  7176. set deoptimizeBody(value) {
  7177. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  7178. }
  7179. get directlyIncluded() {
  7180. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  7181. }
  7182. set directlyIncluded(value) {
  7183. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  7184. }
  7185. addImplicitReturnExpressionToScope() {
  7186. const lastStatement = this.body[this.body.length - 1];
  7187. if (!lastStatement || lastStatement.type !== parseAst_js.ReturnStatement) {
  7188. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7189. }
  7190. }
  7191. createScope(parentScope) {
  7192. this.scope = this.parent.preventChildBlockScope
  7193. ? parentScope
  7194. : new BlockScope(parentScope);
  7195. }
  7196. hasEffects(context) {
  7197. if (this.deoptimizeBody)
  7198. return true;
  7199. for (const node of this.body) {
  7200. if (context.brokenFlow)
  7201. break;
  7202. if (node.hasEffects(context))
  7203. return true;
  7204. }
  7205. return false;
  7206. }
  7207. include(context, includeChildrenRecursively) {
  7208. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7209. this.included = true;
  7210. this.directlyIncluded = true;
  7211. if (this.deoptimizeBody)
  7212. includeChildrenRecursively = true;
  7213. for (const node of this.body) {
  7214. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7215. node.include(context, includeChildrenRecursively);
  7216. }
  7217. }
  7218. }
  7219. initialise() {
  7220. super.initialise();
  7221. const firstBodyStatement = this.body[0];
  7222. this.deoptimizeBody =
  7223. firstBodyStatement instanceof ExpressionStatement &&
  7224. firstBodyStatement.directive === 'use asm';
  7225. }
  7226. render(code, options) {
  7227. if (this.body.length > 0) {
  7228. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7229. }
  7230. else {
  7231. super.render(code, options);
  7232. }
  7233. }
  7234. }
  7235. class RestElement extends NodeBase {
  7236. constructor() {
  7237. super(...arguments);
  7238. this.declarationInit = null;
  7239. }
  7240. addExportedVariables(variables, exportNamesByVariable) {
  7241. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7242. }
  7243. declare(kind, init) {
  7244. this.declarationInit = init;
  7245. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7246. }
  7247. deoptimizePath(path) {
  7248. if (path.length === 0) {
  7249. this.argument.deoptimizePath(EMPTY_PATH);
  7250. }
  7251. }
  7252. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7253. return (path.length > 0 ||
  7254. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7255. }
  7256. markDeclarationReached() {
  7257. this.argument.markDeclarationReached();
  7258. }
  7259. applyDeoptimizations() {
  7260. this.deoptimized = true;
  7261. if (this.declarationInit !== null) {
  7262. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7263. this.scope.context.requestTreeshakingPass();
  7264. }
  7265. }
  7266. }
  7267. class FunctionBase extends NodeBase {
  7268. constructor() {
  7269. super(...arguments);
  7270. this.objectEntity = null;
  7271. this.parameterVariableValuesDeoptimized = false;
  7272. }
  7273. get async() {
  7274. return isFlagSet(this.flags, 256 /* Flag.async */);
  7275. }
  7276. set async(value) {
  7277. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  7278. }
  7279. get deoptimizedReturn() {
  7280. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  7281. }
  7282. set deoptimizedReturn(value) {
  7283. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  7284. }
  7285. get generator() {
  7286. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  7287. }
  7288. set generator(value) {
  7289. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  7290. }
  7291. updateParameterVariableValues(_arguments) {
  7292. for (let position = 0; position < this.params.length; position++) {
  7293. const parameter = this.params[position];
  7294. if (!(parameter instanceof Identifier)) {
  7295. continue;
  7296. }
  7297. const parameterVariable = parameter.variable;
  7298. const argument = _arguments[position + 1] ?? UNDEFINED_EXPRESSION;
  7299. parameterVariable.updateKnownValue(argument);
  7300. }
  7301. }
  7302. deoptimizeParameterVariableValues() {
  7303. for (const parameter of this.params) {
  7304. if (parameter instanceof Identifier) {
  7305. const parameterVariable = parameter.variable;
  7306. parameterVariable.markReassigned();
  7307. }
  7308. }
  7309. }
  7310. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7311. if (interaction.type === INTERACTION_CALLED) {
  7312. const { parameters } = this.scope;
  7313. const { args } = interaction;
  7314. let hasRest = false;
  7315. for (let position = 0; position < args.length - 1; position++) {
  7316. const parameter = this.params[position];
  7317. // Only the "this" argument arg[0] can be null
  7318. const argument = args[position + 1];
  7319. if (argument instanceof SpreadElement) {
  7320. this.deoptimizeParameterVariableValues();
  7321. }
  7322. if (hasRest || parameter instanceof RestElement) {
  7323. hasRest = true;
  7324. argument.deoptimizePath(UNKNOWN_PATH);
  7325. }
  7326. else if (parameter instanceof Identifier) {
  7327. parameters[position][0].addEntityToBeDeoptimized(argument);
  7328. this.addArgumentToBeDeoptimized(argument);
  7329. }
  7330. else if (parameter) {
  7331. argument.deoptimizePath(UNKNOWN_PATH);
  7332. }
  7333. else {
  7334. this.addArgumentToBeDeoptimized(argument);
  7335. }
  7336. }
  7337. this.updateParameterVariableValues(args);
  7338. }
  7339. else {
  7340. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7341. }
  7342. }
  7343. deoptimizePath(path) {
  7344. this.getObjectEntity().deoptimizePath(path);
  7345. if (path.length === 1 && path[0] === UnknownKey) {
  7346. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7347. // which means the return expression and parameters need to be reassigned
  7348. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7349. for (const parameterList of this.scope.parameters) {
  7350. for (const parameter of parameterList) {
  7351. parameter.deoptimizePath(UNKNOWN_PATH);
  7352. parameter.markReassigned();
  7353. }
  7354. }
  7355. }
  7356. }
  7357. getLiteralValueAtPath(path, recursionTracker, origin) {
  7358. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7359. }
  7360. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7361. if (path.length > 0) {
  7362. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7363. }
  7364. if (this.async) {
  7365. if (!this.deoptimizedReturn) {
  7366. this.deoptimizedReturn = true;
  7367. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7368. this.scope.context.requestTreeshakingPass();
  7369. }
  7370. return UNKNOWN_RETURN_EXPRESSION;
  7371. }
  7372. return [this.scope.getReturnExpression(), false];
  7373. }
  7374. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7375. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7376. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7377. }
  7378. if (this.annotationNoSideEffects) {
  7379. return false;
  7380. }
  7381. if (this.async) {
  7382. const { propertyReadSideEffects } = this.scope.context.options
  7383. .treeshake;
  7384. const returnExpression = this.scope.getReturnExpression();
  7385. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7386. (propertyReadSideEffects &&
  7387. (propertyReadSideEffects === 'always' ||
  7388. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7389. return true;
  7390. }
  7391. }
  7392. for (const parameter of this.params) {
  7393. if (parameter.hasEffects(context))
  7394. return true;
  7395. }
  7396. return false;
  7397. }
  7398. /**
  7399. * If the function (expression or declaration) is only used as function calls
  7400. */
  7401. onlyFunctionCallUsed() {
  7402. let variable = null;
  7403. if (this.parent.type === parseAst_js.VariableDeclarator) {
  7404. variable = this.parent.id.variable ?? null;
  7405. }
  7406. if (this.parent.type === parseAst_js.ExportDefaultDeclaration) {
  7407. variable = this.parent.variable;
  7408. }
  7409. return variable?.getOnlyFunctionCallUsed() ?? false;
  7410. }
  7411. include(context, includeChildrenRecursively) {
  7412. if (!this.parameterVariableValuesDeoptimized && !this.onlyFunctionCallUsed()) {
  7413. this.parameterVariableValuesDeoptimized = true;
  7414. this.deoptimizeParameterVariableValues();
  7415. }
  7416. if (!this.deoptimized)
  7417. this.applyDeoptimizations();
  7418. this.included = true;
  7419. const { brokenFlow } = context;
  7420. context.brokenFlow = false;
  7421. this.body.include(context, includeChildrenRecursively);
  7422. context.brokenFlow = brokenFlow;
  7423. }
  7424. includeCallArguments(context, parameters) {
  7425. this.scope.includeCallArguments(context, parameters);
  7426. }
  7427. initialise() {
  7428. super.initialise();
  7429. if (this.body instanceof BlockStatement) {
  7430. this.body.addImplicitReturnExpressionToScope();
  7431. }
  7432. else {
  7433. this.scope.addReturnExpression(this.body);
  7434. }
  7435. if (this.annotations &&
  7436. this.scope.context.options.treeshake.annotations) {
  7437. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  7438. }
  7439. }
  7440. parseNode(esTreeNode) {
  7441. const { body, params } = esTreeNode;
  7442. const { scope } = this;
  7443. const { bodyScope, context } = scope;
  7444. // We need to ensure that parameters are declared before the body is parsed
  7445. // so that the scope already knows all parameters and can detect conflicts
  7446. // when parsing the body.
  7447. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  7448. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  7449. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  7450. return super.parseNode(esTreeNode);
  7451. }
  7452. addArgumentToBeDeoptimized(_argument) { }
  7453. applyDeoptimizations() { }
  7454. }
  7455. FunctionBase.prototype.preventChildBlockScope = true;
  7456. class FunctionNode extends FunctionBase {
  7457. constructor() {
  7458. super(...arguments);
  7459. this.objectEntity = null;
  7460. }
  7461. createScope(parentScope) {
  7462. this.scope = new FunctionScope(parentScope);
  7463. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  7464. // This makes sure that all deoptimizations of "this" are applied to the
  7465. // constructed entity.
  7466. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  7467. }
  7468. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7469. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7470. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  7471. // args[0] is the "this" argument
  7472. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  7473. }
  7474. }
  7475. hasEffects(context) {
  7476. if (!this.deoptimized)
  7477. this.applyDeoptimizations();
  7478. if (this.annotationNoSideEffects) {
  7479. return false;
  7480. }
  7481. return !!this.id?.hasEffects(context);
  7482. }
  7483. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7484. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7485. return true;
  7486. if (this.annotationNoSideEffects) {
  7487. return false;
  7488. }
  7489. if (interaction.type === INTERACTION_CALLED) {
  7490. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7491. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  7492. const { brokenFlow, ignore, replacedVariableInits } = context;
  7493. context.ignore = {
  7494. breaks: false,
  7495. continues: false,
  7496. labels: new Set(),
  7497. returnYield: true,
  7498. this: interaction.withNew
  7499. };
  7500. if (this.body.hasEffects(context))
  7501. return true;
  7502. context.brokenFlow = brokenFlow;
  7503. if (thisInit) {
  7504. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7505. }
  7506. else {
  7507. replacedVariableInits.delete(this.scope.thisVariable);
  7508. }
  7509. context.ignore = ignore;
  7510. }
  7511. return false;
  7512. }
  7513. include(context, includeChildrenRecursively) {
  7514. super.include(context, includeChildrenRecursively);
  7515. this.id?.include();
  7516. const hasArguments = this.scope.argumentsVariable.included;
  7517. for (const parameter of this.params) {
  7518. if (!(parameter instanceof Identifier) || hasArguments) {
  7519. parameter.include(context, includeChildrenRecursively);
  7520. }
  7521. }
  7522. }
  7523. initialise() {
  7524. super.initialise();
  7525. this.id?.declare('function', this);
  7526. }
  7527. addArgumentToBeDeoptimized(argument) {
  7528. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  7529. }
  7530. getObjectEntity() {
  7531. if (this.objectEntity !== null) {
  7532. return this.objectEntity;
  7533. }
  7534. return (this.objectEntity = new ObjectEntity([
  7535. {
  7536. key: 'prototype',
  7537. kind: 'init',
  7538. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7539. }
  7540. ], OBJECT_PROTOTYPE));
  7541. }
  7542. }
  7543. class FunctionDeclaration extends FunctionNode {
  7544. initialise() {
  7545. super.initialise();
  7546. if (this.id !== null) {
  7547. this.id.variable.isId = true;
  7548. }
  7549. }
  7550. onlyFunctionCallUsed() {
  7551. // call super.onlyFunctionCallUsed for export default anonymous function
  7552. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  7553. }
  7554. parseNode(esTreeNode) {
  7555. if (esTreeNode.id !== null) {
  7556. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  7557. }
  7558. return super.parseNode(esTreeNode);
  7559. }
  7560. }
  7561. // The header ends at the first non-white-space after "default"
  7562. function getDeclarationStart(code, start) {
  7563. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  7564. }
  7565. function getFunctionIdInsertPosition(code, start) {
  7566. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  7567. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  7568. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  7569. if (generatorStarPos === -1) {
  7570. return declarationEnd;
  7571. }
  7572. return declarationEnd + generatorStarPos + 1;
  7573. }
  7574. class ExportDefaultDeclaration extends NodeBase {
  7575. include(context, includeChildrenRecursively) {
  7576. super.include(context, includeChildrenRecursively);
  7577. if (includeChildrenRecursively) {
  7578. this.scope.context.includeVariableInModule(this.variable);
  7579. }
  7580. }
  7581. initialise() {
  7582. super.initialise();
  7583. const declaration = this.declaration;
  7584. this.declarationName =
  7585. (declaration.id && declaration.id.name) || this.declaration.name;
  7586. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  7587. this.scope.context.addExport(this);
  7588. }
  7589. removeAnnotations(code) {
  7590. this.declaration.removeAnnotations(code);
  7591. }
  7592. render(code, options, nodeRenderOptions) {
  7593. const { start, end } = nodeRenderOptions;
  7594. const declarationStart = getDeclarationStart(code.original, this.start);
  7595. if (this.declaration instanceof FunctionDeclaration) {
  7596. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  7597. ? getFunctionIdInsertPosition(code.original, declarationStart)
  7598. : null, options);
  7599. }
  7600. else if (this.declaration instanceof ClassDeclaration) {
  7601. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  7602. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  7603. : null, options);
  7604. }
  7605. else if (this.variable.getOriginalVariable() !== this.variable) {
  7606. // Remove altogether to prevent re-declaring the same variable
  7607. treeshakeNode(this, code, start, end);
  7608. return;
  7609. }
  7610. else if (this.variable.included) {
  7611. this.renderVariableDeclaration(code, declarationStart, options);
  7612. }
  7613. else {
  7614. code.remove(this.start, declarationStart);
  7615. this.declaration.render(code, options, {
  7616. renderedSurroundingElement: parseAst_js.ExpressionStatement
  7617. });
  7618. if (code.original[this.end - 1] !== ';') {
  7619. code.appendLeft(this.end, ';');
  7620. }
  7621. return;
  7622. }
  7623. this.declaration.render(code, options);
  7624. }
  7625. applyDeoptimizations() { }
  7626. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  7627. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  7628. const name = this.variable.getName(getPropertyAccess);
  7629. // Remove `export default`
  7630. code.remove(this.start, declarationStart);
  7631. if (idInsertPosition !== null) {
  7632. code.appendLeft(idInsertPosition, ` ${name}`);
  7633. }
  7634. if (format === 'system' &&
  7635. this.declaration instanceof ClassDeclaration &&
  7636. exportNamesByVariable.has(this.variable)) {
  7637. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  7638. }
  7639. }
  7640. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  7641. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  7642. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  7643. if (systemExportNames) {
  7644. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  7645. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  7646. }
  7647. else {
  7648. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  7649. if (!hasTrailingSemicolon) {
  7650. code.appendLeft(this.end, ';');
  7651. }
  7652. }
  7653. }
  7654. }
  7655. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  7656. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  7657. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  7658. const backSlashRegEx = /\\/g;
  7659. function escapeId(id) {
  7660. if (!needsEscapeRegEx.test(id))
  7661. return id;
  7662. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  7663. }
  7664. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  7665. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  7666. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  7667. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  7668. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  7669. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  7670. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  7671. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  7672. const defaultInteropHelpersByInteropType = {
  7673. auto: INTEROP_DEFAULT_VARIABLE,
  7674. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  7675. default: null,
  7676. defaultOnly: null,
  7677. esModule: null
  7678. };
  7679. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  7680. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  7681. const namespaceInteropHelpersByInteropType = {
  7682. auto: INTEROP_NAMESPACE_VARIABLE,
  7683. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  7684. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  7685. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  7686. esModule: null
  7687. };
  7688. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  7689. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  7690. const usedHelpers = new Set(additionalHelpers);
  7691. for (const variable of HELPER_NAMES) {
  7692. if (accessedGlobals.has(variable)) {
  7693. usedHelpers.add(variable);
  7694. }
  7695. }
  7696. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  7697. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  7698. : '').join('');
  7699. };
  7700. const HELPER_GENERATORS = {
  7701. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  7702. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  7703. },
  7704. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  7705. const { _, getDirectReturnFunction, n } = snippets;
  7706. const [left, right] = getDirectReturnFunction(['e'], {
  7707. functionReturn: true,
  7708. lineBreakIndent: null,
  7709. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  7710. });
  7711. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  7712. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  7713. },
  7714. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  7715. const { _, getDirectReturnFunction, n } = snippets;
  7716. const [left, right] = getDirectReturnFunction(['e'], {
  7717. functionReturn: true,
  7718. lineBreakIndent: null,
  7719. name: INTEROP_DEFAULT_VARIABLE
  7720. });
  7721. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  7722. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  7723. },
  7724. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  7725. const { _, getDirectReturnFunction, n } = snippets;
  7726. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  7727. const [left, right] = getDirectReturnFunction(['e'], {
  7728. functionReturn: true,
  7729. lineBreakIndent: null,
  7730. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  7731. });
  7732. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  7733. }
  7734. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  7735. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  7736. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  7737. `}${n}${n}`);
  7738. },
  7739. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  7740. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  7741. const [left, right] = getDirectReturnFunction(['e'], {
  7742. functionReturn: true,
  7743. lineBreakIndent: null,
  7744. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  7745. });
  7746. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  7747. [null, `__proto__:${_}null`],
  7748. ['default', 'e']
  7749. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  7750. },
  7751. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  7752. const { _, n } = snippets;
  7753. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  7754. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  7755. `}${n}${n}`);
  7756. },
  7757. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  7758. const { _, getDirectReturnFunction, n } = snippets;
  7759. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  7760. const [left, right] = getDirectReturnFunction(['e'], {
  7761. functionReturn: true,
  7762. lineBreakIndent: null,
  7763. name: INTEROP_NAMESPACE_VARIABLE
  7764. });
  7765. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  7766. }
  7767. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  7768. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  7769. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  7770. `}${n}${n}`);
  7771. },
  7772. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  7773. const { _, cnst, n } = snippets;
  7774. const useForEach = cnst === 'var' && liveBindings;
  7775. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  7776. `${t}${loopOverNamespaces(`{${n}` +
  7777. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  7778. (liveBindings
  7779. ? useForEach
  7780. ? copyOwnPropertyLiveBinding
  7781. : copyPropertyLiveBinding
  7782. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  7783. `${t}${t}${t}}${n}` +
  7784. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  7785. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  7786. `}${n}${n}`);
  7787. }
  7788. };
  7789. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  7790. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  7791. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  7792. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  7793. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  7794. const copyProperty = `{${n}` +
  7795. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  7796. `${index}${t}}`;
  7797. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  7798. `${index}if${_}(e)${_}{${n}` +
  7799. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  7800. `${index}}${n}` +
  7801. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  7802. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  7803. };
  7804. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  7805. ? `for${_}(${cnst} k in e)${_}${body}`
  7806. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  7807. isAsync: false,
  7808. name: null
  7809. })}${body})${s}`;
  7810. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  7811. if (useForEach) {
  7812. const [left, right] = getDirectReturnFunction(['e'], {
  7813. functionReturn: false,
  7814. lineBreakIndent: { base: t, t },
  7815. name: null
  7816. });
  7817. return (`m.forEach(${left}` +
  7818. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  7819. isAsync: false,
  7820. name: null
  7821. })}${body})${right});`);
  7822. }
  7823. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  7824. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  7825. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  7826. };
  7827. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  7828. const { _, n } = snippets;
  7829. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  7830. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  7831. `${index}}${n}`);
  7832. };
  7833. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  7834. const [left, right] = getDirectReturnFunction([], {
  7835. functionReturn: true,
  7836. lineBreakIndent: null,
  7837. name: null
  7838. });
  7839. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  7840. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  7841. `${index}${t}enumerable:${_}true,${n}` +
  7842. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  7843. `${index}});${n}`);
  7844. };
  7845. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  7846. const [left, right] = getDirectReturnFunction([], {
  7847. functionReturn: true,
  7848. lineBreakIndent: null,
  7849. name: null
  7850. });
  7851. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  7852. `${index}if${_}(d)${_}{${n}` +
  7853. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  7854. `${index}${t}${t}enumerable:${_}true,${n}` +
  7855. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  7856. `${index}${t}});${n}` +
  7857. `${index}}${n}`);
  7858. };
  7859. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  7860. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  7861. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  7862. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  7863. : fragment;
  7864. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  7865. function getToStringTagValue(getObject) {
  7866. return getObject([['value', "'Module'"]], {
  7867. lineBreakIndent: null
  7868. });
  7869. }
  7870. class Literal extends NodeBase {
  7871. deoptimizeArgumentsOnInteractionAtPath() { }
  7872. getLiteralValueAtPath(path) {
  7873. if (path.length > 0 ||
  7874. // unknown literals can also be null but do not start with an "n"
  7875. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  7876. typeof this.value === 'bigint' ||
  7877. // to support shims for regular expressions
  7878. this.scope.context.code.charCodeAt(this.start) === 47) {
  7879. return UnknownValue;
  7880. }
  7881. return this.value;
  7882. }
  7883. getReturnExpressionWhenCalledAtPath(path) {
  7884. if (path.length !== 1)
  7885. return UNKNOWN_RETURN_EXPRESSION;
  7886. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7887. }
  7888. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7889. switch (interaction.type) {
  7890. case INTERACTION_ACCESSED: {
  7891. return path.length > (this.value === null ? 0 : 1);
  7892. }
  7893. case INTERACTION_ASSIGNED: {
  7894. return true;
  7895. }
  7896. case INTERACTION_CALLED: {
  7897. if (this.included &&
  7898. this.value instanceof RegExp &&
  7899. (this.value.global || this.value.sticky)) {
  7900. return true;
  7901. }
  7902. return (path.length !== 1 ||
  7903. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7904. }
  7905. }
  7906. }
  7907. initialise() {
  7908. super.initialise();
  7909. this.members = getLiteralMembersForValue(this.value);
  7910. }
  7911. parseNode(esTreeNode) {
  7912. this.value = esTreeNode.value;
  7913. this.regex = esTreeNode.regex;
  7914. return super.parseNode(esTreeNode);
  7915. }
  7916. render(code) {
  7917. if (typeof this.value === 'string') {
  7918. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7919. }
  7920. }
  7921. }
  7922. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  7923. if ('getLiteralValueAtPathAsChainElement' in object) {
  7924. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  7925. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  7926. return IS_SKIPPED_CHAIN;
  7927. }
  7928. }
  7929. else if (element.optional &&
  7930. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  7931. return IS_SKIPPED_CHAIN;
  7932. }
  7933. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  7934. }
  7935. // To avoid infinite recursions
  7936. const MAX_PATH_DEPTH = 7;
  7937. function getResolvablePropertyKey(memberExpression) {
  7938. return memberExpression.computed
  7939. ? getResolvableComputedPropertyKey(memberExpression.property)
  7940. : memberExpression.property.name;
  7941. }
  7942. function getResolvableComputedPropertyKey(propertyKey) {
  7943. if (propertyKey instanceof Literal) {
  7944. return String(propertyKey.value);
  7945. }
  7946. return null;
  7947. }
  7948. function getPathIfNotComputed(memberExpression) {
  7949. const nextPathKey = memberExpression.propertyKey;
  7950. const object = memberExpression.object;
  7951. if (typeof nextPathKey === 'string') {
  7952. if (object instanceof Identifier) {
  7953. return [
  7954. { key: object.name, pos: object.start },
  7955. { key: nextPathKey, pos: memberExpression.property.start }
  7956. ];
  7957. }
  7958. if (object instanceof MemberExpression) {
  7959. const parentPath = getPathIfNotComputed(object);
  7960. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7961. }
  7962. }
  7963. return null;
  7964. }
  7965. function getStringFromPath(path) {
  7966. let pathString = path[0].key;
  7967. for (let index = 1; index < path.length; index++) {
  7968. pathString += '.' + path[index].key;
  7969. }
  7970. return pathString;
  7971. }
  7972. class MemberExpression extends NodeBase {
  7973. constructor() {
  7974. super(...arguments);
  7975. this.variable = null;
  7976. this.expressionsToBeDeoptimized = [];
  7977. }
  7978. get computed() {
  7979. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  7980. }
  7981. set computed(value) {
  7982. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  7983. }
  7984. get optional() {
  7985. return isFlagSet(this.flags, 128 /* Flag.optional */);
  7986. }
  7987. set optional(value) {
  7988. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  7989. }
  7990. get assignmentDeoptimized() {
  7991. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  7992. }
  7993. set assignmentDeoptimized(value) {
  7994. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  7995. }
  7996. get bound() {
  7997. return isFlagSet(this.flags, 32 /* Flag.bound */);
  7998. }
  7999. set bound(value) {
  8000. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  8001. }
  8002. get isUndefined() {
  8003. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  8004. }
  8005. set isUndefined(value) {
  8006. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  8007. }
  8008. bind() {
  8009. this.bound = true;
  8010. const path = getPathIfNotComputed(this);
  8011. const baseVariable = path && this.scope.findVariable(path[0].key);
  8012. if (baseVariable?.isNamespace) {
  8013. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  8014. if (!resolvedVariable) {
  8015. super.bind();
  8016. }
  8017. else if (resolvedVariable === 'undefined') {
  8018. this.isUndefined = true;
  8019. }
  8020. else {
  8021. this.variable = resolvedVariable;
  8022. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  8023. }
  8024. }
  8025. else {
  8026. super.bind();
  8027. }
  8028. }
  8029. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8030. if (this.variable) {
  8031. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8032. }
  8033. else if (!this.isUndefined) {
  8034. if (path.length < MAX_PATH_DEPTH) {
  8035. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  8036. }
  8037. else {
  8038. deoptimizeInteraction(interaction);
  8039. }
  8040. }
  8041. }
  8042. deoptimizeCache() {
  8043. const { expressionsToBeDeoptimized, object } = this;
  8044. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  8045. this.propertyKey = UnknownKey;
  8046. object.deoptimizePath(UNKNOWN_PATH);
  8047. for (const expression of expressionsToBeDeoptimized) {
  8048. expression.deoptimizeCache();
  8049. }
  8050. }
  8051. deoptimizePath(path) {
  8052. if (path.length === 0)
  8053. this.disallowNamespaceReassignment();
  8054. if (this.variable) {
  8055. this.variable.deoptimizePath(path);
  8056. }
  8057. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  8058. const propertyKey = this.getPropertyKey();
  8059. this.object.deoptimizePath([
  8060. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  8061. ...path
  8062. ]);
  8063. }
  8064. }
  8065. getLiteralValueAtPath(path, recursionTracker, origin) {
  8066. if (this.variable) {
  8067. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8068. }
  8069. if (this.isUndefined) {
  8070. return undefined;
  8071. }
  8072. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8073. this.expressionsToBeDeoptimized.push(origin);
  8074. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  8075. }
  8076. return UnknownValue;
  8077. }
  8078. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  8079. if (this.variable) {
  8080. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8081. }
  8082. if (this.isUndefined) {
  8083. return undefined;
  8084. }
  8085. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  8086. }
  8087. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8088. if (this.variable) {
  8089. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8090. }
  8091. if (this.isUndefined) {
  8092. return [UNDEFINED_EXPRESSION, false];
  8093. }
  8094. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8095. this.expressionsToBeDeoptimized.push(origin);
  8096. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  8097. }
  8098. return UNKNOWN_RETURN_EXPRESSION;
  8099. }
  8100. hasEffects(context) {
  8101. if (!this.deoptimized)
  8102. this.applyDeoptimizations();
  8103. return (this.property.hasEffects(context) ||
  8104. this.object.hasEffects(context) ||
  8105. this.hasAccessEffect(context));
  8106. }
  8107. hasEffectsAsChainElement(context) {
  8108. if (this.variable || this.isUndefined)
  8109. return this.hasEffects(context);
  8110. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  8111. ? this.object.hasEffectsAsChainElement(context)
  8112. : this.object.hasEffects(context);
  8113. if (objectHasEffects === IS_SKIPPED_CHAIN)
  8114. return IS_SKIPPED_CHAIN;
  8115. if (this.optional &&
  8116. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  8117. return objectHasEffects || IS_SKIPPED_CHAIN;
  8118. }
  8119. // We only apply deoptimizations lazily once we know we are not skipping
  8120. if (!this.deoptimized)
  8121. this.applyDeoptimizations();
  8122. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  8123. }
  8124. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8125. if (checkAccess && !this.deoptimized)
  8126. this.applyDeoptimizations();
  8127. if (!this.assignmentDeoptimized)
  8128. this.applyAssignmentDeoptimization();
  8129. return (this.property.hasEffects(context) ||
  8130. this.object.hasEffects(context) ||
  8131. (checkAccess && this.hasAccessEffect(context)) ||
  8132. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8133. }
  8134. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8135. if (this.variable) {
  8136. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8137. }
  8138. if (this.isUndefined) {
  8139. return true;
  8140. }
  8141. if (path.length < MAX_PATH_DEPTH) {
  8142. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  8143. }
  8144. return true;
  8145. }
  8146. include(context, includeChildrenRecursively) {
  8147. if (!this.deoptimized)
  8148. this.applyDeoptimizations();
  8149. this.includeProperties(context, includeChildrenRecursively);
  8150. }
  8151. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8152. if (!this.assignmentDeoptimized)
  8153. this.applyAssignmentDeoptimization();
  8154. if (deoptimizeAccess) {
  8155. this.include(context, includeChildrenRecursively);
  8156. }
  8157. else {
  8158. this.includeProperties(context, includeChildrenRecursively);
  8159. }
  8160. }
  8161. includeCallArguments(context, parameters) {
  8162. if (this.variable) {
  8163. this.variable.includeCallArguments(context, parameters);
  8164. }
  8165. else {
  8166. super.includeCallArguments(context, parameters);
  8167. }
  8168. }
  8169. initialise() {
  8170. super.initialise();
  8171. this.propertyKey = getResolvablePropertyKey(this);
  8172. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  8173. }
  8174. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = parseAst_js.BLANK) {
  8175. if (this.variable || this.isUndefined) {
  8176. const { snippets: { getPropertyAccess } } = options;
  8177. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  8178. if (renderedParentType && isCalleeOfRenderedParent)
  8179. replacement = '0, ' + replacement;
  8180. code.overwrite(this.start, this.end, replacement, {
  8181. contentOnly: true,
  8182. storeName: true
  8183. });
  8184. }
  8185. else {
  8186. if (renderedParentType && isCalleeOfRenderedParent) {
  8187. code.appendRight(this.start, '0, ');
  8188. }
  8189. this.object.render(code, options, { renderedSurroundingElement });
  8190. this.property.render(code, options);
  8191. }
  8192. }
  8193. setAssignedValue(value) {
  8194. this.assignmentInteraction = {
  8195. args: [this.object, value],
  8196. type: INTERACTION_ASSIGNED
  8197. };
  8198. }
  8199. applyDeoptimizations() {
  8200. this.deoptimized = true;
  8201. const { propertyReadSideEffects } = this.scope.context.options
  8202. .treeshake;
  8203. if (
  8204. // Namespaces are not bound and should not be deoptimized
  8205. this.bound &&
  8206. propertyReadSideEffects &&
  8207. !(this.variable || this.isUndefined)) {
  8208. const propertyKey = this.getPropertyKey();
  8209. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8210. this.scope.context.requestTreeshakingPass();
  8211. }
  8212. if (this.variable) {
  8213. this.variable.addUsedPlace(this);
  8214. this.scope.context.requestTreeshakingPass();
  8215. }
  8216. }
  8217. applyAssignmentDeoptimization() {
  8218. this.assignmentDeoptimized = true;
  8219. const { propertyReadSideEffects } = this.scope.context.options
  8220. .treeshake;
  8221. if (
  8222. // Namespaces are not bound and should not be deoptimized
  8223. this.bound &&
  8224. propertyReadSideEffects &&
  8225. !(this.variable || this.isUndefined)) {
  8226. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8227. this.scope.context.requestTreeshakingPass();
  8228. }
  8229. }
  8230. disallowNamespaceReassignment() {
  8231. if (this.object instanceof Identifier) {
  8232. const variable = this.scope.findVariable(this.object.name);
  8233. if (variable.isNamespace) {
  8234. if (this.variable) {
  8235. this.scope.context.includeVariableInModule(this.variable);
  8236. }
  8237. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  8238. }
  8239. }
  8240. }
  8241. getPropertyKey() {
  8242. if (this.propertyKey === null) {
  8243. this.propertyKey = UnknownKey;
  8244. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8245. return (this.propertyKey =
  8246. value === SymbolToStringTag
  8247. ? value
  8248. : typeof value === 'symbol'
  8249. ? UnknownKey
  8250. : String(value));
  8251. }
  8252. return this.propertyKey;
  8253. }
  8254. hasAccessEffect(context) {
  8255. const { propertyReadSideEffects } = this.scope.context.options
  8256. .treeshake;
  8257. return (!(this.variable || this.isUndefined) &&
  8258. propertyReadSideEffects &&
  8259. (propertyReadSideEffects === 'always' ||
  8260. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8261. }
  8262. includeProperties(context, includeChildrenRecursively) {
  8263. if (!this.included) {
  8264. this.included = true;
  8265. if (this.variable) {
  8266. this.scope.context.includeVariableInModule(this.variable);
  8267. }
  8268. }
  8269. this.object.include(context, includeChildrenRecursively);
  8270. this.property.include(context, includeChildrenRecursively);
  8271. }
  8272. }
  8273. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8274. if (path.length === 0)
  8275. return baseVariable;
  8276. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8277. return null;
  8278. const exportName = path[0].key;
  8279. const variable = baseVariable.context.traceExport(exportName);
  8280. if (!variable) {
  8281. if (path.length === 1) {
  8282. const fileName = baseVariable.context.fileName;
  8283. astContext.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  8284. return 'undefined';
  8285. }
  8286. return null;
  8287. }
  8288. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8289. }
  8290. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  8291. const IMPORT = 'import';
  8292. class MetaProperty extends NodeBase {
  8293. constructor() {
  8294. super(...arguments);
  8295. this.metaProperty = null;
  8296. this.preliminaryChunkId = null;
  8297. this.referenceId = null;
  8298. }
  8299. getReferencedFileName(outputPluginDriver) {
  8300. const { meta: { name }, metaProperty } = this;
  8301. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  8302. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  8303. }
  8304. return null;
  8305. }
  8306. hasEffects() {
  8307. return false;
  8308. }
  8309. hasEffectsOnInteractionAtPath(path, { type }) {
  8310. return path.length > 1 || type !== INTERACTION_ACCESSED;
  8311. }
  8312. include() {
  8313. if (!this.included) {
  8314. this.included = true;
  8315. if (this.meta.name === IMPORT) {
  8316. this.scope.context.addImportMeta(this);
  8317. const parent = this.parent;
  8318. const metaProperty = (this.metaProperty =
  8319. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  8320. ? parent.propertyKey
  8321. : null);
  8322. if (metaProperty?.startsWith(FILE_PREFIX)) {
  8323. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  8324. }
  8325. }
  8326. }
  8327. }
  8328. render(code, renderOptions) {
  8329. const { format, pluginDriver, snippets } = renderOptions;
  8330. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  8331. const { id: moduleId } = module;
  8332. if (name !== IMPORT)
  8333. return;
  8334. const chunkId = preliminaryChunkId;
  8335. if (referenceId) {
  8336. const fileName = pluginDriver.getFileName(referenceId);
  8337. const relativePath = parseAst_js.normalize(path.relative(path.dirname(chunkId), fileName));
  8338. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  8339. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  8340. ]) || relativeUrlMechanisms[format](relativePath);
  8341. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8342. return;
  8343. }
  8344. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  8345. metaProperty,
  8346. { chunkId, format, moduleId }
  8347. ]);
  8348. if (!replacement) {
  8349. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  8350. renderOptions.accessedDocumentCurrentScript ||=
  8351. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  8352. }
  8353. if (typeof replacement === 'string') {
  8354. if (parent instanceof MemberExpression) {
  8355. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8356. }
  8357. else {
  8358. code.overwrite(start, end, replacement, { contentOnly: true });
  8359. }
  8360. }
  8361. }
  8362. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  8363. this.preliminaryChunkId = preliminaryChunkId;
  8364. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  8365. if (accessedGlobals.length > 0) {
  8366. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  8367. }
  8368. }
  8369. }
  8370. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  8371. const accessedMetaUrlGlobals = {
  8372. amd: ['document', 'module', 'URL'],
  8373. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  8374. es: [],
  8375. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  8376. system: ['module'],
  8377. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  8378. };
  8379. const accessedFileUrlGlobals = {
  8380. amd: ['document', 'require', 'URL'],
  8381. cjs: ['document', 'require', 'URL'],
  8382. es: [],
  8383. iife: ['document', 'URL'],
  8384. system: ['module', 'URL'],
  8385. umd: ['document', 'require', 'URL']
  8386. };
  8387. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  8388. 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`);
  8389. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  8390. const urlMechanism = getUrl(chunkId);
  8391. return property === null
  8392. ? `({ url: ${urlMechanism} })`
  8393. : property === 'url'
  8394. ? urlMechanism
  8395. : 'undefined';
  8396. };
  8397. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  8398. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  8399. 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)`;
  8400. const relativeUrlMechanisms = {
  8401. amd: relativePath => {
  8402. if (relativePath[0] !== '.')
  8403. relativePath = './' + relativePath;
  8404. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  8405. },
  8406. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  8407. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  8408. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  8409. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  8410. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  8411. };
  8412. const importMetaMechanisms = {
  8413. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  8414. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  8415. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  8416. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  8417. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  8418. };
  8419. class UndefinedVariable extends Variable {
  8420. constructor() {
  8421. super('undefined');
  8422. }
  8423. getLiteralValueAtPath() {
  8424. return undefined;
  8425. }
  8426. }
  8427. class ExportDefaultVariable extends LocalVariable {
  8428. constructor(name, exportDefaultDeclaration, context) {
  8429. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context, 'other');
  8430. this.hasId = false;
  8431. this.originalId = null;
  8432. this.originalVariable = null;
  8433. const declaration = exportDefaultDeclaration.declaration;
  8434. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  8435. declaration.id) {
  8436. this.hasId = true;
  8437. this.originalId = declaration.id;
  8438. }
  8439. else if (declaration instanceof Identifier) {
  8440. this.originalId = declaration;
  8441. }
  8442. }
  8443. addReference(identifier) {
  8444. if (!this.hasId) {
  8445. this.name = identifier.name;
  8446. }
  8447. }
  8448. addUsedPlace(usedPlace) {
  8449. const original = this.getOriginalVariable();
  8450. if (original === this) {
  8451. super.addUsedPlace(usedPlace);
  8452. }
  8453. else {
  8454. original.addUsedPlace(usedPlace);
  8455. }
  8456. }
  8457. forbidName(name) {
  8458. const original = this.getOriginalVariable();
  8459. if (original === this) {
  8460. super.forbidName(name);
  8461. }
  8462. else {
  8463. original.forbidName(name);
  8464. }
  8465. }
  8466. getAssignedVariableName() {
  8467. return (this.originalId && this.originalId.name) || null;
  8468. }
  8469. getBaseVariableName() {
  8470. const original = this.getOriginalVariable();
  8471. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  8472. }
  8473. getDirectOriginalVariable() {
  8474. return this.originalId &&
  8475. (this.hasId ||
  8476. !(this.originalId.isPossibleTDZ() ||
  8477. this.originalId.variable.isReassigned ||
  8478. this.originalId.variable instanceof UndefinedVariable ||
  8479. // this avoids a circular dependency
  8480. 'syntheticNamespace' in this.originalId.variable))
  8481. ? this.originalId.variable
  8482. : null;
  8483. }
  8484. getName(getPropertyAccess) {
  8485. const original = this.getOriginalVariable();
  8486. return original === this
  8487. ? super.getName(getPropertyAccess)
  8488. : original.getName(getPropertyAccess);
  8489. }
  8490. getOriginalVariable() {
  8491. if (this.originalVariable)
  8492. return this.originalVariable;
  8493. // eslint-disable-next-line @typescript-eslint/no-this-alias
  8494. let original = this;
  8495. let currentVariable;
  8496. const checkedVariables = new Set();
  8497. do {
  8498. checkedVariables.add(original);
  8499. currentVariable = original;
  8500. original = currentVariable.getDirectOriginalVariable();
  8501. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  8502. return (this.originalVariable = original || currentVariable);
  8503. }
  8504. }
  8505. class NamespaceVariable extends Variable {
  8506. constructor(context) {
  8507. super(context.getModuleName());
  8508. this.memberVariables = null;
  8509. this.mergedNamespaces = [];
  8510. this.referencedEarly = false;
  8511. this.references = [];
  8512. this.context = context;
  8513. this.module = context.module;
  8514. }
  8515. addReference(identifier) {
  8516. this.references.push(identifier);
  8517. this.name = identifier.name;
  8518. }
  8519. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8520. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  8521. const key = path[0];
  8522. if (typeof key === 'string') {
  8523. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  8524. }
  8525. else {
  8526. deoptimizeInteraction(interaction);
  8527. }
  8528. }
  8529. }
  8530. deoptimizePath(path) {
  8531. if (path.length > 1) {
  8532. const key = path[0];
  8533. if (typeof key === 'string') {
  8534. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  8535. }
  8536. }
  8537. }
  8538. getLiteralValueAtPath(path) {
  8539. if (path[0] === SymbolToStringTag) {
  8540. return 'Module';
  8541. }
  8542. return UnknownValue;
  8543. }
  8544. getMemberVariables() {
  8545. if (this.memberVariables) {
  8546. return this.memberVariables;
  8547. }
  8548. const memberVariables = Object.create(null);
  8549. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  8550. for (const name of sortedExports) {
  8551. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  8552. const exportedVariable = this.context.traceExport(name);
  8553. if (exportedVariable) {
  8554. memberVariables[name] = exportedVariable;
  8555. }
  8556. }
  8557. }
  8558. return (this.memberVariables = memberVariables);
  8559. }
  8560. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8561. const { type } = interaction;
  8562. if (path.length === 0) {
  8563. // This can only be a call anyway
  8564. return true;
  8565. }
  8566. if (path.length === 1 && type !== INTERACTION_CALLED) {
  8567. return type === INTERACTION_ASSIGNED;
  8568. }
  8569. const key = path[0];
  8570. if (typeof key !== 'string') {
  8571. return true;
  8572. }
  8573. const memberVariable = this.getMemberVariables()[key];
  8574. return (!memberVariable ||
  8575. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  8576. }
  8577. include() {
  8578. super.include();
  8579. this.context.includeAllExports();
  8580. }
  8581. prepare(accessedGlobalsByScope) {
  8582. if (this.mergedNamespaces.length > 0) {
  8583. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  8584. }
  8585. }
  8586. renderBlock(options) {
  8587. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  8588. const memberVariables = this.getMemberVariables();
  8589. const members = Object.entries(memberVariables)
  8590. .filter(([_, variable]) => variable.included)
  8591. .map(([name, variable]) => {
  8592. if (this.referencedEarly || variable.isReassigned || variable === this) {
  8593. return [
  8594. null,
  8595. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  8596. ];
  8597. }
  8598. return [name, variable.getName(getPropertyAccess)];
  8599. });
  8600. members.unshift([null, `__proto__:${_}null`]);
  8601. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  8602. if (this.mergedNamespaces.length > 0) {
  8603. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  8604. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  8605. }
  8606. else {
  8607. // The helper to merge namespaces will also take care of freezing and toStringTag
  8608. if (symbols) {
  8609. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  8610. }
  8611. if (freeze) {
  8612. output = `/*#__PURE__*/Object.freeze(${output})`;
  8613. }
  8614. }
  8615. const name = this.getName(getPropertyAccess);
  8616. output = `${cnst} ${name}${_}=${_}${output};`;
  8617. if (format === 'system' && exportNamesByVariable.has(this)) {
  8618. output += `${n}${getSystemExportStatement([this], options)};`;
  8619. }
  8620. return output;
  8621. }
  8622. renderFirst() {
  8623. return this.referencedEarly;
  8624. }
  8625. setMergedNamespaces(mergedNamespaces) {
  8626. this.mergedNamespaces = mergedNamespaces;
  8627. const moduleExecIndex = this.context.getModuleExecIndex();
  8628. for (const identifier of this.references) {
  8629. const { context } = identifier.scope;
  8630. if (context.getModuleExecIndex() <= moduleExecIndex) {
  8631. this.referencedEarly = true;
  8632. break;
  8633. }
  8634. }
  8635. }
  8636. }
  8637. NamespaceVariable.prototype.isNamespace = true;
  8638. class SyntheticNamedExportVariable extends Variable {
  8639. constructor(context, name, syntheticNamespace) {
  8640. super(name);
  8641. this.baseVariable = null;
  8642. this.context = context;
  8643. this.module = context.module;
  8644. this.syntheticNamespace = syntheticNamespace;
  8645. }
  8646. getBaseVariable() {
  8647. if (this.baseVariable)
  8648. return this.baseVariable;
  8649. let baseVariable = this.syntheticNamespace;
  8650. while (baseVariable instanceof ExportDefaultVariable ||
  8651. baseVariable instanceof SyntheticNamedExportVariable) {
  8652. if (baseVariable instanceof ExportDefaultVariable) {
  8653. const original = baseVariable.getOriginalVariable();
  8654. if (original === baseVariable)
  8655. break;
  8656. baseVariable = original;
  8657. }
  8658. if (baseVariable instanceof SyntheticNamedExportVariable) {
  8659. baseVariable = baseVariable.syntheticNamespace;
  8660. }
  8661. }
  8662. return (this.baseVariable = baseVariable);
  8663. }
  8664. getBaseVariableName() {
  8665. return this.syntheticNamespace.getBaseVariableName();
  8666. }
  8667. getName(getPropertyAccess) {
  8668. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  8669. }
  8670. include() {
  8671. super.include();
  8672. this.context.includeVariableInModule(this.syntheticNamespace);
  8673. }
  8674. setRenderNames(baseName, name) {
  8675. super.setRenderNames(baseName, name);
  8676. }
  8677. }
  8678. class ExternalChunk {
  8679. constructor(module, options, inputBase) {
  8680. this.options = options;
  8681. this.inputBase = inputBase;
  8682. this.defaultVariableName = '';
  8683. this.namespaceVariableName = '';
  8684. this.variableName = '';
  8685. this.fileName = null;
  8686. this.importAttributes = null;
  8687. this.id = module.id;
  8688. this.moduleInfo = module.info;
  8689. this.renormalizeRenderPath = module.renormalizeRenderPath;
  8690. this.suggestedVariableName = module.suggestedVariableName;
  8691. }
  8692. getFileName() {
  8693. if (this.fileName) {
  8694. return this.fileName;
  8695. }
  8696. const { paths } = this.options;
  8697. return (this.fileName =
  8698. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  8699. (this.renormalizeRenderPath ? parseAst_js.normalize(path.relative(this.inputBase, this.id)) : this.id));
  8700. }
  8701. getImportAttributes(snippets) {
  8702. return (this.importAttributes ||= formatAttributes(this.options.format === 'es' &&
  8703. this.options.externalImportAttributes &&
  8704. this.moduleInfo.attributes, snippets));
  8705. }
  8706. getImportPath(importer) {
  8707. return escapeId(this.renormalizeRenderPath
  8708. ? parseAst_js.getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  8709. : this.getFileName());
  8710. }
  8711. }
  8712. function formatAttributes(attributes, { getObject }) {
  8713. if (!attributes) {
  8714. return null;
  8715. }
  8716. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  8717. if (assertionEntries.length > 0) {
  8718. return getObject(assertionEntries, { lineBreakIndent: null });
  8719. }
  8720. return null;
  8721. }
  8722. function removeJsExtension(name) {
  8723. return name.endsWith('.js') ? name.slice(0, -3) : name;
  8724. }
  8725. function getCompleteAmdId(options, chunkId) {
  8726. if (options.autoId) {
  8727. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  8728. }
  8729. return options.id ?? '';
  8730. }
  8731. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  8732. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  8733. if (!namedExportsMode) {
  8734. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  8735. }
  8736. let exportBlock = '';
  8737. if (namedExportsMode) {
  8738. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  8739. if (!reexports) {
  8740. continue;
  8741. }
  8742. for (const specifier of reexports) {
  8743. if (specifier.reexported !== '*') {
  8744. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  8745. if (exportBlock)
  8746. exportBlock += n;
  8747. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  8748. const [left, right] = getDirectReturnFunction([], {
  8749. functionReturn: true,
  8750. lineBreakIndent: null,
  8751. name: null
  8752. });
  8753. exportBlock +=
  8754. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  8755. `${t}enumerable:${_}true,${n}` +
  8756. `${t}get:${_}${left}${importName}${right}${n}});`;
  8757. }
  8758. else if (specifier.reexported === '__proto__') {
  8759. exportBlock +=
  8760. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  8761. `${t}enumerable:${_}true,${n}` +
  8762. `${t}value:${_}${importName}${n}});`;
  8763. }
  8764. else {
  8765. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  8766. }
  8767. }
  8768. }
  8769. }
  8770. }
  8771. for (const { exported, local } of exports) {
  8772. const lhs = `exports${getPropertyAccess(exported)}`;
  8773. const rhs = local;
  8774. if (lhs !== rhs) {
  8775. if (exportBlock)
  8776. exportBlock += n;
  8777. exportBlock +=
  8778. exported === '__proto__'
  8779. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  8780. `${t}enumerable:${_}true,${n}` +
  8781. `${t}value:${_}${rhs}${n}});`
  8782. : `${lhs}${_}=${_}${rhs};`;
  8783. }
  8784. }
  8785. if (namedExportsMode) {
  8786. for (const { name, reexports } of dependencies) {
  8787. if (!reexports) {
  8788. continue;
  8789. }
  8790. for (const specifier of reexports) {
  8791. if (specifier.reexported === '*') {
  8792. if (exportBlock)
  8793. exportBlock += n;
  8794. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  8795. const protoString = "'__proto__'";
  8796. exportBlock +=
  8797. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  8798. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  8799. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  8800. `${t}${t}enumerable:${_}true,${n}` +
  8801. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  8802. `${t}});${n}${n}`;
  8803. }
  8804. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  8805. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  8806. isAsync: false,
  8807. name: null
  8808. })}${copyPropertyIfNecessary});`;
  8809. }
  8810. }
  8811. }
  8812. }
  8813. if (exportBlock) {
  8814. return `${n}${n}${exportBlock}`;
  8815. }
  8816. return '';
  8817. }
  8818. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  8819. if (exports.length > 0) {
  8820. return exports[0].local;
  8821. }
  8822. else {
  8823. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  8824. if (reexports) {
  8825. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  8826. }
  8827. }
  8828. }
  8829. }
  8830. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  8831. if (imported === 'default') {
  8832. if (!isChunk) {
  8833. const moduleInterop = interop(moduleId);
  8834. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  8835. ? defaultVariableName
  8836. : moduleVariableName;
  8837. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  8838. ? `${variableName}${getPropertyAccess('default')}`
  8839. : variableName;
  8840. }
  8841. return depNamedExportsMode
  8842. ? `${moduleVariableName}${getPropertyAccess('default')}`
  8843. : moduleVariableName;
  8844. }
  8845. if (imported === '*') {
  8846. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  8847. ? namespaceVariableName
  8848. : moduleVariableName;
  8849. }
  8850. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  8851. }
  8852. function getEsModuleValue(getObject) {
  8853. return getObject([['value', 'true']], {
  8854. lineBreakIndent: null
  8855. });
  8856. }
  8857. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  8858. if (hasNamedExports) {
  8859. if (addEsModule) {
  8860. if (addNamespaceToStringTag) {
  8861. return `Object.defineProperties(exports,${_}${getObject([
  8862. ['__esModule', getEsModuleValue(getObject)],
  8863. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  8864. ], {
  8865. lineBreakIndent: null
  8866. })});`;
  8867. }
  8868. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  8869. }
  8870. if (addNamespaceToStringTag) {
  8871. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  8872. }
  8873. }
  8874. return '';
  8875. }
  8876. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  8877. if (needsLiveBinding) {
  8878. const [left, right] = getDirectReturnFunction([], {
  8879. functionReturn: true,
  8880. lineBreakIndent: null,
  8881. name: null
  8882. });
  8883. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  8884. `${t}${t}enumerable:${_}true,${n}` +
  8885. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  8886. }
  8887. return `exports[k]${_}=${_}${name}[k]`;
  8888. };
  8889. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  8890. const { _, cnst, n } = snippets;
  8891. const neededInteropHelpers = new Set();
  8892. const interopStatements = [];
  8893. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  8894. neededInteropHelpers.add(helper);
  8895. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  8896. };
  8897. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  8898. if (isChunk) {
  8899. for (const { imported, reexported } of [
  8900. ...(imports || []),
  8901. ...(reexports || [])
  8902. ]) {
  8903. if (imported === '*' && reexported !== '*') {
  8904. if (!namedExportsMode) {
  8905. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  8906. }
  8907. break;
  8908. }
  8909. }
  8910. }
  8911. else {
  8912. const moduleInterop = interop(importPath);
  8913. let hasDefault = false;
  8914. let hasNamespace = false;
  8915. for (const { imported, reexported } of [
  8916. ...(imports || []),
  8917. ...(reexports || [])
  8918. ]) {
  8919. let helper;
  8920. let variableName;
  8921. if (imported === 'default') {
  8922. if (!hasDefault) {
  8923. hasDefault = true;
  8924. if (defaultVariableName !== namespaceVariableName) {
  8925. variableName = defaultVariableName;
  8926. helper = defaultInteropHelpersByInteropType[moduleInterop];
  8927. }
  8928. }
  8929. }
  8930. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  8931. hasNamespace = true;
  8932. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  8933. variableName = namespaceVariableName;
  8934. }
  8935. if (helper) {
  8936. addInteropStatement(variableName, helper, name);
  8937. }
  8938. }
  8939. }
  8940. }
  8941. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  8942. }
  8943. function addJsExtension(name) {
  8944. return name.endsWith('.js') ? name : name + '.js';
  8945. }
  8946. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  8947. // The assumption is that this makes sense for all relative ids:
  8948. // https://requirejs.org/docs/api.html#jsfiles
  8949. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  8950. if (id[0] !== '.') {
  8951. return id;
  8952. }
  8953. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  8954. }
  8955. const builtinModules = [
  8956. "assert",
  8957. "assert/strict",
  8958. "async_hooks",
  8959. "buffer",
  8960. "child_process",
  8961. "cluster",
  8962. "console",
  8963. "constants",
  8964. "crypto",
  8965. "dgram",
  8966. "diagnostics_channel",
  8967. "dns",
  8968. "dns/promises",
  8969. "domain",
  8970. "events",
  8971. "fs",
  8972. "fs/promises",
  8973. "http",
  8974. "http2",
  8975. "https",
  8976. "inspector",
  8977. "inspector/promises",
  8978. "module",
  8979. "net",
  8980. "os",
  8981. "path",
  8982. "path/posix",
  8983. "path/win32",
  8984. "perf_hooks",
  8985. "process",
  8986. "punycode",
  8987. "querystring",
  8988. "readline",
  8989. "readline/promises",
  8990. "repl",
  8991. "stream",
  8992. "stream/consumers",
  8993. "stream/promises",
  8994. "stream/web",
  8995. "string_decoder",
  8996. "timers",
  8997. "timers/promises",
  8998. "tls",
  8999. "trace_events",
  9000. "tty",
  9001. "url",
  9002. "util",
  9003. "util/types",
  9004. "v8",
  9005. "vm",
  9006. "wasi",
  9007. "worker_threads",
  9008. "zlib"
  9009. ];
  9010. const nodeBuiltins = new Set(builtinModules);
  9011. function warnOnBuiltins(log, dependencies) {
  9012. const externalBuiltins = dependencies
  9013. .map(({ importPath }) => importPath)
  9014. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  9015. if (externalBuiltins.length === 0)
  9016. return;
  9017. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNodeBuiltins(externalBuiltins));
  9018. }
  9019. 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 }) {
  9020. warnOnBuiltins(log, dependencies);
  9021. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  9022. const parameters = dependencies.map(m => m.name);
  9023. const { n, getNonArrowFunctionIntro, _ } = snippets;
  9024. if (namedExportsMode && hasExports) {
  9025. parameters.unshift(`exports`);
  9026. deps.unshift(`'exports'`);
  9027. }
  9028. if (accessedGlobals.has('require')) {
  9029. parameters.unshift('require');
  9030. deps.unshift(`'require'`);
  9031. }
  9032. if (accessedGlobals.has('module')) {
  9033. parameters.unshift('module');
  9034. deps.unshift(`'module'`);
  9035. }
  9036. const completeAmdId = getCompleteAmdId(amd, id);
  9037. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  9038. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  9039. const useStrict = strict ? `${_}'use strict';` : '';
  9040. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  9041. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9042. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  9043. if (namespaceMarkers) {
  9044. namespaceMarkers = n + n + namespaceMarkers;
  9045. }
  9046. magicString
  9047. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9048. .indent(t)
  9049. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9050. // cf. https://v8.dev/blog/preparser#pife
  9051. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  9052. isAsync: false,
  9053. name: null
  9054. })}{${useStrict}${n}${n}`)
  9055. .append(`${n}${n}}));`);
  9056. }
  9057. 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 }) {
  9058. const { _, n } = snippets;
  9059. const useStrict = strict ? `'use strict';${n}${n}` : '';
  9060. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  9061. if (namespaceMarkers) {
  9062. namespaceMarkers += n + n;
  9063. }
  9064. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  9065. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  9066. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  9067. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  9068. magicString.append(`${exportBlock}${outro}`);
  9069. }
  9070. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  9071. let importBlock = '';
  9072. let definingVariable = false;
  9073. for (const { importPath, name, reexports, imports } of dependencies) {
  9074. if (!reexports && !imports) {
  9075. if (importBlock) {
  9076. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  9077. }
  9078. definingVariable = false;
  9079. importBlock += `require('${importPath}')`;
  9080. }
  9081. else {
  9082. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  9083. definingVariable = true;
  9084. importBlock += `${name}${_}=${_}require('${importPath}')`;
  9085. }
  9086. }
  9087. if (importBlock) {
  9088. return `${importBlock};${n}${n}`;
  9089. }
  9090. return '';
  9091. }
  9092. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  9093. const { n } = snippets;
  9094. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  9095. if (importBlock.length > 0)
  9096. intro += importBlock.join(n) + n + n;
  9097. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  9098. if (intro)
  9099. magicString.prepend(intro);
  9100. const exportBlock = getExportBlock(exports, snippets);
  9101. if (exportBlock.length > 0)
  9102. magicString.append(n + n + exportBlock.join(n).trim());
  9103. if (outro)
  9104. magicString.append(outro);
  9105. magicString.trim();
  9106. }
  9107. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  9108. const importBlock = [];
  9109. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  9110. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  9111. const pathWithAssertion = `'${importPath}'${assertion};`;
  9112. if (!reexports && !imports) {
  9113. importBlock.push(`import${_}${pathWithAssertion}`);
  9114. continue;
  9115. }
  9116. if (imports) {
  9117. let defaultImport = null;
  9118. let starImport = null;
  9119. const importedNames = [];
  9120. for (const specifier of imports) {
  9121. if (specifier.imported === 'default') {
  9122. defaultImport = specifier;
  9123. }
  9124. else if (specifier.imported === '*') {
  9125. starImport = specifier;
  9126. }
  9127. else {
  9128. importedNames.push(specifier);
  9129. }
  9130. }
  9131. if (starImport) {
  9132. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  9133. }
  9134. if (defaultImport && importedNames.length === 0) {
  9135. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  9136. }
  9137. else if (importedNames.length > 0) {
  9138. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  9139. .map(specifier => specifier.imported === specifier.local
  9140. ? specifier.imported
  9141. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  9142. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  9143. }
  9144. }
  9145. if (reexports) {
  9146. let starExport = null;
  9147. const namespaceReexports = [];
  9148. const namedReexports = [];
  9149. for (const specifier of reexports) {
  9150. if (specifier.reexported === '*') {
  9151. starExport = specifier;
  9152. }
  9153. else if (specifier.imported === '*') {
  9154. namespaceReexports.push(specifier);
  9155. }
  9156. else {
  9157. namedReexports.push(specifier);
  9158. }
  9159. }
  9160. if (starExport) {
  9161. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  9162. }
  9163. if (namespaceReexports.length > 0) {
  9164. if (!imports ||
  9165. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  9166. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  9167. }
  9168. for (const specifier of namespaceReexports) {
  9169. importBlock.push(`export${_}{${_}${name === specifier.reexported
  9170. ? name
  9171. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  9172. }
  9173. }
  9174. if (namedReexports.length > 0) {
  9175. importBlock.push(`export${_}{${_}${namedReexports
  9176. .map(specifier => specifier.imported === specifier.reexported
  9177. ? stringifyIdentifierIfNeeded(specifier.imported)
  9178. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  9179. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  9180. }
  9181. }
  9182. }
  9183. return importBlock;
  9184. }
  9185. function getExportBlock(exports, { _, cnst }) {
  9186. const exportBlock = [];
  9187. const exportDeclaration = [];
  9188. for (const specifier of exports) {
  9189. if (specifier.expression) {
  9190. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  9191. }
  9192. exportDeclaration.push(specifier.exported === specifier.local
  9193. ? specifier.local
  9194. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`);
  9195. }
  9196. if (exportDeclaration.length > 0) {
  9197. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  9198. }
  9199. return exportBlock;
  9200. }
  9201. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  9202. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  9203. const parts = name.split('.');
  9204. // Check if the key exists in the object's prototype.
  9205. const isReserved = parts[0] in Object.prototype;
  9206. if (log && isReserved) {
  9207. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  9208. }
  9209. parts[0] =
  9210. (typeof globals === 'function'
  9211. ? globals(parts[0])
  9212. : isReserved
  9213. ? parts[0]
  9214. : globals[parts[0]]) || parts[0];
  9215. parts.pop();
  9216. let propertyPath = root;
  9217. return (parts
  9218. .map(part => {
  9219. propertyPath += getPropertyAccess(part);
  9220. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  9221. })
  9222. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  9223. }
  9224. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  9225. const parts = deepName.split('.');
  9226. // Check if the key exists in the object's prototype.
  9227. const isReserved = parts[0] in Object.prototype;
  9228. if (log && isReserved) {
  9229. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logReservedNamespace(parts[0]));
  9230. }
  9231. parts[0] =
  9232. (typeof globals === 'function'
  9233. ? globals(parts[0])
  9234. : isReserved
  9235. ? parts[0]
  9236. : globals[parts[0]]) || parts[0];
  9237. const last = parts.pop();
  9238. let propertyPath = root;
  9239. let deepAssignment = [
  9240. ...parts.map(part => {
  9241. propertyPath += getPropertyAccess(part);
  9242. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  9243. }),
  9244. `${propertyPath}${getPropertyAccess(last)}`
  9245. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  9246. if (parts.length > 0) {
  9247. deepAssignment = `(${deepAssignment})`;
  9248. }
  9249. return deepAssignment;
  9250. }
  9251. function trimEmptyImports(dependencies) {
  9252. let index = dependencies.length;
  9253. while (index--) {
  9254. const { imports, reexports } = dependencies[index];
  9255. if (imports || reexports) {
  9256. return dependencies.slice(0, index + 1);
  9257. }
  9258. }
  9259. return [];
  9260. }
  9261. 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 }) {
  9262. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  9263. const isNamespaced = name && name.includes('.');
  9264. const useVariableAssignment = !extend && !isNamespaced;
  9265. if (name && useVariableAssignment && !isLegal(name)) {
  9266. return parseAst_js.error(parseAst_js.logIllegalIdentifierAsName(name));
  9267. }
  9268. warnOnBuiltins(log, dependencies);
  9269. const external = trimEmptyImports(dependencies);
  9270. const deps = external.map(dep => dep.globalName || 'null');
  9271. const parameters = external.map(m => m.name);
  9272. if (hasExports && !name) {
  9273. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingNameOptionForIifeExport());
  9274. }
  9275. if (namedExportsMode && hasExports) {
  9276. if (extend) {
  9277. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  9278. parameters.unshift('exports');
  9279. }
  9280. else {
  9281. deps.unshift('{}');
  9282. parameters.unshift('exports');
  9283. }
  9284. }
  9285. const useStrict = strict ? `${t}'use strict';${n}` : '';
  9286. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  9287. magicString.prepend(`${intro}${interopBlock}`);
  9288. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  9289. isAsync: false,
  9290. name: null
  9291. })}{${n}${useStrict}${n}`;
  9292. if (hasExports) {
  9293. if (name && !(extend && namedExportsMode)) {
  9294. wrapperIntro =
  9295. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  9296. `${_}=${_}${wrapperIntro}`;
  9297. }
  9298. if (isNamespaced) {
  9299. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  9300. }
  9301. }
  9302. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  9303. if (hasExports && !extend && namedExportsMode) {
  9304. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  9305. }
  9306. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9307. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  9308. if (namespaceMarkers) {
  9309. namespaceMarkers = n + n + namespaceMarkers;
  9310. }
  9311. magicString
  9312. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9313. .indent(t)
  9314. .prepend(wrapperIntro)
  9315. .append(wrapperOutro);
  9316. }
  9317. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  9318. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  9319. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  9320. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  9321. const registeredName = name ? `'${name}',${_}` : '';
  9322. const wrapperParameters = accessedGlobals.has('module')
  9323. ? ['exports', 'module']
  9324. : hasExports
  9325. ? ['exports']
  9326. : [];
  9327. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9328. // cf. https://v8.dev/blog/preparser#pife
  9329. let wrapperStart = `System.register(${registeredName}[` +
  9330. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  9331. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  9332. isAsync: false,
  9333. name: null
  9334. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  9335. getStarExcludesBlock(starExcludes, t, snippets) +
  9336. getImportBindingsBlock(importBindings, t, snippets) +
  9337. `${n}${t}return${_}{${setters.length > 0
  9338. ? `${n}${t}${t}setters:${_}[${setters
  9339. .map(setter => setter
  9340. ? `${getFunctionIntro(['module'], {
  9341. isAsync: false,
  9342. name: null
  9343. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  9344. : systemNullSetters
  9345. ? `null`
  9346. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  9347. .join(`,${_}`)}],`
  9348. : ''}${n}`;
  9349. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  9350. isAsync: usesTopLevelAwait,
  9351. name: null
  9352. })}{${n}${n}`;
  9353. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  9354. magicString
  9355. .prepend(intro +
  9356. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  9357. getHoistedExportsBlock(exports, t, snippets))
  9358. .append(`${outro}${n}${n}` +
  9359. getSyntheticExportsBlock(exports, t, snippets) +
  9360. getMissingExportsBlock(exports, t, snippets))
  9361. .indent(`${t}${t}${t}`)
  9362. .append(wrapperEnd)
  9363. .prepend(wrapperStart);
  9364. }
  9365. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  9366. const importBindings = [];
  9367. const setters = [];
  9368. let starExcludes = null;
  9369. for (const { imports, reexports } of dependencies) {
  9370. const setter = [];
  9371. if (imports) {
  9372. for (const specifier of imports) {
  9373. importBindings.push(specifier.local);
  9374. if (specifier.imported === '*') {
  9375. setter.push(`${specifier.local}${_}=${_}module;`);
  9376. }
  9377. else {
  9378. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  9379. }
  9380. }
  9381. }
  9382. if (reexports) {
  9383. const reexportedNames = [];
  9384. let hasStarReexport = false;
  9385. for (const { imported, reexported } of reexports) {
  9386. if (reexported === '*') {
  9387. hasStarReexport = true;
  9388. }
  9389. else {
  9390. reexportedNames.push([
  9391. reexported,
  9392. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  9393. ]);
  9394. }
  9395. }
  9396. if (reexportedNames.length > 1 || hasStarReexport) {
  9397. if (hasStarReexport) {
  9398. if (!starExcludes) {
  9399. starExcludes = getStarExcludes({ dependencies, exports });
  9400. }
  9401. reexportedNames.unshift([null, `__proto__:${_}null`]);
  9402. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  9403. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  9404. }
  9405. else {
  9406. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  9407. setter.push(`exports(${exportMapping});`);
  9408. }
  9409. }
  9410. else {
  9411. const [key, value] = reexportedNames[0];
  9412. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  9413. }
  9414. }
  9415. setters.push(setter.join(`${n}${t}${t}${t}`));
  9416. }
  9417. return { importBindings, setters, starExcludes };
  9418. }
  9419. const getStarExcludes = ({ dependencies, exports }) => {
  9420. const starExcludes = new Set(exports.map(expt => expt.exported));
  9421. starExcludes.add('default');
  9422. for (const { reexports } of dependencies) {
  9423. if (reexports) {
  9424. for (const reexport of reexports) {
  9425. if (reexport.reexported !== '*')
  9426. starExcludes.add(reexport.reexported);
  9427. }
  9428. }
  9429. }
  9430. return starExcludes;
  9431. };
  9432. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  9433. if (starExcludes) {
  9434. const fields = [...starExcludes].map(property => [
  9435. property,
  9436. '1'
  9437. ]);
  9438. fields.unshift([null, `__proto__:${_}null`]);
  9439. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  9440. lineBreakIndent: { base: t, t }
  9441. })};`;
  9442. }
  9443. return '';
  9444. };
  9445. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  9446. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  9447. function getExportsBlock(exports, t, { _, n }) {
  9448. if (exports.length === 0) {
  9449. return '';
  9450. }
  9451. if (exports.length === 1) {
  9452. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  9453. }
  9454. return (`exports({${n}` +
  9455. exports
  9456. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  9457. .join(`,${n}`) +
  9458. `${n}});${n}${n}`);
  9459. }
  9460. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  9461. .filter(expt => expt.expression)
  9462. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  9463. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  9464. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  9465. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  9466. function globalProperty(name, globalVariable, getPropertyAccess) {
  9467. if (!name)
  9468. return 'null';
  9469. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  9470. }
  9471. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  9472. let propertyPath = globalVariable;
  9473. return name
  9474. .split('.')
  9475. .map(part => (propertyPath += getPropertyAccess(part)))
  9476. .join(`${_}&&${_}`);
  9477. }
  9478. 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 }) {
  9479. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  9480. const factoryVariable = compact ? 'f' : 'factory';
  9481. const globalVariable = compact ? 'g' : 'global';
  9482. if (hasExports && !name) {
  9483. return parseAst_js.error(parseAst_js.logMissingNameOptionForUmdExport());
  9484. }
  9485. warnOnBuiltins(log, dependencies);
  9486. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  9487. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  9488. const trimmedImports = trimEmptyImports(dependencies);
  9489. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  9490. const factoryParameters = trimmedImports.map(m => m.name);
  9491. if (namedExportsMode && (hasExports || noConflict)) {
  9492. amdDeps.unshift(`'exports'`);
  9493. cjsDeps.unshift(`exports`);
  9494. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  9495. factoryParameters.unshift('exports');
  9496. }
  9497. const completeAmdId = getCompleteAmdId(amd, id);
  9498. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  9499. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  9500. const define = amd.define;
  9501. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  9502. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  9503. let iifeExport;
  9504. if (noConflict) {
  9505. const noConflictExportsVariable = compact ? 'e' : 'exports';
  9506. let factory;
  9507. if (!namedExportsMode && hasExports) {
  9508. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  9509. }
  9510. else {
  9511. const module = globalDeps.shift();
  9512. factory =
  9513. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  9514. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  9515. }
  9516. iifeExport =
  9517. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  9518. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  9519. `${t}${t}${factory}${n}` +
  9520. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  9521. isAsync: false,
  9522. name: null
  9523. })}{${_}` +
  9524. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  9525. `${t}})()`;
  9526. }
  9527. else {
  9528. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  9529. if (!namedExportsMode && hasExports) {
  9530. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  9531. }
  9532. }
  9533. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  9534. const wrapperParameters = [factoryVariable];
  9535. if (iifeNeedsGlobal) {
  9536. wrapperParameters.unshift(globalVariable);
  9537. }
  9538. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  9539. const iifeStart = iifeNeedsGlobal
  9540. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  9541. : '';
  9542. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  9543. const cjsIntro = iifeNeedsGlobal
  9544. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  9545. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  9546. : '';
  9547. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  9548. cjsIntro +
  9549. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  9550. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  9551. // factory function should be wrapped by parentheses to avoid lazy parsing,
  9552. // cf. https://v8.dev/blog/preparser#pife
  9553. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  9554. isAsync: false,
  9555. name: null
  9556. })}{${useStrict}${n}`;
  9557. const wrapperOutro = n + n + '}));';
  9558. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  9559. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  9560. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  9561. if (namespaceMarkers) {
  9562. namespaceMarkers = n + n + namespaceMarkers;
  9563. }
  9564. magicString
  9565. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  9566. .trim()
  9567. .indent(t)
  9568. .append(wrapperOutro)
  9569. .prepend(wrapperIntro);
  9570. }
  9571. const finalisers = { amd, cjs, es, iife, system, umd };
  9572. function getDefaultExportFromCjs (x) {
  9573. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  9574. }
  9575. function getAugmentedNamespace(n) {
  9576. if (n.__esModule) return n;
  9577. var f = n.default;
  9578. if (typeof f == "function") {
  9579. var a = function a () {
  9580. if (this instanceof a) {
  9581. return Reflect.construct(f, arguments, this.constructor);
  9582. }
  9583. return f.apply(this, arguments);
  9584. };
  9585. a.prototype = f.prototype;
  9586. } else a = {};
  9587. Object.defineProperty(a, '__esModule', {value: true});
  9588. Object.keys(n).forEach(function (k) {
  9589. var d = Object.getOwnPropertyDescriptor(n, k);
  9590. Object.defineProperty(a, k, d.get ? d : {
  9591. enumerable: true,
  9592. get: function () {
  9593. return n[k];
  9594. }
  9595. });
  9596. });
  9597. return a;
  9598. }
  9599. var utils = {};
  9600. var constants;
  9601. var hasRequiredConstants;
  9602. function requireConstants () {
  9603. if (hasRequiredConstants) return constants;
  9604. hasRequiredConstants = 1;
  9605. const WIN_SLASH = '\\\\/';
  9606. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  9607. /**
  9608. * Posix glob regex
  9609. */
  9610. const DOT_LITERAL = '\\.';
  9611. const PLUS_LITERAL = '\\+';
  9612. const QMARK_LITERAL = '\\?';
  9613. const SLASH_LITERAL = '\\/';
  9614. const ONE_CHAR = '(?=.)';
  9615. const QMARK = '[^/]';
  9616. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  9617. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  9618. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  9619. const NO_DOT = `(?!${DOT_LITERAL})`;
  9620. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  9621. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  9622. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  9623. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  9624. const STAR = `${QMARK}*?`;
  9625. const SEP = '/';
  9626. const POSIX_CHARS = {
  9627. DOT_LITERAL,
  9628. PLUS_LITERAL,
  9629. QMARK_LITERAL,
  9630. SLASH_LITERAL,
  9631. ONE_CHAR,
  9632. QMARK,
  9633. END_ANCHOR,
  9634. DOTS_SLASH,
  9635. NO_DOT,
  9636. NO_DOTS,
  9637. NO_DOT_SLASH,
  9638. NO_DOTS_SLASH,
  9639. QMARK_NO_DOT,
  9640. STAR,
  9641. START_ANCHOR,
  9642. SEP
  9643. };
  9644. /**
  9645. * Windows glob regex
  9646. */
  9647. const WINDOWS_CHARS = {
  9648. ...POSIX_CHARS,
  9649. SLASH_LITERAL: `[${WIN_SLASH}]`,
  9650. QMARK: WIN_NO_SLASH,
  9651. STAR: `${WIN_NO_SLASH}*?`,
  9652. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  9653. NO_DOT: `(?!${DOT_LITERAL})`,
  9654. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  9655. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  9656. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  9657. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  9658. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  9659. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  9660. SEP: '\\'
  9661. };
  9662. /**
  9663. * POSIX Bracket Regex
  9664. */
  9665. const POSIX_REGEX_SOURCE = {
  9666. alnum: 'a-zA-Z0-9',
  9667. alpha: 'a-zA-Z',
  9668. ascii: '\\x00-\\x7F',
  9669. blank: ' \\t',
  9670. cntrl: '\\x00-\\x1F\\x7F',
  9671. digit: '0-9',
  9672. graph: '\\x21-\\x7E',
  9673. lower: 'a-z',
  9674. print: '\\x20-\\x7E ',
  9675. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  9676. space: ' \\t\\r\\n\\v\\f',
  9677. upper: 'A-Z',
  9678. word: 'A-Za-z0-9_',
  9679. xdigit: 'A-Fa-f0-9'
  9680. };
  9681. constants = {
  9682. MAX_LENGTH: 1024 * 64,
  9683. POSIX_REGEX_SOURCE,
  9684. // regular expressions
  9685. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  9686. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  9687. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  9688. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  9689. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  9690. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  9691. // Replace globs with equivalent patterns to reduce parsing time.
  9692. REPLACEMENTS: {
  9693. '***': '*',
  9694. '**/**': '**',
  9695. '**/**/**': '**'
  9696. },
  9697. // Digits
  9698. CHAR_0: 48, /* 0 */
  9699. CHAR_9: 57, /* 9 */
  9700. // Alphabet chars.
  9701. CHAR_UPPERCASE_A: 65, /* A */
  9702. CHAR_LOWERCASE_A: 97, /* a */
  9703. CHAR_UPPERCASE_Z: 90, /* Z */
  9704. CHAR_LOWERCASE_Z: 122, /* z */
  9705. CHAR_LEFT_PARENTHESES: 40, /* ( */
  9706. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  9707. CHAR_ASTERISK: 42, /* * */
  9708. // Non-alphabetic chars.
  9709. CHAR_AMPERSAND: 38, /* & */
  9710. CHAR_AT: 64, /* @ */
  9711. CHAR_BACKWARD_SLASH: 92, /* \ */
  9712. CHAR_CARRIAGE_RETURN: 13, /* \r */
  9713. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  9714. CHAR_COLON: 58, /* : */
  9715. CHAR_COMMA: 44, /* , */
  9716. CHAR_DOT: 46, /* . */
  9717. CHAR_DOUBLE_QUOTE: 34, /* " */
  9718. CHAR_EQUAL: 61, /* = */
  9719. CHAR_EXCLAMATION_MARK: 33, /* ! */
  9720. CHAR_FORM_FEED: 12, /* \f */
  9721. CHAR_FORWARD_SLASH: 47, /* / */
  9722. CHAR_GRAVE_ACCENT: 96, /* ` */
  9723. CHAR_HASH: 35, /* # */
  9724. CHAR_HYPHEN_MINUS: 45, /* - */
  9725. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  9726. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  9727. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  9728. CHAR_LINE_FEED: 10, /* \n */
  9729. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  9730. CHAR_PERCENT: 37, /* % */
  9731. CHAR_PLUS: 43, /* + */
  9732. CHAR_QUESTION_MARK: 63, /* ? */
  9733. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  9734. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  9735. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  9736. CHAR_SEMICOLON: 59, /* ; */
  9737. CHAR_SINGLE_QUOTE: 39, /* ' */
  9738. CHAR_SPACE: 32, /* */
  9739. CHAR_TAB: 9, /* \t */
  9740. CHAR_UNDERSCORE: 95, /* _ */
  9741. CHAR_VERTICAL_LINE: 124, /* | */
  9742. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  9743. /**
  9744. * Create EXTGLOB_CHARS
  9745. */
  9746. extglobChars(chars) {
  9747. return {
  9748. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  9749. '?': { type: 'qmark', open: '(?:', close: ')?' },
  9750. '+': { type: 'plus', open: '(?:', close: ')+' },
  9751. '*': { type: 'star', open: '(?:', close: ')*' },
  9752. '@': { type: 'at', open: '(?:', close: ')' }
  9753. };
  9754. },
  9755. /**
  9756. * Create GLOB_CHARS
  9757. */
  9758. globChars(win32) {
  9759. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  9760. }
  9761. };
  9762. return constants;
  9763. }
  9764. /*global navigator*/
  9765. var hasRequiredUtils;
  9766. function requireUtils () {
  9767. if (hasRequiredUtils) return utils;
  9768. hasRequiredUtils = 1;
  9769. (function (exports) {
  9770. const {
  9771. REGEX_BACKSLASH,
  9772. REGEX_REMOVE_BACKSLASH,
  9773. REGEX_SPECIAL_CHARS,
  9774. REGEX_SPECIAL_CHARS_GLOBAL
  9775. } = /*@__PURE__*/ requireConstants();
  9776. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  9777. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  9778. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  9779. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  9780. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  9781. exports.isWindows = () => {
  9782. if (typeof navigator !== 'undefined' && navigator.platform) {
  9783. const platform = navigator.platform.toLowerCase();
  9784. return platform === 'win32' || platform === 'windows';
  9785. }
  9786. if (typeof process !== 'undefined' && process.platform) {
  9787. return process.platform === 'win32';
  9788. }
  9789. return false;
  9790. };
  9791. exports.removeBackslashes = str => {
  9792. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  9793. return match === '\\' ? '' : match;
  9794. });
  9795. };
  9796. exports.escapeLast = (input, char, lastIdx) => {
  9797. const idx = input.lastIndexOf(char, lastIdx);
  9798. if (idx === -1) return input;
  9799. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  9800. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  9801. };
  9802. exports.removePrefix = (input, state = {}) => {
  9803. let output = input;
  9804. if (output.startsWith('./')) {
  9805. output = output.slice(2);
  9806. state.prefix = './';
  9807. }
  9808. return output;
  9809. };
  9810. exports.wrapOutput = (input, state = {}, options = {}) => {
  9811. const prepend = options.contains ? '' : '^';
  9812. const append = options.contains ? '' : '$';
  9813. let output = `${prepend}(?:${input})${append}`;
  9814. if (state.negated === true) {
  9815. output = `(?:^(?!${output}).*$)`;
  9816. }
  9817. return output;
  9818. };
  9819. exports.basename = (path, { windows } = {}) => {
  9820. const segs = path.split(windows ? /[\\/]/ : '/');
  9821. const last = segs[segs.length - 1];
  9822. if (last === '') {
  9823. return segs[segs.length - 2];
  9824. }
  9825. return last;
  9826. };
  9827. } (utils));
  9828. return utils;
  9829. }
  9830. var scan_1;
  9831. var hasRequiredScan;
  9832. function requireScan () {
  9833. if (hasRequiredScan) return scan_1;
  9834. hasRequiredScan = 1;
  9835. const utils = /*@__PURE__*/ requireUtils();
  9836. const {
  9837. CHAR_ASTERISK, /* * */
  9838. CHAR_AT, /* @ */
  9839. CHAR_BACKWARD_SLASH, /* \ */
  9840. CHAR_COMMA, /* , */
  9841. CHAR_DOT, /* . */
  9842. CHAR_EXCLAMATION_MARK, /* ! */
  9843. CHAR_FORWARD_SLASH, /* / */
  9844. CHAR_LEFT_CURLY_BRACE, /* { */
  9845. CHAR_LEFT_PARENTHESES, /* ( */
  9846. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  9847. CHAR_PLUS, /* + */
  9848. CHAR_QUESTION_MARK, /* ? */
  9849. CHAR_RIGHT_CURLY_BRACE, /* } */
  9850. CHAR_RIGHT_PARENTHESES, /* ) */
  9851. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  9852. } = /*@__PURE__*/ requireConstants();
  9853. const isPathSeparator = code => {
  9854. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  9855. };
  9856. const depth = token => {
  9857. if (token.isPrefix !== true) {
  9858. token.depth = token.isGlobstar ? Infinity : 1;
  9859. }
  9860. };
  9861. /**
  9862. * Quickly scans a glob pattern and returns an object with a handful of
  9863. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  9864. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  9865. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  9866. *
  9867. * ```js
  9868. * const pm = require('picomatch');
  9869. * console.log(pm.scan('foo/bar/*.js'));
  9870. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  9871. * ```
  9872. * @param {String} `str`
  9873. * @param {Object} `options`
  9874. * @return {Object} Returns an object with tokens and regex source string.
  9875. * @api public
  9876. */
  9877. const scan = (input, options) => {
  9878. const opts = options || {};
  9879. const length = input.length - 1;
  9880. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  9881. const slashes = [];
  9882. const tokens = [];
  9883. const parts = [];
  9884. let str = input;
  9885. let index = -1;
  9886. let start = 0;
  9887. let lastIndex = 0;
  9888. let isBrace = false;
  9889. let isBracket = false;
  9890. let isGlob = false;
  9891. let isExtglob = false;
  9892. let isGlobstar = false;
  9893. let braceEscaped = false;
  9894. let backslashes = false;
  9895. let negated = false;
  9896. let negatedExtglob = false;
  9897. let finished = false;
  9898. let braces = 0;
  9899. let prev;
  9900. let code;
  9901. let token = { value: '', depth: 0, isGlob: false };
  9902. const eos = () => index >= length;
  9903. const peek = () => str.charCodeAt(index + 1);
  9904. const advance = () => {
  9905. prev = code;
  9906. return str.charCodeAt(++index);
  9907. };
  9908. while (index < length) {
  9909. code = advance();
  9910. let next;
  9911. if (code === CHAR_BACKWARD_SLASH) {
  9912. backslashes = token.backslashes = true;
  9913. code = advance();
  9914. if (code === CHAR_LEFT_CURLY_BRACE) {
  9915. braceEscaped = true;
  9916. }
  9917. continue;
  9918. }
  9919. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  9920. braces++;
  9921. while (eos() !== true && (code = advance())) {
  9922. if (code === CHAR_BACKWARD_SLASH) {
  9923. backslashes = token.backslashes = true;
  9924. advance();
  9925. continue;
  9926. }
  9927. if (code === CHAR_LEFT_CURLY_BRACE) {
  9928. braces++;
  9929. continue;
  9930. }
  9931. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  9932. isBrace = token.isBrace = true;
  9933. isGlob = token.isGlob = true;
  9934. finished = true;
  9935. if (scanToEnd === true) {
  9936. continue;
  9937. }
  9938. break;
  9939. }
  9940. if (braceEscaped !== true && code === CHAR_COMMA) {
  9941. isBrace = token.isBrace = true;
  9942. isGlob = token.isGlob = true;
  9943. finished = true;
  9944. if (scanToEnd === true) {
  9945. continue;
  9946. }
  9947. break;
  9948. }
  9949. if (code === CHAR_RIGHT_CURLY_BRACE) {
  9950. braces--;
  9951. if (braces === 0) {
  9952. braceEscaped = false;
  9953. isBrace = token.isBrace = true;
  9954. finished = true;
  9955. break;
  9956. }
  9957. }
  9958. }
  9959. if (scanToEnd === true) {
  9960. continue;
  9961. }
  9962. break;
  9963. }
  9964. if (code === CHAR_FORWARD_SLASH) {
  9965. slashes.push(index);
  9966. tokens.push(token);
  9967. token = { value: '', depth: 0, isGlob: false };
  9968. if (finished === true) continue;
  9969. if (prev === CHAR_DOT && index === (start + 1)) {
  9970. start += 2;
  9971. continue;
  9972. }
  9973. lastIndex = index + 1;
  9974. continue;
  9975. }
  9976. if (opts.noext !== true) {
  9977. const isExtglobChar = code === CHAR_PLUS
  9978. || code === CHAR_AT
  9979. || code === CHAR_ASTERISK
  9980. || code === CHAR_QUESTION_MARK
  9981. || code === CHAR_EXCLAMATION_MARK;
  9982. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  9983. isGlob = token.isGlob = true;
  9984. isExtglob = token.isExtglob = true;
  9985. finished = true;
  9986. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  9987. negatedExtglob = true;
  9988. }
  9989. if (scanToEnd === true) {
  9990. while (eos() !== true && (code = advance())) {
  9991. if (code === CHAR_BACKWARD_SLASH) {
  9992. backslashes = token.backslashes = true;
  9993. code = advance();
  9994. continue;
  9995. }
  9996. if (code === CHAR_RIGHT_PARENTHESES) {
  9997. isGlob = token.isGlob = true;
  9998. finished = true;
  9999. break;
  10000. }
  10001. }
  10002. continue;
  10003. }
  10004. break;
  10005. }
  10006. }
  10007. if (code === CHAR_ASTERISK) {
  10008. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  10009. isGlob = token.isGlob = true;
  10010. finished = true;
  10011. if (scanToEnd === true) {
  10012. continue;
  10013. }
  10014. break;
  10015. }
  10016. if (code === CHAR_QUESTION_MARK) {
  10017. isGlob = token.isGlob = true;
  10018. finished = true;
  10019. if (scanToEnd === true) {
  10020. continue;
  10021. }
  10022. break;
  10023. }
  10024. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  10025. while (eos() !== true && (next = advance())) {
  10026. if (next === CHAR_BACKWARD_SLASH) {
  10027. backslashes = token.backslashes = true;
  10028. advance();
  10029. continue;
  10030. }
  10031. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  10032. isBracket = token.isBracket = true;
  10033. isGlob = token.isGlob = true;
  10034. finished = true;
  10035. break;
  10036. }
  10037. }
  10038. if (scanToEnd === true) {
  10039. continue;
  10040. }
  10041. break;
  10042. }
  10043. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  10044. negated = token.negated = true;
  10045. start++;
  10046. continue;
  10047. }
  10048. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  10049. isGlob = token.isGlob = true;
  10050. if (scanToEnd === true) {
  10051. while (eos() !== true && (code = advance())) {
  10052. if (code === CHAR_LEFT_PARENTHESES) {
  10053. backslashes = token.backslashes = true;
  10054. code = advance();
  10055. continue;
  10056. }
  10057. if (code === CHAR_RIGHT_PARENTHESES) {
  10058. finished = true;
  10059. break;
  10060. }
  10061. }
  10062. continue;
  10063. }
  10064. break;
  10065. }
  10066. if (isGlob === true) {
  10067. finished = true;
  10068. if (scanToEnd === true) {
  10069. continue;
  10070. }
  10071. break;
  10072. }
  10073. }
  10074. if (opts.noext === true) {
  10075. isExtglob = false;
  10076. isGlob = false;
  10077. }
  10078. let base = str;
  10079. let prefix = '';
  10080. let glob = '';
  10081. if (start > 0) {
  10082. prefix = str.slice(0, start);
  10083. str = str.slice(start);
  10084. lastIndex -= start;
  10085. }
  10086. if (base && isGlob === true && lastIndex > 0) {
  10087. base = str.slice(0, lastIndex);
  10088. glob = str.slice(lastIndex);
  10089. } else if (isGlob === true) {
  10090. base = '';
  10091. glob = str;
  10092. } else {
  10093. base = str;
  10094. }
  10095. if (base && base !== '' && base !== '/' && base !== str) {
  10096. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  10097. base = base.slice(0, -1);
  10098. }
  10099. }
  10100. if (opts.unescape === true) {
  10101. if (glob) glob = utils.removeBackslashes(glob);
  10102. if (base && backslashes === true) {
  10103. base = utils.removeBackslashes(base);
  10104. }
  10105. }
  10106. const state = {
  10107. prefix,
  10108. input,
  10109. start,
  10110. base,
  10111. glob,
  10112. isBrace,
  10113. isBracket,
  10114. isGlob,
  10115. isExtglob,
  10116. isGlobstar,
  10117. negated,
  10118. negatedExtglob
  10119. };
  10120. if (opts.tokens === true) {
  10121. state.maxDepth = 0;
  10122. if (!isPathSeparator(code)) {
  10123. tokens.push(token);
  10124. }
  10125. state.tokens = tokens;
  10126. }
  10127. if (opts.parts === true || opts.tokens === true) {
  10128. let prevIndex;
  10129. for (let idx = 0; idx < slashes.length; idx++) {
  10130. const n = prevIndex ? prevIndex + 1 : start;
  10131. const i = slashes[idx];
  10132. const value = input.slice(n, i);
  10133. if (opts.tokens) {
  10134. if (idx === 0 && start !== 0) {
  10135. tokens[idx].isPrefix = true;
  10136. tokens[idx].value = prefix;
  10137. } else {
  10138. tokens[idx].value = value;
  10139. }
  10140. depth(tokens[idx]);
  10141. state.maxDepth += tokens[idx].depth;
  10142. }
  10143. if (idx !== 0 || value !== '') {
  10144. parts.push(value);
  10145. }
  10146. prevIndex = i;
  10147. }
  10148. if (prevIndex && prevIndex + 1 < input.length) {
  10149. const value = input.slice(prevIndex + 1);
  10150. parts.push(value);
  10151. if (opts.tokens) {
  10152. tokens[tokens.length - 1].value = value;
  10153. depth(tokens[tokens.length - 1]);
  10154. state.maxDepth += tokens[tokens.length - 1].depth;
  10155. }
  10156. }
  10157. state.slashes = slashes;
  10158. state.parts = parts;
  10159. }
  10160. return state;
  10161. };
  10162. scan_1 = scan;
  10163. return scan_1;
  10164. }
  10165. var parse_1;
  10166. var hasRequiredParse;
  10167. function requireParse () {
  10168. if (hasRequiredParse) return parse_1;
  10169. hasRequiredParse = 1;
  10170. const constants = /*@__PURE__*/ requireConstants();
  10171. const utils = /*@__PURE__*/ requireUtils();
  10172. /**
  10173. * Constants
  10174. */
  10175. const {
  10176. MAX_LENGTH,
  10177. POSIX_REGEX_SOURCE,
  10178. REGEX_NON_SPECIAL_CHARS,
  10179. REGEX_SPECIAL_CHARS_BACKREF,
  10180. REPLACEMENTS
  10181. } = constants;
  10182. /**
  10183. * Helpers
  10184. */
  10185. const expandRange = (args, options) => {
  10186. if (typeof options.expandRange === 'function') {
  10187. return options.expandRange(...args, options);
  10188. }
  10189. args.sort();
  10190. const value = `[${args.join('-')}]`;
  10191. return value;
  10192. };
  10193. /**
  10194. * Create the message for a syntax error
  10195. */
  10196. const syntaxError = (type, char) => {
  10197. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  10198. };
  10199. /**
  10200. * Parse the given input string.
  10201. * @param {String} input
  10202. * @param {Object} options
  10203. * @return {Object}
  10204. */
  10205. const parse = (input, options) => {
  10206. if (typeof input !== 'string') {
  10207. throw new TypeError('Expected a string');
  10208. }
  10209. input = REPLACEMENTS[input] || input;
  10210. const opts = { ...options };
  10211. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10212. let len = input.length;
  10213. if (len > max) {
  10214. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10215. }
  10216. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  10217. const tokens = [bos];
  10218. const capture = opts.capture ? '' : '?:';
  10219. // create constants based on platform, for windows or posix
  10220. const PLATFORM_CHARS = constants.globChars(opts.windows);
  10221. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  10222. const {
  10223. DOT_LITERAL,
  10224. PLUS_LITERAL,
  10225. SLASH_LITERAL,
  10226. ONE_CHAR,
  10227. DOTS_SLASH,
  10228. NO_DOT,
  10229. NO_DOT_SLASH,
  10230. NO_DOTS_SLASH,
  10231. QMARK,
  10232. QMARK_NO_DOT,
  10233. STAR,
  10234. START_ANCHOR
  10235. } = PLATFORM_CHARS;
  10236. const globstar = opts => {
  10237. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  10238. };
  10239. const nodot = opts.dot ? '' : NO_DOT;
  10240. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  10241. let star = opts.bash === true ? globstar(opts) : STAR;
  10242. if (opts.capture) {
  10243. star = `(${star})`;
  10244. }
  10245. // minimatch options support
  10246. if (typeof opts.noext === 'boolean') {
  10247. opts.noextglob = opts.noext;
  10248. }
  10249. const state = {
  10250. input,
  10251. index: -1,
  10252. start: 0,
  10253. dot: opts.dot === true,
  10254. consumed: '',
  10255. output: '',
  10256. prefix: '',
  10257. backtrack: false,
  10258. negated: false,
  10259. brackets: 0,
  10260. braces: 0,
  10261. parens: 0,
  10262. quotes: 0,
  10263. globstar: false,
  10264. tokens
  10265. };
  10266. input = utils.removePrefix(input, state);
  10267. len = input.length;
  10268. const extglobs = [];
  10269. const braces = [];
  10270. const stack = [];
  10271. let prev = bos;
  10272. let value;
  10273. /**
  10274. * Tokenizing helpers
  10275. */
  10276. const eos = () => state.index === len - 1;
  10277. const peek = state.peek = (n = 1) => input[state.index + n];
  10278. const advance = state.advance = () => input[++state.index] || '';
  10279. const remaining = () => input.slice(state.index + 1);
  10280. const consume = (value = '', num = 0) => {
  10281. state.consumed += value;
  10282. state.index += num;
  10283. };
  10284. const append = token => {
  10285. state.output += token.output != null ? token.output : token.value;
  10286. consume(token.value);
  10287. };
  10288. const negate = () => {
  10289. let count = 1;
  10290. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  10291. advance();
  10292. state.start++;
  10293. count++;
  10294. }
  10295. if (count % 2 === 0) {
  10296. return false;
  10297. }
  10298. state.negated = true;
  10299. state.start++;
  10300. return true;
  10301. };
  10302. const increment = type => {
  10303. state[type]++;
  10304. stack.push(type);
  10305. };
  10306. const decrement = type => {
  10307. state[type]--;
  10308. stack.pop();
  10309. };
  10310. /**
  10311. * Push tokens onto the tokens array. This helper speeds up
  10312. * tokenizing by 1) helping us avoid backtracking as much as possible,
  10313. * and 2) helping us avoid creating extra tokens when consecutive
  10314. * characters are plain text. This improves performance and simplifies
  10315. * lookbehinds.
  10316. */
  10317. const push = tok => {
  10318. if (prev.type === 'globstar') {
  10319. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  10320. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  10321. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  10322. state.output = state.output.slice(0, -prev.output.length);
  10323. prev.type = 'star';
  10324. prev.value = '*';
  10325. prev.output = star;
  10326. state.output += prev.output;
  10327. }
  10328. }
  10329. if (extglobs.length && tok.type !== 'paren') {
  10330. extglobs[extglobs.length - 1].inner += tok.value;
  10331. }
  10332. if (tok.value || tok.output) append(tok);
  10333. if (prev && prev.type === 'text' && tok.type === 'text') {
  10334. prev.output = (prev.output || prev.value) + tok.value;
  10335. prev.value += tok.value;
  10336. return;
  10337. }
  10338. tok.prev = prev;
  10339. tokens.push(tok);
  10340. prev = tok;
  10341. };
  10342. const extglobOpen = (type, value) => {
  10343. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  10344. token.prev = prev;
  10345. token.parens = state.parens;
  10346. token.output = state.output;
  10347. const output = (opts.capture ? '(' : '') + token.open;
  10348. increment('parens');
  10349. push({ type, value, output: state.output ? '' : ONE_CHAR });
  10350. push({ type: 'paren', extglob: true, value: advance(), output });
  10351. extglobs.push(token);
  10352. };
  10353. const extglobClose = token => {
  10354. let output = token.close + (opts.capture ? ')' : '');
  10355. let rest;
  10356. if (token.type === 'negate') {
  10357. let extglobStar = star;
  10358. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  10359. extglobStar = globstar(opts);
  10360. }
  10361. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  10362. output = token.close = `)$))${extglobStar}`;
  10363. }
  10364. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  10365. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  10366. // In this case, we need to parse the string and use it in the output of the original pattern.
  10367. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  10368. //
  10369. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  10370. const expression = parse(rest, { ...options, fastpaths: false }).output;
  10371. output = token.close = `)${expression})${extglobStar})`;
  10372. }
  10373. if (token.prev.type === 'bos') {
  10374. state.negatedExtglob = true;
  10375. }
  10376. }
  10377. push({ type: 'paren', extglob: true, value, output });
  10378. decrement('parens');
  10379. };
  10380. /**
  10381. * Fast paths
  10382. */
  10383. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  10384. let backslashes = false;
  10385. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  10386. if (first === '\\') {
  10387. backslashes = true;
  10388. return m;
  10389. }
  10390. if (first === '?') {
  10391. if (esc) {
  10392. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  10393. }
  10394. if (index === 0) {
  10395. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  10396. }
  10397. return QMARK.repeat(chars.length);
  10398. }
  10399. if (first === '.') {
  10400. return DOT_LITERAL.repeat(chars.length);
  10401. }
  10402. if (first === '*') {
  10403. if (esc) {
  10404. return esc + first + (rest ? star : '');
  10405. }
  10406. return star;
  10407. }
  10408. return esc ? m : `\\${m}`;
  10409. });
  10410. if (backslashes === true) {
  10411. if (opts.unescape === true) {
  10412. output = output.replace(/\\/g, '');
  10413. } else {
  10414. output = output.replace(/\\+/g, m => {
  10415. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  10416. });
  10417. }
  10418. }
  10419. if (output === input && opts.contains === true) {
  10420. state.output = input;
  10421. return state;
  10422. }
  10423. state.output = utils.wrapOutput(output, state, options);
  10424. return state;
  10425. }
  10426. /**
  10427. * Tokenize input until we reach end-of-string
  10428. */
  10429. while (!eos()) {
  10430. value = advance();
  10431. if (value === '\u0000') {
  10432. continue;
  10433. }
  10434. /**
  10435. * Escaped characters
  10436. */
  10437. if (value === '\\') {
  10438. const next = peek();
  10439. if (next === '/' && opts.bash !== true) {
  10440. continue;
  10441. }
  10442. if (next === '.' || next === ';') {
  10443. continue;
  10444. }
  10445. if (!next) {
  10446. value += '\\';
  10447. push({ type: 'text', value });
  10448. continue;
  10449. }
  10450. // collapse slashes to reduce potential for exploits
  10451. const match = /^\\+/.exec(remaining());
  10452. let slashes = 0;
  10453. if (match && match[0].length > 2) {
  10454. slashes = match[0].length;
  10455. state.index += slashes;
  10456. if (slashes % 2 !== 0) {
  10457. value += '\\';
  10458. }
  10459. }
  10460. if (opts.unescape === true) {
  10461. value = advance();
  10462. } else {
  10463. value += advance();
  10464. }
  10465. if (state.brackets === 0) {
  10466. push({ type: 'text', value });
  10467. continue;
  10468. }
  10469. }
  10470. /**
  10471. * If we're inside a regex character class, continue
  10472. * until we reach the closing bracket.
  10473. */
  10474. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  10475. if (opts.posix !== false && value === ':') {
  10476. const inner = prev.value.slice(1);
  10477. if (inner.includes('[')) {
  10478. prev.posix = true;
  10479. if (inner.includes(':')) {
  10480. const idx = prev.value.lastIndexOf('[');
  10481. const pre = prev.value.slice(0, idx);
  10482. const rest = prev.value.slice(idx + 2);
  10483. const posix = POSIX_REGEX_SOURCE[rest];
  10484. if (posix) {
  10485. prev.value = pre + posix;
  10486. state.backtrack = true;
  10487. advance();
  10488. if (!bos.output && tokens.indexOf(prev) === 1) {
  10489. bos.output = ONE_CHAR;
  10490. }
  10491. continue;
  10492. }
  10493. }
  10494. }
  10495. }
  10496. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  10497. value = `\\${value}`;
  10498. }
  10499. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  10500. value = `\\${value}`;
  10501. }
  10502. if (opts.posix === true && value === '!' && prev.value === '[') {
  10503. value = '^';
  10504. }
  10505. prev.value += value;
  10506. append({ value });
  10507. continue;
  10508. }
  10509. /**
  10510. * If we're inside a quoted string, continue
  10511. * until we reach the closing double quote.
  10512. */
  10513. if (state.quotes === 1 && value !== '"') {
  10514. value = utils.escapeRegex(value);
  10515. prev.value += value;
  10516. append({ value });
  10517. continue;
  10518. }
  10519. /**
  10520. * Double quotes
  10521. */
  10522. if (value === '"') {
  10523. state.quotes = state.quotes === 1 ? 0 : 1;
  10524. if (opts.keepQuotes === true) {
  10525. push({ type: 'text', value });
  10526. }
  10527. continue;
  10528. }
  10529. /**
  10530. * Parentheses
  10531. */
  10532. if (value === '(') {
  10533. increment('parens');
  10534. push({ type: 'paren', value });
  10535. continue;
  10536. }
  10537. if (value === ')') {
  10538. if (state.parens === 0 && opts.strictBrackets === true) {
  10539. throw new SyntaxError(syntaxError('opening', '('));
  10540. }
  10541. const extglob = extglobs[extglobs.length - 1];
  10542. if (extglob && state.parens === extglob.parens + 1) {
  10543. extglobClose(extglobs.pop());
  10544. continue;
  10545. }
  10546. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  10547. decrement('parens');
  10548. continue;
  10549. }
  10550. /**
  10551. * Square brackets
  10552. */
  10553. if (value === '[') {
  10554. if (opts.nobracket === true || !remaining().includes(']')) {
  10555. if (opts.nobracket !== true && opts.strictBrackets === true) {
  10556. throw new SyntaxError(syntaxError('closing', ']'));
  10557. }
  10558. value = `\\${value}`;
  10559. } else {
  10560. increment('brackets');
  10561. }
  10562. push({ type: 'bracket', value });
  10563. continue;
  10564. }
  10565. if (value === ']') {
  10566. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  10567. push({ type: 'text', value, output: `\\${value}` });
  10568. continue;
  10569. }
  10570. if (state.brackets === 0) {
  10571. if (opts.strictBrackets === true) {
  10572. throw new SyntaxError(syntaxError('opening', '['));
  10573. }
  10574. push({ type: 'text', value, output: `\\${value}` });
  10575. continue;
  10576. }
  10577. decrement('brackets');
  10578. const prevValue = prev.value.slice(1);
  10579. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  10580. value = `/${value}`;
  10581. }
  10582. prev.value += value;
  10583. append({ value });
  10584. // when literal brackets are explicitly disabled
  10585. // assume we should match with a regex character class
  10586. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  10587. continue;
  10588. }
  10589. const escaped = utils.escapeRegex(prev.value);
  10590. state.output = state.output.slice(0, -prev.value.length);
  10591. // when literal brackets are explicitly enabled
  10592. // assume we should escape the brackets to match literal characters
  10593. if (opts.literalBrackets === true) {
  10594. state.output += escaped;
  10595. prev.value = escaped;
  10596. continue;
  10597. }
  10598. // when the user specifies nothing, try to match both
  10599. prev.value = `(${capture}${escaped}|${prev.value})`;
  10600. state.output += prev.value;
  10601. continue;
  10602. }
  10603. /**
  10604. * Braces
  10605. */
  10606. if (value === '{' && opts.nobrace !== true) {
  10607. increment('braces');
  10608. const open = {
  10609. type: 'brace',
  10610. value,
  10611. output: '(',
  10612. outputIndex: state.output.length,
  10613. tokensIndex: state.tokens.length
  10614. };
  10615. braces.push(open);
  10616. push(open);
  10617. continue;
  10618. }
  10619. if (value === '}') {
  10620. const brace = braces[braces.length - 1];
  10621. if (opts.nobrace === true || !brace) {
  10622. push({ type: 'text', value, output: value });
  10623. continue;
  10624. }
  10625. let output = ')';
  10626. if (brace.dots === true) {
  10627. const arr = tokens.slice();
  10628. const range = [];
  10629. for (let i = arr.length - 1; i >= 0; i--) {
  10630. tokens.pop();
  10631. if (arr[i].type === 'brace') {
  10632. break;
  10633. }
  10634. if (arr[i].type !== 'dots') {
  10635. range.unshift(arr[i].value);
  10636. }
  10637. }
  10638. output = expandRange(range, opts);
  10639. state.backtrack = true;
  10640. }
  10641. if (brace.comma !== true && brace.dots !== true) {
  10642. const out = state.output.slice(0, brace.outputIndex);
  10643. const toks = state.tokens.slice(brace.tokensIndex);
  10644. brace.value = brace.output = '\\{';
  10645. value = output = '\\}';
  10646. state.output = out;
  10647. for (const t of toks) {
  10648. state.output += (t.output || t.value);
  10649. }
  10650. }
  10651. push({ type: 'brace', value, output });
  10652. decrement('braces');
  10653. braces.pop();
  10654. continue;
  10655. }
  10656. /**
  10657. * Pipes
  10658. */
  10659. if (value === '|') {
  10660. if (extglobs.length > 0) {
  10661. extglobs[extglobs.length - 1].conditions++;
  10662. }
  10663. push({ type: 'text', value });
  10664. continue;
  10665. }
  10666. /**
  10667. * Commas
  10668. */
  10669. if (value === ',') {
  10670. let output = value;
  10671. const brace = braces[braces.length - 1];
  10672. if (brace && stack[stack.length - 1] === 'braces') {
  10673. brace.comma = true;
  10674. output = '|';
  10675. }
  10676. push({ type: 'comma', value, output });
  10677. continue;
  10678. }
  10679. /**
  10680. * Slashes
  10681. */
  10682. if (value === '/') {
  10683. // if the beginning of the glob is "./", advance the start
  10684. // to the current index, and don't add the "./" characters
  10685. // to the state. This greatly simplifies lookbehinds when
  10686. // checking for BOS characters like "!" and "." (not "./")
  10687. if (prev.type === 'dot' && state.index === state.start + 1) {
  10688. state.start = state.index + 1;
  10689. state.consumed = '';
  10690. state.output = '';
  10691. tokens.pop();
  10692. prev = bos; // reset "prev" to the first token
  10693. continue;
  10694. }
  10695. push({ type: 'slash', value, output: SLASH_LITERAL });
  10696. continue;
  10697. }
  10698. /**
  10699. * Dots
  10700. */
  10701. if (value === '.') {
  10702. if (state.braces > 0 && prev.type === 'dot') {
  10703. if (prev.value === '.') prev.output = DOT_LITERAL;
  10704. const brace = braces[braces.length - 1];
  10705. prev.type = 'dots';
  10706. prev.output += value;
  10707. prev.value += value;
  10708. brace.dots = true;
  10709. continue;
  10710. }
  10711. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  10712. push({ type: 'text', value, output: DOT_LITERAL });
  10713. continue;
  10714. }
  10715. push({ type: 'dot', value, output: DOT_LITERAL });
  10716. continue;
  10717. }
  10718. /**
  10719. * Question marks
  10720. */
  10721. if (value === '?') {
  10722. const isGroup = prev && prev.value === '(';
  10723. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10724. extglobOpen('qmark', value);
  10725. continue;
  10726. }
  10727. if (prev && prev.type === 'paren') {
  10728. const next = peek();
  10729. let output = value;
  10730. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  10731. output = `\\${value}`;
  10732. }
  10733. push({ type: 'text', value, output });
  10734. continue;
  10735. }
  10736. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  10737. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  10738. continue;
  10739. }
  10740. push({ type: 'qmark', value, output: QMARK });
  10741. continue;
  10742. }
  10743. /**
  10744. * Exclamation
  10745. */
  10746. if (value === '!') {
  10747. if (opts.noextglob !== true && peek() === '(') {
  10748. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  10749. extglobOpen('negate', value);
  10750. continue;
  10751. }
  10752. }
  10753. if (opts.nonegate !== true && state.index === 0) {
  10754. negate();
  10755. continue;
  10756. }
  10757. }
  10758. /**
  10759. * Plus
  10760. */
  10761. if (value === '+') {
  10762. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10763. extglobOpen('plus', value);
  10764. continue;
  10765. }
  10766. if ((prev && prev.value === '(') || opts.regex === false) {
  10767. push({ type: 'plus', value, output: PLUS_LITERAL });
  10768. continue;
  10769. }
  10770. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  10771. push({ type: 'plus', value });
  10772. continue;
  10773. }
  10774. push({ type: 'plus', value: PLUS_LITERAL });
  10775. continue;
  10776. }
  10777. /**
  10778. * Plain text
  10779. */
  10780. if (value === '@') {
  10781. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10782. push({ type: 'at', extglob: true, value, output: '' });
  10783. continue;
  10784. }
  10785. push({ type: 'text', value });
  10786. continue;
  10787. }
  10788. /**
  10789. * Plain text
  10790. */
  10791. if (value !== '*') {
  10792. if (value === '$' || value === '^') {
  10793. value = `\\${value}`;
  10794. }
  10795. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  10796. if (match) {
  10797. value += match[0];
  10798. state.index += match[0].length;
  10799. }
  10800. push({ type: 'text', value });
  10801. continue;
  10802. }
  10803. /**
  10804. * Stars
  10805. */
  10806. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  10807. prev.type = 'star';
  10808. prev.star = true;
  10809. prev.value += value;
  10810. prev.output = star;
  10811. state.backtrack = true;
  10812. state.globstar = true;
  10813. consume(value);
  10814. continue;
  10815. }
  10816. let rest = remaining();
  10817. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  10818. extglobOpen('star', value);
  10819. continue;
  10820. }
  10821. if (prev.type === 'star') {
  10822. if (opts.noglobstar === true) {
  10823. consume(value);
  10824. continue;
  10825. }
  10826. const prior = prev.prev;
  10827. const before = prior.prev;
  10828. const isStart = prior.type === 'slash' || prior.type === 'bos';
  10829. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  10830. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  10831. push({ type: 'star', value, output: '' });
  10832. continue;
  10833. }
  10834. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  10835. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  10836. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  10837. push({ type: 'star', value, output: '' });
  10838. continue;
  10839. }
  10840. // strip consecutive `/**/`
  10841. while (rest.slice(0, 3) === '/**') {
  10842. const after = input[state.index + 4];
  10843. if (after && after !== '/') {
  10844. break;
  10845. }
  10846. rest = rest.slice(3);
  10847. consume('/**', 3);
  10848. }
  10849. if (prior.type === 'bos' && eos()) {
  10850. prev.type = 'globstar';
  10851. prev.value += value;
  10852. prev.output = globstar(opts);
  10853. state.output = prev.output;
  10854. state.globstar = true;
  10855. consume(value);
  10856. continue;
  10857. }
  10858. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  10859. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  10860. prior.output = `(?:${prior.output}`;
  10861. prev.type = 'globstar';
  10862. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  10863. prev.value += value;
  10864. state.globstar = true;
  10865. state.output += prior.output + prev.output;
  10866. consume(value);
  10867. continue;
  10868. }
  10869. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  10870. const end = rest[1] !== void 0 ? '|$' : '';
  10871. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  10872. prior.output = `(?:${prior.output}`;
  10873. prev.type = 'globstar';
  10874. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  10875. prev.value += value;
  10876. state.output += prior.output + prev.output;
  10877. state.globstar = true;
  10878. consume(value + advance());
  10879. push({ type: 'slash', value: '/', output: '' });
  10880. continue;
  10881. }
  10882. if (prior.type === 'bos' && rest[0] === '/') {
  10883. prev.type = 'globstar';
  10884. prev.value += value;
  10885. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  10886. state.output = prev.output;
  10887. state.globstar = true;
  10888. consume(value + advance());
  10889. push({ type: 'slash', value: '/', output: '' });
  10890. continue;
  10891. }
  10892. // remove single star from output
  10893. state.output = state.output.slice(0, -prev.output.length);
  10894. // reset previous token to globstar
  10895. prev.type = 'globstar';
  10896. prev.output = globstar(opts);
  10897. prev.value += value;
  10898. // reset output with globstar
  10899. state.output += prev.output;
  10900. state.globstar = true;
  10901. consume(value);
  10902. continue;
  10903. }
  10904. const token = { type: 'star', value, output: star };
  10905. if (opts.bash === true) {
  10906. token.output = '.*?';
  10907. if (prev.type === 'bos' || prev.type === 'slash') {
  10908. token.output = nodot + token.output;
  10909. }
  10910. push(token);
  10911. continue;
  10912. }
  10913. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  10914. token.output = value;
  10915. push(token);
  10916. continue;
  10917. }
  10918. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  10919. if (prev.type === 'dot') {
  10920. state.output += NO_DOT_SLASH;
  10921. prev.output += NO_DOT_SLASH;
  10922. } else if (opts.dot === true) {
  10923. state.output += NO_DOTS_SLASH;
  10924. prev.output += NO_DOTS_SLASH;
  10925. } else {
  10926. state.output += nodot;
  10927. prev.output += nodot;
  10928. }
  10929. if (peek() !== '*') {
  10930. state.output += ONE_CHAR;
  10931. prev.output += ONE_CHAR;
  10932. }
  10933. }
  10934. push(token);
  10935. }
  10936. while (state.brackets > 0) {
  10937. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  10938. state.output = utils.escapeLast(state.output, '[');
  10939. decrement('brackets');
  10940. }
  10941. while (state.parens > 0) {
  10942. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  10943. state.output = utils.escapeLast(state.output, '(');
  10944. decrement('parens');
  10945. }
  10946. while (state.braces > 0) {
  10947. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  10948. state.output = utils.escapeLast(state.output, '{');
  10949. decrement('braces');
  10950. }
  10951. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  10952. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  10953. }
  10954. // rebuild the output if we had to backtrack at any point
  10955. if (state.backtrack === true) {
  10956. state.output = '';
  10957. for (const token of state.tokens) {
  10958. state.output += token.output != null ? token.output : token.value;
  10959. if (token.suffix) {
  10960. state.output += token.suffix;
  10961. }
  10962. }
  10963. }
  10964. return state;
  10965. };
  10966. /**
  10967. * Fast paths for creating regular expressions for common glob patterns.
  10968. * This can significantly speed up processing and has very little downside
  10969. * impact when none of the fast paths match.
  10970. */
  10971. parse.fastpaths = (input, options) => {
  10972. const opts = { ...options };
  10973. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10974. const len = input.length;
  10975. if (len > max) {
  10976. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10977. }
  10978. input = REPLACEMENTS[input] || input;
  10979. // create constants based on platform, for windows or posix
  10980. const {
  10981. DOT_LITERAL,
  10982. SLASH_LITERAL,
  10983. ONE_CHAR,
  10984. DOTS_SLASH,
  10985. NO_DOT,
  10986. NO_DOTS,
  10987. NO_DOTS_SLASH,
  10988. STAR,
  10989. START_ANCHOR
  10990. } = constants.globChars(opts.windows);
  10991. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  10992. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  10993. const capture = opts.capture ? '' : '?:';
  10994. const state = { negated: false, prefix: '' };
  10995. let star = opts.bash === true ? '.*?' : STAR;
  10996. if (opts.capture) {
  10997. star = `(${star})`;
  10998. }
  10999. const globstar = opts => {
  11000. if (opts.noglobstar === true) return star;
  11001. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  11002. };
  11003. const create = str => {
  11004. switch (str) {
  11005. case '*':
  11006. return `${nodot}${ONE_CHAR}${star}`;
  11007. case '.*':
  11008. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  11009. case '*.*':
  11010. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  11011. case '*/*':
  11012. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  11013. case '**':
  11014. return nodot + globstar(opts);
  11015. case '**/*':
  11016. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  11017. case '**/*.*':
  11018. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  11019. case '**/.*':
  11020. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  11021. default: {
  11022. const match = /^(.*?)\.(\w+)$/.exec(str);
  11023. if (!match) return;
  11024. const source = create(match[1]);
  11025. if (!source) return;
  11026. return source + DOT_LITERAL + match[2];
  11027. }
  11028. }
  11029. };
  11030. const output = utils.removePrefix(input, state);
  11031. let source = create(output);
  11032. if (source && opts.strictSlashes !== true) {
  11033. source += `${SLASH_LITERAL}?`;
  11034. }
  11035. return source;
  11036. };
  11037. parse_1 = parse;
  11038. return parse_1;
  11039. }
  11040. var picomatch_1$1;
  11041. var hasRequiredPicomatch$1;
  11042. function requirePicomatch$1 () {
  11043. if (hasRequiredPicomatch$1) return picomatch_1$1;
  11044. hasRequiredPicomatch$1 = 1;
  11045. const scan = /*@__PURE__*/ requireScan();
  11046. const parse = /*@__PURE__*/ requireParse();
  11047. const utils = /*@__PURE__*/ requireUtils();
  11048. const constants = /*@__PURE__*/ requireConstants();
  11049. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  11050. /**
  11051. * Creates a matcher function from one or more glob patterns. The
  11052. * returned function takes a string to match as its first argument,
  11053. * and returns true if the string is a match. The returned matcher
  11054. * function also takes a boolean as the second argument that, when true,
  11055. * returns an object with additional information.
  11056. *
  11057. * ```js
  11058. * const picomatch = require('picomatch');
  11059. * // picomatch(glob[, options]);
  11060. *
  11061. * const isMatch = picomatch('*.!(*a)');
  11062. * console.log(isMatch('a.a')); //=> false
  11063. * console.log(isMatch('a.b')); //=> true
  11064. * ```
  11065. * @name picomatch
  11066. * @param {String|Array} `globs` One or more glob patterns.
  11067. * @param {Object=} `options`
  11068. * @return {Function=} Returns a matcher function.
  11069. * @api public
  11070. */
  11071. const picomatch = (glob, options, returnState = false) => {
  11072. if (Array.isArray(glob)) {
  11073. const fns = glob.map(input => picomatch(input, options, returnState));
  11074. const arrayMatcher = str => {
  11075. for (const isMatch of fns) {
  11076. const state = isMatch(str);
  11077. if (state) return state;
  11078. }
  11079. return false;
  11080. };
  11081. return arrayMatcher;
  11082. }
  11083. const isState = isObject(glob) && glob.tokens && glob.input;
  11084. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  11085. throw new TypeError('Expected pattern to be a non-empty string');
  11086. }
  11087. const opts = options || {};
  11088. const posix = opts.windows;
  11089. const regex = isState
  11090. ? picomatch.compileRe(glob, options)
  11091. : picomatch.makeRe(glob, options, false, true);
  11092. const state = regex.state;
  11093. delete regex.state;
  11094. let isIgnored = () => false;
  11095. if (opts.ignore) {
  11096. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  11097. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  11098. }
  11099. const matcher = (input, returnObject = false) => {
  11100. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  11101. const result = { glob, state, regex, posix, input, output, match, isMatch };
  11102. if (typeof opts.onResult === 'function') {
  11103. opts.onResult(result);
  11104. }
  11105. if (isMatch === false) {
  11106. result.isMatch = false;
  11107. return returnObject ? result : false;
  11108. }
  11109. if (isIgnored(input)) {
  11110. if (typeof opts.onIgnore === 'function') {
  11111. opts.onIgnore(result);
  11112. }
  11113. result.isMatch = false;
  11114. return returnObject ? result : false;
  11115. }
  11116. if (typeof opts.onMatch === 'function') {
  11117. opts.onMatch(result);
  11118. }
  11119. return returnObject ? result : true;
  11120. };
  11121. if (returnState) {
  11122. matcher.state = state;
  11123. }
  11124. return matcher;
  11125. };
  11126. /**
  11127. * Test `input` with the given `regex`. This is used by the main
  11128. * `picomatch()` function to test the input string.
  11129. *
  11130. * ```js
  11131. * const picomatch = require('picomatch');
  11132. * // picomatch.test(input, regex[, options]);
  11133. *
  11134. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  11135. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  11136. * ```
  11137. * @param {String} `input` String to test.
  11138. * @param {RegExp} `regex`
  11139. * @return {Object} Returns an object with matching info.
  11140. * @api public
  11141. */
  11142. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  11143. if (typeof input !== 'string') {
  11144. throw new TypeError('Expected input to be a string');
  11145. }
  11146. if (input === '') {
  11147. return { isMatch: false, output: '' };
  11148. }
  11149. const opts = options || {};
  11150. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  11151. let match = input === glob;
  11152. let output = (match && format) ? format(input) : input;
  11153. if (match === false) {
  11154. output = format ? format(input) : input;
  11155. match = output === glob;
  11156. }
  11157. if (match === false || opts.capture === true) {
  11158. if (opts.matchBase === true || opts.basename === true) {
  11159. match = picomatch.matchBase(input, regex, options, posix);
  11160. } else {
  11161. match = regex.exec(output);
  11162. }
  11163. }
  11164. return { isMatch: Boolean(match), match, output };
  11165. };
  11166. /**
  11167. * Match the basename of a filepath.
  11168. *
  11169. * ```js
  11170. * const picomatch = require('picomatch');
  11171. * // picomatch.matchBase(input, glob[, options]);
  11172. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  11173. * ```
  11174. * @param {String} `input` String to test.
  11175. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  11176. * @return {Boolean}
  11177. * @api public
  11178. */
  11179. picomatch.matchBase = (input, glob, options) => {
  11180. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  11181. return regex.test(utils.basename(input));
  11182. };
  11183. /**
  11184. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  11185. *
  11186. * ```js
  11187. * const picomatch = require('picomatch');
  11188. * // picomatch.isMatch(string, patterns[, options]);
  11189. *
  11190. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  11191. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  11192. * ```
  11193. * @param {String|Array} str The string to test.
  11194. * @param {String|Array} patterns One or more glob patterns to use for matching.
  11195. * @param {Object} [options] See available [options](#options).
  11196. * @return {Boolean} Returns true if any patterns match `str`
  11197. * @api public
  11198. */
  11199. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  11200. /**
  11201. * Parse a glob pattern to create the source string for a regular
  11202. * expression.
  11203. *
  11204. * ```js
  11205. * const picomatch = require('picomatch');
  11206. * const result = picomatch.parse(pattern[, options]);
  11207. * ```
  11208. * @param {String} `pattern`
  11209. * @param {Object} `options`
  11210. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  11211. * @api public
  11212. */
  11213. picomatch.parse = (pattern, options) => {
  11214. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  11215. return parse(pattern, { ...options, fastpaths: false });
  11216. };
  11217. /**
  11218. * Scan a glob pattern to separate the pattern into segments.
  11219. *
  11220. * ```js
  11221. * const picomatch = require('picomatch');
  11222. * // picomatch.scan(input[, options]);
  11223. *
  11224. * const result = picomatch.scan('!./foo/*.js');
  11225. * console.log(result);
  11226. * { prefix: '!./',
  11227. * input: '!./foo/*.js',
  11228. * start: 3,
  11229. * base: 'foo',
  11230. * glob: '*.js',
  11231. * isBrace: false,
  11232. * isBracket: false,
  11233. * isGlob: true,
  11234. * isExtglob: false,
  11235. * isGlobstar: false,
  11236. * negated: true }
  11237. * ```
  11238. * @param {String} `input` Glob pattern to scan.
  11239. * @param {Object} `options`
  11240. * @return {Object} Returns an object with
  11241. * @api public
  11242. */
  11243. picomatch.scan = (input, options) => scan(input, options);
  11244. /**
  11245. * Compile a regular expression from the `state` object returned by the
  11246. * [parse()](#parse) method.
  11247. *
  11248. * @param {Object} `state`
  11249. * @param {Object} `options`
  11250. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  11251. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  11252. * @return {RegExp}
  11253. * @api public
  11254. */
  11255. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  11256. if (returnOutput === true) {
  11257. return state.output;
  11258. }
  11259. const opts = options || {};
  11260. const prepend = opts.contains ? '' : '^';
  11261. const append = opts.contains ? '' : '$';
  11262. let source = `${prepend}(?:${state.output})${append}`;
  11263. if (state && state.negated === true) {
  11264. source = `^(?!${source}).*$`;
  11265. }
  11266. const regex = picomatch.toRegex(source, options);
  11267. if (returnState === true) {
  11268. regex.state = state;
  11269. }
  11270. return regex;
  11271. };
  11272. /**
  11273. * Create a regular expression from a parsed glob pattern.
  11274. *
  11275. * ```js
  11276. * const picomatch = require('picomatch');
  11277. * const state = picomatch.parse('*.js');
  11278. * // picomatch.compileRe(state[, options]);
  11279. *
  11280. * console.log(picomatch.compileRe(state));
  11281. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  11282. * ```
  11283. * @param {String} `state` The object returned from the `.parse` method.
  11284. * @param {Object} `options`
  11285. * @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.
  11286. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  11287. * @return {RegExp} Returns a regex created from the given pattern.
  11288. * @api public
  11289. */
  11290. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  11291. if (!input || typeof input !== 'string') {
  11292. throw new TypeError('Expected a non-empty string');
  11293. }
  11294. let parsed = { negated: false, fastpaths: true };
  11295. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  11296. parsed.output = parse.fastpaths(input, options);
  11297. }
  11298. if (!parsed.output) {
  11299. parsed = parse(input, options);
  11300. }
  11301. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  11302. };
  11303. /**
  11304. * Create a regular expression from the given regex source string.
  11305. *
  11306. * ```js
  11307. * const picomatch = require('picomatch');
  11308. * // picomatch.toRegex(source[, options]);
  11309. *
  11310. * const { output } = picomatch.parse('*.js');
  11311. * console.log(picomatch.toRegex(output));
  11312. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  11313. * ```
  11314. * @param {String} `source` Regular expression source string.
  11315. * @param {Object} `options`
  11316. * @return {RegExp}
  11317. * @api public
  11318. */
  11319. picomatch.toRegex = (source, options) => {
  11320. try {
  11321. const opts = options || {};
  11322. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  11323. } catch (err) {
  11324. if (options && options.debug === true) throw err;
  11325. return /$^/;
  11326. }
  11327. };
  11328. /**
  11329. * Picomatch constants.
  11330. * @return {Object}
  11331. */
  11332. picomatch.constants = constants;
  11333. /**
  11334. * Expose "picomatch"
  11335. */
  11336. picomatch_1$1 = picomatch;
  11337. return picomatch_1$1;
  11338. }
  11339. var picomatch_1;
  11340. var hasRequiredPicomatch;
  11341. function requirePicomatch () {
  11342. if (hasRequiredPicomatch) return picomatch_1;
  11343. hasRequiredPicomatch = 1;
  11344. const pico = /*@__PURE__*/ requirePicomatch$1();
  11345. const utils = /*@__PURE__*/ requireUtils();
  11346. function picomatch(glob, options, returnState = false) {
  11347. // default to os.platform()
  11348. if (options && (options.windows === null || options.windows === undefined)) {
  11349. // don't mutate the original options object
  11350. options = { ...options, windows: utils.isWindows() };
  11351. }
  11352. return pico(glob, options, returnState);
  11353. }
  11354. Object.assign(picomatch, pico);
  11355. picomatch_1 = picomatch;
  11356. return picomatch_1;
  11357. }
  11358. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  11359. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  11360. const extractors = {
  11361. ArrayPattern(names, param) {
  11362. for (const element of param.elements) {
  11363. if (element)
  11364. extractors[element.type](names, element);
  11365. }
  11366. },
  11367. AssignmentPattern(names, param) {
  11368. extractors[param.left.type](names, param.left);
  11369. },
  11370. Identifier(names, param) {
  11371. names.push(param.name);
  11372. },
  11373. MemberExpression() { },
  11374. ObjectPattern(names, param) {
  11375. for (const prop of param.properties) {
  11376. // @ts-ignore Typescript reports that this is not a valid type
  11377. if (prop.type === 'RestElement') {
  11378. extractors.RestElement(names, prop);
  11379. }
  11380. else {
  11381. extractors[prop.value.type](names, prop.value);
  11382. }
  11383. }
  11384. },
  11385. RestElement(names, param) {
  11386. extractors[param.argument.type](names, param.argument);
  11387. }
  11388. };
  11389. const extractAssignedNames = function extractAssignedNames(param) {
  11390. const names = [];
  11391. extractors[param.type](names, param);
  11392. return names;
  11393. };
  11394. // Helper since Typescript can't detect readonly arrays with Array.isArray
  11395. function isArray(arg) {
  11396. return Array.isArray(arg);
  11397. }
  11398. function ensureArray(thing) {
  11399. if (isArray(thing))
  11400. return thing;
  11401. if (thing == null)
  11402. return [];
  11403. return [thing];
  11404. }
  11405. const normalizePathRegExp = new RegExp(`\\${require$$0.win32.sep}`, 'g');
  11406. const normalizePath = function normalizePath(filename) {
  11407. return filename.replace(normalizePathRegExp, require$$0.posix.sep);
  11408. };
  11409. function getMatcherString(id, resolutionBase) {
  11410. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('**')) {
  11411. return normalizePath(id);
  11412. }
  11413. // resolve('') is valid and will default to process.cwd()
  11414. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  11415. // escape all possible (posix + win) path characters that might interfere with regex
  11416. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  11417. // Note that we use posix.join because:
  11418. // 1. the basePath has been normalized to use /
  11419. // 2. the incoming glob (id) matcher, also uses /
  11420. // otherwise Node will force backslash (\) on windows
  11421. return require$$0.posix.join(basePath, normalizePath(id));
  11422. }
  11423. const createFilter = function createFilter(include, exclude, options) {
  11424. const resolutionBase = options && options.resolve;
  11425. const getMatcher = (id) => id instanceof RegExp
  11426. ? id
  11427. : {
  11428. test: (what) => {
  11429. // this refactor is a tad overly verbose but makes for easy debugging
  11430. const pattern = getMatcherString(id, resolutionBase);
  11431. const fn = pm(pattern, { dot: true });
  11432. const result = fn(what);
  11433. return result;
  11434. }
  11435. };
  11436. const includeMatchers = ensureArray(include).map(getMatcher);
  11437. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  11438. if (!includeMatchers.length && !excludeMatchers.length)
  11439. return (id) => typeof id === 'string' && !id.includes('\0');
  11440. return function result(id) {
  11441. if (typeof id !== 'string')
  11442. return false;
  11443. if (id.includes('\0'))
  11444. return false;
  11445. const pathId = normalizePath(id);
  11446. for (let i = 0; i < excludeMatchers.length; ++i) {
  11447. const matcher = excludeMatchers[i];
  11448. if (matcher.test(pathId))
  11449. return false;
  11450. }
  11451. for (let i = 0; i < includeMatchers.length; ++i) {
  11452. const matcher = includeMatchers[i];
  11453. if (matcher.test(pathId))
  11454. return true;
  11455. }
  11456. return !includeMatchers.length;
  11457. };
  11458. };
  11459. 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';
  11460. 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';
  11461. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  11462. forbiddenIdentifiers.add('');
  11463. class ArrayPattern extends NodeBase {
  11464. addExportedVariables(variables, exportNamesByVariable) {
  11465. for (const element of this.elements) {
  11466. element?.addExportedVariables(variables, exportNamesByVariable);
  11467. }
  11468. }
  11469. declare(kind) {
  11470. const variables = [];
  11471. for (const element of this.elements) {
  11472. if (element !== null) {
  11473. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  11474. }
  11475. }
  11476. return variables;
  11477. }
  11478. // Patterns can only be deoptimized at the empty path at the moment
  11479. deoptimizePath() {
  11480. for (const element of this.elements) {
  11481. element?.deoptimizePath(EMPTY_PATH);
  11482. }
  11483. }
  11484. // Patterns are only checked at the empty path at the moment
  11485. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  11486. for (const element of this.elements) {
  11487. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  11488. return true;
  11489. }
  11490. return false;
  11491. }
  11492. markDeclarationReached() {
  11493. for (const element of this.elements) {
  11494. element?.markDeclarationReached();
  11495. }
  11496. }
  11497. }
  11498. class ArrowFunctionExpression extends FunctionBase {
  11499. constructor() {
  11500. super(...arguments);
  11501. this.objectEntity = null;
  11502. }
  11503. get expression() {
  11504. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  11505. }
  11506. set expression(value) {
  11507. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  11508. }
  11509. createScope(parentScope) {
  11510. this.scope = new ReturnValueScope(parentScope, false);
  11511. }
  11512. hasEffects() {
  11513. if (!this.deoptimized)
  11514. this.applyDeoptimizations();
  11515. return false;
  11516. }
  11517. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11518. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  11519. return true;
  11520. }
  11521. if (this.annotationNoSideEffects) {
  11522. return false;
  11523. }
  11524. if (interaction.type === INTERACTION_CALLED) {
  11525. const { ignore, brokenFlow } = context;
  11526. context.ignore = {
  11527. breaks: false,
  11528. continues: false,
  11529. labels: new Set(),
  11530. returnYield: true,
  11531. this: false
  11532. };
  11533. if (this.body.hasEffects(context))
  11534. return true;
  11535. context.ignore = ignore;
  11536. context.brokenFlow = brokenFlow;
  11537. }
  11538. return false;
  11539. }
  11540. onlyFunctionCallUsed() {
  11541. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  11542. this.parent.callee === this;
  11543. return isIIFE || super.onlyFunctionCallUsed();
  11544. }
  11545. include(context, includeChildrenRecursively) {
  11546. super.include(context, includeChildrenRecursively);
  11547. for (const parameter of this.params) {
  11548. if (!(parameter instanceof Identifier)) {
  11549. parameter.include(context, includeChildrenRecursively);
  11550. }
  11551. }
  11552. }
  11553. getObjectEntity() {
  11554. if (this.objectEntity !== null) {
  11555. return this.objectEntity;
  11556. }
  11557. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  11558. }
  11559. }
  11560. class ObjectPattern extends NodeBase {
  11561. addExportedVariables(variables, exportNamesByVariable) {
  11562. for (const property of this.properties) {
  11563. if (property.type === parseAst_js.Property) {
  11564. property.value.addExportedVariables(variables, exportNamesByVariable);
  11565. }
  11566. else {
  11567. property.argument.addExportedVariables(variables, exportNamesByVariable);
  11568. }
  11569. }
  11570. }
  11571. declare(kind, init) {
  11572. const variables = [];
  11573. for (const property of this.properties) {
  11574. variables.push(...property.declare(kind, init));
  11575. }
  11576. return variables;
  11577. }
  11578. deoptimizePath(path) {
  11579. if (path.length === 0) {
  11580. for (const property of this.properties) {
  11581. property.deoptimizePath(path);
  11582. }
  11583. }
  11584. }
  11585. hasEffectsOnInteractionAtPath(
  11586. // At the moment, this is only triggered for assignment left-hand sides,
  11587. // where the path is empty
  11588. _path, interaction, context) {
  11589. for (const property of this.properties) {
  11590. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  11591. return true;
  11592. }
  11593. return false;
  11594. }
  11595. markDeclarationReached() {
  11596. for (const property of this.properties) {
  11597. property.markDeclarationReached();
  11598. }
  11599. }
  11600. }
  11601. class AssignmentExpression extends NodeBase {
  11602. hasEffects(context) {
  11603. const { deoptimized, left, operator, right } = this;
  11604. if (!deoptimized)
  11605. this.applyDeoptimizations();
  11606. // MemberExpressions do not access the property before assignments if the
  11607. // operator is '='.
  11608. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  11609. }
  11610. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11611. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  11612. }
  11613. include(context, includeChildrenRecursively) {
  11614. const { deoptimized, left, right, operator } = this;
  11615. if (!deoptimized)
  11616. this.applyDeoptimizations();
  11617. this.included = true;
  11618. if (includeChildrenRecursively ||
  11619. operator !== '=' ||
  11620. left.included ||
  11621. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  11622. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  11623. }
  11624. right.include(context, includeChildrenRecursively);
  11625. }
  11626. initialise() {
  11627. super.initialise();
  11628. if (this.left instanceof Identifier) {
  11629. const variable = this.scope.variables.get(this.left.name);
  11630. if (variable?.kind === 'const') {
  11631. this.scope.context.error(parseAst_js.logConstVariableReassignError(), this.left.start);
  11632. }
  11633. }
  11634. this.left.setAssignedValue(this.right);
  11635. }
  11636. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  11637. const { left, right, start, end, parent } = this;
  11638. if (left.included) {
  11639. left.render(code, options);
  11640. right.render(code, options);
  11641. }
  11642. else {
  11643. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  11644. code.remove(start, inclusionStart);
  11645. if (preventASI) {
  11646. removeLineBreaks(code, inclusionStart, right.start);
  11647. }
  11648. right.render(code, options, {
  11649. renderedParentType: renderedParentType || parent.type,
  11650. renderedSurroundingElement: renderedSurroundingElement || parent.type
  11651. });
  11652. }
  11653. if (options.format === 'system') {
  11654. if (left instanceof Identifier) {
  11655. const variable = left.variable;
  11656. const exportNames = options.exportNamesByVariable.get(variable);
  11657. if (exportNames) {
  11658. if (exportNames.length === 1) {
  11659. renderSystemExportExpression(variable, start, end, code, options);
  11660. }
  11661. else {
  11662. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== parseAst_js.ExpressionStatement, code, options);
  11663. }
  11664. return;
  11665. }
  11666. }
  11667. else {
  11668. const systemPatternExports = [];
  11669. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  11670. if (systemPatternExports.length > 0) {
  11671. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === parseAst_js.ExpressionStatement, code, options);
  11672. return;
  11673. }
  11674. }
  11675. }
  11676. if (left.included &&
  11677. left instanceof ObjectPattern &&
  11678. (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  11679. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression)) {
  11680. code.appendRight(start, '(');
  11681. code.prependLeft(end, ')');
  11682. }
  11683. }
  11684. applyDeoptimizations() {
  11685. this.deoptimized = true;
  11686. this.left.deoptimizePath(EMPTY_PATH);
  11687. this.right.deoptimizePath(UNKNOWN_PATH);
  11688. this.scope.context.requestTreeshakingPass();
  11689. }
  11690. }
  11691. class AssignmentPattern extends NodeBase {
  11692. addExportedVariables(variables, exportNamesByVariable) {
  11693. this.left.addExportedVariables(variables, exportNamesByVariable);
  11694. }
  11695. declare(kind, init) {
  11696. return this.left.declare(kind, init);
  11697. }
  11698. deoptimizePath(path) {
  11699. if (path.length === 0) {
  11700. this.left.deoptimizePath(path);
  11701. }
  11702. }
  11703. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11704. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  11705. }
  11706. markDeclarationReached() {
  11707. this.left.markDeclarationReached();
  11708. }
  11709. render(code, options, { isShorthandProperty } = parseAst_js.BLANK) {
  11710. this.left.render(code, options, { isShorthandProperty });
  11711. this.right.render(code, options);
  11712. }
  11713. applyDeoptimizations() {
  11714. this.deoptimized = true;
  11715. this.left.deoptimizePath(EMPTY_PATH);
  11716. this.right.deoptimizePath(UNKNOWN_PATH);
  11717. this.scope.context.requestTreeshakingPass();
  11718. }
  11719. }
  11720. class AwaitExpression extends NodeBase {
  11721. hasEffects() {
  11722. if (!this.deoptimized)
  11723. this.applyDeoptimizations();
  11724. return true;
  11725. }
  11726. include(context, includeChildrenRecursively) {
  11727. if (!this.deoptimized)
  11728. this.applyDeoptimizations();
  11729. if (!this.included) {
  11730. this.included = true;
  11731. checkTopLevelAwait: if (!this.scope.context.usesTopLevelAwait) {
  11732. let parent = this.parent;
  11733. do {
  11734. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  11735. break checkTopLevelAwait;
  11736. } while ((parent = parent.parent));
  11737. this.scope.context.usesTopLevelAwait = true;
  11738. }
  11739. }
  11740. this.argument.include(context, includeChildrenRecursively);
  11741. }
  11742. }
  11743. const binaryOperators = {
  11744. '!=': (left, right) => left != right,
  11745. '!==': (left, right) => left !== right,
  11746. '%': (left, right) => left % right,
  11747. '&': (left, right) => left & right,
  11748. '*': (left, right) => left * right,
  11749. // At the moment, "**" will be transpiled to Math.pow
  11750. '**': (left, right) => left ** right,
  11751. '+': (left, right) => left + right,
  11752. '-': (left, right) => left - right,
  11753. '/': (left, right) => left / right,
  11754. '<': (left, right) => left < right,
  11755. '<<': (left, right) => left << right,
  11756. '<=': (left, right) => left <= right,
  11757. '==': (left, right) => left == right,
  11758. '===': (left, right) => left === right,
  11759. '>': (left, right) => left > right,
  11760. '>=': (left, right) => left >= right,
  11761. '>>': (left, right) => left >> right,
  11762. '>>>': (left, right) => left >>> right,
  11763. '^': (left, right) => left ^ right,
  11764. '|': (left, right) => left | right
  11765. // We use the fallback for cases where we return something unknown
  11766. // in: () => UnknownValue,
  11767. // instanceof: () => UnknownValue,
  11768. };
  11769. class BinaryExpression extends NodeBase {
  11770. deoptimizeCache() { }
  11771. getLiteralValueAtPath(path, recursionTracker, origin) {
  11772. if (path.length > 0)
  11773. return UnknownValue;
  11774. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11775. if (typeof leftValue === 'symbol')
  11776. return UnknownValue;
  11777. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11778. if (typeof rightValue === 'symbol')
  11779. return UnknownValue;
  11780. const operatorFunction = binaryOperators[this.operator];
  11781. if (!operatorFunction)
  11782. return UnknownValue;
  11783. return operatorFunction(leftValue, rightValue);
  11784. }
  11785. hasEffects(context) {
  11786. // support some implicit type coercion runtime errors
  11787. if (this.operator === '+' &&
  11788. this.parent instanceof ExpressionStatement &&
  11789. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  11790. return true;
  11791. }
  11792. return super.hasEffects(context);
  11793. }
  11794. hasEffectsOnInteractionAtPath(path, { type }) {
  11795. return type !== INTERACTION_ACCESSED || path.length > 1;
  11796. }
  11797. removeAnnotations(code) {
  11798. this.left.removeAnnotations(code);
  11799. }
  11800. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  11801. this.left.render(code, options, { renderedSurroundingElement });
  11802. this.right.render(code, options);
  11803. }
  11804. }
  11805. class BreakStatement extends NodeBase {
  11806. hasEffects(context) {
  11807. if (this.label) {
  11808. if (!context.ignore.labels.has(this.label.name))
  11809. return true;
  11810. context.includedLabels.add(this.label.name);
  11811. }
  11812. else {
  11813. if (!context.ignore.breaks)
  11814. return true;
  11815. context.hasBreak = true;
  11816. }
  11817. context.brokenFlow = true;
  11818. return false;
  11819. }
  11820. include(context) {
  11821. this.included = true;
  11822. if (this.label) {
  11823. this.label.include();
  11824. context.includedLabels.add(this.label.name);
  11825. }
  11826. else {
  11827. context.hasBreak = true;
  11828. }
  11829. context.brokenFlow = true;
  11830. }
  11831. }
  11832. function renderCallArguments(code, options, node) {
  11833. if (node.arguments.length > 0) {
  11834. if (node.arguments[node.arguments.length - 1].included) {
  11835. for (const argument of node.arguments) {
  11836. argument.render(code, options);
  11837. }
  11838. }
  11839. else {
  11840. let lastIncludedIndex = node.arguments.length - 2;
  11841. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  11842. lastIncludedIndex--;
  11843. }
  11844. if (lastIncludedIndex >= 0) {
  11845. for (let index = 0; index <= lastIncludedIndex; index++) {
  11846. node.arguments[index].render(code, options);
  11847. }
  11848. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  11849. }
  11850. else {
  11851. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  11852. }
  11853. }
  11854. }
  11855. }
  11856. class CallExpressionBase extends NodeBase {
  11857. constructor() {
  11858. super(...arguments);
  11859. this.returnExpression = null;
  11860. this.deoptimizableDependentExpressions = [];
  11861. this.expressionsToBeDeoptimized = new Set();
  11862. }
  11863. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11864. const { args } = interaction;
  11865. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  11866. if (isPure)
  11867. return;
  11868. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  11869. if (deoptimizedExpressions.length === 0)
  11870. return;
  11871. if (returnExpression === UNKNOWN_EXPRESSION) {
  11872. for (const expression of deoptimizedExpressions) {
  11873. expression.deoptimizePath(UNKNOWN_PATH);
  11874. }
  11875. }
  11876. else {
  11877. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11878. for (const expression of deoptimizedExpressions) {
  11879. this.expressionsToBeDeoptimized.add(expression);
  11880. }
  11881. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11882. }, null);
  11883. }
  11884. }
  11885. deoptimizeCache() {
  11886. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  11887. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11888. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  11889. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_SET;
  11890. this.deoptimizableDependentExpressions = parseAst_js.EMPTY_ARRAY;
  11891. for (const expression of deoptimizableDependentExpressions) {
  11892. expression.deoptimizeCache();
  11893. }
  11894. for (const expression of expressionsToBeDeoptimized) {
  11895. expression.deoptimizePath(UNKNOWN_PATH);
  11896. }
  11897. }
  11898. }
  11899. deoptimizePath(path) {
  11900. if (path.length === 0 ||
  11901. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  11902. return;
  11903. }
  11904. const [returnExpression] = this.getReturnExpression();
  11905. if (returnExpression !== UNKNOWN_EXPRESSION) {
  11906. returnExpression.deoptimizePath(path);
  11907. }
  11908. }
  11909. getLiteralValueAtPath(path, recursionTracker, origin) {
  11910. const [returnExpression] = this.getReturnExpression(recursionTracker);
  11911. if (returnExpression === UNKNOWN_EXPRESSION) {
  11912. return UnknownValue;
  11913. }
  11914. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11915. this.deoptimizableDependentExpressions.push(origin);
  11916. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  11917. }, UnknownValue);
  11918. }
  11919. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11920. const returnExpression = this.getReturnExpression(recursionTracker);
  11921. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  11922. return returnExpression;
  11923. }
  11924. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11925. this.deoptimizableDependentExpressions.push(origin);
  11926. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11927. return [expression, isPure || returnExpression[1]];
  11928. }, UNKNOWN_RETURN_EXPRESSION);
  11929. }
  11930. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11931. const { type } = interaction;
  11932. if (type === INTERACTION_CALLED) {
  11933. const { args, withNew } = interaction;
  11934. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  11935. return false;
  11936. }
  11937. }
  11938. else if ((type === INTERACTION_ASSIGNED
  11939. ? context.assigned
  11940. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  11941. return false;
  11942. }
  11943. const [returnExpression, isPure] = this.getReturnExpression();
  11944. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  11945. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  11946. }
  11947. }
  11948. class CallExpression extends CallExpressionBase {
  11949. get optional() {
  11950. return isFlagSet(this.flags, 128 /* Flag.optional */);
  11951. }
  11952. set optional(value) {
  11953. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  11954. }
  11955. bind() {
  11956. super.bind();
  11957. if (this.callee instanceof Identifier) {
  11958. const variable = this.scope.findVariable(this.callee.name);
  11959. if (variable.isNamespace) {
  11960. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(this.callee.name), this.start);
  11961. }
  11962. if (this.callee.name === 'eval') {
  11963. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEval(this.scope.context.module.id), this.start);
  11964. }
  11965. }
  11966. this.interaction = {
  11967. args: [
  11968. this.callee instanceof MemberExpression && !this.callee.variable
  11969. ? this.callee.object
  11970. : null,
  11971. ...this.arguments
  11972. ],
  11973. type: INTERACTION_CALLED,
  11974. withNew: false
  11975. };
  11976. }
  11977. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  11978. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  11979. }
  11980. hasEffects(context) {
  11981. if (!this.deoptimized)
  11982. this.applyDeoptimizations();
  11983. for (const argument of this.arguments) {
  11984. if (argument.hasEffects(context))
  11985. return true;
  11986. }
  11987. if (this.annotationPure) {
  11988. return false;
  11989. }
  11990. return (this.callee.hasEffects(context) ||
  11991. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11992. }
  11993. hasEffectsAsChainElement(context) {
  11994. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  11995. ? this.callee.hasEffectsAsChainElement(context)
  11996. : this.callee.hasEffects(context);
  11997. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  11998. return IS_SKIPPED_CHAIN;
  11999. if (this.optional &&
  12000. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  12001. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  12002. }
  12003. // We only apply deoptimizations lazily once we know we are not skipping
  12004. if (!this.deoptimized)
  12005. this.applyDeoptimizations();
  12006. for (const argument of this.arguments) {
  12007. if (argument.hasEffects(context))
  12008. return true;
  12009. }
  12010. return (!this.annotationPure &&
  12011. (calleeHasEffects ||
  12012. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  12013. }
  12014. include(context, includeChildrenRecursively) {
  12015. if (!this.deoptimized)
  12016. this.applyDeoptimizations();
  12017. if (includeChildrenRecursively) {
  12018. super.include(context, includeChildrenRecursively);
  12019. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  12020. this.callee instanceof Identifier &&
  12021. this.callee.variable) {
  12022. this.callee.variable.markCalledFromTryStatement();
  12023. }
  12024. }
  12025. else {
  12026. this.included = true;
  12027. this.callee.include(context, false);
  12028. }
  12029. this.callee.includeCallArguments(context, this.arguments);
  12030. }
  12031. initialise() {
  12032. super.initialise();
  12033. if (this.annotations &&
  12034. this.scope.context.options.treeshake.annotations) {
  12035. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  12036. }
  12037. }
  12038. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12039. this.callee.render(code, options, {
  12040. isCalleeOfRenderedParent: true,
  12041. renderedSurroundingElement
  12042. });
  12043. renderCallArguments(code, options, this);
  12044. }
  12045. applyDeoptimizations() {
  12046. this.deoptimized = true;
  12047. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12048. this.scope.context.requestTreeshakingPass();
  12049. }
  12050. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  12051. if (this.returnExpression === null) {
  12052. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12053. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  12054. }
  12055. return this.returnExpression;
  12056. }
  12057. }
  12058. class CatchClause extends NodeBase {
  12059. createScope(parentScope) {
  12060. this.scope = new ParameterScope(parentScope, true);
  12061. }
  12062. parseNode(esTreeNode) {
  12063. const { body, param, type } = esTreeNode;
  12064. this.type = type;
  12065. if (param) {
  12066. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  12067. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  12068. }
  12069. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  12070. return super.parseNode(esTreeNode);
  12071. }
  12072. }
  12073. CatchClause.prototype.preventChildBlockScope = true;
  12074. class ChainExpression extends NodeBase {
  12075. // deoptimizations are not relevant as we are not caching values
  12076. deoptimizeCache() { }
  12077. getLiteralValueAtPath(path, recursionTracker, origin) {
  12078. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  12079. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  12080. }
  12081. hasEffects(context) {
  12082. return this.expression.hasEffectsAsChainElement(context) === true;
  12083. }
  12084. removeAnnotations(code) {
  12085. this.expression.removeAnnotations(code);
  12086. }
  12087. applyDeoptimizations() { }
  12088. }
  12089. class ClassBodyScope extends ChildScope {
  12090. constructor(parent, classNode) {
  12091. const { context } = parent;
  12092. super(parent, context);
  12093. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context, 'other')));
  12094. this.instanceScope = new ChildScope(this, context);
  12095. this.instanceScope.variables.set('this', new ThisVariable(context));
  12096. }
  12097. findLexicalBoundary() {
  12098. return this;
  12099. }
  12100. }
  12101. class ClassBody extends NodeBase {
  12102. createScope(parentScope) {
  12103. this.scope = new ClassBodyScope(parentScope, this.parent);
  12104. }
  12105. include(context, includeChildrenRecursively) {
  12106. this.included = true;
  12107. this.scope.context.includeVariableInModule(this.scope.thisVariable);
  12108. for (const definition of this.body) {
  12109. definition.include(context, includeChildrenRecursively);
  12110. }
  12111. }
  12112. parseNode(esTreeNode) {
  12113. const body = (this.body = []);
  12114. for (const definition of esTreeNode.body) {
  12115. body.push(new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition));
  12116. }
  12117. return super.parseNode(esTreeNode);
  12118. }
  12119. applyDeoptimizations() { }
  12120. }
  12121. class ClassExpression extends ClassNode {
  12122. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12123. super.render(code, options);
  12124. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  12125. code.appendRight(this.start, '(');
  12126. code.prependLeft(this.end, ')');
  12127. }
  12128. }
  12129. }
  12130. class MultiExpression extends ExpressionEntity {
  12131. constructor(expressions) {
  12132. super();
  12133. this.expressions = expressions;
  12134. }
  12135. deoptimizePath(path) {
  12136. for (const expression of this.expressions) {
  12137. expression.deoptimizePath(path);
  12138. }
  12139. }
  12140. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12141. return [
  12142. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  12143. false
  12144. ];
  12145. }
  12146. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12147. for (const expression of this.expressions) {
  12148. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  12149. return true;
  12150. }
  12151. return false;
  12152. }
  12153. }
  12154. class ConditionalExpression extends NodeBase {
  12155. constructor() {
  12156. super(...arguments);
  12157. this.expressionsToBeDeoptimized = [];
  12158. this.usedBranch = null;
  12159. }
  12160. get isBranchResolutionAnalysed() {
  12161. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  12162. }
  12163. set isBranchResolutionAnalysed(value) {
  12164. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  12165. }
  12166. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12167. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12168. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12169. }
  12170. deoptimizeCache() {
  12171. if (this.usedBranch !== null) {
  12172. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  12173. this.usedBranch = null;
  12174. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12175. const { expressionsToBeDeoptimized } = this;
  12176. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  12177. for (const expression of expressionsToBeDeoptimized) {
  12178. expression.deoptimizeCache();
  12179. }
  12180. }
  12181. }
  12182. deoptimizePath(path) {
  12183. const usedBranch = this.getUsedBranch();
  12184. if (usedBranch) {
  12185. usedBranch.deoptimizePath(path);
  12186. }
  12187. else {
  12188. this.consequent.deoptimizePath(path);
  12189. this.alternate.deoptimizePath(path);
  12190. }
  12191. }
  12192. getLiteralValueAtPath(path, recursionTracker, origin) {
  12193. const usedBranch = this.getUsedBranch();
  12194. if (!usedBranch)
  12195. return UnknownValue;
  12196. this.expressionsToBeDeoptimized.push(origin);
  12197. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12198. }
  12199. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12200. const usedBranch = this.getUsedBranch();
  12201. if (!usedBranch)
  12202. return [
  12203. new MultiExpression([
  12204. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  12205. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  12206. ]),
  12207. false
  12208. ];
  12209. this.expressionsToBeDeoptimized.push(origin);
  12210. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12211. }
  12212. hasEffects(context) {
  12213. if (this.test.hasEffects(context))
  12214. return true;
  12215. const usedBranch = this.getUsedBranch();
  12216. if (!usedBranch) {
  12217. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  12218. }
  12219. return usedBranch.hasEffects(context);
  12220. }
  12221. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12222. const usedBranch = this.getUsedBranch();
  12223. if (!usedBranch) {
  12224. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  12225. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  12226. }
  12227. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  12228. }
  12229. include(context, includeChildrenRecursively) {
  12230. this.included = true;
  12231. const usedBranch = this.getUsedBranch();
  12232. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  12233. this.test.include(context, includeChildrenRecursively);
  12234. this.consequent.include(context, includeChildrenRecursively);
  12235. this.alternate.include(context, includeChildrenRecursively);
  12236. }
  12237. else {
  12238. usedBranch.include(context, includeChildrenRecursively);
  12239. }
  12240. }
  12241. includeCallArguments(context, parameters) {
  12242. const usedBranch = this.getUsedBranch();
  12243. if (usedBranch) {
  12244. usedBranch.includeCallArguments(context, parameters);
  12245. }
  12246. else {
  12247. this.consequent.includeCallArguments(context, parameters);
  12248. this.alternate.includeCallArguments(context, parameters);
  12249. }
  12250. }
  12251. removeAnnotations(code) {
  12252. this.test.removeAnnotations(code);
  12253. }
  12254. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  12255. const usedBranch = this.getUsedBranch();
  12256. if (this.test.included) {
  12257. this.test.render(code, options, { renderedSurroundingElement });
  12258. this.consequent.render(code, options);
  12259. this.alternate.render(code, options);
  12260. }
  12261. else {
  12262. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  12263. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  12264. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  12265. : colonPos) + 1);
  12266. if (preventASI) {
  12267. removeLineBreaks(code, inclusionStart, usedBranch.start);
  12268. }
  12269. code.remove(this.start, inclusionStart);
  12270. if (this.consequent.included) {
  12271. code.remove(colonPos, this.end);
  12272. }
  12273. this.test.removeAnnotations(code);
  12274. usedBranch.render(code, options, {
  12275. isCalleeOfRenderedParent,
  12276. preventASI: true,
  12277. renderedParentType: renderedParentType || this.parent.type,
  12278. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12279. });
  12280. }
  12281. }
  12282. getUsedBranch() {
  12283. if (this.isBranchResolutionAnalysed) {
  12284. return this.usedBranch;
  12285. }
  12286. this.isBranchResolutionAnalysed = true;
  12287. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12288. return typeof testValue === 'symbol'
  12289. ? null
  12290. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  12291. }
  12292. }
  12293. class ContinueStatement extends NodeBase {
  12294. hasEffects(context) {
  12295. if (this.label) {
  12296. if (!context.ignore.labels.has(this.label.name))
  12297. return true;
  12298. context.includedLabels.add(this.label.name);
  12299. }
  12300. else {
  12301. if (!context.ignore.continues)
  12302. return true;
  12303. context.hasContinue = true;
  12304. }
  12305. context.brokenFlow = true;
  12306. return false;
  12307. }
  12308. include(context) {
  12309. this.included = true;
  12310. if (this.label) {
  12311. this.label.include();
  12312. context.includedLabels.add(this.label.name);
  12313. }
  12314. else {
  12315. context.hasContinue = true;
  12316. }
  12317. context.brokenFlow = true;
  12318. }
  12319. }
  12320. class DebuggerStatement extends NodeBase {
  12321. hasEffects() {
  12322. return true;
  12323. }
  12324. }
  12325. class Decorator extends NodeBase {
  12326. hasEffects(context) {
  12327. return (this.expression.hasEffects(context) ||
  12328. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  12329. }
  12330. }
  12331. function hasLoopBodyEffects(context, body) {
  12332. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  12333. const { breaks, continues } = ignore;
  12334. ignore.breaks = true;
  12335. ignore.continues = true;
  12336. context.hasBreak = false;
  12337. context.hasContinue = false;
  12338. if (body.hasEffects(context))
  12339. return true;
  12340. ignore.breaks = breaks;
  12341. ignore.continues = continues;
  12342. context.hasBreak = hasBreak;
  12343. context.hasContinue = hasContinue;
  12344. context.brokenFlow = brokenFlow;
  12345. return false;
  12346. }
  12347. function includeLoopBody(context, body, includeChildrenRecursively) {
  12348. const { brokenFlow, hasBreak, hasContinue } = context;
  12349. context.hasBreak = false;
  12350. context.hasContinue = false;
  12351. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  12352. context.hasBreak = hasBreak;
  12353. context.hasContinue = hasContinue;
  12354. context.brokenFlow = brokenFlow;
  12355. }
  12356. class DoWhileStatement extends NodeBase {
  12357. hasEffects(context) {
  12358. if (this.test.hasEffects(context))
  12359. return true;
  12360. return hasLoopBodyEffects(context, this.body);
  12361. }
  12362. include(context, includeChildrenRecursively) {
  12363. this.included = true;
  12364. this.test.include(context, includeChildrenRecursively);
  12365. includeLoopBody(context, this.body, includeChildrenRecursively);
  12366. }
  12367. }
  12368. class EmptyStatement extends NodeBase {
  12369. hasEffects() {
  12370. return false;
  12371. }
  12372. }
  12373. class ExportAllDeclaration extends NodeBase {
  12374. hasEffects() {
  12375. return false;
  12376. }
  12377. initialise() {
  12378. super.initialise();
  12379. this.scope.context.addExport(this);
  12380. }
  12381. render(code, _options, nodeRenderOptions) {
  12382. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12383. }
  12384. applyDeoptimizations() { }
  12385. }
  12386. ExportAllDeclaration.prototype.needsBoundaries = true;
  12387. class ExportNamedDeclaration extends NodeBase {
  12388. bind() {
  12389. // Do not bind specifiers
  12390. this.declaration?.bind();
  12391. }
  12392. hasEffects(context) {
  12393. return !!this.declaration?.hasEffects(context);
  12394. }
  12395. initialise() {
  12396. super.initialise();
  12397. this.scope.context.addExport(this);
  12398. }
  12399. removeAnnotations(code) {
  12400. this.declaration?.removeAnnotations(code);
  12401. }
  12402. render(code, options, nodeRenderOptions) {
  12403. const { start, end } = nodeRenderOptions;
  12404. if (this.declaration === null) {
  12405. code.remove(start, end);
  12406. }
  12407. else {
  12408. code.remove(this.start, this.declaration.start);
  12409. this.declaration.render(code, options, { end, start });
  12410. }
  12411. }
  12412. applyDeoptimizations() { }
  12413. }
  12414. ExportNamedDeclaration.prototype.needsBoundaries = true;
  12415. class ExportSpecifier extends NodeBase {
  12416. applyDeoptimizations() { }
  12417. }
  12418. class ForInStatement extends NodeBase {
  12419. createScope(parentScope) {
  12420. this.scope = new BlockScope(parentScope);
  12421. }
  12422. hasEffects(context) {
  12423. const { body, deoptimized, left, right } = this;
  12424. if (!deoptimized)
  12425. this.applyDeoptimizations();
  12426. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  12427. return true;
  12428. return hasLoopBodyEffects(context, body);
  12429. }
  12430. include(context, includeChildrenRecursively) {
  12431. const { body, deoptimized, left, right } = this;
  12432. if (!deoptimized)
  12433. this.applyDeoptimizations();
  12434. this.included = true;
  12435. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  12436. right.include(context, includeChildrenRecursively);
  12437. includeLoopBody(context, body, includeChildrenRecursively);
  12438. }
  12439. initialise() {
  12440. super.initialise();
  12441. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  12442. }
  12443. render(code, options) {
  12444. this.left.render(code, options, NO_SEMICOLON);
  12445. this.right.render(code, options, NO_SEMICOLON);
  12446. // handle no space between "in" and the right side
  12447. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  12448. code.prependLeft(this.right.start, ' ');
  12449. }
  12450. this.body.render(code, options);
  12451. }
  12452. applyDeoptimizations() {
  12453. this.deoptimized = true;
  12454. this.left.deoptimizePath(EMPTY_PATH);
  12455. this.scope.context.requestTreeshakingPass();
  12456. }
  12457. }
  12458. class ForOfStatement extends NodeBase {
  12459. get await() {
  12460. return isFlagSet(this.flags, 131072 /* Flag.await */);
  12461. }
  12462. set await(value) {
  12463. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  12464. }
  12465. createScope(parentScope) {
  12466. this.scope = new BlockScope(parentScope);
  12467. }
  12468. hasEffects() {
  12469. if (!this.deoptimized)
  12470. this.applyDeoptimizations();
  12471. // Placeholder until proper Symbol.Iterator support
  12472. return true;
  12473. }
  12474. include(context, includeChildrenRecursively) {
  12475. const { body, deoptimized, left, right } = this;
  12476. if (!deoptimized)
  12477. this.applyDeoptimizations();
  12478. this.included = true;
  12479. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  12480. right.include(context, includeChildrenRecursively);
  12481. includeLoopBody(context, body, includeChildrenRecursively);
  12482. }
  12483. initialise() {
  12484. super.initialise();
  12485. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  12486. }
  12487. render(code, options) {
  12488. this.left.render(code, options, NO_SEMICOLON);
  12489. this.right.render(code, options, NO_SEMICOLON);
  12490. // handle no space between "of" and the right side
  12491. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  12492. code.prependLeft(this.right.start, ' ');
  12493. }
  12494. this.body.render(code, options);
  12495. }
  12496. applyDeoptimizations() {
  12497. this.deoptimized = true;
  12498. this.left.deoptimizePath(EMPTY_PATH);
  12499. this.right.deoptimizePath(UNKNOWN_PATH);
  12500. this.scope.context.requestTreeshakingPass();
  12501. }
  12502. }
  12503. class ForStatement extends NodeBase {
  12504. createScope(parentScope) {
  12505. this.scope = new BlockScope(parentScope);
  12506. }
  12507. hasEffects(context) {
  12508. if (this.init?.hasEffects(context) ||
  12509. this.test?.hasEffects(context) ||
  12510. this.update?.hasEffects(context)) {
  12511. return true;
  12512. }
  12513. return hasLoopBodyEffects(context, this.body);
  12514. }
  12515. include(context, includeChildrenRecursively) {
  12516. this.included = true;
  12517. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  12518. this.test?.include(context, includeChildrenRecursively);
  12519. this.update?.include(context, includeChildrenRecursively);
  12520. includeLoopBody(context, this.body, includeChildrenRecursively);
  12521. }
  12522. render(code, options) {
  12523. this.init?.render(code, options, NO_SEMICOLON);
  12524. this.test?.render(code, options, NO_SEMICOLON);
  12525. this.update?.render(code, options, NO_SEMICOLON);
  12526. this.body.render(code, options);
  12527. }
  12528. }
  12529. class FunctionExpression extends FunctionNode {
  12530. createScope(parentScope) {
  12531. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  12532. }
  12533. parseNode(esTreeNode) {
  12534. if (esTreeNode.id !== null) {
  12535. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  12536. }
  12537. return super.parseNode(esTreeNode);
  12538. }
  12539. onlyFunctionCallUsed() {
  12540. const isIIFE = this.parent.type === parseAst_js.CallExpression &&
  12541. this.parent.callee === this &&
  12542. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  12543. return isIIFE || super.onlyFunctionCallUsed();
  12544. }
  12545. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  12546. super.render(code, options);
  12547. if (renderedSurroundingElement === parseAst_js.ExpressionStatement) {
  12548. code.appendRight(this.start, '(');
  12549. code.prependLeft(this.end, ')');
  12550. }
  12551. }
  12552. }
  12553. class TrackingScope extends BlockScope {
  12554. constructor() {
  12555. super(...arguments);
  12556. this.hoistedDeclarations = [];
  12557. }
  12558. addDeclaration(identifier, context, init, kind) {
  12559. this.hoistedDeclarations.push(identifier);
  12560. return super.addDeclaration(identifier, context, init, kind);
  12561. }
  12562. }
  12563. const unset = Symbol('unset');
  12564. class IfStatement extends NodeBase {
  12565. constructor() {
  12566. super(...arguments);
  12567. this.testValue = unset;
  12568. }
  12569. deoptimizeCache() {
  12570. this.testValue = UnknownValue;
  12571. }
  12572. hasEffects(context) {
  12573. if (this.test.hasEffects(context)) {
  12574. return true;
  12575. }
  12576. const testValue = this.getTestValue();
  12577. if (typeof testValue === 'symbol') {
  12578. const { brokenFlow } = context;
  12579. if (this.consequent.hasEffects(context))
  12580. return true;
  12581. const consequentBrokenFlow = context.brokenFlow;
  12582. context.brokenFlow = brokenFlow;
  12583. if (this.alternate === null)
  12584. return false;
  12585. if (this.alternate.hasEffects(context))
  12586. return true;
  12587. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12588. return false;
  12589. }
  12590. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  12591. }
  12592. include(context, includeChildrenRecursively) {
  12593. this.included = true;
  12594. if (includeChildrenRecursively) {
  12595. this.includeRecursively(includeChildrenRecursively, context);
  12596. }
  12597. else {
  12598. const testValue = this.getTestValue();
  12599. if (typeof testValue === 'symbol') {
  12600. this.includeUnknownTest(context);
  12601. }
  12602. else {
  12603. this.includeKnownTest(context, testValue);
  12604. }
  12605. }
  12606. }
  12607. parseNode(esTreeNode) {
  12608. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  12609. if (esTreeNode.alternate) {
  12610. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  12611. }
  12612. return super.parseNode(esTreeNode);
  12613. }
  12614. render(code, options) {
  12615. const { snippets: { getPropertyAccess } } = options;
  12616. // Note that unknown test values are always included
  12617. const testValue = this.getTestValue();
  12618. const hoistedDeclarations = [];
  12619. const includesIfElse = this.test.included;
  12620. const noTreeshake = !this.scope.context.options.treeshake;
  12621. if (includesIfElse) {
  12622. this.test.render(code, options);
  12623. }
  12624. else {
  12625. code.remove(this.start, this.consequent.start);
  12626. }
  12627. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  12628. this.consequent.render(code, options);
  12629. }
  12630. else {
  12631. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  12632. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  12633. }
  12634. if (this.alternate) {
  12635. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  12636. if (includesIfElse) {
  12637. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  12638. code.prependLeft(this.alternate.start, ' ');
  12639. }
  12640. }
  12641. else {
  12642. code.remove(this.consequent.end, this.alternate.start);
  12643. }
  12644. this.alternate.render(code, options);
  12645. }
  12646. else {
  12647. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  12648. code.overwrite(this.alternate.start, this.end, ';');
  12649. }
  12650. else {
  12651. code.remove(this.consequent.end, this.end);
  12652. }
  12653. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  12654. }
  12655. }
  12656. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  12657. }
  12658. applyDeoptimizations() { }
  12659. getTestValue() {
  12660. if (this.testValue === unset) {
  12661. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  12662. }
  12663. return this.testValue;
  12664. }
  12665. includeKnownTest(context, testValue) {
  12666. if (this.test.shouldBeIncluded(context)) {
  12667. this.test.include(context, false);
  12668. }
  12669. if (testValue && this.consequent.shouldBeIncluded(context)) {
  12670. this.consequent.include(context, false, { asSingleStatement: true });
  12671. }
  12672. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  12673. this.alternate.include(context, false, { asSingleStatement: true });
  12674. }
  12675. }
  12676. includeRecursively(includeChildrenRecursively, context) {
  12677. this.test.include(context, includeChildrenRecursively);
  12678. this.consequent.include(context, includeChildrenRecursively);
  12679. this.alternate?.include(context, includeChildrenRecursively);
  12680. }
  12681. includeUnknownTest(context) {
  12682. this.test.include(context, false);
  12683. const { brokenFlow } = context;
  12684. let consequentBrokenFlow = false;
  12685. if (this.consequent.shouldBeIncluded(context)) {
  12686. this.consequent.include(context, false, { asSingleStatement: true });
  12687. consequentBrokenFlow = context.brokenFlow;
  12688. context.brokenFlow = brokenFlow;
  12689. }
  12690. if (this.alternate?.shouldBeIncluded(context)) {
  12691. this.alternate.include(context, false, { asSingleStatement: true });
  12692. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12693. }
  12694. }
  12695. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  12696. const hoistedVariables = [
  12697. ...new Set(hoistedDeclarations.map(identifier => {
  12698. const variable = identifier.variable;
  12699. return variable.included ? variable.getName(getPropertyAccess) : '';
  12700. }))
  12701. ]
  12702. .filter(Boolean)
  12703. .join(', ');
  12704. if (hoistedVariables) {
  12705. const parentType = this.parent.type;
  12706. const needsBraces = parentType !== parseAst_js.Program && parentType !== parseAst_js.BlockStatement;
  12707. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  12708. if (needsBraces) {
  12709. code.appendLeft(this.end, ` }`);
  12710. }
  12711. }
  12712. }
  12713. shouldKeepAlternateBranch() {
  12714. let currentParent = this.parent;
  12715. do {
  12716. if (currentParent instanceof IfStatement && currentParent.alternate) {
  12717. return true;
  12718. }
  12719. if (currentParent instanceof BlockStatement) {
  12720. return false;
  12721. }
  12722. currentParent = currentParent.parent;
  12723. } while (currentParent);
  12724. return false;
  12725. }
  12726. }
  12727. class ImportAttribute extends NodeBase {
  12728. }
  12729. class ImportDeclaration extends NodeBase {
  12730. // Do not bind specifiers or attributes
  12731. bind() { }
  12732. hasEffects() {
  12733. return false;
  12734. }
  12735. initialise() {
  12736. super.initialise();
  12737. this.scope.context.addImport(this);
  12738. }
  12739. render(code, _options, nodeRenderOptions) {
  12740. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12741. }
  12742. applyDeoptimizations() { }
  12743. }
  12744. ImportDeclaration.prototype.needsBoundaries = true;
  12745. class ImportDefaultSpecifier extends NodeBase {
  12746. applyDeoptimizations() { }
  12747. }
  12748. function isReassignedExportsMember(variable, exportNamesByVariable) {
  12749. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  12750. }
  12751. class VariableDeclarator extends NodeBase {
  12752. declareDeclarator(kind, isUsingDeclaration) {
  12753. this.isUsingDeclaration = isUsingDeclaration;
  12754. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  12755. }
  12756. deoptimizePath(path) {
  12757. this.id.deoptimizePath(path);
  12758. }
  12759. hasEffects(context) {
  12760. if (!this.deoptimized)
  12761. this.applyDeoptimizations();
  12762. const initEffect = this.init?.hasEffects(context);
  12763. this.id.markDeclarationReached();
  12764. return initEffect || this.id.hasEffects(context) || this.isUsingDeclaration;
  12765. }
  12766. include(context, includeChildrenRecursively) {
  12767. const { deoptimized, id, init } = this;
  12768. if (!deoptimized)
  12769. this.applyDeoptimizations();
  12770. this.included = true;
  12771. init?.include(context, includeChildrenRecursively);
  12772. id.markDeclarationReached();
  12773. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  12774. id.include(context, includeChildrenRecursively);
  12775. }
  12776. }
  12777. removeAnnotations(code) {
  12778. this.init?.removeAnnotations(code);
  12779. }
  12780. render(code, options) {
  12781. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  12782. const { end, id, init, start } = this;
  12783. const renderId = id.included || this.isUsingDeclaration;
  12784. if (renderId) {
  12785. id.render(code, options);
  12786. }
  12787. else {
  12788. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  12789. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  12790. }
  12791. if (init) {
  12792. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12793. const renderedVariable = id.variable.getName(getPropertyAccess);
  12794. if (renderedVariable !== id.name) {
  12795. code.appendLeft(init.start + 5, ` ${id.name}`);
  12796. }
  12797. }
  12798. init.render(code, options, renderId ? parseAst_js.BLANK : { renderedSurroundingElement: parseAst_js.ExpressionStatement });
  12799. }
  12800. else if (id instanceof Identifier &&
  12801. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  12802. code.appendLeft(end, `${_}=${_}void 0`);
  12803. }
  12804. }
  12805. applyDeoptimizations() {
  12806. this.deoptimized = true;
  12807. const { id, init } = this;
  12808. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  12809. const { name, variable } = id;
  12810. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  12811. if (accessedVariable !== variable) {
  12812. accessedVariable.forbidName(name);
  12813. }
  12814. }
  12815. }
  12816. }
  12817. }
  12818. class ImportExpression extends NodeBase {
  12819. constructor() {
  12820. super(...arguments);
  12821. this.inlineNamespace = null;
  12822. this.attributes = null;
  12823. this.mechanism = null;
  12824. this.namespaceExportName = undefined;
  12825. this.resolution = null;
  12826. this.resolutionString = null;
  12827. }
  12828. // Do not bind attributes
  12829. bind() {
  12830. this.source.bind();
  12831. }
  12832. /**
  12833. * Get imported variables for deterministic usage, valid cases are:
  12834. *
  12835. * - `const { foo } = await import('bar')`.
  12836. * - `(await import('bar')).foo`
  12837. * - `import('bar').then(({ foo }) => {})`
  12838. *
  12839. * Returns empty array if it's side-effect only import.
  12840. * Returns undefined if it's not fully deterministic.
  12841. */
  12842. getDeterministicImportedNames() {
  12843. const parent1 = this.parent;
  12844. // Side-effect only: import('bar')
  12845. if (parent1 instanceof ExpressionStatement) {
  12846. return parseAst_js.EMPTY_ARRAY;
  12847. }
  12848. if (parent1 instanceof AwaitExpression) {
  12849. const parent2 = parent1.parent;
  12850. // Side-effect only: await import('bar')
  12851. if (parent2 instanceof ExpressionStatement) {
  12852. return parseAst_js.EMPTY_ARRAY;
  12853. }
  12854. // Case 1: const { foo } = await import('bar')
  12855. if (parent2 instanceof VariableDeclarator) {
  12856. const declaration = parent2.id;
  12857. return declaration instanceof ObjectPattern
  12858. ? getDeterministicObjectDestructure(declaration)
  12859. : undefined;
  12860. }
  12861. // Case 2: (await import('bar')).foo
  12862. if (parent2 instanceof MemberExpression) {
  12863. const id = parent2.property;
  12864. if (!parent2.computed && id instanceof Identifier) {
  12865. return [id.name];
  12866. }
  12867. }
  12868. return;
  12869. }
  12870. // Case 3: import('bar').then(({ foo }) => {})
  12871. if (parent1 instanceof MemberExpression) {
  12872. const callExpression = parent1.parent;
  12873. const property = parent1.property;
  12874. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  12875. return;
  12876. }
  12877. const memberName = property.name;
  12878. // side-effect only, when only chaining .catch or .finally
  12879. if (callExpression.parent instanceof ExpressionStatement &&
  12880. ['catch', 'finally'].includes(memberName)) {
  12881. return parseAst_js.EMPTY_ARRAY;
  12882. }
  12883. if (memberName !== 'then')
  12884. return;
  12885. // Side-effect only: import('bar').then()
  12886. if (callExpression.arguments.length === 0) {
  12887. return parseAst_js.EMPTY_ARRAY;
  12888. }
  12889. const argument = callExpression.arguments[0];
  12890. if (callExpression.arguments.length !== 1 ||
  12891. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  12892. return;
  12893. }
  12894. // Side-effect only: import('bar').then(() => {})
  12895. if (argument.params.length === 0) {
  12896. return parseAst_js.EMPTY_ARRAY;
  12897. }
  12898. const declaration = argument.params[0];
  12899. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  12900. return getDeterministicObjectDestructure(declaration);
  12901. }
  12902. return;
  12903. }
  12904. }
  12905. hasEffects() {
  12906. return true;
  12907. }
  12908. include(context, includeChildrenRecursively) {
  12909. if (!this.included) {
  12910. this.included = true;
  12911. this.scope.context.includeDynamicImport(this);
  12912. this.scope.addAccessedDynamicImport(this);
  12913. }
  12914. this.source.include(context, includeChildrenRecursively);
  12915. }
  12916. initialise() {
  12917. super.initialise();
  12918. this.scope.context.addDynamicImport(this);
  12919. }
  12920. parseNode(esTreeNode) {
  12921. this.sourceAstNode = esTreeNode.source;
  12922. return super.parseNode(esTreeNode);
  12923. }
  12924. render(code, options) {
  12925. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  12926. if (this.inlineNamespace) {
  12927. const [left, right] = getDirectReturnFunction([], {
  12928. functionReturn: true,
  12929. lineBreakIndent: null,
  12930. name: null
  12931. });
  12932. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12933. return;
  12934. }
  12935. if (this.mechanism) {
  12936. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12937. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12938. }
  12939. if (this.resolutionString) {
  12940. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12941. if (this.namespaceExportName) {
  12942. const [left, right] = getDirectReturnFunction(['n'], {
  12943. functionReturn: true,
  12944. lineBreakIndent: null,
  12945. name: null
  12946. });
  12947. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12948. }
  12949. }
  12950. else {
  12951. this.source.render(code, options);
  12952. }
  12953. if (this.attributes !== true) {
  12954. if (this.options) {
  12955. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12956. }
  12957. if (this.attributes) {
  12958. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.attributes]], {
  12959. lineBreakIndent: null
  12960. })}`);
  12961. }
  12962. }
  12963. }
  12964. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes) {
  12965. const { format } = options;
  12966. this.inlineNamespace = null;
  12967. this.resolution = resolution;
  12968. this.resolutionString = resolutionString;
  12969. this.namespaceExportName = namespaceExportName;
  12970. this.attributes = attributes;
  12971. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12972. let helper;
  12973. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  12974. if (helper) {
  12975. accessedGlobals.push(helper);
  12976. }
  12977. if (accessedGlobals.length > 0) {
  12978. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12979. }
  12980. }
  12981. setInternalResolution(inlineNamespace) {
  12982. this.inlineNamespace = inlineNamespace;
  12983. }
  12984. applyDeoptimizations() { }
  12985. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  12986. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12987. {
  12988. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12989. format,
  12990. moduleId: this.scope.context.module.id,
  12991. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12992. }
  12993. ]);
  12994. if (mechanism) {
  12995. return { helper: null, mechanism };
  12996. }
  12997. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12998. switch (format) {
  12999. case 'cjs': {
  13000. if (dynamicImportInCjs &&
  13001. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  13002. return { helper: null, mechanism: null };
  13003. }
  13004. const helper = getInteropHelper(resolution, exportMode, interop);
  13005. let left = `require(`;
  13006. let right = `)`;
  13007. if (helper) {
  13008. left = `/*#__PURE__*/${helper}(${left}`;
  13009. right += ')';
  13010. }
  13011. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  13012. functionReturn: true,
  13013. lineBreakIndent: null,
  13014. name: null
  13015. });
  13016. left = `Promise.resolve().then(${functionLeft}${left}`;
  13017. right += `${functionRight})`;
  13018. if (!arrowFunctions && hasDynamicTarget) {
  13019. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13020. needsArrowReturnParens: false,
  13021. needsWrappedFunction: true
  13022. });
  13023. right = ')';
  13024. }
  13025. return {
  13026. helper,
  13027. mechanism: { left, right }
  13028. };
  13029. }
  13030. case 'amd': {
  13031. const resolve = compact ? 'c' : 'resolve';
  13032. const reject = compact ? 'e' : 'reject';
  13033. const helper = getInteropHelper(resolution, exportMode, interop);
  13034. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  13035. functionReturn: false,
  13036. lineBreakIndent: null,
  13037. name: null
  13038. });
  13039. const resolveNamespace = helper
  13040. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  13041. : resolve;
  13042. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  13043. functionReturn: false,
  13044. lineBreakIndent: null,
  13045. name: null
  13046. });
  13047. let left = `new Promise(${handlerLeft}require([`;
  13048. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  13049. if (!arrowFunctions && hasDynamicTarget) {
  13050. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  13051. needsArrowReturnParens: false,
  13052. needsWrappedFunction: true
  13053. });
  13054. right = ')';
  13055. }
  13056. return {
  13057. helper,
  13058. mechanism: { left, right }
  13059. };
  13060. }
  13061. case 'system': {
  13062. return {
  13063. helper: null,
  13064. mechanism: {
  13065. left: 'module.import(',
  13066. right: ')'
  13067. }
  13068. };
  13069. }
  13070. }
  13071. return { helper: null, mechanism: null };
  13072. }
  13073. }
  13074. function getInteropHelper(resolution, exportMode, interop) {
  13075. return exportMode === 'external'
  13076. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  13077. : exportMode === 'default'
  13078. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  13079. : null;
  13080. }
  13081. const accessedImportGlobals = {
  13082. amd: ['require'],
  13083. cjs: ['require'],
  13084. system: ['module']
  13085. };
  13086. function getDeterministicObjectDestructure(objectPattern) {
  13087. const variables = [];
  13088. for (const property of objectPattern.properties) {
  13089. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  13090. return;
  13091. variables.push(property.key.name);
  13092. }
  13093. return variables;
  13094. }
  13095. class ImportNamespaceSpecifier extends NodeBase {
  13096. applyDeoptimizations() { }
  13097. }
  13098. class ImportSpecifier extends NodeBase {
  13099. applyDeoptimizations() { }
  13100. }
  13101. class JSXIdentifier extends IdentifierBase {
  13102. constructor() {
  13103. super(...arguments);
  13104. this.isNativeElement = false;
  13105. }
  13106. bind() {
  13107. const type = this.getType();
  13108. if (type === 0 /* IdentifierType.Reference */) {
  13109. this.variable = this.scope.findVariable(this.name);
  13110. this.variable.addReference(this);
  13111. }
  13112. else if (type === 1 /* IdentifierType.NativeElementName */) {
  13113. this.isNativeElement = true;
  13114. }
  13115. }
  13116. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  13117. if (this.variable) {
  13118. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  13119. if (name !== this.name) {
  13120. code.overwrite(this.start, this.end, name, {
  13121. contentOnly: true,
  13122. storeName: true
  13123. });
  13124. }
  13125. }
  13126. else if (this.isNativeElement &&
  13127. this.scope.context.options.jsx.mode !== 'preserve') {
  13128. code.update(this.start, this.end, JSON.stringify(this.name));
  13129. }
  13130. }
  13131. getType() {
  13132. switch (this.parent.type) {
  13133. case 'JSXOpeningElement':
  13134. case 'JSXClosingElement': {
  13135. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  13136. ? 0 /* IdentifierType.Reference */
  13137. : 1 /* IdentifierType.NativeElementName */;
  13138. }
  13139. case 'JSXMemberExpression': {
  13140. return this.parent.object === this
  13141. ? 0 /* IdentifierType.Reference */
  13142. : 2 /* IdentifierType.Other */;
  13143. }
  13144. case 'JSXAttribute':
  13145. case 'JSXNamespacedName': {
  13146. return 2 /* IdentifierType.Other */;
  13147. }
  13148. default: {
  13149. /* istanbul ignore next */
  13150. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  13151. }
  13152. }
  13153. }
  13154. }
  13155. class JSXAttribute extends NodeBase {
  13156. render(code, options, { jsxMode } = parseAst_js.BLANK) {
  13157. super.render(code, options);
  13158. if (['classic', 'automatic'].includes(jsxMode)) {
  13159. const { name, value } = this;
  13160. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  13161. if (!(jsxMode === 'automatic' && key === 'key')) {
  13162. const safeKey = stringifyObjectKeyIfNeeded(key);
  13163. if (key !== safeKey) {
  13164. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  13165. }
  13166. if (value) {
  13167. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  13168. }
  13169. else {
  13170. code.appendLeft(name.end, ': true');
  13171. }
  13172. }
  13173. }
  13174. }
  13175. }
  13176. class JSXClosingBase extends NodeBase {
  13177. render(code, options) {
  13178. const { mode } = this.scope.context.options.jsx;
  13179. if (mode !== 'preserve') {
  13180. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  13181. }
  13182. else {
  13183. super.render(code, options);
  13184. }
  13185. }
  13186. }
  13187. class JSXClosingElement extends JSXClosingBase {
  13188. }
  13189. class JSXClosingFragment extends JSXClosingBase {
  13190. }
  13191. class JSXSpreadAttribute extends NodeBase {
  13192. render(code, options) {
  13193. this.argument.render(code, options);
  13194. const { mode } = this.scope.context.options.jsx;
  13195. if (mode !== 'preserve') {
  13196. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  13197. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  13198. }
  13199. }
  13200. }
  13201. class JSXEmptyExpression extends NodeBase {
  13202. }
  13203. class JSXExpressionContainer extends NodeBase {
  13204. render(code, options) {
  13205. const { mode } = this.scope.context.options.jsx;
  13206. if (mode !== 'preserve') {
  13207. code.remove(this.start, this.expression.start);
  13208. code.remove(this.expression.end, this.end);
  13209. }
  13210. this.expression.render(code, options);
  13211. }
  13212. }
  13213. function getRenderedJsxChildren(children) {
  13214. let renderedChildren = 0;
  13215. for (const child of children) {
  13216. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  13217. renderedChildren++;
  13218. }
  13219. }
  13220. return renderedChildren;
  13221. }
  13222. function getAndIncludeFactoryVariable(factory, preserve, importSource, node) {
  13223. const [baseName, nestedName] = factory.split('.');
  13224. let factoryVariable;
  13225. if (importSource) {
  13226. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  13227. if (preserve) {
  13228. // This pretends we are accessing an included global variable of the same name
  13229. const globalVariable = node.scope.findGlobal(baseName);
  13230. globalVariable.include();
  13231. // This excludes this variable from renaming
  13232. factoryVariable.globalName = baseName;
  13233. }
  13234. }
  13235. else {
  13236. factoryVariable = node.scope.findGlobal(baseName);
  13237. }
  13238. node.scope.context.includeVariableInModule(factoryVariable);
  13239. if (factoryVariable instanceof LocalVariable) {
  13240. factoryVariable.consolidateInitializers();
  13241. factoryVariable.addUsedPlace(node);
  13242. node.scope.context.requestTreeshakingPass();
  13243. }
  13244. return factoryVariable;
  13245. }
  13246. class JSXElementBase extends NodeBase {
  13247. constructor() {
  13248. super(...arguments);
  13249. this.factoryVariable = null;
  13250. this.factory = null;
  13251. }
  13252. initialise() {
  13253. super.initialise();
  13254. const { importSource } = (this.jsxMode = this.getRenderingMode());
  13255. if (importSource) {
  13256. this.scope.context.addImportSource(importSource);
  13257. }
  13258. }
  13259. include(context, includeChildrenRecursively) {
  13260. if (!this.included) {
  13261. const { factory, importSource, mode } = this.jsxMode;
  13262. if (factory) {
  13263. this.factory = factory;
  13264. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this);
  13265. }
  13266. }
  13267. super.include(context, includeChildrenRecursively);
  13268. }
  13269. applyDeoptimizations() { }
  13270. getRenderingMode() {
  13271. const jsx = this.scope.context.options.jsx;
  13272. const { mode, factory, importSource } = jsx;
  13273. if (mode === 'automatic') {
  13274. return {
  13275. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  13276. importSource: jsx.jsxImportSource,
  13277. mode
  13278. };
  13279. }
  13280. return { factory, importSource, mode };
  13281. }
  13282. renderChildren(code, options, openingEnd) {
  13283. const { children } = this;
  13284. let hasMultipleChildren = false;
  13285. let childrenEnd = openingEnd;
  13286. let firstChild = null;
  13287. for (const child of children) {
  13288. if (child instanceof JSXExpressionContainer &&
  13289. child.expression instanceof JSXEmptyExpression) {
  13290. code.remove(childrenEnd, child.end);
  13291. }
  13292. else {
  13293. code.appendLeft(childrenEnd, ', ');
  13294. child.render(code, options);
  13295. if (firstChild) {
  13296. hasMultipleChildren = true;
  13297. }
  13298. else {
  13299. firstChild = child;
  13300. }
  13301. }
  13302. childrenEnd = child.end;
  13303. }
  13304. return { childrenEnd, firstChild, hasMultipleChildren };
  13305. }
  13306. }
  13307. class JSXElement extends JSXElementBase {
  13308. render(code, options) {
  13309. switch (this.jsxMode.mode) {
  13310. case 'classic': {
  13311. this.renderClassicMode(code, options);
  13312. break;
  13313. }
  13314. case 'automatic': {
  13315. this.renderAutomaticMode(code, options);
  13316. break;
  13317. }
  13318. default: {
  13319. super.render(code, options);
  13320. }
  13321. }
  13322. }
  13323. getRenderingMode() {
  13324. const jsx = this.scope.context.options.jsx;
  13325. const { mode, factory, importSource } = jsx;
  13326. if (mode === 'automatic') {
  13327. // In the case there is a key after a spread attribute, we fall back to
  13328. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  13329. // for reasoning.
  13330. let hasSpread = false;
  13331. for (const attribute of this.openingElement.attributes) {
  13332. if (attribute instanceof JSXSpreadAttribute) {
  13333. hasSpread = true;
  13334. }
  13335. else if (hasSpread && attribute.name.name === 'key') {
  13336. return { factory, importSource, mode: 'classic' };
  13337. }
  13338. }
  13339. }
  13340. return super.getRenderingMode();
  13341. }
  13342. renderClassicMode(code, options) {
  13343. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13344. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  13345. const [, ...nestedName] = factory.split('.');
  13346. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  13347. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  13348. this.renderChildren(code, options, openingEnd);
  13349. if (selfClosing) {
  13350. code.appendLeft(end, ')');
  13351. }
  13352. else {
  13353. closingElement.render(code, options);
  13354. }
  13355. }
  13356. renderAutomaticMode(code, options) {
  13357. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13358. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  13359. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  13360. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  13361. if (firstChild) {
  13362. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  13363. if (!inObject) {
  13364. code.prependRight(firstChild.start, '{ ');
  13365. inObject = true;
  13366. }
  13367. previousEnd = closingElement.start;
  13368. if (hasMultipleChildren) {
  13369. code.appendLeft(previousEnd, ']');
  13370. }
  13371. }
  13372. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  13373. if (keyAttribute) {
  13374. const { value } = keyAttribute;
  13375. // This will appear to the left of the moved code...
  13376. code.appendLeft(childrenEnd, ', ');
  13377. if (value) {
  13378. code.move(value.start, value.end, childrenEnd);
  13379. }
  13380. else {
  13381. code.appendLeft(childrenEnd, 'true');
  13382. }
  13383. }
  13384. if (selfClosing) {
  13385. // Moving the key attribute will also move the parenthesis to the right position
  13386. code.appendLeft(keyAttribute?.value?.end || end, ')');
  13387. }
  13388. else {
  13389. closingElement.render(code, options);
  13390. }
  13391. }
  13392. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  13393. const { jsxMode: { mode }, openingElement } = this;
  13394. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  13395. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  13396. openingElement.render(code, options, { jsxMode: mode });
  13397. let keyAttribute = null;
  13398. let hasSpread = false;
  13399. let inObject = false;
  13400. let previousEnd = nameEnd;
  13401. let hasAttributes = false;
  13402. let firstAttribute = null;
  13403. for (const attribute of attributes) {
  13404. if (attribute instanceof JSXAttribute) {
  13405. if (extractKeyAttribute && attribute.name.name === 'key') {
  13406. keyAttribute = attribute;
  13407. code.remove(previousEnd, attribute.value?.start || attribute.end);
  13408. continue;
  13409. }
  13410. code.appendLeft(previousEnd, ',');
  13411. if (!inObject) {
  13412. code.prependRight(attribute.start, '{ ');
  13413. inObject = true;
  13414. }
  13415. hasAttributes = true;
  13416. }
  13417. else {
  13418. if (inObject) {
  13419. if (hasAttributes) {
  13420. code.appendLeft(previousEnd, ' ');
  13421. }
  13422. code.appendLeft(previousEnd, '},');
  13423. inObject = false;
  13424. }
  13425. else {
  13426. code.appendLeft(previousEnd, ',');
  13427. }
  13428. hasSpread = true;
  13429. }
  13430. previousEnd = attribute.end;
  13431. if (!firstAttribute) {
  13432. firstAttribute = attribute;
  13433. }
  13434. }
  13435. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  13436. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  13437. }
  13438. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  13439. if (inObject) {
  13440. code.appendLeft(attributesEnd, ' }');
  13441. }
  13442. if (hasSpread) {
  13443. if (hasAttributes) {
  13444. const { start } = firstAttribute;
  13445. if (firstAttribute instanceof JSXSpreadAttribute) {
  13446. code.prependRight(start, '{}, ');
  13447. }
  13448. code.prependRight(start, 'Object.assign(');
  13449. code.appendLeft(attributesEnd, ')');
  13450. }
  13451. }
  13452. else if (!hasAttributes) {
  13453. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  13454. }
  13455. }
  13456. }
  13457. class JSXFragment extends JSXElementBase {
  13458. render(code, options) {
  13459. switch (this.jsxMode.mode) {
  13460. case 'classic': {
  13461. this.renderClassicMode(code, options);
  13462. break;
  13463. }
  13464. case 'automatic': {
  13465. this.renderAutomaticMode(code, options);
  13466. break;
  13467. }
  13468. default: {
  13469. super.render(code, options);
  13470. }
  13471. }
  13472. }
  13473. renderClassicMode(code, options) {
  13474. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13475. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  13476. const [, ...nestedName] = factory.split('.');
  13477. openingFragment.render(code, options);
  13478. code.prependRight(start, `/*#__PURE__*/${[
  13479. factoryVariable.getName(getPropertyAccess, useOriginalName),
  13480. ...nestedName
  13481. ].join('.')}(`);
  13482. code.appendLeft(openingFragment.end, ', null');
  13483. this.renderChildren(code, options, openingFragment.end);
  13484. closingFragment.render(code, options);
  13485. }
  13486. renderAutomaticMode(code, options) {
  13487. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13488. const { closingFragment, factoryVariable, openingFragment, start } = this;
  13489. openingFragment.render(code, options);
  13490. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  13491. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  13492. if (firstChild) {
  13493. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  13494. if (hasMultipleChildren) {
  13495. code.appendLeft(closingFragment.start, ']');
  13496. }
  13497. code.appendLeft(childrenEnd, ' }');
  13498. }
  13499. else {
  13500. code.appendLeft(openingFragment.end, ', {}');
  13501. }
  13502. closingFragment.render(code, options);
  13503. }
  13504. }
  13505. class JSXMemberExpression extends NodeBase {
  13506. }
  13507. class JSXNamespacedName extends NodeBase {
  13508. }
  13509. class JSXOpeningElement extends NodeBase {
  13510. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  13511. this.name.render(code, options);
  13512. for (const attribute of this.attributes) {
  13513. attribute.render(code, options, { jsxMode });
  13514. }
  13515. }
  13516. }
  13517. class JSXOpeningFragment extends NodeBase {
  13518. constructor() {
  13519. super(...arguments);
  13520. this.fragment = null;
  13521. this.fragmentVariable = null;
  13522. }
  13523. include(context, includeChildrenRecursively) {
  13524. if (!this.included) {
  13525. const jsx = this.scope.context.options.jsx;
  13526. if (jsx.mode === 'automatic') {
  13527. this.fragment = 'Fragment';
  13528. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this);
  13529. }
  13530. else {
  13531. const { fragment, importSource, mode } = jsx;
  13532. if (fragment != null) {
  13533. this.fragment = fragment;
  13534. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this);
  13535. }
  13536. }
  13537. }
  13538. super.include(context, includeChildrenRecursively);
  13539. }
  13540. render(code, options) {
  13541. const { mode } = this.scope.context.options.jsx;
  13542. if (mode !== 'preserve') {
  13543. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13544. const [, ...nestedFragment] = this.fragment.split('.');
  13545. const fragment = [
  13546. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  13547. ...nestedFragment
  13548. ].join('.');
  13549. code.update(this.start, this.end, fragment);
  13550. }
  13551. }
  13552. }
  13553. class JSXSpreadChild extends NodeBase {
  13554. render(code, options) {
  13555. super.render(code, options);
  13556. const { mode } = this.scope.context.options.jsx;
  13557. if (mode !== 'preserve') {
  13558. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  13559. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  13560. }
  13561. }
  13562. }
  13563. class JSXText extends NodeBase {
  13564. render(code) {
  13565. const { mode } = this.scope.context.options.jsx;
  13566. if (mode !== 'preserve') {
  13567. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  13568. contentOnly: true
  13569. });
  13570. }
  13571. }
  13572. }
  13573. class LabeledStatement extends NodeBase {
  13574. hasEffects(context) {
  13575. const { brokenFlow, includedLabels } = context;
  13576. context.ignore.labels.add(this.label.name);
  13577. context.includedLabels = new Set();
  13578. let bodyHasEffects = false;
  13579. if (this.body.hasEffects(context)) {
  13580. bodyHasEffects = true;
  13581. }
  13582. else {
  13583. context.ignore.labels.delete(this.label.name);
  13584. if (context.includedLabels.has(this.label.name)) {
  13585. context.includedLabels.delete(this.label.name);
  13586. context.brokenFlow = brokenFlow;
  13587. }
  13588. }
  13589. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13590. return bodyHasEffects;
  13591. }
  13592. include(context, includeChildrenRecursively) {
  13593. this.included = true;
  13594. const { brokenFlow, includedLabels } = context;
  13595. context.includedLabels = new Set();
  13596. this.body.include(context, includeChildrenRecursively);
  13597. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  13598. this.label.include();
  13599. context.includedLabels.delete(this.label.name);
  13600. context.brokenFlow = brokenFlow;
  13601. }
  13602. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13603. }
  13604. render(code, options) {
  13605. if (this.label.included) {
  13606. this.label.render(code, options);
  13607. }
  13608. else {
  13609. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  13610. }
  13611. this.body.render(code, options);
  13612. }
  13613. }
  13614. class LogicalExpression extends NodeBase {
  13615. constructor() {
  13616. super(...arguments);
  13617. // We collect deoptimization information if usedBranch !== null
  13618. this.expressionsToBeDeoptimized = [];
  13619. this.usedBranch = null;
  13620. }
  13621. //private isBranchResolutionAnalysed = false;
  13622. get isBranchResolutionAnalysed() {
  13623. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13624. }
  13625. set isBranchResolutionAnalysed(value) {
  13626. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13627. }
  13628. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13629. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13630. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13631. }
  13632. deoptimizeCache() {
  13633. if (this.usedBranch) {
  13634. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  13635. this.usedBranch = null;
  13636. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13637. const { scope: { context }, expressionsToBeDeoptimized } = this;
  13638. this.expressionsToBeDeoptimized = parseAst_js.EMPTY_ARRAY;
  13639. for (const expression of expressionsToBeDeoptimized) {
  13640. expression.deoptimizeCache();
  13641. }
  13642. // Request another pass because we need to ensure "include" runs again if
  13643. // it is rendered
  13644. context.requestTreeshakingPass();
  13645. }
  13646. }
  13647. deoptimizePath(path) {
  13648. const usedBranch = this.getUsedBranch();
  13649. if (usedBranch) {
  13650. usedBranch.deoptimizePath(path);
  13651. }
  13652. else {
  13653. this.left.deoptimizePath(path);
  13654. this.right.deoptimizePath(path);
  13655. }
  13656. }
  13657. getLiteralValueAtPath(path, recursionTracker, origin) {
  13658. const usedBranch = this.getUsedBranch();
  13659. if (!usedBranch)
  13660. return UnknownValue;
  13661. this.expressionsToBeDeoptimized.push(origin);
  13662. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13663. }
  13664. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13665. const usedBranch = this.getUsedBranch();
  13666. if (!usedBranch)
  13667. return [
  13668. new MultiExpression([
  13669. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13670. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13671. ]),
  13672. false
  13673. ];
  13674. this.expressionsToBeDeoptimized.push(origin);
  13675. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13676. }
  13677. hasEffects(context) {
  13678. if (this.left.hasEffects(context)) {
  13679. return true;
  13680. }
  13681. if (this.getUsedBranch() !== this.left) {
  13682. return this.right.hasEffects(context);
  13683. }
  13684. return false;
  13685. }
  13686. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13687. const usedBranch = this.getUsedBranch();
  13688. if (!usedBranch) {
  13689. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13690. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  13691. }
  13692. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13693. }
  13694. include(context, includeChildrenRecursively) {
  13695. this.included = true;
  13696. const usedBranch = this.getUsedBranch();
  13697. if (includeChildrenRecursively ||
  13698. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  13699. !usedBranch) {
  13700. this.left.include(context, includeChildrenRecursively);
  13701. this.right.include(context, includeChildrenRecursively);
  13702. }
  13703. else {
  13704. usedBranch.include(context, includeChildrenRecursively);
  13705. }
  13706. }
  13707. removeAnnotations(code) {
  13708. this.left.removeAnnotations(code);
  13709. }
  13710. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = parseAst_js.BLANK) {
  13711. if (!this.left.included || !this.right.included) {
  13712. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  13713. if (this.right.included) {
  13714. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  13715. code.remove(this.start, removePos);
  13716. if (preventASI) {
  13717. removeLineBreaks(code, removePos, this.right.start);
  13718. }
  13719. this.left.removeAnnotations(code);
  13720. }
  13721. else {
  13722. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  13723. }
  13724. this.getUsedBranch().render(code, options, {
  13725. isCalleeOfRenderedParent,
  13726. preventASI,
  13727. renderedParentType: renderedParentType || this.parent.type,
  13728. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13729. });
  13730. }
  13731. else {
  13732. this.left.render(code, options, {
  13733. preventASI,
  13734. renderedSurroundingElement
  13735. });
  13736. this.right.render(code, options);
  13737. }
  13738. }
  13739. getUsedBranch() {
  13740. if (!this.isBranchResolutionAnalysed) {
  13741. this.isBranchResolutionAnalysed = true;
  13742. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13743. if (typeof leftValue === 'symbol') {
  13744. return null;
  13745. }
  13746. else {
  13747. this.usedBranch =
  13748. (this.operator === '||' && leftValue) ||
  13749. (this.operator === '&&' && !leftValue) ||
  13750. (this.operator === '??' && leftValue != null)
  13751. ? this.left
  13752. : this.right;
  13753. }
  13754. }
  13755. return this.usedBranch;
  13756. }
  13757. }
  13758. class NewExpression extends NodeBase {
  13759. hasEffects(context) {
  13760. if (!this.deoptimized)
  13761. this.applyDeoptimizations();
  13762. for (const argument of this.arguments) {
  13763. if (argument.hasEffects(context))
  13764. return true;
  13765. }
  13766. if (this.annotationPure) {
  13767. return false;
  13768. }
  13769. return (this.callee.hasEffects(context) ||
  13770. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13771. }
  13772. hasEffectsOnInteractionAtPath(path, { type }) {
  13773. return path.length > 0 || type !== INTERACTION_ACCESSED;
  13774. }
  13775. include(context, includeChildrenRecursively) {
  13776. if (!this.deoptimized)
  13777. this.applyDeoptimizations();
  13778. if (includeChildrenRecursively) {
  13779. super.include(context, includeChildrenRecursively);
  13780. }
  13781. else {
  13782. this.included = true;
  13783. this.callee.include(context, false);
  13784. }
  13785. this.callee.includeCallArguments(context, this.arguments);
  13786. }
  13787. initialise() {
  13788. super.initialise();
  13789. this.interaction = {
  13790. args: [null, ...this.arguments],
  13791. type: INTERACTION_CALLED,
  13792. withNew: true
  13793. };
  13794. if (this.annotations &&
  13795. this.scope.context.options.treeshake.annotations) {
  13796. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13797. }
  13798. }
  13799. render(code, options) {
  13800. this.callee.render(code, options);
  13801. renderCallArguments(code, options, this);
  13802. }
  13803. applyDeoptimizations() {
  13804. this.deoptimized = true;
  13805. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13806. this.scope.context.requestTreeshakingPass();
  13807. }
  13808. }
  13809. class ObjectExpression extends NodeBase {
  13810. constructor() {
  13811. super(...arguments);
  13812. this.objectEntity = null;
  13813. }
  13814. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13815. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13816. }
  13817. deoptimizeCache() {
  13818. this.getObjectEntity().deoptimizeAllProperties();
  13819. }
  13820. deoptimizePath(path) {
  13821. this.getObjectEntity().deoptimizePath(path);
  13822. }
  13823. getLiteralValueAtPath(path, recursionTracker, origin) {
  13824. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  13825. }
  13826. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13827. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13828. }
  13829. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13830. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  13831. }
  13832. render(code, options, { renderedSurroundingElement } = parseAst_js.BLANK) {
  13833. super.render(code, options);
  13834. if (renderedSurroundingElement === parseAst_js.ExpressionStatement ||
  13835. renderedSurroundingElement === parseAst_js.ArrowFunctionExpression) {
  13836. code.appendRight(this.start, '(');
  13837. code.prependLeft(this.end, ')');
  13838. }
  13839. }
  13840. applyDeoptimizations() { }
  13841. getObjectEntity() {
  13842. if (this.objectEntity !== null) {
  13843. return this.objectEntity;
  13844. }
  13845. let prototype = OBJECT_PROTOTYPE;
  13846. const properties = [];
  13847. for (const property of this.properties) {
  13848. if (property instanceof SpreadElement) {
  13849. properties.push({ key: UnknownKey, kind: 'init', property });
  13850. continue;
  13851. }
  13852. let key;
  13853. if (property.computed) {
  13854. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13855. if (typeof keyValue === 'symbol') {
  13856. properties.push({ key: UnknownKey, kind: property.kind, property });
  13857. continue;
  13858. }
  13859. else {
  13860. key = String(keyValue);
  13861. }
  13862. }
  13863. else {
  13864. key =
  13865. property.key instanceof Identifier
  13866. ? property.key.name
  13867. : String(property.key.value);
  13868. if (key === '__proto__' && property.kind === 'init') {
  13869. prototype =
  13870. property.value instanceof Literal && property.value.value === null
  13871. ? null
  13872. : property.value;
  13873. continue;
  13874. }
  13875. }
  13876. properties.push({ key, kind: property.kind, property });
  13877. }
  13878. return (this.objectEntity = new ObjectEntity(properties, prototype));
  13879. }
  13880. }
  13881. class PanicError extends NodeBase {
  13882. initialise() {
  13883. const id = this.scope.context.module.id;
  13884. // This simulates the current nested error structure. We could also just
  13885. // replace it with a flat error.
  13886. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message));
  13887. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  13888. return parseAst_js.error(moduleParseError);
  13889. }
  13890. }
  13891. class ParseError extends NodeBase {
  13892. initialise() {
  13893. const pos = this.start;
  13894. const id = this.scope.context.module.id;
  13895. // This simulates the current nested error structure. We could also just
  13896. // replace it with a flat error.
  13897. const parseError = parseAst_js.getRollupError(parseAst_js.logParseError(this.message, pos));
  13898. const moduleParseError = parseAst_js.logModuleParseError(parseError, id);
  13899. this.scope.context.error(moduleParseError, pos);
  13900. }
  13901. }
  13902. class PrivateIdentifier extends NodeBase {
  13903. }
  13904. class Program extends NodeBase {
  13905. constructor() {
  13906. super(...arguments);
  13907. this.hasCachedEffect = null;
  13908. this.hasLoggedEffect = false;
  13909. }
  13910. hasCachedEffects() {
  13911. if (!this.included) {
  13912. return false;
  13913. }
  13914. return this.hasCachedEffect === null
  13915. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  13916. : this.hasCachedEffect;
  13917. }
  13918. hasEffects(context) {
  13919. for (const node of this.body) {
  13920. if (node.hasEffects(context)) {
  13921. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  13922. this.hasLoggedEffect = true;
  13923. const { code, log, module } = this.scope.context;
  13924. log(parseAst_js.LOGLEVEL_INFO, parseAst_js.logFirstSideEffect(code, module.id, parseAst_js.locate(code, node.start, { offsetLine: 1 })), node.start);
  13925. }
  13926. return (this.hasCachedEffect = true);
  13927. }
  13928. }
  13929. return false;
  13930. }
  13931. include(context, includeChildrenRecursively) {
  13932. this.included = true;
  13933. for (const node of this.body) {
  13934. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  13935. node.include(context, includeChildrenRecursively);
  13936. }
  13937. }
  13938. }
  13939. initialise() {
  13940. super.initialise();
  13941. if (this.invalidAnnotations)
  13942. for (const { start, end, type } of this.invalidAnnotations) {
  13943. this.scope.context.magicString.remove(start, end);
  13944. if (type === 'pure' || type === 'noSideEffects') {
  13945. 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);
  13946. }
  13947. }
  13948. }
  13949. render(code, options) {
  13950. let start = this.start;
  13951. if (code.original.startsWith('#!')) {
  13952. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  13953. code.remove(0, start);
  13954. }
  13955. if (this.body.length > 0) {
  13956. // Keep all consecutive lines that start with a comment
  13957. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  13958. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  13959. if (firstLineBreak[0] === -1) {
  13960. break;
  13961. }
  13962. start += firstLineBreak[1];
  13963. }
  13964. renderStatementList(this.body, code, start, this.end, options);
  13965. }
  13966. else {
  13967. super.render(code, options);
  13968. }
  13969. }
  13970. applyDeoptimizations() { }
  13971. }
  13972. class Property extends MethodBase {
  13973. constructor() {
  13974. super(...arguments);
  13975. this.declarationInit = null;
  13976. }
  13977. //declare method: boolean;
  13978. get method() {
  13979. return isFlagSet(this.flags, 262144 /* Flag.method */);
  13980. }
  13981. set method(value) {
  13982. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  13983. }
  13984. //declare shorthand: boolean;
  13985. get shorthand() {
  13986. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  13987. }
  13988. set shorthand(value) {
  13989. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  13990. }
  13991. declare(kind, init) {
  13992. this.declarationInit = init;
  13993. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  13994. }
  13995. hasEffects(context) {
  13996. if (!this.deoptimized)
  13997. this.applyDeoptimizations();
  13998. const propertyReadSideEffects = this.scope.context.options.treeshake.propertyReadSideEffects;
  13999. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  14000. this.key.hasEffects(context) ||
  14001. this.value.hasEffects(context));
  14002. }
  14003. markDeclarationReached() {
  14004. this.value.markDeclarationReached();
  14005. }
  14006. render(code, options) {
  14007. if (!this.shorthand) {
  14008. this.key.render(code, options);
  14009. }
  14010. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  14011. }
  14012. applyDeoptimizations() {
  14013. this.deoptimized = true;
  14014. if (this.declarationInit !== null) {
  14015. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  14016. this.scope.context.requestTreeshakingPass();
  14017. }
  14018. }
  14019. }
  14020. class PropertyDefinition extends NodeBase {
  14021. get computed() {
  14022. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  14023. }
  14024. set computed(value) {
  14025. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  14026. }
  14027. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14028. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14029. }
  14030. deoptimizePath(path) {
  14031. this.value?.deoptimizePath(path);
  14032. }
  14033. getLiteralValueAtPath(path, recursionTracker, origin) {
  14034. return this.value
  14035. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  14036. : UnknownValue;
  14037. }
  14038. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14039. return this.value
  14040. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  14041. : UNKNOWN_RETURN_EXPRESSION;
  14042. }
  14043. hasEffects(context) {
  14044. return (this.key.hasEffects(context) ||
  14045. (this.static && !!this.value?.hasEffects(context)) ||
  14046. checkEffectForNodes(this.decorators, context));
  14047. }
  14048. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14049. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  14050. }
  14051. applyDeoptimizations() { }
  14052. }
  14053. class ReturnStatement extends NodeBase {
  14054. hasEffects(context) {
  14055. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  14056. return true;
  14057. context.brokenFlow = true;
  14058. return false;
  14059. }
  14060. include(context, includeChildrenRecursively) {
  14061. this.included = true;
  14062. this.argument?.include(context, includeChildrenRecursively);
  14063. context.brokenFlow = true;
  14064. }
  14065. initialise() {
  14066. super.initialise();
  14067. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  14068. }
  14069. render(code, options) {
  14070. if (this.argument) {
  14071. this.argument.render(code, options, { preventASI: true });
  14072. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  14073. code.prependLeft(this.start + 6, ' ');
  14074. }
  14075. }
  14076. }
  14077. }
  14078. class SequenceExpression extends NodeBase {
  14079. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14080. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14081. }
  14082. deoptimizePath(path) {
  14083. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  14084. }
  14085. getLiteralValueAtPath(path, recursionTracker, origin) {
  14086. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  14087. }
  14088. hasEffects(context) {
  14089. for (const expression of this.expressions) {
  14090. if (expression.hasEffects(context))
  14091. return true;
  14092. }
  14093. return false;
  14094. }
  14095. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14096. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  14097. }
  14098. include(context, includeChildrenRecursively) {
  14099. this.included = true;
  14100. const lastExpression = this.expressions[this.expressions.length - 1];
  14101. for (const expression of this.expressions) {
  14102. if (includeChildrenRecursively ||
  14103. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  14104. expression.shouldBeIncluded(context))
  14105. expression.include(context, includeChildrenRecursively);
  14106. }
  14107. }
  14108. removeAnnotations(code) {
  14109. this.expressions[0].removeAnnotations(code);
  14110. }
  14111. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = parseAst_js.BLANK) {
  14112. let includedNodes = 0;
  14113. let lastSeparatorPos = null;
  14114. const lastNode = this.expressions[this.expressions.length - 1];
  14115. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  14116. if (!node.included) {
  14117. treeshakeNode(node, code, start, end);
  14118. continue;
  14119. }
  14120. includedNodes++;
  14121. lastSeparatorPos = separator;
  14122. if (includedNodes === 1 && preventASI) {
  14123. removeLineBreaks(code, start, node.start);
  14124. }
  14125. if (includedNodes === 1) {
  14126. const parentType = renderedParentType || this.parent.type;
  14127. node.render(code, options, {
  14128. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  14129. renderedParentType: parentType,
  14130. renderedSurroundingElement: parentType
  14131. });
  14132. }
  14133. else {
  14134. node.render(code, options);
  14135. }
  14136. }
  14137. if (lastSeparatorPos) {
  14138. code.remove(lastSeparatorPos, this.end);
  14139. }
  14140. }
  14141. }
  14142. class Super extends NodeBase {
  14143. bind() {
  14144. this.variable = this.scope.findVariable('this');
  14145. }
  14146. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14147. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14148. }
  14149. deoptimizePath(path) {
  14150. this.variable.deoptimizePath(path);
  14151. }
  14152. include() {
  14153. if (!this.included) {
  14154. this.included = true;
  14155. this.scope.context.includeVariableInModule(this.variable);
  14156. }
  14157. }
  14158. }
  14159. class SwitchCase extends NodeBase {
  14160. hasEffects(context) {
  14161. if (this.test?.hasEffects(context))
  14162. return true;
  14163. for (const node of this.consequent) {
  14164. if (context.brokenFlow)
  14165. break;
  14166. if (node.hasEffects(context))
  14167. return true;
  14168. }
  14169. return false;
  14170. }
  14171. include(context, includeChildrenRecursively) {
  14172. this.included = true;
  14173. this.test?.include(context, includeChildrenRecursively);
  14174. for (const node of this.consequent) {
  14175. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  14176. node.include(context, includeChildrenRecursively);
  14177. }
  14178. }
  14179. render(code, options, nodeRenderOptions) {
  14180. if (this.consequent.length > 0) {
  14181. if (this.test) {
  14182. this.test.render(code, options);
  14183. }
  14184. const testEnd = this.test
  14185. ? this.test.end
  14186. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  14187. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  14188. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  14189. }
  14190. else {
  14191. super.render(code, options);
  14192. }
  14193. }
  14194. }
  14195. SwitchCase.prototype.needsBoundaries = true;
  14196. class SwitchStatement extends NodeBase {
  14197. createScope(parentScope) {
  14198. this.parentScope = parentScope;
  14199. this.scope = new BlockScope(parentScope);
  14200. }
  14201. hasEffects(context) {
  14202. if (this.discriminant.hasEffects(context))
  14203. return true;
  14204. const { brokenFlow, hasBreak, ignore } = context;
  14205. const { breaks } = ignore;
  14206. ignore.breaks = true;
  14207. context.hasBreak = false;
  14208. let onlyHasBrokenFlow = true;
  14209. for (const switchCase of this.cases) {
  14210. if (switchCase.hasEffects(context))
  14211. return true;
  14212. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  14213. context.hasBreak = false;
  14214. context.brokenFlow = brokenFlow;
  14215. }
  14216. if (this.defaultCase !== null) {
  14217. context.brokenFlow = onlyHasBrokenFlow;
  14218. }
  14219. ignore.breaks = breaks;
  14220. context.hasBreak = hasBreak;
  14221. return false;
  14222. }
  14223. include(context, includeChildrenRecursively) {
  14224. this.included = true;
  14225. this.discriminant.include(context, includeChildrenRecursively);
  14226. const { brokenFlow, hasBreak } = context;
  14227. context.hasBreak = false;
  14228. let onlyHasBrokenFlow = true;
  14229. let isCaseIncluded = includeChildrenRecursively ||
  14230. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  14231. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  14232. const switchCase = this.cases[caseIndex];
  14233. if (switchCase.included) {
  14234. isCaseIncluded = true;
  14235. }
  14236. if (!isCaseIncluded) {
  14237. const hasEffectsContext = createHasEffectsContext();
  14238. hasEffectsContext.ignore.breaks = true;
  14239. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  14240. }
  14241. if (isCaseIncluded) {
  14242. switchCase.include(context, includeChildrenRecursively);
  14243. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  14244. context.hasBreak = false;
  14245. context.brokenFlow = brokenFlow;
  14246. }
  14247. else {
  14248. onlyHasBrokenFlow = brokenFlow;
  14249. }
  14250. }
  14251. if (isCaseIncluded && this.defaultCase !== null) {
  14252. context.brokenFlow = onlyHasBrokenFlow;
  14253. }
  14254. context.hasBreak = hasBreak;
  14255. }
  14256. initialise() {
  14257. super.initialise();
  14258. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  14259. if (this.cases[caseIndex].test === null) {
  14260. this.defaultCase = caseIndex;
  14261. return;
  14262. }
  14263. }
  14264. this.defaultCase = null;
  14265. }
  14266. parseNode(esTreeNode) {
  14267. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  14268. return super.parseNode(esTreeNode);
  14269. }
  14270. render(code, options) {
  14271. this.discriminant.render(code, options);
  14272. if (this.cases.length > 0) {
  14273. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  14274. }
  14275. }
  14276. }
  14277. class TaggedTemplateExpression extends CallExpressionBase {
  14278. bind() {
  14279. super.bind();
  14280. if (this.tag.type === parseAst_js.Identifier) {
  14281. const name = this.tag.name;
  14282. const variable = this.scope.findVariable(name);
  14283. if (variable.isNamespace) {
  14284. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCannotCallNamespace(name), this.start);
  14285. }
  14286. }
  14287. }
  14288. hasEffects(context) {
  14289. if (!this.deoptimized)
  14290. this.applyDeoptimizations();
  14291. for (const argument of this.quasi.expressions) {
  14292. if (argument.hasEffects(context))
  14293. return true;
  14294. }
  14295. return (this.tag.hasEffects(context) ||
  14296. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14297. }
  14298. include(context, includeChildrenRecursively) {
  14299. if (!this.deoptimized)
  14300. this.applyDeoptimizations();
  14301. if (includeChildrenRecursively) {
  14302. super.include(context, includeChildrenRecursively);
  14303. }
  14304. else {
  14305. this.included = true;
  14306. this.tag.include(context, includeChildrenRecursively);
  14307. this.quasi.include(context, includeChildrenRecursively);
  14308. }
  14309. this.tag.includeCallArguments(context, this.args);
  14310. const [returnExpression] = this.getReturnExpression();
  14311. if (!returnExpression.included) {
  14312. returnExpression.include(context, false);
  14313. }
  14314. }
  14315. initialise() {
  14316. super.initialise();
  14317. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  14318. this.interaction = {
  14319. args: [
  14320. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  14321. ...this.args
  14322. ],
  14323. type: INTERACTION_CALLED,
  14324. withNew: false
  14325. };
  14326. }
  14327. render(code, options) {
  14328. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  14329. this.quasi.render(code, options);
  14330. }
  14331. applyDeoptimizations() {
  14332. this.deoptimized = true;
  14333. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  14334. this.scope.context.requestTreeshakingPass();
  14335. }
  14336. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  14337. if (this.returnExpression === null) {
  14338. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  14339. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  14340. }
  14341. return this.returnExpression;
  14342. }
  14343. }
  14344. class TemplateElement extends NodeBase {
  14345. get tail() {
  14346. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  14347. }
  14348. set tail(value) {
  14349. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  14350. }
  14351. // Do not try to bind value
  14352. bind() { }
  14353. hasEffects() {
  14354. return false;
  14355. }
  14356. include() {
  14357. this.included = true;
  14358. }
  14359. parseNode(esTreeNode) {
  14360. this.value = esTreeNode.value;
  14361. return super.parseNode(esTreeNode);
  14362. }
  14363. render() { }
  14364. }
  14365. class TemplateLiteral extends NodeBase {
  14366. deoptimizeArgumentsOnInteractionAtPath() { }
  14367. getLiteralValueAtPath(path) {
  14368. if (path.length > 0 || this.quasis.length !== 1) {
  14369. return UnknownValue;
  14370. }
  14371. return this.quasis[0].value.cooked;
  14372. }
  14373. getReturnExpressionWhenCalledAtPath(path) {
  14374. if (path.length !== 1) {
  14375. return UNKNOWN_RETURN_EXPRESSION;
  14376. }
  14377. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  14378. }
  14379. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14380. if (interaction.type === INTERACTION_ACCESSED) {
  14381. return path.length > 1;
  14382. }
  14383. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  14384. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  14385. }
  14386. return true;
  14387. }
  14388. render(code, options) {
  14389. code.indentExclusionRanges.push([this.start, this.end]);
  14390. super.render(code, options);
  14391. }
  14392. }
  14393. class ModuleScope extends ChildScope {
  14394. constructor(parent, context) {
  14395. super(parent, context);
  14396. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context, 'other'));
  14397. }
  14398. addDeclaration(identifier, context, init, kind) {
  14399. if (this.context.module.importDescriptions.has(identifier.name)) {
  14400. context.error(parseAst_js.logRedeclarationError(identifier.name), identifier.start);
  14401. }
  14402. return super.addDeclaration(identifier, context, init, kind);
  14403. }
  14404. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  14405. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  14406. this.variables.set('default', variable);
  14407. return variable;
  14408. }
  14409. addNamespaceMemberAccess() { }
  14410. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  14411. // all module level variables are already deconflicted when deconflicting the chunk
  14412. for (const scope of this.children)
  14413. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14414. }
  14415. findLexicalBoundary() {
  14416. return this;
  14417. }
  14418. findVariable(name) {
  14419. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  14420. if (knownVariable) {
  14421. return knownVariable;
  14422. }
  14423. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  14424. if (variable instanceof GlobalVariable) {
  14425. this.accessedOutsideVariables.set(name, variable);
  14426. }
  14427. return variable;
  14428. }
  14429. }
  14430. class ThisExpression extends NodeBase {
  14431. bind() {
  14432. this.variable = this.scope.findVariable('this');
  14433. }
  14434. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14435. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14436. }
  14437. deoptimizePath(path) {
  14438. this.variable.deoptimizePath(path);
  14439. }
  14440. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14441. if (path.length === 0) {
  14442. return interaction.type !== INTERACTION_ACCESSED;
  14443. }
  14444. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  14445. }
  14446. include() {
  14447. if (!this.included) {
  14448. this.included = true;
  14449. this.scope.context.includeVariableInModule(this.variable);
  14450. }
  14451. }
  14452. initialise() {
  14453. super.initialise();
  14454. this.alias =
  14455. this.scope.findLexicalBoundary() instanceof ModuleScope
  14456. ? this.scope.context.moduleContext
  14457. : null;
  14458. if (this.alias === 'undefined') {
  14459. this.scope.context.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logThisIsUndefined(), this.start);
  14460. }
  14461. }
  14462. render(code) {
  14463. if (this.alias !== null) {
  14464. code.overwrite(this.start, this.end, this.alias, {
  14465. contentOnly: false,
  14466. storeName: true
  14467. });
  14468. }
  14469. }
  14470. }
  14471. class ThrowStatement extends NodeBase {
  14472. hasEffects() {
  14473. return true;
  14474. }
  14475. include(context, includeChildrenRecursively) {
  14476. this.included = true;
  14477. this.argument.include(context, includeChildrenRecursively);
  14478. context.brokenFlow = true;
  14479. }
  14480. render(code, options) {
  14481. this.argument.render(code, options, { preventASI: true });
  14482. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  14483. code.prependLeft(this.start + 5, ' ');
  14484. }
  14485. }
  14486. }
  14487. class TryStatement extends NodeBase {
  14488. constructor() {
  14489. super(...arguments);
  14490. this.directlyIncluded = false;
  14491. this.includedLabelsAfterBlock = null;
  14492. }
  14493. hasEffects(context) {
  14494. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  14495. ? this.block.body.length > 0
  14496. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  14497. }
  14498. include(context, includeChildrenRecursively) {
  14499. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  14500. const { brokenFlow, includedLabels } = context;
  14501. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  14502. this.included = true;
  14503. this.directlyIncluded = true;
  14504. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  14505. if (includedLabels.size > 0) {
  14506. this.includedLabelsAfterBlock = [...includedLabels];
  14507. }
  14508. context.brokenFlow = brokenFlow;
  14509. }
  14510. else if (this.includedLabelsAfterBlock) {
  14511. for (const label of this.includedLabelsAfterBlock) {
  14512. includedLabels.add(label);
  14513. }
  14514. }
  14515. if (this.handler !== null) {
  14516. this.handler.include(context, includeChildrenRecursively);
  14517. context.brokenFlow = brokenFlow;
  14518. }
  14519. this.finalizer?.include(context, includeChildrenRecursively);
  14520. }
  14521. }
  14522. const unaryOperators = {
  14523. '!': value => !value,
  14524. '+': value => +value,
  14525. '-': value => -value,
  14526. delete: () => UnknownValue,
  14527. typeof: value => typeof value,
  14528. void: () => undefined,
  14529. '~': value => ~value
  14530. };
  14531. class UnaryExpression extends NodeBase {
  14532. get prefix() {
  14533. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  14534. }
  14535. set prefix(value) {
  14536. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  14537. }
  14538. getLiteralValueAtPath(path, recursionTracker, origin) {
  14539. if (path.length > 0)
  14540. return UnknownValue;
  14541. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  14542. if (typeof argumentValue === 'symbol')
  14543. return UnknownValue;
  14544. return unaryOperators[this.operator](argumentValue);
  14545. }
  14546. hasEffects(context) {
  14547. if (!this.deoptimized)
  14548. this.applyDeoptimizations();
  14549. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  14550. return false;
  14551. return (this.argument.hasEffects(context) ||
  14552. (this.operator === 'delete' &&
  14553. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  14554. }
  14555. hasEffectsOnInteractionAtPath(path, { type }) {
  14556. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  14557. }
  14558. applyDeoptimizations() {
  14559. this.deoptimized = true;
  14560. if (this.operator === 'delete') {
  14561. this.argument.deoptimizePath(EMPTY_PATH);
  14562. this.scope.context.requestTreeshakingPass();
  14563. }
  14564. }
  14565. }
  14566. class UpdateExpression extends NodeBase {
  14567. hasEffects(context) {
  14568. if (!this.deoptimized)
  14569. this.applyDeoptimizations();
  14570. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  14571. }
  14572. hasEffectsOnInteractionAtPath(path, { type }) {
  14573. return path.length > 1 || type !== INTERACTION_ACCESSED;
  14574. }
  14575. include(context, includeChildrenRecursively) {
  14576. if (!this.deoptimized)
  14577. this.applyDeoptimizations();
  14578. this.included = true;
  14579. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  14580. }
  14581. initialise() {
  14582. super.initialise();
  14583. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  14584. }
  14585. render(code, options) {
  14586. const { exportNamesByVariable, format, snippets: { _ } } = options;
  14587. this.argument.render(code, options);
  14588. if (format === 'system') {
  14589. const variable = this.argument.variable;
  14590. const exportNames = exportNamesByVariable.get(variable);
  14591. if (exportNames) {
  14592. if (this.prefix) {
  14593. if (exportNames.length === 1) {
  14594. renderSystemExportExpression(variable, this.start, this.end, code, options);
  14595. }
  14596. else {
  14597. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options);
  14598. }
  14599. }
  14600. else {
  14601. const operator = this.operator[0];
  14602. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== parseAst_js.ExpressionStatement, code, options, `${_}${operator}${_}1`);
  14603. }
  14604. }
  14605. }
  14606. }
  14607. applyDeoptimizations() {
  14608. this.deoptimized = true;
  14609. this.argument.deoptimizePath(EMPTY_PATH);
  14610. if (this.argument instanceof Identifier) {
  14611. const variable = this.scope.findVariable(this.argument.name);
  14612. variable.markReassigned();
  14613. }
  14614. this.scope.context.requestTreeshakingPass();
  14615. }
  14616. }
  14617. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  14618. for (const declarator of declarations) {
  14619. if (!declarator.id.included)
  14620. return false;
  14621. if (declarator.id.type === parseAst_js.Identifier) {
  14622. if (exportNamesByVariable.has(declarator.id.variable))
  14623. return false;
  14624. }
  14625. else {
  14626. const exportedVariables = [];
  14627. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  14628. if (exportedVariables.length > 0)
  14629. return false;
  14630. }
  14631. }
  14632. return true;
  14633. }
  14634. class VariableDeclaration extends NodeBase {
  14635. deoptimizePath() {
  14636. for (const declarator of this.declarations) {
  14637. declarator.deoptimizePath(EMPTY_PATH);
  14638. }
  14639. }
  14640. hasEffectsOnInteractionAtPath() {
  14641. return false;
  14642. }
  14643. include(context, includeChildrenRecursively, { asSingleStatement } = parseAst_js.BLANK) {
  14644. this.included = true;
  14645. for (const declarator of this.declarations) {
  14646. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  14647. declarator.include(context, includeChildrenRecursively);
  14648. const { id, init } = declarator;
  14649. if (asSingleStatement) {
  14650. id.include(context, includeChildrenRecursively);
  14651. }
  14652. if (init &&
  14653. id.included &&
  14654. !init.included &&
  14655. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  14656. init.include(context, includeChildrenRecursively);
  14657. }
  14658. }
  14659. }
  14660. initialise() {
  14661. super.initialise();
  14662. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  14663. for (const declarator of this.declarations) {
  14664. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  14665. }
  14666. }
  14667. removeAnnotations(code) {
  14668. this.declarations[0].removeAnnotations(code);
  14669. }
  14670. render(code, options, nodeRenderOptions = parseAst_js.BLANK) {
  14671. if (this.isUsingDeclaration ||
  14672. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  14673. for (const declarator of this.declarations) {
  14674. declarator.render(code, options);
  14675. }
  14676. if (!nodeRenderOptions.isNoStatement &&
  14677. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  14678. code.appendLeft(this.end, ';');
  14679. }
  14680. }
  14681. else {
  14682. this.renderReplacedDeclarations(code, options);
  14683. }
  14684. }
  14685. applyDeoptimizations() { }
  14686. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  14687. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  14688. code.remove(this.end - 1, this.end);
  14689. }
  14690. separatorString += ';';
  14691. if (lastSeparatorPos === null) {
  14692. code.appendLeft(renderedContentEnd, separatorString);
  14693. }
  14694. else {
  14695. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  14696. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  14697. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  14698. actualContentEnd--;
  14699. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  14700. actualContentEnd--;
  14701. }
  14702. }
  14703. if (actualContentEnd === lastSeparatorPos + 1) {
  14704. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  14705. }
  14706. else {
  14707. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14708. code.remove(actualContentEnd, renderedContentEnd);
  14709. }
  14710. }
  14711. if (systemPatternExports.length > 0) {
  14712. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  14713. }
  14714. }
  14715. renderReplacedDeclarations(code, options) {
  14716. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  14717. let actualContentEnd, renderedContentEnd;
  14718. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  14719. let lastSeparatorPos = renderedContentEnd - 1;
  14720. code.remove(this.start, lastSeparatorPos);
  14721. let isInDeclaration = false;
  14722. let hasRenderedContent = false;
  14723. let separatorString = '', leadingString, nextSeparatorString;
  14724. const aggregatedSystemExports = [];
  14725. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  14726. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  14727. if (!node.included) {
  14728. code.remove(start, end);
  14729. node.removeAnnotations(code);
  14730. continue;
  14731. }
  14732. node.render(code, options);
  14733. leadingString = '';
  14734. nextSeparatorString = '';
  14735. if (!node.id.included ||
  14736. (node.id instanceof Identifier &&
  14737. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  14738. if (hasRenderedContent) {
  14739. separatorString += ';';
  14740. }
  14741. isInDeclaration = false;
  14742. }
  14743. else {
  14744. if (singleSystemExport && singleSystemExport === node.id.variable) {
  14745. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  14746. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  14747. }
  14748. if (isInDeclaration) {
  14749. separatorString += ',';
  14750. }
  14751. else {
  14752. if (hasRenderedContent) {
  14753. separatorString += ';';
  14754. }
  14755. leadingString += `${this.kind} `;
  14756. isInDeclaration = true;
  14757. }
  14758. }
  14759. if (renderedContentEnd === lastSeparatorPos + 1) {
  14760. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  14761. }
  14762. else {
  14763. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14764. code.appendLeft(renderedContentEnd, leadingString);
  14765. }
  14766. actualContentEnd = contentEnd;
  14767. renderedContentEnd = end;
  14768. hasRenderedContent = true;
  14769. lastSeparatorPos = separator;
  14770. separatorString = nextSeparatorString;
  14771. }
  14772. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  14773. }
  14774. }
  14775. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  14776. let singleSystemExport = null;
  14777. if (options.format === 'system') {
  14778. for (const { node } of separatedNodes) {
  14779. if (node.id instanceof Identifier &&
  14780. node.init &&
  14781. aggregatedSystemExports.length === 0 &&
  14782. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  14783. singleSystemExport = node.id.variable;
  14784. aggregatedSystemExports.push(singleSystemExport);
  14785. }
  14786. else {
  14787. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  14788. }
  14789. }
  14790. if (aggregatedSystemExports.length > 1) {
  14791. singleSystemExport = null;
  14792. }
  14793. else if (singleSystemExport) {
  14794. aggregatedSystemExports.length = 0;
  14795. }
  14796. }
  14797. return singleSystemExport;
  14798. }
  14799. class WhileStatement extends NodeBase {
  14800. hasEffects(context) {
  14801. if (this.test.hasEffects(context))
  14802. return true;
  14803. return hasLoopBodyEffects(context, this.body);
  14804. }
  14805. include(context, includeChildrenRecursively) {
  14806. this.included = true;
  14807. this.test.include(context, includeChildrenRecursively);
  14808. includeLoopBody(context, this.body, includeChildrenRecursively);
  14809. }
  14810. }
  14811. class YieldExpression extends NodeBase {
  14812. hasEffects(context) {
  14813. if (!this.deoptimized)
  14814. this.applyDeoptimizations();
  14815. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  14816. }
  14817. render(code, options) {
  14818. if (this.argument) {
  14819. this.argument.render(code, options, { preventASI: true });
  14820. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  14821. code.prependLeft(this.start + 5, ' ');
  14822. }
  14823. }
  14824. }
  14825. }
  14826. // This file is generated by scripts/generate-buffer-parsers.js.
  14827. // Do not edit this file directly.
  14828. function convertProgram(buffer, parent, parentScope) {
  14829. return convertNode(parent, parentScope, 0, parseAst_js.getAstBuffer(buffer));
  14830. }
  14831. const nodeTypeStrings = [
  14832. 'PanicError',
  14833. 'ParseError',
  14834. 'ArrayExpression',
  14835. 'ArrayPattern',
  14836. 'ArrowFunctionExpression',
  14837. 'AssignmentExpression',
  14838. 'AssignmentPattern',
  14839. 'AwaitExpression',
  14840. 'BinaryExpression',
  14841. 'BlockStatement',
  14842. 'BreakStatement',
  14843. 'CallExpression',
  14844. 'CatchClause',
  14845. 'ChainExpression',
  14846. 'ClassBody',
  14847. 'ClassDeclaration',
  14848. 'ClassExpression',
  14849. 'ConditionalExpression',
  14850. 'ContinueStatement',
  14851. 'DebuggerStatement',
  14852. 'Decorator',
  14853. 'ExpressionStatement',
  14854. 'DoWhileStatement',
  14855. 'EmptyStatement',
  14856. 'ExportAllDeclaration',
  14857. 'ExportDefaultDeclaration',
  14858. 'ExportNamedDeclaration',
  14859. 'ExportSpecifier',
  14860. 'ExpressionStatement',
  14861. 'ForInStatement',
  14862. 'ForOfStatement',
  14863. 'ForStatement',
  14864. 'FunctionDeclaration',
  14865. 'FunctionExpression',
  14866. 'Identifier',
  14867. 'IfStatement',
  14868. 'ImportAttribute',
  14869. 'ImportDeclaration',
  14870. 'ImportDefaultSpecifier',
  14871. 'ImportExpression',
  14872. 'ImportNamespaceSpecifier',
  14873. 'ImportSpecifier',
  14874. 'JSXAttribute',
  14875. 'JSXClosingElement',
  14876. 'JSXClosingFragment',
  14877. 'JSXElement',
  14878. 'JSXEmptyExpression',
  14879. 'JSXExpressionContainer',
  14880. 'JSXFragment',
  14881. 'JSXIdentifier',
  14882. 'JSXMemberExpression',
  14883. 'JSXNamespacedName',
  14884. 'JSXOpeningElement',
  14885. 'JSXOpeningFragment',
  14886. 'JSXSpreadAttribute',
  14887. 'JSXSpreadChild',
  14888. 'JSXText',
  14889. 'LabeledStatement',
  14890. 'Literal',
  14891. 'Literal',
  14892. 'Literal',
  14893. 'Literal',
  14894. 'Literal',
  14895. 'Literal',
  14896. 'LogicalExpression',
  14897. 'MemberExpression',
  14898. 'MetaProperty',
  14899. 'MethodDefinition',
  14900. 'NewExpression',
  14901. 'ObjectExpression',
  14902. 'ObjectPattern',
  14903. 'PrivateIdentifier',
  14904. 'Program',
  14905. 'Property',
  14906. 'PropertyDefinition',
  14907. 'RestElement',
  14908. 'ReturnStatement',
  14909. 'SequenceExpression',
  14910. 'SpreadElement',
  14911. 'StaticBlock',
  14912. 'Super',
  14913. 'SwitchCase',
  14914. 'SwitchStatement',
  14915. 'TaggedTemplateExpression',
  14916. 'TemplateElement',
  14917. 'TemplateLiteral',
  14918. 'ThisExpression',
  14919. 'ThrowStatement',
  14920. 'TryStatement',
  14921. 'UnaryExpression',
  14922. 'UpdateExpression',
  14923. 'VariableDeclaration',
  14924. 'VariableDeclarator',
  14925. 'WhileStatement',
  14926. 'YieldExpression'
  14927. ];
  14928. const nodeConstructors$1 = [
  14929. PanicError,
  14930. ParseError,
  14931. ArrayExpression,
  14932. ArrayPattern,
  14933. ArrowFunctionExpression,
  14934. AssignmentExpression,
  14935. AssignmentPattern,
  14936. AwaitExpression,
  14937. BinaryExpression,
  14938. BlockStatement,
  14939. BreakStatement,
  14940. CallExpression,
  14941. CatchClause,
  14942. ChainExpression,
  14943. ClassBody,
  14944. ClassDeclaration,
  14945. ClassExpression,
  14946. ConditionalExpression,
  14947. ContinueStatement,
  14948. DebuggerStatement,
  14949. Decorator,
  14950. ExpressionStatement,
  14951. DoWhileStatement,
  14952. EmptyStatement,
  14953. ExportAllDeclaration,
  14954. ExportDefaultDeclaration,
  14955. ExportNamedDeclaration,
  14956. ExportSpecifier,
  14957. ExpressionStatement,
  14958. ForInStatement,
  14959. ForOfStatement,
  14960. ForStatement,
  14961. FunctionDeclaration,
  14962. FunctionExpression,
  14963. Identifier,
  14964. IfStatement,
  14965. ImportAttribute,
  14966. ImportDeclaration,
  14967. ImportDefaultSpecifier,
  14968. ImportExpression,
  14969. ImportNamespaceSpecifier,
  14970. ImportSpecifier,
  14971. JSXAttribute,
  14972. JSXClosingElement,
  14973. JSXClosingFragment,
  14974. JSXElement,
  14975. JSXEmptyExpression,
  14976. JSXExpressionContainer,
  14977. JSXFragment,
  14978. JSXIdentifier,
  14979. JSXMemberExpression,
  14980. JSXNamespacedName,
  14981. JSXOpeningElement,
  14982. JSXOpeningFragment,
  14983. JSXSpreadAttribute,
  14984. JSXSpreadChild,
  14985. JSXText,
  14986. LabeledStatement,
  14987. Literal,
  14988. Literal,
  14989. Literal,
  14990. Literal,
  14991. Literal,
  14992. Literal,
  14993. LogicalExpression,
  14994. MemberExpression,
  14995. MetaProperty,
  14996. MethodDefinition,
  14997. NewExpression,
  14998. ObjectExpression,
  14999. ObjectPattern,
  15000. PrivateIdentifier,
  15001. Program,
  15002. Property,
  15003. PropertyDefinition,
  15004. RestElement,
  15005. ReturnStatement,
  15006. SequenceExpression,
  15007. SpreadElement,
  15008. StaticBlock,
  15009. Super,
  15010. SwitchCase,
  15011. SwitchStatement,
  15012. TaggedTemplateExpression,
  15013. TemplateElement,
  15014. TemplateLiteral,
  15015. ThisExpression,
  15016. ThrowStatement,
  15017. TryStatement,
  15018. UnaryExpression,
  15019. UpdateExpression,
  15020. VariableDeclaration,
  15021. VariableDeclarator,
  15022. WhileStatement,
  15023. YieldExpression
  15024. ];
  15025. const bufferParsers = [
  15026. function panicError(node, position, buffer) {
  15027. node.message = buffer.convertString(buffer[position]);
  15028. },
  15029. function parseError(node, position, buffer) {
  15030. node.message = buffer.convertString(buffer[position]);
  15031. },
  15032. function arrayExpression(node, position, buffer) {
  15033. const { scope } = node;
  15034. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  15035. },
  15036. function arrayPattern(node, position, buffer) {
  15037. const { scope } = node;
  15038. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  15039. },
  15040. function arrowFunctionExpression(node, position, buffer) {
  15041. const { scope } = node;
  15042. const flags = buffer[position];
  15043. node.async = (flags & 1) === 1;
  15044. node.expression = (flags & 2) === 2;
  15045. node.generator = (flags & 4) === 4;
  15046. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  15047. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15048. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  15049. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15050. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  15051. },
  15052. function assignmentExpression(node, position, buffer) {
  15053. const { scope } = node;
  15054. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  15055. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15056. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15057. },
  15058. function assignmentPattern(node, position, buffer) {
  15059. const { scope } = node;
  15060. node.left = convertNode(node, scope, buffer[position], buffer);
  15061. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  15062. },
  15063. function awaitExpression(node, position, buffer) {
  15064. const { scope } = node;
  15065. node.argument = convertNode(node, scope, buffer[position], buffer);
  15066. },
  15067. function binaryExpression(node, position, buffer) {
  15068. const { scope } = node;
  15069. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  15070. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15071. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15072. },
  15073. function blockStatement(node, position, buffer) {
  15074. const { scope } = node;
  15075. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15076. },
  15077. function breakStatement(node, position, buffer) {
  15078. const { scope } = node;
  15079. const labelPosition = buffer[position];
  15080. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  15081. },
  15082. function callExpression(node, position, buffer) {
  15083. const { scope } = node;
  15084. const flags = buffer[position];
  15085. node.optional = (flags & 1) === 1;
  15086. node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  15087. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  15088. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  15089. },
  15090. function catchClause(node, position, buffer) {
  15091. const { scope } = node;
  15092. const parameterPosition = buffer[position];
  15093. const parameter = (node.param =
  15094. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  15095. parameter?.declare('parameter', UNKNOWN_EXPRESSION);
  15096. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  15097. },
  15098. function chainExpression(node, position, buffer) {
  15099. const { scope } = node;
  15100. node.expression = convertNode(node, scope, buffer[position], buffer);
  15101. },
  15102. function classBody(node, position, buffer) {
  15103. const { scope } = node;
  15104. const bodyPosition = buffer[position];
  15105. const body = (node.body = []);
  15106. if (bodyPosition) {
  15107. const length = buffer[bodyPosition];
  15108. for (let index = 0; index < length; index++) {
  15109. const nodePosition = buffer[bodyPosition + 1 + index];
  15110. body.push(convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer));
  15111. }
  15112. }
  15113. },
  15114. function classDeclaration(node, position, buffer) {
  15115. const { scope } = node;
  15116. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  15117. const idPosition = buffer[position + 1];
  15118. node.id =
  15119. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  15120. const superClassPosition = buffer[position + 2];
  15121. node.superClass =
  15122. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  15123. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15124. },
  15125. function classExpression(node, position, buffer) {
  15126. const { scope } = node;
  15127. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  15128. const idPosition = buffer[position + 1];
  15129. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  15130. const superClassPosition = buffer[position + 2];
  15131. node.superClass =
  15132. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  15133. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15134. },
  15135. function conditionalExpression(node, position, buffer) {
  15136. const { scope } = node;
  15137. node.test = convertNode(node, scope, buffer[position], buffer);
  15138. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  15139. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  15140. },
  15141. function continueStatement(node, position, buffer) {
  15142. const { scope } = node;
  15143. const labelPosition = buffer[position];
  15144. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  15145. },
  15146. function debuggerStatement() { },
  15147. function decorator(node, position, buffer) {
  15148. const { scope } = node;
  15149. node.expression = convertNode(node, scope, buffer[position], buffer);
  15150. },
  15151. function directive(node, position, buffer) {
  15152. const { scope } = node;
  15153. node.directive = buffer.convertString(buffer[position]);
  15154. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  15155. },
  15156. function doWhileStatement(node, position, buffer) {
  15157. const { scope } = node;
  15158. node.body = convertNode(node, scope, buffer[position], buffer);
  15159. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  15160. },
  15161. function emptyStatement() { },
  15162. function exportAllDeclaration(node, position, buffer) {
  15163. const { scope } = node;
  15164. const exportedPosition = buffer[position];
  15165. node.exported =
  15166. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  15167. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15168. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15169. },
  15170. function exportDefaultDeclaration(node, position, buffer) {
  15171. const { scope } = node;
  15172. node.declaration = convertNode(node, scope, buffer[position], buffer);
  15173. },
  15174. function exportNamedDeclaration(node, position, buffer) {
  15175. const { scope } = node;
  15176. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15177. const sourcePosition = buffer[position + 1];
  15178. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  15179. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15180. const declarationPosition = buffer[position + 3];
  15181. node.declaration =
  15182. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  15183. },
  15184. function exportSpecifier(node, position, buffer) {
  15185. const { scope } = node;
  15186. node.local = convertNode(node, scope, buffer[position], buffer);
  15187. const exportedPosition = buffer[position + 1];
  15188. node.exported =
  15189. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  15190. },
  15191. function expressionStatement(node, position, buffer) {
  15192. const { scope } = node;
  15193. node.expression = convertNode(node, scope, buffer[position], buffer);
  15194. },
  15195. function forInStatement(node, position, buffer) {
  15196. const { scope } = node;
  15197. node.left = convertNode(node, scope, buffer[position], buffer);
  15198. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  15199. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  15200. },
  15201. function forOfStatement(node, position, buffer) {
  15202. const { scope } = node;
  15203. const flags = buffer[position];
  15204. node.await = (flags & 1) === 1;
  15205. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15206. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15207. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15208. },
  15209. function forStatement(node, position, buffer) {
  15210. const { scope } = node;
  15211. const initPosition = buffer[position];
  15212. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15213. const testPosition = buffer[position + 1];
  15214. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15215. const updatePosition = buffer[position + 2];
  15216. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  15217. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15218. },
  15219. function functionDeclaration(node, position, buffer) {
  15220. const { scope } = node;
  15221. const flags = buffer[position];
  15222. node.async = (flags & 1) === 1;
  15223. node.generator = (flags & 2) === 2;
  15224. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  15225. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15226. const idPosition = buffer[position + 2];
  15227. node.id =
  15228. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  15229. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15230. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15231. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15232. },
  15233. function functionExpression(node, position, buffer) {
  15234. const { scope } = node;
  15235. const flags = buffer[position];
  15236. node.async = (flags & 1) === 1;
  15237. node.generator = (flags & 2) === 2;
  15238. const annotations = (node.annotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer));
  15239. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15240. const idPosition = buffer[position + 2];
  15241. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  15242. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15243. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15244. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15245. },
  15246. function identifier(node, position, buffer) {
  15247. node.name = buffer.convertString(buffer[position]);
  15248. },
  15249. function ifStatement(node, position, buffer) {
  15250. const { scope } = node;
  15251. node.test = convertNode(node, scope, buffer[position], buffer);
  15252. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  15253. const alternatePosition = buffer[position + 2];
  15254. node.alternate =
  15255. alternatePosition === 0
  15256. ? null
  15257. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  15258. },
  15259. function importAttribute(node, position, buffer) {
  15260. const { scope } = node;
  15261. node.key = convertNode(node, scope, buffer[position], buffer);
  15262. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  15263. },
  15264. function importDeclaration(node, position, buffer) {
  15265. const { scope } = node;
  15266. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15267. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15268. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15269. },
  15270. function importDefaultSpecifier(node, position, buffer) {
  15271. const { scope } = node;
  15272. node.local = convertNode(node, scope, buffer[position], buffer);
  15273. },
  15274. function importExpression(node, position, buffer) {
  15275. const { scope } = node;
  15276. node.source = convertNode(node, scope, buffer[position], buffer);
  15277. node.sourceAstNode = parseAst_js.convertNode(buffer[position], buffer);
  15278. const optionsPosition = buffer[position + 1];
  15279. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  15280. },
  15281. function importNamespaceSpecifier(node, position, buffer) {
  15282. const { scope } = node;
  15283. node.local = convertNode(node, scope, buffer[position], buffer);
  15284. },
  15285. function importSpecifier(node, position, buffer) {
  15286. const { scope } = node;
  15287. const importedPosition = buffer[position];
  15288. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  15289. node.imported =
  15290. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  15291. },
  15292. function jsxAttribute(node, position, buffer) {
  15293. const { scope } = node;
  15294. node.name = convertNode(node, scope, buffer[position], buffer);
  15295. const valuePosition = buffer[position + 1];
  15296. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15297. },
  15298. function jsxClosingElement(node, position, buffer) {
  15299. const { scope } = node;
  15300. node.name = convertNode(node, scope, buffer[position], buffer);
  15301. },
  15302. function jsxClosingFragment() { },
  15303. function jsxElement(node, position, buffer) {
  15304. const { scope } = node;
  15305. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  15306. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15307. const closingElementPosition = buffer[position + 2];
  15308. node.closingElement =
  15309. closingElementPosition === 0
  15310. ? null
  15311. : convertNode(node, scope, closingElementPosition, buffer);
  15312. },
  15313. function jsxEmptyExpression() { },
  15314. function jsxExpressionContainer(node, position, buffer) {
  15315. const { scope } = node;
  15316. node.expression = convertNode(node, scope, buffer[position], buffer);
  15317. },
  15318. function jsxFragment(node, position, buffer) {
  15319. const { scope } = node;
  15320. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  15321. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15322. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  15323. },
  15324. function jsxIdentifier(node, position, buffer) {
  15325. node.name = buffer.convertString(buffer[position]);
  15326. },
  15327. function jsxMemberExpression(node, position, buffer) {
  15328. const { scope } = node;
  15329. node.object = convertNode(node, scope, buffer[position], buffer);
  15330. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15331. },
  15332. function jsxNamespacedName(node, position, buffer) {
  15333. const { scope } = node;
  15334. node.namespace = convertNode(node, scope, buffer[position], buffer);
  15335. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15336. },
  15337. function jsxOpeningElement(node, position, buffer) {
  15338. const { scope } = node;
  15339. const flags = buffer[position];
  15340. node.selfClosing = (flags & 1) === 1;
  15341. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15342. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15343. },
  15344. function jsxOpeningFragment(node) {
  15345. node.attributes = [];
  15346. node.selfClosing = false;
  15347. },
  15348. function jsxSpreadAttribute(node, position, buffer) {
  15349. const { scope } = node;
  15350. node.argument = convertNode(node, scope, buffer[position], buffer);
  15351. },
  15352. function jsxSpreadChild(node, position, buffer) {
  15353. const { scope } = node;
  15354. node.expression = convertNode(node, scope, buffer[position], buffer);
  15355. },
  15356. function jsxText(node, position, buffer) {
  15357. node.value = buffer.convertString(buffer[position]);
  15358. node.raw = buffer.convertString(buffer[position + 1]);
  15359. },
  15360. function labeledStatement(node, position, buffer) {
  15361. const { scope } = node;
  15362. node.label = convertNode(node, scope, buffer[position], buffer);
  15363. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15364. },
  15365. function literalBigInt(node, position, buffer) {
  15366. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  15367. node.raw = buffer.convertString(buffer[position + 1]);
  15368. node.value = BigInt(bigint);
  15369. },
  15370. function literalBoolean(node, position, buffer) {
  15371. const flags = buffer[position];
  15372. const value = (node.value = (flags & 1) === 1);
  15373. node.raw = value ? 'true' : 'false';
  15374. },
  15375. function literalNull(node) {
  15376. node.value = null;
  15377. },
  15378. function literalNumber(node, position, buffer) {
  15379. const rawPosition = buffer[position];
  15380. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15381. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  15382. },
  15383. function literalRegExp(node, position, buffer) {
  15384. const flags = buffer.convertString(buffer[position]);
  15385. const pattern = buffer.convertString(buffer[position + 1]);
  15386. node.raw = `/${pattern}/${flags}`;
  15387. node.regex = { flags, pattern };
  15388. node.value = new RegExp(pattern, flags);
  15389. },
  15390. function literalString(node, position, buffer) {
  15391. node.value = buffer.convertString(buffer[position]);
  15392. const rawPosition = buffer[position + 1];
  15393. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15394. },
  15395. function logicalExpression(node, position, buffer) {
  15396. const { scope } = node;
  15397. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  15398. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15399. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15400. },
  15401. function memberExpression(node, position, buffer) {
  15402. const { scope } = node;
  15403. const flags = buffer[position];
  15404. node.computed = (flags & 1) === 1;
  15405. node.optional = (flags & 2) === 2;
  15406. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  15407. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  15408. },
  15409. function metaProperty(node, position, buffer) {
  15410. const { scope } = node;
  15411. node.meta = convertNode(node, scope, buffer[position], buffer);
  15412. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15413. },
  15414. function methodDefinition(node, position, buffer) {
  15415. const { scope } = node;
  15416. const flags = buffer[position];
  15417. node.static = (flags & 1) === 1;
  15418. node.computed = (flags & 2) === 2;
  15419. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15420. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15421. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  15422. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 4]];
  15423. },
  15424. function newExpression(node, position, buffer) {
  15425. const { scope } = node;
  15426. node.annotations = parseAst_js.convertAnnotations(buffer[position], buffer);
  15427. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  15428. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  15429. },
  15430. function objectExpression(node, position, buffer) {
  15431. const { scope } = node;
  15432. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15433. },
  15434. function objectPattern(node, position, buffer) {
  15435. const { scope } = node;
  15436. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15437. },
  15438. function privateIdentifier(node, position, buffer) {
  15439. node.name = buffer.convertString(buffer[position]);
  15440. },
  15441. function program(node, position, buffer) {
  15442. const { scope } = node;
  15443. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15444. node.invalidAnnotations = parseAst_js.convertAnnotations(buffer[position + 1], buffer);
  15445. },
  15446. function property(node, position, buffer) {
  15447. const { scope } = node;
  15448. const flags = buffer[position];
  15449. node.method = (flags & 1) === 1;
  15450. node.shorthand = (flags & 2) === 2;
  15451. node.computed = (flags & 4) === 4;
  15452. const keyPosition = buffer[position + 1];
  15453. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  15454. node.kind = parseAst_js.FIXED_STRINGS[buffer[position + 3]];
  15455. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  15456. },
  15457. function propertyDefinition(node, position, buffer) {
  15458. const { scope } = node;
  15459. const flags = buffer[position];
  15460. node.static = (flags & 1) === 1;
  15461. node.computed = (flags & 2) === 2;
  15462. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15463. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15464. const valuePosition = buffer[position + 3];
  15465. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15466. },
  15467. function restElement(node, position, buffer) {
  15468. const { scope } = node;
  15469. node.argument = convertNode(node, scope, buffer[position], buffer);
  15470. },
  15471. function returnStatement(node, position, buffer) {
  15472. const { scope } = node;
  15473. const argumentPosition = buffer[position];
  15474. node.argument =
  15475. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15476. },
  15477. function sequenceExpression(node, position, buffer) {
  15478. const { scope } = node;
  15479. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  15480. },
  15481. function spreadElement(node, position, buffer) {
  15482. const { scope } = node;
  15483. node.argument = convertNode(node, scope, buffer[position], buffer);
  15484. },
  15485. function staticBlock(node, position, buffer) {
  15486. const { scope } = node;
  15487. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15488. },
  15489. function superElement() { },
  15490. function switchCase(node, position, buffer) {
  15491. const { scope } = node;
  15492. const testPosition = buffer[position];
  15493. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15494. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  15495. },
  15496. function switchStatement(node, position, buffer) {
  15497. const { scope } = node;
  15498. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  15499. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  15500. },
  15501. function taggedTemplateExpression(node, position, buffer) {
  15502. const { scope } = node;
  15503. node.tag = convertNode(node, scope, buffer[position], buffer);
  15504. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  15505. },
  15506. function templateElement(node, position, buffer) {
  15507. const flags = buffer[position];
  15508. node.tail = (flags & 1) === 1;
  15509. const cookedPosition = buffer[position + 1];
  15510. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  15511. const raw = buffer.convertString(buffer[position + 2]);
  15512. node.value = { cooked, raw };
  15513. },
  15514. function templateLiteral(node, position, buffer) {
  15515. const { scope } = node;
  15516. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  15517. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  15518. },
  15519. function thisExpression() { },
  15520. function throwStatement(node, position, buffer) {
  15521. const { scope } = node;
  15522. node.argument = convertNode(node, scope, buffer[position], buffer);
  15523. },
  15524. function tryStatement(node, position, buffer) {
  15525. const { scope } = node;
  15526. node.block = convertNode(node, scope, buffer[position], buffer);
  15527. const handlerPosition = buffer[position + 1];
  15528. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  15529. const finalizerPosition = buffer[position + 2];
  15530. node.finalizer =
  15531. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  15532. },
  15533. function unaryExpression(node, position, buffer) {
  15534. const { scope } = node;
  15535. node.operator = parseAst_js.FIXED_STRINGS[buffer[position]];
  15536. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  15537. },
  15538. function updateExpression(node, position, buffer) {
  15539. const { scope } = node;
  15540. const flags = buffer[position];
  15541. node.prefix = (flags & 1) === 1;
  15542. node.operator = parseAst_js.FIXED_STRINGS[buffer[position + 1]];
  15543. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  15544. },
  15545. function variableDeclaration(node, position, buffer) {
  15546. const { scope } = node;
  15547. node.kind = parseAst_js.FIXED_STRINGS[buffer[position]];
  15548. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  15549. },
  15550. function variableDeclarator(node, position, buffer) {
  15551. const { scope } = node;
  15552. node.id = convertNode(node, scope, buffer[position], buffer);
  15553. const initPosition = buffer[position + 1];
  15554. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15555. },
  15556. function whileStatement(node, position, buffer) {
  15557. const { scope } = node;
  15558. node.test = convertNode(node, scope, buffer[position], buffer);
  15559. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15560. },
  15561. function yieldExpression(node, position, buffer) {
  15562. const { scope } = node;
  15563. const flags = buffer[position];
  15564. node.delegate = (flags & 1) === 1;
  15565. const argumentPosition = buffer[position + 1];
  15566. node.argument =
  15567. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15568. }
  15569. ];
  15570. function convertNode(parent, parentScope, position, buffer) {
  15571. const nodeType = buffer[position];
  15572. const NodeConstructor = nodeConstructors$1[nodeType];
  15573. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  15574. if (!NodeConstructor) {
  15575. console.trace();
  15576. throw new Error(`Unknown node type: ${nodeType}`);
  15577. }
  15578. const node = new NodeConstructor(parent, parentScope);
  15579. node.type = nodeTypeStrings[nodeType];
  15580. node.start = buffer[position + 1];
  15581. node.end = buffer[position + 2];
  15582. bufferParsers[nodeType](node, position + 3, buffer);
  15583. node.initialise();
  15584. return node;
  15585. }
  15586. function convertNodeList(parent, parentScope, position, buffer) {
  15587. if (position === 0)
  15588. return parseAst_js.EMPTY_ARRAY;
  15589. const length = buffer[position++];
  15590. const list = [];
  15591. for (let index = 0; index < length; index++) {
  15592. const nodePosition = buffer[position++];
  15593. list.push(nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null);
  15594. }
  15595. return list;
  15596. }
  15597. class UnknownNode extends NodeBase {
  15598. hasEffects() {
  15599. return true;
  15600. }
  15601. include(context) {
  15602. super.include(context, true);
  15603. }
  15604. }
  15605. // This file is generated by scripts/generate-node-index.js.
  15606. // Do not edit this file directly.
  15607. const nodeConstructors = {
  15608. ArrayExpression,
  15609. ArrayPattern,
  15610. ArrowFunctionExpression,
  15611. AssignmentExpression,
  15612. AssignmentPattern,
  15613. AwaitExpression,
  15614. BinaryExpression,
  15615. BlockStatement,
  15616. BreakStatement,
  15617. CallExpression,
  15618. CatchClause,
  15619. ChainExpression,
  15620. ClassBody,
  15621. ClassDeclaration,
  15622. ClassExpression,
  15623. ConditionalExpression,
  15624. ContinueStatement,
  15625. DebuggerStatement,
  15626. Decorator,
  15627. DoWhileStatement,
  15628. EmptyStatement,
  15629. ExportAllDeclaration,
  15630. ExportDefaultDeclaration,
  15631. ExportNamedDeclaration,
  15632. ExportSpecifier,
  15633. ExpressionStatement,
  15634. ForInStatement,
  15635. ForOfStatement,
  15636. ForStatement,
  15637. FunctionDeclaration,
  15638. FunctionExpression,
  15639. Identifier,
  15640. IfStatement,
  15641. ImportAttribute,
  15642. ImportDeclaration,
  15643. ImportDefaultSpecifier,
  15644. ImportExpression,
  15645. ImportNamespaceSpecifier,
  15646. ImportSpecifier,
  15647. JSXAttribute,
  15648. JSXClosingElement,
  15649. JSXClosingFragment,
  15650. JSXElement,
  15651. JSXEmptyExpression,
  15652. JSXExpressionContainer,
  15653. JSXFragment,
  15654. JSXIdentifier,
  15655. JSXMemberExpression,
  15656. JSXNamespacedName,
  15657. JSXOpeningElement,
  15658. JSXOpeningFragment,
  15659. JSXSpreadAttribute,
  15660. JSXSpreadChild,
  15661. JSXText,
  15662. LabeledStatement,
  15663. Literal,
  15664. LogicalExpression,
  15665. MemberExpression,
  15666. MetaProperty,
  15667. MethodDefinition,
  15668. NewExpression,
  15669. ObjectExpression,
  15670. ObjectPattern,
  15671. PanicError,
  15672. ParseError,
  15673. PrivateIdentifier,
  15674. Program,
  15675. Property,
  15676. PropertyDefinition,
  15677. RestElement,
  15678. ReturnStatement,
  15679. SequenceExpression,
  15680. SpreadElement,
  15681. StaticBlock,
  15682. Super,
  15683. SwitchCase,
  15684. SwitchStatement,
  15685. TaggedTemplateExpression,
  15686. TemplateElement,
  15687. TemplateLiteral,
  15688. ThisExpression,
  15689. ThrowStatement,
  15690. TryStatement,
  15691. UnaryExpression,
  15692. UnknownNode,
  15693. UpdateExpression,
  15694. VariableDeclaration,
  15695. VariableDeclarator,
  15696. WhileStatement,
  15697. YieldExpression
  15698. };
  15699. class ExportShimVariable extends Variable {
  15700. constructor(module) {
  15701. super(MISSING_EXPORT_SHIM_VARIABLE);
  15702. this.module = module;
  15703. }
  15704. include() {
  15705. super.include();
  15706. this.module.needsExportShim = true;
  15707. }
  15708. }
  15709. const sourceMapCache = new WeakMap();
  15710. /**
  15711. * This clears the decoded array and falls back to the encoded string form.
  15712. * Sourcemap mappings arrays can be very large and holding on to them for longer
  15713. * than is necessary leads to poor heap utilization.
  15714. */
  15715. function resetCacheToEncoded(cache) {
  15716. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  15717. cache.encodedMappings = encode(cache.decodedMappings);
  15718. }
  15719. cache.decodedMappings = undefined;
  15720. }
  15721. function resetSourcemapCache(map, sourcemapChain) {
  15722. if (map) {
  15723. const cache = sourceMapCache.get(map);
  15724. if (cache) {
  15725. resetCacheToEncoded(cache);
  15726. }
  15727. }
  15728. if (!sourcemapChain) {
  15729. return;
  15730. }
  15731. for (const map of sourcemapChain) {
  15732. if (map.missing)
  15733. continue;
  15734. resetSourcemapCache(map);
  15735. }
  15736. }
  15737. function decodedSourcemap(map) {
  15738. if (!map)
  15739. return null;
  15740. if (typeof map === 'string') {
  15741. map = JSON.parse(map);
  15742. }
  15743. if (!map.mappings) {
  15744. return {
  15745. mappings: [],
  15746. names: [],
  15747. sources: [],
  15748. version: 3
  15749. };
  15750. }
  15751. const originalMappings = map.mappings;
  15752. const isAlreadyDecoded = Array.isArray(originalMappings);
  15753. const cache = {
  15754. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  15755. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  15756. };
  15757. const decodedMap = {
  15758. ...map,
  15759. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  15760. // where the mappings field is never actually accessed. This appears to greatly reduce
  15761. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  15762. get mappings() {
  15763. if (cache.decodedMappings) {
  15764. return cache.decodedMappings;
  15765. }
  15766. // If decodedMappings doesn't exist then encodedMappings should.
  15767. // The only scenario where cache.encodedMappings should be undefined is if the map
  15768. // this was constructed from was already decoded, or if mappings was set to a new
  15769. // decoded string. In either case, this line shouldn't get hit.
  15770. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  15771. cache.encodedMappings = undefined;
  15772. return cache.decodedMappings;
  15773. }
  15774. };
  15775. sourceMapCache.set(decodedMap, cache);
  15776. return decodedMap;
  15777. }
  15778. function getId(m) {
  15779. return m.id;
  15780. }
  15781. function getOriginalLocation(sourcemapChain, location) {
  15782. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  15783. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  15784. const sourcemap = filteredSourcemapChain.pop();
  15785. const line = sourcemap.mappings[location.line - 1];
  15786. if (line) {
  15787. const filteredLine = line.filter((segment) => segment.length > 1);
  15788. const lastSegment = filteredLine[filteredLine.length - 1];
  15789. for (const segment of filteredLine) {
  15790. if (segment[0] >= location.column || segment === lastSegment) {
  15791. location = {
  15792. column: segment[3],
  15793. line: segment[2] + 1
  15794. };
  15795. continue traceSourcemap;
  15796. }
  15797. }
  15798. }
  15799. throw new Error("Can't resolve original location of error.");
  15800. }
  15801. return location;
  15802. }
  15803. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  15804. function getAttributesFromImportExpression(node) {
  15805. const { scope: { context }, options, start } = node;
  15806. if (!(options instanceof ObjectExpression)) {
  15807. if (options) {
  15808. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), start);
  15809. }
  15810. return parseAst_js.EMPTY_OBJECT;
  15811. }
  15812. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  15813. if (!assertProperty) {
  15814. return parseAst_js.EMPTY_OBJECT;
  15815. }
  15816. if (!(assertProperty instanceof ObjectExpression)) {
  15817. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportOptionsAreInvalid(context.module.id), start);
  15818. return parseAst_js.EMPTY_OBJECT;
  15819. }
  15820. const assertFields = assertProperty.properties
  15821. .map(property => {
  15822. const key = getPropertyKey(property);
  15823. if (typeof key === 'string' &&
  15824. typeof property.value.value === 'string') {
  15825. return [key, property.value.value];
  15826. }
  15827. context.module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logImportAttributeIsInvalid(context.module.id), property.start);
  15828. return null;
  15829. })
  15830. .filter((property) => !!property);
  15831. if (assertFields.length > 0) {
  15832. return Object.fromEntries(assertFields);
  15833. }
  15834. return parseAst_js.EMPTY_OBJECT;
  15835. }
  15836. const getPropertyKey = (property) => {
  15837. const key = property.key;
  15838. return (key &&
  15839. !property.computed &&
  15840. (key.name || key.value));
  15841. };
  15842. function getAttributesFromImportExportDeclaration(attributes) {
  15843. return attributes?.length
  15844. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  15845. : parseAst_js.EMPTY_OBJECT;
  15846. }
  15847. function doAttributesDiffer(assertionA, assertionB) {
  15848. const keysA = Object.keys(assertionA);
  15849. return (keysA.length !== Object.keys(assertionB).length ||
  15850. keysA.some(key => assertionA[key] !== assertionB[key]));
  15851. }
  15852. let timers = new Map();
  15853. function getPersistedLabel(label, level) {
  15854. switch (level) {
  15855. case 1: {
  15856. return `# ${label}`;
  15857. }
  15858. case 2: {
  15859. return `## ${label}`;
  15860. }
  15861. case 3: {
  15862. return label;
  15863. }
  15864. default: {
  15865. return `- ${label}`;
  15866. }
  15867. }
  15868. }
  15869. function timeStartImpl(label, level = 3) {
  15870. label = getPersistedLabel(label, level);
  15871. const startMemory = process$1.memoryUsage().heapUsed;
  15872. const startTime = node_perf_hooks.performance.now();
  15873. const timer = timers.get(label);
  15874. if (timer === undefined) {
  15875. timers.set(label, {
  15876. memory: 0,
  15877. startMemory,
  15878. startTime,
  15879. time: 0,
  15880. totalMemory: 0
  15881. });
  15882. }
  15883. else {
  15884. timer.startMemory = startMemory;
  15885. timer.startTime = startTime;
  15886. }
  15887. }
  15888. function timeEndImpl(label, level = 3) {
  15889. label = getPersistedLabel(label, level);
  15890. const timer = timers.get(label);
  15891. if (timer !== undefined) {
  15892. const currentMemory = process$1.memoryUsage().heapUsed;
  15893. timer.memory += currentMemory - timer.startMemory;
  15894. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  15895. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  15896. }
  15897. }
  15898. function getTimings() {
  15899. const newTimings = {};
  15900. for (const [label, { memory, time, totalMemory }] of timers) {
  15901. newTimings[label] = [time, memory, totalMemory];
  15902. }
  15903. return newTimings;
  15904. }
  15905. let timeStart = doNothing;
  15906. let timeEnd = doNothing;
  15907. const TIMED_PLUGIN_HOOKS = [
  15908. 'augmentChunkHash',
  15909. 'buildEnd',
  15910. 'buildStart',
  15911. 'generateBundle',
  15912. 'load',
  15913. 'moduleParsed',
  15914. 'options',
  15915. 'outputOptions',
  15916. 'renderChunk',
  15917. 'renderDynamicImport',
  15918. 'renderStart',
  15919. 'resolveDynamicImport',
  15920. 'resolveFileUrl',
  15921. 'resolveId',
  15922. 'resolveImportMeta',
  15923. 'shouldTransformCachedModule',
  15924. 'transform',
  15925. 'writeBundle'
  15926. ];
  15927. function getPluginWithTimers(plugin, index) {
  15928. if (plugin._hasTimer)
  15929. return plugin;
  15930. plugin._hasTimer = true;
  15931. for (const hook of TIMED_PLUGIN_HOOKS) {
  15932. if (hook in plugin) {
  15933. let timerLabel = `plugin ${index}`;
  15934. if (plugin.name) {
  15935. timerLabel += ` (${plugin.name})`;
  15936. }
  15937. timerLabel += ` - ${hook}`;
  15938. const handler = function (...parameters) {
  15939. timeStart(timerLabel, 4);
  15940. const result = hookFunction.apply(this, parameters);
  15941. timeEnd(timerLabel, 4);
  15942. return result;
  15943. };
  15944. let hookFunction;
  15945. if (typeof plugin[hook].handler === 'function') {
  15946. hookFunction = plugin[hook].handler;
  15947. plugin[hook].handler = handler;
  15948. }
  15949. else {
  15950. hookFunction = plugin[hook];
  15951. plugin[hook] = handler;
  15952. }
  15953. }
  15954. }
  15955. return plugin;
  15956. }
  15957. function initialiseTimers(inputOptions) {
  15958. if (inputOptions.perf) {
  15959. timers = new Map();
  15960. timeStart = timeStartImpl;
  15961. timeEnd = timeEndImpl;
  15962. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  15963. }
  15964. else {
  15965. timeStart = doNothing;
  15966. timeEnd = doNothing;
  15967. }
  15968. }
  15969. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  15970. identifier: null,
  15971. localName: MISSING_EXPORT_SHIM_VARIABLE
  15972. };
  15973. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  15974. const searchedModules = searchedNamesAndModules.get(name);
  15975. if (searchedModules) {
  15976. if (searchedModules.has(target)) {
  15977. return isExportAllSearch ? [null] : parseAst_js.error(parseAst_js.logCircularReexport(name, target.id));
  15978. }
  15979. searchedModules.add(target);
  15980. }
  15981. else {
  15982. searchedNamesAndModules.set(name, new Set([target]));
  15983. }
  15984. return target.getVariableForExportName(name, {
  15985. importerForSideEffects,
  15986. isExportAllSearch,
  15987. searchedNamesAndModules
  15988. });
  15989. }
  15990. function getAndExtendSideEffectModules(variable, module) {
  15991. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  15992. let currentVariable = variable;
  15993. const referencedVariables = new Set([currentVariable]);
  15994. while (true) {
  15995. const importingModule = currentVariable.module;
  15996. currentVariable =
  15997. currentVariable instanceof ExportDefaultVariable
  15998. ? currentVariable.getDirectOriginalVariable()
  15999. : currentVariable instanceof SyntheticNamedExportVariable
  16000. ? currentVariable.syntheticNamespace
  16001. : null;
  16002. if (!currentVariable || referencedVariables.has(currentVariable)) {
  16003. break;
  16004. }
  16005. referencedVariables.add(currentVariable);
  16006. sideEffectModules.add(importingModule);
  16007. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  16008. if (originalSideEffects) {
  16009. for (const module of originalSideEffects) {
  16010. sideEffectModules.add(module);
  16011. }
  16012. }
  16013. }
  16014. return sideEffectModules;
  16015. }
  16016. class Module {
  16017. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  16018. this.graph = graph;
  16019. this.id = id;
  16020. this.options = options;
  16021. this.alternativeReexportModules = new Map();
  16022. this.chunkFileNames = new Set();
  16023. this.chunkNames = [];
  16024. this.cycles = new Set();
  16025. this.dependencies = new Set();
  16026. this.dynamicDependencies = new Set();
  16027. this.dynamicImporters = [];
  16028. this.dynamicImports = [];
  16029. this.execIndex = Infinity;
  16030. this.hasTreeShakingPassStarted = false;
  16031. this.implicitlyLoadedAfter = new Set();
  16032. this.implicitlyLoadedBefore = new Set();
  16033. this.importDescriptions = new Map();
  16034. this.importMetas = [];
  16035. this.importedFromNotTreeshaken = false;
  16036. this.importers = [];
  16037. this.includedDynamicImporters = [];
  16038. this.includedImports = new Set();
  16039. this.isExecuted = false;
  16040. this.isUserDefinedEntryPoint = false;
  16041. this.needsExportShim = false;
  16042. this.sideEffectDependenciesByVariable = new Map();
  16043. this.sourcesWithAttributes = new Map();
  16044. this.allExportNames = null;
  16045. this.ast = null;
  16046. this.exportAllModules = [];
  16047. this.exportAllSources = new Set();
  16048. this.exportNamesByVariable = null;
  16049. this.exportShimVariable = new ExportShimVariable(this);
  16050. this.exports = new Map();
  16051. this.namespaceReexportsByName = new Map();
  16052. this.reexportDescriptions = new Map();
  16053. this.relevantDependencies = null;
  16054. this.syntheticExports = new Map();
  16055. this.syntheticNamespace = null;
  16056. this.transformDependencies = [];
  16057. this.transitiveReexports = null;
  16058. this.excludeFromSourcemap = /\0/.test(id);
  16059. this.context = options.moduleContext(id);
  16060. this.preserveSignature = this.options.preserveEntrySignatures;
  16061. // eslint-disable-next-line @typescript-eslint/no-this-alias
  16062. const module = this;
  16063. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  16064. this.info = {
  16065. ast: null,
  16066. attributes,
  16067. code: null,
  16068. get dynamicallyImportedIdResolutions() {
  16069. return dynamicImports
  16070. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  16071. .filter(Boolean);
  16072. },
  16073. get dynamicallyImportedIds() {
  16074. // We cannot use this.dynamicDependencies because this is needed before
  16075. // dynamicDependencies are populated
  16076. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  16077. },
  16078. get dynamicImporters() {
  16079. return dynamicImporters.sort();
  16080. },
  16081. get exportedBindings() {
  16082. const exportBindings = { '.': [...exports.keys()] };
  16083. for (const [name, { source }] of reexportDescriptions) {
  16084. (exportBindings[source] ??= []).push(name);
  16085. }
  16086. for (const source of exportAllSources) {
  16087. (exportBindings[source] ??= []).push('*');
  16088. }
  16089. return exportBindings;
  16090. },
  16091. get exports() {
  16092. return [
  16093. ...exports.keys(),
  16094. ...reexportDescriptions.keys(),
  16095. ...[...exportAllSources].map(() => '*')
  16096. ];
  16097. },
  16098. get hasDefaultExport() {
  16099. // This information is only valid after parsing
  16100. if (!module.ast) {
  16101. return null;
  16102. }
  16103. return module.exports.has('default') || reexportDescriptions.has('default');
  16104. },
  16105. id,
  16106. get implicitlyLoadedAfterOneOf() {
  16107. return Array.from(implicitlyLoadedAfter, getId).sort();
  16108. },
  16109. get implicitlyLoadedBefore() {
  16110. return Array.from(implicitlyLoadedBefore, getId).sort();
  16111. },
  16112. get importedIdResolutions() {
  16113. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  16114. },
  16115. get importedIds() {
  16116. // We cannot use this.dependencies because this is needed before
  16117. // dependencies are populated
  16118. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  16119. },
  16120. get importers() {
  16121. return importers.sort();
  16122. },
  16123. isEntry,
  16124. isExternal: false,
  16125. get isIncluded() {
  16126. if (graph.phase !== BuildPhase.GENERATE) {
  16127. return null;
  16128. }
  16129. return module.isIncluded();
  16130. },
  16131. meta: { ...meta },
  16132. moduleSideEffects,
  16133. syntheticNamedExports
  16134. };
  16135. }
  16136. basename() {
  16137. const base = path.basename(this.id);
  16138. const extension = path.extname(this.id);
  16139. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  16140. }
  16141. bindReferences() {
  16142. this.ast.bind();
  16143. }
  16144. cacheInfoGetters() {
  16145. cacheObjectGetters(this.info, [
  16146. 'dynamicallyImportedIdResolutions',
  16147. 'dynamicallyImportedIds',
  16148. 'dynamicImporters',
  16149. 'exportedBindings',
  16150. 'exports',
  16151. 'hasDefaultExport',
  16152. 'implicitlyLoadedAfterOneOf',
  16153. 'implicitlyLoadedBefore',
  16154. 'importedIdResolutions',
  16155. 'importedIds',
  16156. 'importers'
  16157. ]);
  16158. }
  16159. error(properties, pos) {
  16160. if (pos !== undefined) {
  16161. this.addLocationToLogProps(properties, pos);
  16162. }
  16163. return parseAst_js.error(properties);
  16164. }
  16165. // sum up the length of all ast nodes that are included
  16166. estimateSize() {
  16167. let size = 0;
  16168. for (const node of this.ast.body) {
  16169. if (node.included) {
  16170. size += node.end - node.start;
  16171. }
  16172. }
  16173. return size;
  16174. }
  16175. getAllExportNames() {
  16176. if (this.allExportNames) {
  16177. return this.allExportNames;
  16178. }
  16179. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  16180. for (const module of this.exportAllModules) {
  16181. if (module instanceof ExternalModule) {
  16182. this.allExportNames.add(`*${module.id}`);
  16183. continue;
  16184. }
  16185. for (const name of module.getAllExportNames()) {
  16186. if (name !== 'default')
  16187. this.allExportNames.add(name);
  16188. }
  16189. }
  16190. // We do not count the synthetic namespace as a regular export to hide it
  16191. // from entry signatures and namespace objects
  16192. if (typeof this.info.syntheticNamedExports === 'string') {
  16193. this.allExportNames.delete(this.info.syntheticNamedExports);
  16194. }
  16195. return this.allExportNames;
  16196. }
  16197. getDependenciesToBeIncluded() {
  16198. if (this.relevantDependencies)
  16199. return this.relevantDependencies;
  16200. this.relevantDependencies = new Set();
  16201. const necessaryDependencies = new Set();
  16202. const alwaysCheckedDependencies = new Set();
  16203. const dependencyVariables = new Set(this.includedImports);
  16204. if (this.info.isEntry ||
  16205. this.includedDynamicImporters.length > 0 ||
  16206. this.namespace.included ||
  16207. this.implicitlyLoadedAfter.size > 0) {
  16208. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  16209. const [exportedVariable] = this.getVariableForExportName(exportName);
  16210. if (exportedVariable?.included) {
  16211. dependencyVariables.add(exportedVariable);
  16212. }
  16213. }
  16214. }
  16215. for (let variable of dependencyVariables) {
  16216. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  16217. if (sideEffectDependencies) {
  16218. for (const module of sideEffectDependencies) {
  16219. alwaysCheckedDependencies.add(module);
  16220. }
  16221. }
  16222. if (variable instanceof SyntheticNamedExportVariable) {
  16223. variable = variable.getBaseVariable();
  16224. }
  16225. else if (variable instanceof ExportDefaultVariable) {
  16226. variable = variable.getOriginalVariable();
  16227. }
  16228. necessaryDependencies.add(variable.module);
  16229. }
  16230. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  16231. for (const dependency of this.dependencies) {
  16232. this.relevantDependencies.add(dependency);
  16233. }
  16234. }
  16235. else {
  16236. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  16237. }
  16238. for (const dependency of necessaryDependencies) {
  16239. this.relevantDependencies.add(dependency);
  16240. }
  16241. return this.relevantDependencies;
  16242. }
  16243. getExportNamesByVariable() {
  16244. if (this.exportNamesByVariable) {
  16245. return this.exportNamesByVariable;
  16246. }
  16247. const exportNamesByVariable = new Map();
  16248. for (const exportName of this.getAllExportNames()) {
  16249. let [tracedVariable] = this.getVariableForExportName(exportName);
  16250. if (tracedVariable instanceof ExportDefaultVariable) {
  16251. tracedVariable = tracedVariable.getOriginalVariable();
  16252. }
  16253. if (!tracedVariable ||
  16254. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  16255. continue;
  16256. }
  16257. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  16258. if (existingExportNames) {
  16259. existingExportNames.push(exportName);
  16260. }
  16261. else {
  16262. exportNamesByVariable.set(tracedVariable, [exportName]);
  16263. }
  16264. }
  16265. return (this.exportNamesByVariable = exportNamesByVariable);
  16266. }
  16267. getExports() {
  16268. return [...this.exports.keys()];
  16269. }
  16270. getReexports() {
  16271. if (this.transitiveReexports) {
  16272. return this.transitiveReexports;
  16273. }
  16274. // to avoid infinite recursion when using circular `export * from X`
  16275. this.transitiveReexports = [];
  16276. const reexports = new Set(this.reexportDescriptions.keys());
  16277. for (const module of this.exportAllModules) {
  16278. if (module instanceof ExternalModule) {
  16279. reexports.add(`*${module.id}`);
  16280. }
  16281. else {
  16282. for (const name of [...module.getReexports(), ...module.getExports()]) {
  16283. if (name !== 'default')
  16284. reexports.add(name);
  16285. }
  16286. }
  16287. }
  16288. return (this.transitiveReexports = [...reexports]);
  16289. }
  16290. getRenderedExports() {
  16291. // only direct exports are counted here, not reexports at all
  16292. const renderedExports = [];
  16293. const removedExports = [];
  16294. for (const exportName of this.exports.keys()) {
  16295. const [variable] = this.getVariableForExportName(exportName);
  16296. (variable?.included ? renderedExports : removedExports).push(exportName);
  16297. }
  16298. return { removedExports, renderedExports };
  16299. }
  16300. getSyntheticNamespace() {
  16301. if (this.syntheticNamespace === null) {
  16302. this.syntheticNamespace = undefined;
  16303. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  16304. ? this.info.syntheticNamedExports
  16305. : 'default', { onlyExplicit: true });
  16306. }
  16307. if (!this.syntheticNamespace) {
  16308. return parseAst_js.error(parseAst_js.logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  16309. }
  16310. return this.syntheticNamespace;
  16311. }
  16312. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  16313. if (name[0] === '*') {
  16314. if (name.length === 1) {
  16315. // export * from './other'
  16316. return [this.namespace];
  16317. }
  16318. // export * from 'external'
  16319. const module = this.graph.modulesById.get(name.slice(1));
  16320. return module.getVariableForExportName('*');
  16321. }
  16322. // export { foo } from './other'
  16323. const reexportDeclaration = this.reexportDescriptions.get(name);
  16324. if (reexportDeclaration) {
  16325. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  16326. if (!variable) {
  16327. return this.error(parseAst_js.logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  16328. }
  16329. if (importerForSideEffects) {
  16330. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16331. if (this.info.moduleSideEffects) {
  16332. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16333. }
  16334. }
  16335. return [variable];
  16336. }
  16337. const exportDeclaration = this.exports.get(name);
  16338. if (exportDeclaration) {
  16339. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  16340. return [this.exportShimVariable];
  16341. }
  16342. const name = exportDeclaration.localName;
  16343. const variable = this.traceVariable(name, {
  16344. importerForSideEffects,
  16345. searchedNamesAndModules
  16346. });
  16347. if (importerForSideEffects) {
  16348. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16349. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16350. }
  16351. return [variable];
  16352. }
  16353. if (onlyExplicit) {
  16354. return [null];
  16355. }
  16356. if (name !== 'default') {
  16357. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  16358. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  16359. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  16360. if (foundNamespaceReexport[0]) {
  16361. return foundNamespaceReexport;
  16362. }
  16363. }
  16364. if (this.info.syntheticNamedExports) {
  16365. return [
  16366. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  16367. ];
  16368. }
  16369. // we don't want to create shims when we are just
  16370. // probing export * modules for exports
  16371. if (!isExportAllSearch && this.options.shimMissingExports) {
  16372. this.shimMissingExport(name);
  16373. return [this.exportShimVariable];
  16374. }
  16375. return [null];
  16376. }
  16377. hasEffects() {
  16378. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  16379. }
  16380. include() {
  16381. const context = createInclusionContext();
  16382. if (this.ast.shouldBeIncluded(context))
  16383. this.ast.include(context, false);
  16384. }
  16385. includeAllExports(includeNamespaceMembers) {
  16386. if (!this.isExecuted) {
  16387. markModuleAndImpureDependenciesAsExecuted(this);
  16388. this.graph.needsTreeshakingPass = true;
  16389. }
  16390. for (const exportName of this.exports.keys()) {
  16391. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  16392. const variable = this.getVariableForExportName(exportName)[0];
  16393. if (!variable) {
  16394. return parseAst_js.error(parseAst_js.logMissingEntryExport(exportName, this.id));
  16395. }
  16396. variable.deoptimizePath(UNKNOWN_PATH);
  16397. if (!variable.included) {
  16398. this.includeVariable(variable);
  16399. }
  16400. }
  16401. }
  16402. for (const name of this.getReexports()) {
  16403. const [variable] = this.getVariableForExportName(name);
  16404. if (variable) {
  16405. variable.deoptimizePath(UNKNOWN_PATH);
  16406. if (!variable.included) {
  16407. this.includeVariable(variable);
  16408. }
  16409. if (variable instanceof ExternalVariable) {
  16410. variable.module.reexported = true;
  16411. }
  16412. }
  16413. }
  16414. if (includeNamespaceMembers) {
  16415. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16416. }
  16417. }
  16418. includeAllInBundle() {
  16419. this.ast.include(createInclusionContext(), true);
  16420. this.includeAllExports(false);
  16421. }
  16422. includeExportsByNames(names) {
  16423. if (!this.isExecuted) {
  16424. markModuleAndImpureDependenciesAsExecuted(this);
  16425. this.graph.needsTreeshakingPass = true;
  16426. }
  16427. let includeNamespaceMembers = false;
  16428. for (const name of names) {
  16429. const variable = this.getVariableForExportName(name)[0];
  16430. if (variable) {
  16431. variable.deoptimizePath(UNKNOWN_PATH);
  16432. if (!variable.included) {
  16433. this.includeVariable(variable);
  16434. }
  16435. }
  16436. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  16437. includeNamespaceMembers = true;
  16438. }
  16439. }
  16440. if (includeNamespaceMembers) {
  16441. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  16442. }
  16443. }
  16444. isIncluded() {
  16445. // Modules where this.ast is missing have been loaded via this.load and are
  16446. // not yet fully processed, hence they cannot be included.
  16447. return (this.ast &&
  16448. (this.ast.included ||
  16449. this.namespace.included ||
  16450. this.importedFromNotTreeshaken ||
  16451. this.exportShimVariable.included));
  16452. }
  16453. linkImports() {
  16454. this.addModulesToImportDescriptions(this.importDescriptions);
  16455. this.addModulesToImportDescriptions(this.reexportDescriptions);
  16456. const externalExportAllModules = [];
  16457. for (const source of this.exportAllSources) {
  16458. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  16459. if (module instanceof ExternalModule) {
  16460. externalExportAllModules.push(module);
  16461. continue;
  16462. }
  16463. this.exportAllModules.push(module);
  16464. }
  16465. this.exportAllModules.push(...externalExportAllModules);
  16466. }
  16467. log(level, properties, pos) {
  16468. this.addLocationToLogProps(properties, pos);
  16469. this.options.onLog(level, properties);
  16470. }
  16471. render(options) {
  16472. const source = this.magicString.clone();
  16473. this.ast.render(source, options);
  16474. source.trim();
  16475. const { usesTopLevelAwait } = this.astContext;
  16476. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  16477. return parseAst_js.error(parseAst_js.logInvalidFormatForTopLevelAwait(this.id, options.format));
  16478. }
  16479. return { source, usesTopLevelAwait };
  16480. }
  16481. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  16482. timeStart('generate ast', 3);
  16483. if (code.startsWith('#!')) {
  16484. const shebangEndPosition = code.indexOf('\n');
  16485. this.shebang = code.slice(2, shebangEndPosition);
  16486. }
  16487. this.info.code = code;
  16488. this.originalCode = originalCode;
  16489. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  16490. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  16491. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  16492. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  16493. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  16494. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  16495. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  16496. if (transformFiles) {
  16497. this.transformFiles = transformFiles;
  16498. }
  16499. this.transformDependencies = transformDependencies;
  16500. this.customTransformCache = customTransformCache;
  16501. this.updateOptions(moduleOptions);
  16502. this.resolvedIds = resolvedIds ?? Object.create(null);
  16503. // By default, `id` is the file name. Custom resolvers and loaders
  16504. // can change that, but it makes sense to use it for the source file name
  16505. const fileName = this.id;
  16506. this.magicString = new MagicString(code, {
  16507. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  16508. indentExclusionRanges: []
  16509. });
  16510. this.astContext = {
  16511. addDynamicImport: this.addDynamicImport.bind(this),
  16512. addExport: this.addExport.bind(this),
  16513. addImport: this.addImport.bind(this),
  16514. addImportMeta: this.addImportMeta.bind(this),
  16515. addImportSource: this.addImportSource.bind(this),
  16516. code, // Only needed for debugging
  16517. deoptimizationTracker: this.graph.deoptimizationTracker,
  16518. error: this.error.bind(this),
  16519. fileName, // Needed for warnings
  16520. getExports: this.getExports.bind(this),
  16521. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  16522. getModuleExecIndex: () => this.execIndex,
  16523. getModuleName: this.basename.bind(this),
  16524. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  16525. getReexports: this.getReexports.bind(this),
  16526. importDescriptions: this.importDescriptions,
  16527. includeAllExports: () => this.includeAllExports(true),
  16528. includeDynamicImport: this.includeDynamicImport.bind(this),
  16529. includeVariableInModule: this.includeVariableInModule.bind(this),
  16530. log: this.log.bind(this),
  16531. magicString: this.magicString,
  16532. manualPureFunctions: this.graph.pureFunctions,
  16533. module: this,
  16534. moduleContext: this.context,
  16535. options: this.options,
  16536. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  16537. traceExport: (name) => this.getVariableForExportName(name)[0],
  16538. traceVariable: this.traceVariable.bind(this),
  16539. usesTopLevelAwait: false
  16540. };
  16541. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  16542. this.namespace = new NamespaceVariable(this.astContext);
  16543. const programParent = { context: this.astContext, type: 'Module' };
  16544. if (ast) {
  16545. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  16546. this.info.ast = ast;
  16547. }
  16548. else {
  16549. // Measuring asynchronous code does not provide reasonable results
  16550. timeEnd('generate ast', 3);
  16551. const astBuffer = await native_js.parseAsync(code, false, this.options.jsx !== false);
  16552. timeStart('generate ast', 3);
  16553. this.ast = convertProgram(astBuffer, programParent, this.scope);
  16554. // Make lazy and apply LRU cache to not hog the memory
  16555. Object.defineProperty(this.info, 'ast', {
  16556. get: () => {
  16557. if (this.graph.astLru.has(fileName)) {
  16558. return this.graph.astLru.get(fileName);
  16559. }
  16560. else {
  16561. const parsedAst = this.tryParse();
  16562. // If the cache is not disabled, we need to keep the AST in memory
  16563. // until the end when the cache is generated
  16564. if (this.options.cache !== false) {
  16565. Object.defineProperty(this.info, 'ast', {
  16566. value: parsedAst
  16567. });
  16568. return parsedAst;
  16569. }
  16570. // Otherwise, we keep it in a small LRU cache to not hog too much
  16571. // memory but allow the same AST to be requested several times.
  16572. this.graph.astLru.set(fileName, parsedAst);
  16573. return parsedAst;
  16574. }
  16575. }
  16576. });
  16577. }
  16578. timeEnd('generate ast', 3);
  16579. }
  16580. toJSON() {
  16581. return {
  16582. ast: this.info.ast,
  16583. attributes: this.info.attributes,
  16584. code: this.info.code,
  16585. customTransformCache: this.customTransformCache,
  16586. dependencies: Array.from(this.dependencies, getId),
  16587. id: this.id,
  16588. meta: this.info.meta,
  16589. moduleSideEffects: this.info.moduleSideEffects,
  16590. originalCode: this.originalCode,
  16591. originalSourcemap: this.originalSourcemap,
  16592. resolvedIds: this.resolvedIds,
  16593. sourcemapChain: this.sourcemapChain,
  16594. syntheticNamedExports: this.info.syntheticNamedExports,
  16595. transformDependencies: this.transformDependencies,
  16596. transformFiles: this.transformFiles
  16597. };
  16598. }
  16599. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = parseAst_js.EMPTY_OBJECT) {
  16600. const localVariable = this.scope.variables.get(name);
  16601. if (localVariable) {
  16602. return localVariable;
  16603. }
  16604. const importDescription = this.importDescriptions.get(name);
  16605. if (importDescription) {
  16606. const otherModule = importDescription.module;
  16607. if (otherModule instanceof Module && importDescription.name === '*') {
  16608. return otherModule.namespace;
  16609. }
  16610. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  16611. if (!declaration) {
  16612. return this.error(parseAst_js.logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  16613. }
  16614. return declaration;
  16615. }
  16616. return null;
  16617. }
  16618. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  16619. if (moduleSideEffects != null) {
  16620. this.info.moduleSideEffects = moduleSideEffects;
  16621. }
  16622. if (syntheticNamedExports != null) {
  16623. this.info.syntheticNamedExports = syntheticNamedExports;
  16624. }
  16625. if (meta != null) {
  16626. Object.assign(this.info.meta, meta);
  16627. }
  16628. }
  16629. addDynamicImport(node) {
  16630. let argument = node.sourceAstNode;
  16631. if (argument.type === parseAst_js.TemplateLiteral) {
  16632. if (argument.quasis.length === 1 &&
  16633. typeof argument.quasis[0].value.cooked === 'string') {
  16634. argument = argument.quasis[0].value.cooked;
  16635. }
  16636. }
  16637. else if (argument.type === parseAst_js.Literal &&
  16638. typeof argument.value === 'string') {
  16639. argument = argument.value;
  16640. }
  16641. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  16642. }
  16643. assertUniqueExportName(name, nodeStart) {
  16644. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  16645. this.error(parseAst_js.logDuplicateExportError(name), nodeStart);
  16646. }
  16647. }
  16648. addExport(node) {
  16649. if (node instanceof ExportDefaultDeclaration) {
  16650. // export default foo;
  16651. this.assertUniqueExportName('default', node.start);
  16652. this.exports.set('default', {
  16653. identifier: node.variable.getAssignedVariableName(),
  16654. localName: 'default'
  16655. });
  16656. }
  16657. else if (node instanceof ExportAllDeclaration) {
  16658. const source = node.source.value;
  16659. this.addSource(source, node);
  16660. if (node.exported) {
  16661. // export * as name from './other'
  16662. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  16663. this.assertUniqueExportName(name, node.exported.start);
  16664. this.reexportDescriptions.set(name, {
  16665. localName: '*',
  16666. module: null, // filled in later,
  16667. source,
  16668. start: node.start
  16669. });
  16670. }
  16671. else {
  16672. // export * from './other'
  16673. this.exportAllSources.add(source);
  16674. }
  16675. }
  16676. else if (node.source instanceof Literal) {
  16677. // export { name } from './other'
  16678. const source = node.source.value;
  16679. this.addSource(source, node);
  16680. for (const { exported, local, start } of node.specifiers) {
  16681. const name = exported instanceof Literal ? exported.value : exported.name;
  16682. this.assertUniqueExportName(name, start);
  16683. this.reexportDescriptions.set(name, {
  16684. localName: local instanceof Literal ? local.value : local.name,
  16685. module: null, // filled in later,
  16686. source,
  16687. start
  16688. });
  16689. }
  16690. }
  16691. else if (node.declaration) {
  16692. const declaration = node.declaration;
  16693. if (declaration instanceof VariableDeclaration) {
  16694. // export var { foo, bar } = ...
  16695. // export var foo = 1, bar = 2;
  16696. for (const declarator of declaration.declarations) {
  16697. for (const localName of extractAssignedNames(declarator.id)) {
  16698. this.assertUniqueExportName(localName, declarator.id.start);
  16699. this.exports.set(localName, { identifier: null, localName });
  16700. }
  16701. }
  16702. }
  16703. else {
  16704. // export function foo () {}
  16705. const localName = declaration.id.name;
  16706. this.assertUniqueExportName(localName, declaration.id.start);
  16707. this.exports.set(localName, { identifier: null, localName });
  16708. }
  16709. }
  16710. else {
  16711. // export { foo, bar, baz }
  16712. for (const { local, exported } of node.specifiers) {
  16713. // except for reexports, local must be an Identifier
  16714. const localName = local.name;
  16715. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  16716. this.assertUniqueExportName(exportedName, exported.start);
  16717. this.exports.set(exportedName, { identifier: null, localName });
  16718. }
  16719. }
  16720. }
  16721. addImport(node) {
  16722. const source = node.source.value;
  16723. this.addSource(source, node);
  16724. for (const specifier of node.specifiers) {
  16725. const localName = specifier.local.name;
  16726. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  16727. this.error(parseAst_js.logRedeclarationError(localName), specifier.local.start);
  16728. }
  16729. const name = specifier instanceof ImportDefaultSpecifier
  16730. ? 'default'
  16731. : specifier instanceof ImportNamespaceSpecifier
  16732. ? '*'
  16733. : specifier.imported instanceof Identifier
  16734. ? specifier.imported.name
  16735. : specifier.imported.value;
  16736. this.importDescriptions.set(localName, {
  16737. module: null, // filled in later
  16738. name,
  16739. source,
  16740. start: specifier.start
  16741. });
  16742. }
  16743. }
  16744. addImportSource(importSource) {
  16745. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  16746. this.sourcesWithAttributes.set(importSource, parseAst_js.EMPTY_OBJECT);
  16747. }
  16748. }
  16749. addImportMeta(node) {
  16750. this.importMetas.push(node);
  16751. }
  16752. addLocationToLogProps(properties, pos) {
  16753. properties.id = this.id;
  16754. properties.pos = pos;
  16755. let code = this.info.code;
  16756. const location = parseAst_js.locate(code, pos, { offsetLine: 1 });
  16757. if (location) {
  16758. let { column, line } = location;
  16759. try {
  16760. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  16761. code = this.originalCode;
  16762. }
  16763. catch (error_) {
  16764. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInvalidSourcemapForError(error_, this.id, column, line, pos));
  16765. }
  16766. parseAst_js.augmentCodeLocation(properties, { column, line }, code, this.id);
  16767. }
  16768. }
  16769. addModulesToImportDescriptions(importDescription) {
  16770. for (const specifier of importDescription.values()) {
  16771. const { id } = this.resolvedIds[specifier.source];
  16772. specifier.module = this.graph.modulesById.get(id);
  16773. }
  16774. }
  16775. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  16776. const handledDependencies = new Set();
  16777. const addSideEffectDependencies = (possibleDependencies) => {
  16778. for (const dependency of possibleDependencies) {
  16779. if (handledDependencies.has(dependency)) {
  16780. continue;
  16781. }
  16782. handledDependencies.add(dependency);
  16783. if (necessaryDependencies.has(dependency)) {
  16784. relevantDependencies.add(dependency);
  16785. continue;
  16786. }
  16787. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  16788. continue;
  16789. }
  16790. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  16791. relevantDependencies.add(dependency);
  16792. continue;
  16793. }
  16794. addSideEffectDependencies(dependency.dependencies);
  16795. }
  16796. };
  16797. addSideEffectDependencies(this.dependencies);
  16798. addSideEffectDependencies(alwaysCheckedDependencies);
  16799. }
  16800. addSource(source, declaration) {
  16801. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  16802. const existingAttributes = this.sourcesWithAttributes.get(source);
  16803. if (existingAttributes) {
  16804. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  16805. this.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  16806. }
  16807. }
  16808. else {
  16809. this.sourcesWithAttributes.set(source, parsedAttributes);
  16810. }
  16811. }
  16812. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  16813. const { id } = this.resolvedIds[importSource];
  16814. const module = this.graph.modulesById.get(id);
  16815. const [variable] = module.getVariableForExportName(baseName);
  16816. if (!variable) {
  16817. return this.error(parseAst_js.logMissingJsxExport(baseName, id, this.id), nodeStart);
  16818. }
  16819. return variable;
  16820. }
  16821. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  16822. let foundSyntheticDeclaration = null;
  16823. const foundInternalDeclarations = new Map();
  16824. const foundExternalDeclarations = new Set();
  16825. for (const module of this.exportAllModules) {
  16826. // Synthetic namespaces should not hide "regular" exports of the same name
  16827. if (module.info.syntheticNamedExports === name) {
  16828. continue;
  16829. }
  16830. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  16831. // We are creating a copy to handle the case where the same binding is
  16832. // imported through different namespace reexports gracefully
  16833. copyNameToModulesMap(searchedNamesAndModules));
  16834. if (module instanceof ExternalModule || indirectExternal) {
  16835. foundExternalDeclarations.add(variable);
  16836. }
  16837. else if (variable instanceof SyntheticNamedExportVariable) {
  16838. if (!foundSyntheticDeclaration) {
  16839. foundSyntheticDeclaration = variable;
  16840. }
  16841. }
  16842. else if (variable) {
  16843. foundInternalDeclarations.set(variable, module);
  16844. }
  16845. }
  16846. if (foundInternalDeclarations.size > 0) {
  16847. const foundDeclarationList = [...foundInternalDeclarations];
  16848. const usedDeclaration = foundDeclarationList[0][0];
  16849. if (foundDeclarationList.length === 1) {
  16850. return [usedDeclaration];
  16851. }
  16852. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  16853. // TODO we are pretending it was not found while it should behave like "undefined"
  16854. return [null];
  16855. }
  16856. if (foundExternalDeclarations.size > 0) {
  16857. const foundDeclarationList = [...foundExternalDeclarations];
  16858. const usedDeclaration = foundDeclarationList[0];
  16859. if (foundDeclarationList.length > 1) {
  16860. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  16861. }
  16862. return [usedDeclaration, true];
  16863. }
  16864. if (foundSyntheticDeclaration) {
  16865. return [foundSyntheticDeclaration];
  16866. }
  16867. return [null];
  16868. }
  16869. includeAndGetAdditionalMergedNamespaces() {
  16870. const externalNamespaces = new Set();
  16871. const syntheticNamespaces = new Set();
  16872. for (const module of [this, ...this.exportAllModules]) {
  16873. if (module instanceof ExternalModule) {
  16874. const [externalVariable] = module.getVariableForExportName('*');
  16875. externalVariable.include();
  16876. this.includedImports.add(externalVariable);
  16877. externalNamespaces.add(externalVariable);
  16878. }
  16879. else if (module.info.syntheticNamedExports) {
  16880. const syntheticNamespace = module.getSyntheticNamespace();
  16881. syntheticNamespace.include();
  16882. this.includedImports.add(syntheticNamespace);
  16883. syntheticNamespaces.add(syntheticNamespace);
  16884. }
  16885. }
  16886. return [...syntheticNamespaces, ...externalNamespaces];
  16887. }
  16888. includeDynamicImport(node) {
  16889. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  16890. if (resolution instanceof Module) {
  16891. resolution.includedDynamicImporters.push(this);
  16892. const importedNames = this.options.treeshake
  16893. ? node.getDeterministicImportedNames()
  16894. : undefined;
  16895. if (importedNames) {
  16896. resolution.includeExportsByNames(importedNames);
  16897. }
  16898. else {
  16899. resolution.includeAllExports(true);
  16900. }
  16901. }
  16902. }
  16903. includeVariable(variable) {
  16904. const variableModule = variable.module;
  16905. if (variable.included) {
  16906. if (variableModule instanceof Module && variableModule !== this) {
  16907. getAndExtendSideEffectModules(variable, this);
  16908. }
  16909. }
  16910. else {
  16911. variable.include();
  16912. this.graph.needsTreeshakingPass = true;
  16913. if (variableModule instanceof Module) {
  16914. if (!variableModule.isExecuted) {
  16915. markModuleAndImpureDependenciesAsExecuted(variableModule);
  16916. }
  16917. if (variableModule !== this) {
  16918. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  16919. for (const module of sideEffectModules) {
  16920. if (!module.isExecuted) {
  16921. markModuleAndImpureDependenciesAsExecuted(module);
  16922. }
  16923. }
  16924. }
  16925. }
  16926. }
  16927. }
  16928. includeVariableInModule(variable) {
  16929. this.includeVariable(variable);
  16930. const variableModule = variable.module;
  16931. if (variableModule && variableModule !== this) {
  16932. this.includedImports.add(variable);
  16933. }
  16934. }
  16935. shimMissingExport(name) {
  16936. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logShimmedExport(this.id, name));
  16937. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  16938. }
  16939. tryParse() {
  16940. try {
  16941. return parseAst_js.parseAst(this.info.code, { jsx: this.options.jsx !== false });
  16942. }
  16943. catch (error_) {
  16944. return this.error(parseAst_js.logModuleParseError(error_, this.id), error_.pos);
  16945. }
  16946. }
  16947. }
  16948. // if there is a cyclic import in the reexport chain, we should not
  16949. // import from the original module but from the cyclic module to not
  16950. // mess up execution order.
  16951. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  16952. if (variable.module instanceof Module && variable.module !== reexporter) {
  16953. const exporterCycles = variable.module.cycles;
  16954. if (exporterCycles.size > 0) {
  16955. const importerCycles = reexporter.cycles;
  16956. for (const cycleSymbol of importerCycles) {
  16957. if (exporterCycles.has(cycleSymbol)) {
  16958. importer.alternativeReexportModules.set(variable, reexporter);
  16959. break;
  16960. }
  16961. }
  16962. }
  16963. }
  16964. }
  16965. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  16966. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  16967. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  16968. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  16969. async function createAddons(options, outputPluginDriver, chunk) {
  16970. try {
  16971. let [banner, footer, intro, outro] = await Promise.all([
  16972. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  16973. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  16974. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  16975. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  16976. ]);
  16977. if (intro)
  16978. intro += '\n\n';
  16979. if (outro)
  16980. outro = `\n\n${outro}`;
  16981. if (banner)
  16982. banner += '\n';
  16983. if (footer)
  16984. footer = '\n' + footer;
  16985. return { banner, footer, intro, outro };
  16986. }
  16987. catch (error_) {
  16988. return parseAst_js.error(parseAst_js.logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  16989. }
  16990. }
  16991. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  16992. amd: deconflictImportsOther,
  16993. cjs: deconflictImportsOther,
  16994. es: deconflictImportsEsmOrSystem,
  16995. iife: deconflictImportsOther,
  16996. system: deconflictImportsEsmOrSystem,
  16997. umd: deconflictImportsOther
  16998. };
  16999. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  17000. const reversedModules = [...modules].reverse();
  17001. for (const module of reversedModules) {
  17002. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  17003. }
  17004. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  17005. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  17006. for (const module of reversedModules) {
  17007. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  17008. }
  17009. }
  17010. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  17011. // This is needed for namespace reexports
  17012. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  17013. if (preserveModules || dependency instanceof ExternalChunk) {
  17014. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  17015. }
  17016. }
  17017. for (const variable of imports) {
  17018. const module = variable.module;
  17019. const name = variable.name;
  17020. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  17021. variable.setRenderNames(null, (module instanceof ExternalModule
  17022. ? externalChunkByModule.get(module)
  17023. : chunkByModule.get(module)).variableName);
  17024. }
  17025. else if (module instanceof ExternalModule && name === 'default') {
  17026. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  17027. ? module.suggestedVariableName + '__default'
  17028. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  17029. }
  17030. else {
  17031. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  17032. }
  17033. }
  17034. for (const variable of syntheticExports) {
  17035. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  17036. }
  17037. }
  17038. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  17039. for (const chunk of dependencies) {
  17040. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  17041. }
  17042. for (const chunk of deconflictedNamespace) {
  17043. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  17044. }
  17045. for (const externalModule of deconflictedDefault) {
  17046. externalModule.defaultVariableName =
  17047. deconflictedNamespace.has(externalModule) &&
  17048. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  17049. ? externalModule.namespaceVariableName
  17050. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  17051. }
  17052. for (const variable of imports) {
  17053. const module = variable.module;
  17054. if (module instanceof ExternalModule) {
  17055. const chunk = externalChunkByModule.get(module);
  17056. const name = variable.name;
  17057. if (name === 'default') {
  17058. const moduleInterop = interop(module.id);
  17059. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  17060. ? chunk.defaultVariableName
  17061. : chunk.variableName;
  17062. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  17063. variable.setRenderNames(variableName, 'default');
  17064. }
  17065. else {
  17066. variable.setRenderNames(null, variableName);
  17067. }
  17068. }
  17069. else if (name === '*') {
  17070. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  17071. ? chunk.namespaceVariableName
  17072. : chunk.variableName);
  17073. }
  17074. else {
  17075. // if the second parameter is `null`, it uses its "name" for the property name
  17076. variable.setRenderNames(chunk.variableName, null);
  17077. }
  17078. }
  17079. else {
  17080. const chunk = chunkByModule.get(module);
  17081. if (preserveModules && variable.isNamespace) {
  17082. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  17083. }
  17084. else if (chunk.exportMode === 'default') {
  17085. variable.setRenderNames(null, chunk.variableName);
  17086. }
  17087. else {
  17088. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  17089. }
  17090. }
  17091. }
  17092. }
  17093. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  17094. for (const module of modules) {
  17095. for (const variable of module.scope.variables.values()) {
  17096. if (variable.included &&
  17097. // this will only happen for exports in some formats
  17098. !(variable.renderBaseName ||
  17099. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  17100. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  17101. }
  17102. }
  17103. if (includedNamespaces.has(module)) {
  17104. const namespace = module.namespace;
  17105. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  17106. }
  17107. }
  17108. }
  17109. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  17110. let nameIndex = 0;
  17111. for (const variable of exports) {
  17112. let [exportName] = variable.name;
  17113. if (exportsByName.has(exportName)) {
  17114. do {
  17115. exportName = toBase64(++nameIndex);
  17116. // skip past leading number identifiers
  17117. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  17118. nameIndex += 9 * 64 ** (exportName.length - 1);
  17119. exportName = toBase64(nameIndex);
  17120. }
  17121. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  17122. }
  17123. exportsByName.set(exportName, variable);
  17124. exportNamesByVariable.set(variable, [exportName]);
  17125. }
  17126. }
  17127. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  17128. for (const variable of exports) {
  17129. let nameIndex = 0;
  17130. let exportName = variable.name;
  17131. while (exportsByName.has(exportName)) {
  17132. exportName = variable.name + '$' + ++nameIndex;
  17133. }
  17134. exportsByName.set(exportName, variable);
  17135. exportNamesByVariable.set(variable, [exportName]);
  17136. }
  17137. }
  17138. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  17139. const exportKeys = chunk.getExportNames();
  17140. if (exportMode === 'default') {
  17141. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  17142. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  17143. }
  17144. }
  17145. else if (exportMode === 'none' && exportKeys.length > 0) {
  17146. return parseAst_js.error(parseAst_js.logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  17147. }
  17148. if (exportMode === 'auto') {
  17149. if (exportKeys.length === 0) {
  17150. exportMode = 'none';
  17151. }
  17152. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  17153. exportMode = 'default';
  17154. }
  17155. else {
  17156. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  17157. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMixedExport(facadeModuleId, name));
  17158. }
  17159. exportMode = 'named';
  17160. }
  17161. }
  17162. return exportMode;
  17163. }
  17164. function guessIndentString(code) {
  17165. const lines = code.split('\n');
  17166. const tabbed = lines.filter(line => /^\t+/.test(line));
  17167. const spaced = lines.filter(line => /^ {2,}/.test(line));
  17168. if (tabbed.length === 0 && spaced.length === 0) {
  17169. return null;
  17170. }
  17171. // More lines tabbed than spaced? Assume tabs, and
  17172. // default to tabs in the case of a tie (or nothing
  17173. // to go on)
  17174. if (tabbed.length >= spaced.length) {
  17175. return '\t';
  17176. }
  17177. // Otherwise, we need to guess the multiple
  17178. const min = spaced.reduce((previous, current) => {
  17179. const numberSpaces = /^ +/.exec(current)[0].length;
  17180. return Math.min(numberSpaces, previous);
  17181. }, Infinity);
  17182. return ' '.repeat(min);
  17183. }
  17184. function getIndentString(modules, options) {
  17185. if (options.indent !== true)
  17186. return options.indent;
  17187. for (const module of modules) {
  17188. const indent = guessIndentString(module.originalCode);
  17189. if (indent !== null)
  17190. return indent;
  17191. }
  17192. return '\t';
  17193. }
  17194. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  17195. const staticDependencyBlocks = [];
  17196. const handledDependencies = new Set();
  17197. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  17198. const module = orderedModules[modulePos];
  17199. if (!handledDependencies.has(module)) {
  17200. const staticDependencies = [];
  17201. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  17202. staticDependencyBlocks.unshift(staticDependencies);
  17203. }
  17204. }
  17205. const dependencies = new Set();
  17206. for (const block of staticDependencyBlocks) {
  17207. for (const dependency of block) {
  17208. dependencies.add(dependency);
  17209. }
  17210. }
  17211. return dependencies;
  17212. }
  17213. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  17214. const dependencies = module.getDependenciesToBeIncluded();
  17215. for (const dependency of dependencies) {
  17216. if (dependency instanceof ExternalModule) {
  17217. staticDependencies.push(externalChunkByModule.get(dependency));
  17218. continue;
  17219. }
  17220. const dependencyChunk = chunkByModule.get(dependency);
  17221. if (dependencyChunk !== chunk) {
  17222. staticDependencies.push(dependencyChunk);
  17223. continue;
  17224. }
  17225. if (!handledModules.has(dependency)) {
  17226. handledModules.add(dependency);
  17227. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  17228. }
  17229. }
  17230. }
  17231. const NON_ASSET_EXTENSIONS = new Set([
  17232. '.js',
  17233. '.jsx',
  17234. '.ts',
  17235. '.tsx',
  17236. '.mjs',
  17237. '.mts',
  17238. '.cjs',
  17239. '.cts'
  17240. ]);
  17241. function getGlobalName(chunk, globals, hasExports, log) {
  17242. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  17243. if (globalName) {
  17244. return globalName;
  17245. }
  17246. if (hasExports) {
  17247. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingGlobalName(chunk.id, chunk.variableName));
  17248. return chunk.variableName;
  17249. }
  17250. }
  17251. class Chunk {
  17252. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  17253. this.orderedModules = orderedModules;
  17254. this.inputOptions = inputOptions;
  17255. this.outputOptions = outputOptions;
  17256. this.unsetOptions = unsetOptions;
  17257. this.pluginDriver = pluginDriver;
  17258. this.modulesById = modulesById;
  17259. this.chunkByModule = chunkByModule;
  17260. this.externalChunkByModule = externalChunkByModule;
  17261. this.facadeChunkByModule = facadeChunkByModule;
  17262. this.includedNamespaces = includedNamespaces;
  17263. this.manualChunkAlias = manualChunkAlias;
  17264. this.getPlaceholder = getPlaceholder;
  17265. this.bundle = bundle;
  17266. this.inputBase = inputBase;
  17267. this.snippets = snippets;
  17268. this.entryModules = [];
  17269. this.exportMode = 'named';
  17270. this.facadeModule = null;
  17271. this.namespaceVariableName = '';
  17272. this.variableName = '';
  17273. this.accessedGlobalsByScope = new Map();
  17274. this.dependencies = new Set();
  17275. this.dynamicEntryModules = [];
  17276. this.dynamicName = null;
  17277. this.exportNamesByVariable = new Map();
  17278. this.exports = new Set();
  17279. this.exportsByName = new Map();
  17280. this.fileName = null;
  17281. this.implicitEntryModules = [];
  17282. this.implicitlyLoadedBefore = new Set();
  17283. this.imports = new Set();
  17284. this.includedDynamicImports = null;
  17285. this.includedReexportsByModule = new Map();
  17286. // This may be updated in the constructor
  17287. this.isEmpty = true;
  17288. this.name = null;
  17289. this.needsExportsShim = false;
  17290. this.preRenderedChunkInfo = null;
  17291. this.preliminaryFileName = null;
  17292. this.preliminarySourcemapFileName = null;
  17293. this.renderedChunkInfo = null;
  17294. this.renderedDependencies = null;
  17295. this.renderedModules = Object.create(null);
  17296. this.sortedExportNames = null;
  17297. this.strictFacade = false;
  17298. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  17299. const chunkModules = new Set(orderedModules);
  17300. for (const module of orderedModules) {
  17301. chunkByModule.set(module, this);
  17302. if (module.namespace.included && !outputOptions.preserveModules) {
  17303. includedNamespaces.add(module);
  17304. }
  17305. if (this.isEmpty && module.isIncluded()) {
  17306. this.isEmpty = false;
  17307. }
  17308. if (module.info.isEntry || outputOptions.preserveModules) {
  17309. this.entryModules.push(module);
  17310. }
  17311. for (const importer of module.includedDynamicImporters) {
  17312. if (!chunkModules.has(importer)) {
  17313. this.dynamicEntryModules.push(module);
  17314. // Modules with synthetic exports need an artificial namespace for dynamic imports
  17315. if (module.info.syntheticNamedExports) {
  17316. includedNamespaces.add(module);
  17317. this.exports.add(module.namespace);
  17318. }
  17319. }
  17320. }
  17321. if (module.implicitlyLoadedAfter.size > 0) {
  17322. this.implicitEntryModules.push(module);
  17323. }
  17324. }
  17325. this.suggestedVariableName = makeLegal(this.generateVariableName());
  17326. }
  17327. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  17328. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  17329. chunk.assignFacadeName(facadeName, facadedModule);
  17330. if (!facadeChunkByModule.has(facadedModule)) {
  17331. facadeChunkByModule.set(facadedModule, chunk);
  17332. }
  17333. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  17334. chunk.dependencies.add(dependency instanceof Module
  17335. ? chunkByModule.get(dependency)
  17336. : externalChunkByModule.get(dependency));
  17337. }
  17338. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  17339. facadedModule.info.moduleSideEffects &&
  17340. facadedModule.hasEffects()) {
  17341. chunk.dependencies.add(chunkByModule.get(facadedModule));
  17342. }
  17343. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  17344. chunk.facadeModule = facadedModule;
  17345. chunk.strictFacade = true;
  17346. return chunk;
  17347. }
  17348. canModuleBeFacade(module, exposedVariables) {
  17349. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  17350. // All exports of this chunk need to be exposed by the candidate module
  17351. for (const exposedVariable of this.exports) {
  17352. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  17353. return false;
  17354. }
  17355. }
  17356. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  17357. for (const exposedVariable of exposedVariables) {
  17358. if (!(exposedVariable.module === module ||
  17359. moduleExportNamesByVariable.has(exposedVariable) ||
  17360. (exposedVariable instanceof SyntheticNamedExportVariable &&
  17361. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  17362. return false;
  17363. }
  17364. }
  17365. return true;
  17366. }
  17367. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  17368. const renderedChunkInfo = this.getRenderedChunkInfo();
  17369. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  17370. const preliminaryFileName = renderedChunkInfo.fileName;
  17371. const fileName = (this.fileName = finalize(preliminaryFileName));
  17372. return {
  17373. ...renderedChunkInfo,
  17374. code,
  17375. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  17376. fileName,
  17377. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  17378. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  17379. finalize(fileName),
  17380. bindings
  17381. ])),
  17382. imports: renderedChunkInfo.imports.map(finalize),
  17383. map,
  17384. preliminaryFileName,
  17385. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  17386. sourcemapFileName
  17387. };
  17388. }
  17389. generateExports() {
  17390. this.sortedExportNames = null;
  17391. const remainingExports = new Set(this.exports);
  17392. if (this.facadeModule !== null &&
  17393. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  17394. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  17395. for (const [variable, exportNames] of exportNamesByVariable) {
  17396. this.exportNamesByVariable.set(variable, [...exportNames]);
  17397. for (const exportName of exportNames) {
  17398. this.exportsByName.set(exportName, variable);
  17399. }
  17400. remainingExports.delete(variable);
  17401. }
  17402. }
  17403. if (this.outputOptions.minifyInternalExports) {
  17404. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17405. }
  17406. else {
  17407. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17408. }
  17409. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  17410. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  17411. }
  17412. generateFacades() {
  17413. const facades = [];
  17414. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  17415. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  17416. for (const module of entryModules) {
  17417. if (module.preserveSignature) {
  17418. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  17419. // We need to expose all entry exports from this chunk
  17420. if (this.chunkByModule.get(exportedVariable.module) === this) {
  17421. exposedVariables.add(exportedVariable);
  17422. }
  17423. }
  17424. }
  17425. }
  17426. for (const module of entryModules) {
  17427. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  17428. // mapping must run after Set 'name' dedupe
  17429. name => ({
  17430. name
  17431. }));
  17432. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  17433. requiredFacades.push({});
  17434. }
  17435. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  17436. if (requiredFacades.length === 0) {
  17437. requiredFacades.push({});
  17438. }
  17439. if (!this.facadeModule) {
  17440. const needsStrictFacade = !this.outputOptions.preserveModules &&
  17441. (module.preserveSignature === 'strict' ||
  17442. (module.preserveSignature === 'exports-only' &&
  17443. module.getExportNamesByVariable().size > 0));
  17444. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  17445. this.facadeModule = module;
  17446. this.facadeChunkByModule.set(module, this);
  17447. if (module.preserveSignature) {
  17448. this.strictFacade = needsStrictFacade;
  17449. }
  17450. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  17451. }
  17452. }
  17453. for (const facadeName of requiredFacades) {
  17454. 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));
  17455. }
  17456. }
  17457. for (const module of this.dynamicEntryModules) {
  17458. if (module.info.syntheticNamedExports)
  17459. continue;
  17460. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  17461. this.facadeModule = module;
  17462. this.facadeChunkByModule.set(module, this);
  17463. this.strictFacade = true;
  17464. this.dynamicName = getChunkNameFromModule(module);
  17465. }
  17466. else if (this.facadeModule === module &&
  17467. !this.strictFacade &&
  17468. this.canModuleBeFacade(module, exposedVariables)) {
  17469. this.strictFacade = true;
  17470. }
  17471. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  17472. this.includedNamespaces.add(module);
  17473. this.exports.add(module.namespace);
  17474. }
  17475. }
  17476. if (!this.outputOptions.preserveModules) {
  17477. this.addNecessaryImportsForFacades();
  17478. }
  17479. return facades;
  17480. }
  17481. getChunkName() {
  17482. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  17483. }
  17484. getExportNames() {
  17485. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  17486. }
  17487. getFileName() {
  17488. return this.fileName || this.getPreliminaryFileName().fileName;
  17489. }
  17490. getImportPath(importer) {
  17491. return escapeId(parseAst_js.getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  17492. }
  17493. getPreliminaryFileName() {
  17494. if (this.preliminaryFileName) {
  17495. return this.preliminaryFileName;
  17496. }
  17497. let fileName;
  17498. let hashPlaceholder = null;
  17499. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  17500. if (file) {
  17501. fileName = path.basename(file);
  17502. }
  17503. else if (this.fileName === null) {
  17504. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  17505. ? [entryFileNames, 'output.entryFileNames']
  17506. : [chunkFileNames, 'output.chunkFileNames'];
  17507. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17508. format: () => format,
  17509. hash: size => hashPlaceholder ||
  17510. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17511. name: () => this.getChunkName()
  17512. });
  17513. if (!hashPlaceholder) {
  17514. fileName = makeUnique(fileName, this.bundle);
  17515. }
  17516. }
  17517. else {
  17518. fileName = this.fileName;
  17519. }
  17520. if (!hashPlaceholder) {
  17521. this.bundle[fileName] = FILE_PLACEHOLDER;
  17522. }
  17523. // Caching is essential to not conflict with the file name reservation above
  17524. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  17525. }
  17526. getPreliminarySourcemapFileName() {
  17527. if (this.preliminarySourcemapFileName) {
  17528. return this.preliminarySourcemapFileName;
  17529. }
  17530. let sourcemapFileName = null;
  17531. let hashPlaceholder = null;
  17532. const { sourcemapFileNames, format } = this.outputOptions;
  17533. if (sourcemapFileNames) {
  17534. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  17535. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17536. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  17537. format: () => format,
  17538. hash: size => hashPlaceholder ||
  17539. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17540. name: () => this.getChunkName()
  17541. });
  17542. if (!hashPlaceholder) {
  17543. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  17544. }
  17545. }
  17546. else {
  17547. return null;
  17548. }
  17549. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  17550. }
  17551. getRenderedChunkInfo() {
  17552. if (this.renderedChunkInfo) {
  17553. return this.renderedChunkInfo;
  17554. }
  17555. return (this.renderedChunkInfo = {
  17556. ...this.getPreRenderedChunkInfo(),
  17557. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  17558. fileName: this.getFileName(),
  17559. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  17560. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  17561. imports: Array.from(this.dependencies, resolveFileName),
  17562. modules: this.renderedModules,
  17563. referencedFiles: this.getReferencedFiles()
  17564. });
  17565. }
  17566. getVariableExportName(variable) {
  17567. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  17568. return '*';
  17569. }
  17570. return this.exportNamesByVariable.get(variable)[0];
  17571. }
  17572. link() {
  17573. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  17574. for (const module of this.orderedModules) {
  17575. this.addImplicitlyLoadedBeforeFromModule(module);
  17576. this.setUpChunkImportsAndExportsForModule(module);
  17577. }
  17578. }
  17579. async render() {
  17580. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  17581. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  17582. // for static and dynamic entry points, add transitive dependencies to this
  17583. // chunk's dependencies to avoid loading latency
  17584. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  17585. for (const dep of dependencies) {
  17586. if (dep instanceof Chunk)
  17587. this.inlineChunkDependencies(dep);
  17588. }
  17589. }
  17590. const preliminaryFileName = this.getPreliminaryFileName();
  17591. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  17592. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  17593. const renderedDependencies = [...this.getRenderedDependencies().values()];
  17594. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  17595. let hasExports = renderedExports.length > 0;
  17596. let hasDefaultExport = false;
  17597. for (const renderedDependency of renderedDependencies) {
  17598. const { reexports } = renderedDependency;
  17599. if (reexports?.length) {
  17600. hasExports = true;
  17601. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  17602. hasDefaultExport = true;
  17603. }
  17604. if (format === 'es') {
  17605. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  17606. }
  17607. }
  17608. }
  17609. if (!hasDefaultExport) {
  17610. for (const { exported } of renderedExports) {
  17611. if (exported === 'default') {
  17612. hasDefaultExport = true;
  17613. break;
  17614. }
  17615. }
  17616. }
  17617. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  17618. finalisers[format](renderedSource, {
  17619. accessedGlobals,
  17620. dependencies: renderedDependencies,
  17621. exports: renderedExports,
  17622. hasDefaultExport,
  17623. hasExports,
  17624. id: preliminaryFileName.fileName,
  17625. indent,
  17626. intro,
  17627. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  17628. isModuleFacade: facadeModule !== null,
  17629. log: onLog,
  17630. namedExportsMode: exportMode !== 'default',
  17631. outro,
  17632. snippets,
  17633. usesTopLevelAwait
  17634. }, outputOptions);
  17635. if (banner)
  17636. magicString.prepend(banner);
  17637. if (format === 'es' || format === 'cjs') {
  17638. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  17639. if (shebang) {
  17640. magicString.prepend(`#!${shebang}\n`);
  17641. }
  17642. }
  17643. if (footer)
  17644. magicString.append(footer);
  17645. return {
  17646. chunk: this,
  17647. magicString,
  17648. preliminaryFileName,
  17649. preliminarySourcemapFileName,
  17650. usedModules
  17651. };
  17652. }
  17653. addImplicitlyLoadedBeforeFromModule(baseModule) {
  17654. const { chunkByModule, implicitlyLoadedBefore } = this;
  17655. for (const module of baseModule.implicitlyLoadedBefore) {
  17656. const chunk = chunkByModule.get(module);
  17657. if (chunk && chunk !== this) {
  17658. implicitlyLoadedBefore.add(chunk);
  17659. }
  17660. }
  17661. }
  17662. addNecessaryImportsForFacades() {
  17663. for (const [module, variables] of this.includedReexportsByModule) {
  17664. if (this.includedNamespaces.has(module)) {
  17665. for (const variable of variables) {
  17666. this.imports.add(variable);
  17667. }
  17668. }
  17669. }
  17670. }
  17671. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  17672. if (fileName) {
  17673. this.fileName = fileName;
  17674. }
  17675. else {
  17676. this.name = this.outputOptions.sanitizeFileName(name ||
  17677. (preservePath
  17678. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  17679. : getChunkNameFromModule(facadedModule)));
  17680. }
  17681. }
  17682. checkCircularDependencyImport(variable, importingModule) {
  17683. const variableModule = variable.module;
  17684. if (variableModule instanceof Module) {
  17685. const exportChunk = this.chunkByModule.get(variableModule);
  17686. let alternativeReexportModule;
  17687. do {
  17688. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  17689. if (alternativeReexportModule) {
  17690. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  17691. if (exportingChunk !== exportChunk) {
  17692. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCyclicCrossChunkReexport(
  17693. // Namespaces do not have an export name
  17694. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  17695. }
  17696. importingModule = alternativeReexportModule;
  17697. }
  17698. } while (alternativeReexportModule);
  17699. }
  17700. }
  17701. ensureReexportsAreAvailableForModule(module) {
  17702. const includedReexports = [];
  17703. const map = module.getExportNamesByVariable();
  17704. for (const exportedVariable of map.keys()) {
  17705. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  17706. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  17707. this.checkCircularDependencyImport(importedVariable, module);
  17708. // When preserving modules, we do not create namespace objects but directly
  17709. // use the actual namespaces, which would be broken by this logic.
  17710. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17711. const exportingModule = importedVariable.module;
  17712. if (exportingModule instanceof Module) {
  17713. const chunk = this.chunkByModule.get(exportingModule);
  17714. if (chunk && chunk !== this) {
  17715. chunk.exports.add(importedVariable);
  17716. includedReexports.push(importedVariable);
  17717. if (isSynthetic) {
  17718. this.imports.add(importedVariable);
  17719. }
  17720. }
  17721. }
  17722. }
  17723. }
  17724. if (includedReexports.length > 0) {
  17725. this.includedReexportsByModule.set(module, includedReexports);
  17726. }
  17727. }
  17728. generateVariableName() {
  17729. if (this.manualChunkAlias) {
  17730. return this.manualChunkAlias;
  17731. }
  17732. const moduleForNaming = this.entryModules[0] ||
  17733. this.implicitEntryModules[0] ||
  17734. this.dynamicEntryModules[0] ||
  17735. this.orderedModules[this.orderedModules.length - 1];
  17736. if (moduleForNaming) {
  17737. return getChunkNameFromModule(moduleForNaming);
  17738. }
  17739. return 'chunk';
  17740. }
  17741. getChunkExportDeclarations(format) {
  17742. const exports = [];
  17743. for (const exportName of this.getExportNames()) {
  17744. if (exportName[0] === '*')
  17745. continue;
  17746. const variable = this.exportsByName.get(exportName);
  17747. if (!(variable instanceof SyntheticNamedExportVariable)) {
  17748. const module = variable.module;
  17749. if (module) {
  17750. const chunk = this.chunkByModule.get(module);
  17751. if (chunk !== this) {
  17752. if (!chunk || format !== 'es') {
  17753. continue;
  17754. }
  17755. const chunkDep = this.renderedDependencies.get(chunk);
  17756. if (!chunkDep) {
  17757. continue;
  17758. }
  17759. const { imports, reexports } = chunkDep;
  17760. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  17761. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  17762. if (!isImported) {
  17763. continue;
  17764. }
  17765. }
  17766. }
  17767. }
  17768. let expression = null;
  17769. let hoisted = false;
  17770. let local = variable.getName(this.snippets.getPropertyAccess);
  17771. if (variable instanceof LocalVariable) {
  17772. for (const declaration of variable.declarations) {
  17773. if (declaration.parent instanceof FunctionDeclaration ||
  17774. (declaration instanceof ExportDefaultDeclaration &&
  17775. declaration.declaration instanceof FunctionDeclaration)) {
  17776. hoisted = true;
  17777. break;
  17778. }
  17779. }
  17780. }
  17781. else if (variable instanceof SyntheticNamedExportVariable) {
  17782. expression = local;
  17783. if (format === 'es') {
  17784. local = variable.renderName;
  17785. }
  17786. }
  17787. exports.push({
  17788. exported: exportName,
  17789. expression,
  17790. hoisted,
  17791. local
  17792. });
  17793. }
  17794. return exports;
  17795. }
  17796. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  17797. const dependencies = new Set();
  17798. const deconflictedDefault = new Set();
  17799. const deconflictedNamespace = new Set();
  17800. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  17801. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  17802. const module = variable.module;
  17803. if (module instanceof ExternalModule) {
  17804. const chunk = this.externalChunkByModule.get(module);
  17805. dependencies.add(chunk);
  17806. if (addNonNamespacesAndInteropHelpers) {
  17807. if (variable.name === 'default') {
  17808. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  17809. deconflictedDefault.add(chunk);
  17810. }
  17811. }
  17812. else if (variable.isNamespace &&
  17813. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  17814. (this.imports.has(variable) ||
  17815. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  17816. // We only need to deconflict it if the namespace is actually
  17817. // created as a variable, i.e. because it is used internally or
  17818. // because it is reexported as an object
  17819. deconflictedNamespace.add(chunk);
  17820. }
  17821. }
  17822. }
  17823. else {
  17824. const chunk = this.chunkByModule.get(module);
  17825. if (chunk !== this) {
  17826. dependencies.add(chunk);
  17827. if (addNonNamespacesAndInteropHelpers &&
  17828. chunk.exportMode === 'default' &&
  17829. variable.isNamespace) {
  17830. deconflictedNamespace.add(chunk);
  17831. }
  17832. }
  17833. }
  17834. }
  17835. }
  17836. if (addDependenciesWithoutBindings) {
  17837. for (const dependency of this.dependencies) {
  17838. dependencies.add(dependency);
  17839. }
  17840. }
  17841. return { deconflictedDefault, deconflictedNamespace, dependencies };
  17842. }
  17843. getDynamicDependencies() {
  17844. return this.getIncludedDynamicImports()
  17845. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  17846. resolvedDynamicImport.chunk ||
  17847. resolvedDynamicImport.externalChunk ||
  17848. resolvedDynamicImport.resolution)
  17849. .filter((resolution) => resolution !== this &&
  17850. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  17851. }
  17852. getDynamicImportStringAndAttributes(resolution, fileName) {
  17853. if (resolution instanceof ExternalModule) {
  17854. const chunk = this.externalChunkByModule.get(resolution);
  17855. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  17856. }
  17857. return [
  17858. resolution || '',
  17859. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAttributes) || null
  17860. ];
  17861. }
  17862. getFallbackChunkName() {
  17863. if (this.manualChunkAlias) {
  17864. return this.manualChunkAlias;
  17865. }
  17866. if (this.dynamicName) {
  17867. return this.dynamicName;
  17868. }
  17869. if (this.fileName) {
  17870. return parseAst_js.getAliasName(this.fileName);
  17871. }
  17872. return parseAst_js.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  17873. }
  17874. getImportSpecifiers() {
  17875. const { interop } = this.outputOptions;
  17876. const importsByDependency = new Map();
  17877. for (const variable of this.imports) {
  17878. const module = variable.module;
  17879. let dependency;
  17880. let imported;
  17881. if (module instanceof ExternalModule) {
  17882. dependency = this.externalChunkByModule.get(module);
  17883. imported = variable.name;
  17884. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  17885. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, false));
  17886. }
  17887. }
  17888. else {
  17889. dependency = this.chunkByModule.get(module);
  17890. imported = dependency.getVariableExportName(variable);
  17891. }
  17892. getOrCreate(importsByDependency, dependency, getNewArray).push({
  17893. imported,
  17894. local: variable.getName(this.snippets.getPropertyAccess)
  17895. });
  17896. }
  17897. return importsByDependency;
  17898. }
  17899. getIncludedDynamicImports() {
  17900. if (this.includedDynamicImports) {
  17901. return this.includedDynamicImports;
  17902. }
  17903. const includedDynamicImports = [];
  17904. for (const module of this.orderedModules) {
  17905. for (const { node, resolution } of module.dynamicImports) {
  17906. if (!node.included) {
  17907. continue;
  17908. }
  17909. includedDynamicImports.push(resolution instanceof Module
  17910. ? {
  17911. chunk: this.chunkByModule.get(resolution),
  17912. externalChunk: null,
  17913. facadeChunk: this.facadeChunkByModule.get(resolution),
  17914. node,
  17915. resolution
  17916. }
  17917. : resolution instanceof ExternalModule
  17918. ? {
  17919. chunk: null,
  17920. externalChunk: this.externalChunkByModule.get(resolution),
  17921. facadeChunk: null,
  17922. node,
  17923. resolution
  17924. }
  17925. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  17926. }
  17927. }
  17928. return (this.includedDynamicImports = includedDynamicImports);
  17929. }
  17930. getPreRenderedChunkInfo() {
  17931. if (this.preRenderedChunkInfo) {
  17932. return this.preRenderedChunkInfo;
  17933. }
  17934. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  17935. return (this.preRenderedChunkInfo = {
  17936. exports: this.getExportNames(),
  17937. facadeModuleId: facadeModule && facadeModule.id,
  17938. isDynamicEntry: dynamicEntryModules.length > 0,
  17939. isEntry: !!facadeModule?.info.isEntry,
  17940. isImplicitEntry: implicitEntryModules.length > 0,
  17941. moduleIds: orderedModules.map(({ id }) => id),
  17942. name: this.getChunkName(),
  17943. type: 'chunk'
  17944. });
  17945. }
  17946. getPreserveModulesChunkNameFromModule(module) {
  17947. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  17948. if (predefinedChunkName)
  17949. return predefinedChunkName;
  17950. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  17951. const sanitizedId = sanitizeFileName(parseAst_js.normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  17952. const extensionName = path.extname(sanitizedId);
  17953. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  17954. ? sanitizedId.slice(0, -extensionName.length)
  17955. : sanitizedId;
  17956. if (parseAst_js.isAbsolute(idWithoutExtension)) {
  17957. if (preserveModulesRoot && path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)) {
  17958. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  17959. }
  17960. else {
  17961. // handle edge case in Windows
  17962. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  17963. return parseAst_js.relative(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  17964. }
  17965. return parseAst_js.relative(this.inputBase, idWithoutExtension);
  17966. }
  17967. }
  17968. else {
  17969. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + path.basename(idWithoutExtension));
  17970. }
  17971. }
  17972. getReexportSpecifiers() {
  17973. const { externalLiveBindings, interop } = this.outputOptions;
  17974. const reexportSpecifiers = new Map();
  17975. for (let exportName of this.getExportNames()) {
  17976. let dependency;
  17977. let imported;
  17978. let needsLiveBinding = false;
  17979. if (exportName[0] === '*') {
  17980. const id = exportName.slice(1);
  17981. if (interop(id) === 'defaultOnly') {
  17982. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnexpectedNamespaceReexport(id));
  17983. }
  17984. needsLiveBinding = externalLiveBindings;
  17985. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  17986. imported = exportName = '*';
  17987. }
  17988. else {
  17989. const variable = this.exportsByName.get(exportName);
  17990. if (variable instanceof SyntheticNamedExportVariable)
  17991. continue;
  17992. const module = variable.module;
  17993. if (module instanceof Module) {
  17994. dependency = this.chunkByModule.get(module);
  17995. if (dependency === this)
  17996. continue;
  17997. imported = dependency.getVariableExportName(variable);
  17998. needsLiveBinding = variable.isReassigned;
  17999. }
  18000. else {
  18001. dependency = this.externalChunkByModule.get(module);
  18002. imported = variable.name;
  18003. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  18004. return parseAst_js.error(parseAst_js.logUnexpectedNamedImport(module.id, imported, true));
  18005. }
  18006. needsLiveBinding =
  18007. externalLiveBindings &&
  18008. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  18009. }
  18010. }
  18011. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  18012. imported,
  18013. needsLiveBinding,
  18014. reexported: exportName
  18015. });
  18016. }
  18017. return reexportSpecifiers;
  18018. }
  18019. getReferencedFiles() {
  18020. const referencedFiles = new Set();
  18021. for (const module of this.orderedModules) {
  18022. for (const meta of module.importMetas) {
  18023. const fileName = meta.getReferencedFileName(this.pluginDriver);
  18024. if (fileName) {
  18025. referencedFiles.add(fileName);
  18026. }
  18027. }
  18028. }
  18029. return [...referencedFiles];
  18030. }
  18031. getRenderedDependencies() {
  18032. if (this.renderedDependencies) {
  18033. return this.renderedDependencies;
  18034. }
  18035. const importSpecifiers = this.getImportSpecifiers();
  18036. const reexportSpecifiers = this.getReexportSpecifiers();
  18037. const renderedDependencies = new Map();
  18038. const fileName = this.getFileName();
  18039. for (const dependency of this.dependencies) {
  18040. const imports = importSpecifiers.get(dependency) || null;
  18041. const reexports = reexportSpecifiers.get(dependency) || null;
  18042. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  18043. const importPath = dependency.getImportPath(fileName);
  18044. renderedDependencies.set(dependency, {
  18045. attributes: dependency instanceof ExternalChunk
  18046. ? dependency.getImportAttributes(this.snippets)
  18047. : null,
  18048. defaultVariableName: dependency.defaultVariableName,
  18049. globalName: dependency instanceof ExternalChunk &&
  18050. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  18051. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  18052. importPath,
  18053. imports,
  18054. isChunk: dependency instanceof Chunk,
  18055. name: dependency.variableName,
  18056. namedExportsMode,
  18057. namespaceVariableName: dependency.namespaceVariableName,
  18058. reexports
  18059. });
  18060. }
  18061. return (this.renderedDependencies = renderedDependencies);
  18062. }
  18063. inlineChunkDependencies(chunk) {
  18064. for (const dep of chunk.dependencies) {
  18065. if (this.dependencies.has(dep))
  18066. continue;
  18067. this.dependencies.add(dep);
  18068. if (dep instanceof Chunk) {
  18069. this.inlineChunkDependencies(dep);
  18070. }
  18071. }
  18072. }
  18073. // This method changes properties on the AST before rendering and must not be async
  18074. renderModules(fileName) {
  18075. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  18076. const { compact, format, freeze, generatedCode: { symbols } } = outputOptions;
  18077. const { _, cnst, n } = snippets;
  18078. this.setDynamicImportResolutions(fileName);
  18079. this.setImportMetaResolutions(fileName);
  18080. this.setIdentifierRenderResolutions();
  18081. const magicString = new Bundle$1({ separator: `${n}${n}` });
  18082. const indent = getIndentString(orderedModules, outputOptions);
  18083. const usedModules = [];
  18084. let hoistedSource = '';
  18085. const accessedGlobals = new Set();
  18086. const renderedModuleSources = new Map();
  18087. const renderOptions = {
  18088. accessedDocumentCurrentScript: false,
  18089. exportNamesByVariable,
  18090. format,
  18091. freeze,
  18092. indent,
  18093. pluginDriver,
  18094. snippets,
  18095. symbols,
  18096. useOriginalName: null
  18097. };
  18098. let usesTopLevelAwait = false;
  18099. for (const module of orderedModules) {
  18100. let renderedLength = 0;
  18101. let source;
  18102. if (module.isIncluded() || includedNamespaces.has(module)) {
  18103. const rendered = module.render(renderOptions);
  18104. if (!renderOptions.accessedDocumentCurrentScript &&
  18105. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  18106. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  18107. }
  18108. renderOptions.accessedDocumentCurrentScript = false;
  18109. ({ source } = rendered);
  18110. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  18111. renderedLength = source.length();
  18112. if (renderedLength) {
  18113. if (compact && source.lastLine().includes('//'))
  18114. source.append('\n');
  18115. renderedModuleSources.set(module, source);
  18116. magicString.addSource(source);
  18117. usedModules.push(module);
  18118. }
  18119. const namespace = module.namespace;
  18120. if (includedNamespaces.has(module)) {
  18121. const rendered = namespace.renderBlock(renderOptions);
  18122. if (namespace.renderFirst())
  18123. hoistedSource += n + rendered;
  18124. else
  18125. magicString.addSource(new MagicString(rendered));
  18126. }
  18127. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  18128. if (accessedGlobalVariables) {
  18129. for (const name of accessedGlobalVariables) {
  18130. accessedGlobals.add(name);
  18131. }
  18132. }
  18133. }
  18134. const { renderedExports, removedExports } = module.getRenderedExports();
  18135. renderedModules[module.id] = {
  18136. get code() {
  18137. return source?.toString() ?? null;
  18138. },
  18139. originalLength: module.originalCode.length,
  18140. removedExports,
  18141. renderedExports,
  18142. renderedLength
  18143. };
  18144. }
  18145. if (hoistedSource)
  18146. magicString.prepend(hoistedSource + n + n);
  18147. if (this.needsExportsShim) {
  18148. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  18149. }
  18150. const renderedSource = compact ? magicString : magicString.trim();
  18151. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  18152. onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logEmptyChunk(this.getChunkName()));
  18153. }
  18154. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  18155. }
  18156. setDynamicImportResolutions(fileName) {
  18157. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  18158. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  18159. if (resolvedDynamicImport.chunk) {
  18160. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  18161. if (chunk === this) {
  18162. node.setInternalResolution(resolution.namespace);
  18163. }
  18164. else {
  18165. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  18166. }
  18167. }
  18168. else {
  18169. const { node, resolution } = resolvedDynamicImport;
  18170. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName);
  18171. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes);
  18172. }
  18173. }
  18174. }
  18175. setIdentifierRenderResolutions() {
  18176. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  18177. const syntheticExports = new Set();
  18178. for (const exportName of this.getExportNames()) {
  18179. const exportVariable = this.exportsByName.get(exportName);
  18180. if (format !== 'es' &&
  18181. format !== 'system' &&
  18182. exportVariable.isReassigned &&
  18183. !exportVariable.isId) {
  18184. exportVariable.setRenderNames('exports', exportName);
  18185. }
  18186. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  18187. syntheticExports.add(exportVariable);
  18188. }
  18189. else {
  18190. exportVariable.setRenderNames(null, null);
  18191. }
  18192. }
  18193. for (const module of this.orderedModules) {
  18194. if (module.needsExportShim) {
  18195. this.needsExportsShim = true;
  18196. break;
  18197. }
  18198. }
  18199. const usedNames = new Set(['Object', 'Promise']);
  18200. if (this.needsExportsShim) {
  18201. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  18202. }
  18203. if (symbols) {
  18204. usedNames.add('Symbol');
  18205. }
  18206. switch (format) {
  18207. case 'system': {
  18208. usedNames.add('module').add('exports');
  18209. break;
  18210. }
  18211. case 'es': {
  18212. break;
  18213. }
  18214. case 'cjs': {
  18215. usedNames.add('module').add('require').add('__filename').add('__dirname');
  18216. }
  18217. // fallthrough
  18218. default: {
  18219. usedNames.add('exports');
  18220. for (const helper of HELPER_NAMES) {
  18221. usedNames.add(helper);
  18222. }
  18223. }
  18224. }
  18225. 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);
  18226. }
  18227. setImportMetaResolutions(fileName) {
  18228. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  18229. for (const module of orderedModules) {
  18230. for (const importMeta of module.importMetas) {
  18231. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  18232. }
  18233. if (includedNamespaces.has(module)) {
  18234. module.namespace.prepare(accessedGlobalsByScope);
  18235. }
  18236. }
  18237. }
  18238. setUpChunkImportsAndExportsForModule(module) {
  18239. const moduleImports = new Set(module.includedImports);
  18240. // when we are not preserving modules, we need to make all namespace variables available for
  18241. // rendering the namespace object
  18242. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  18243. const memberVariables = module.namespace.getMemberVariables();
  18244. for (const variable of Object.values(memberVariables)) {
  18245. if (variable.included) {
  18246. moduleImports.add(variable);
  18247. }
  18248. }
  18249. }
  18250. for (let variable of moduleImports) {
  18251. if (variable instanceof ExportDefaultVariable) {
  18252. variable = variable.getOriginalVariable();
  18253. }
  18254. if (variable instanceof SyntheticNamedExportVariable) {
  18255. variable = variable.getBaseVariable();
  18256. }
  18257. const chunk = this.chunkByModule.get(variable.module);
  18258. if (chunk !== this) {
  18259. this.imports.add(variable);
  18260. if (variable.module instanceof Module) {
  18261. this.checkCircularDependencyImport(variable, module);
  18262. // When preserving modules, we do not create namespace objects but directly
  18263. // use the actual namespaces, which would be broken by this logic.
  18264. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18265. chunk.exports.add(variable);
  18266. }
  18267. }
  18268. }
  18269. }
  18270. if (this.includedNamespaces.has(module) ||
  18271. (module.info.isEntry && module.preserveSignature !== false) ||
  18272. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  18273. this.ensureReexportsAreAvailableForModule(module);
  18274. }
  18275. for (const { node, resolution } of module.dynamicImports) {
  18276. if (node.included &&
  18277. resolution instanceof Module &&
  18278. this.chunkByModule.get(resolution) === this &&
  18279. !this.includedNamespaces.has(resolution)) {
  18280. this.includedNamespaces.add(resolution);
  18281. this.ensureReexportsAreAvailableForModule(resolution);
  18282. }
  18283. }
  18284. }
  18285. }
  18286. function getChunkNameFromModule(module) {
  18287. return getPredefinedChunkNameFromModule(module) ?? parseAst_js.getAliasName(module.id);
  18288. }
  18289. function getPredefinedChunkNameFromModule(module) {
  18290. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  18291. }
  18292. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  18293. const importedBindingsPerDependency = {};
  18294. for (const [dependency, declaration] of renderedDependencies) {
  18295. const specifiers = new Set();
  18296. if (declaration.imports) {
  18297. for (const { imported } of declaration.imports) {
  18298. specifiers.add(imported);
  18299. }
  18300. }
  18301. if (declaration.reexports) {
  18302. for (const { imported } of declaration.reexports) {
  18303. specifiers.add(imported);
  18304. }
  18305. }
  18306. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  18307. }
  18308. return importedBindingsPerDependency;
  18309. }
  18310. const QUERY_HASH_REGEX = /[#?]/;
  18311. const resolveFileName = (dependency) => dependency.getFileName();
  18312. /**
  18313. * Concatenate a number of iterables to a new iterable without fully evaluating
  18314. * their iterators. Useful when e.g. working with large sets or lists and when
  18315. * there is a chance that the iterators will not be fully exhausted.
  18316. */
  18317. function* concatLazy(iterables) {
  18318. for (const iterable of iterables) {
  18319. yield* iterable;
  18320. }
  18321. }
  18322. /**
  18323. * At its core, the algorithm first starts from each static or dynamic entry
  18324. * point and then assigns that entry point to all modules than can be reached
  18325. * via static imports. We call this the *dependent entry points* of that
  18326. * module.
  18327. *
  18328. * Then we group all modules with the same dependent entry points into chunks
  18329. * as those modules will always be loaded together.
  18330. *
  18331. * One non-trivial optimization we can apply is that dynamic entries are
  18332. * different from static entries in so far as when a dynamic import occurs,
  18333. * some modules are already in memory. If some of these modules are also
  18334. * dependencies of the dynamic entry, then it does not make sense to create a
  18335. * separate chunk for them. Instead, the dynamic import target can load them
  18336. * from the importing chunk.
  18337. *
  18338. * With regard to chunking, if B is implicitly loaded after A, then this can be
  18339. * handled the same way as if there was a dynamic import A => B.
  18340. *
  18341. * Example:
  18342. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  18343. * Then the initial algorithm would assign A into the A chunk, C into the C
  18344. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  18345. * points A and C.
  18346. * However we know that C can only be loaded from A, so A and its dependency B
  18347. * must already be in memory when C is loaded. So it is enough to create only
  18348. * two chunks A containing [AB] and C containing [C].
  18349. *
  18350. * So we do not assign the dynamic entry C as dependent entry point to modules
  18351. * that are already loaded.
  18352. *
  18353. * In a more complex example, let us assume that we have entry points X and Y.
  18354. * Further, let us assume
  18355. * X -> A, X -> B, X -> C,
  18356. * Y -> A, Y -> B,
  18357. * A => D,
  18358. * D -> B, D -> C
  18359. * So without dynamic import optimization, the dependent entry points are
  18360. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  18361. * chunks.
  18362. *
  18363. * Now D is loaded only after A is loaded. But A is loaded if either X is
  18364. * loaded or Y is loaded. So the modules that are already in memory when D is
  18365. * loaded are the intersection of all modules that X depends on with all
  18366. * modules that Y depends on, which in this case are the modules A and B.
  18367. * We could also say they are all modules that have both X and Y as dependent
  18368. * entry points.
  18369. *
  18370. * So we can remove D as dependent entry point from A and B, which means they
  18371. * both now have only XY as dependent entry points and can be merged into the
  18372. * same chunk.
  18373. *
  18374. * Now let us extend this to the most general case where we have several
  18375. * dynamic importers for one dynamic entry point.
  18376. *
  18377. * In the most general form, it works like this:
  18378. * For each dynamic entry point, we have a number of dynamic importers, which
  18379. * are the modules importing it. Using the previous ideas, we can determine
  18380. * the modules already in memory for each dynamic importer by looking for all
  18381. * modules that have all the dependent entry points of the dynamic importer as
  18382. * dependent entry points.
  18383. * So the modules that are guaranteed to be in memory when the dynamic entry
  18384. * point is loaded are the intersection of the modules already in memory for
  18385. * each dynamic importer.
  18386. *
  18387. * Assuming that A => D and B => D and A has dependent entry points XY and B
  18388. * has dependent entry points YZ, then the modules guaranteed to be in memory
  18389. * are all modules that have at least XYZ as dependent entry points.
  18390. * We call XYZ the *dynamically dependent entry points* of D.
  18391. *
  18392. * Now there is one last case to consider: If one of the dynamically dependent
  18393. * entries is itself a dynamic entry, then any module is in memory that either
  18394. * is a dependency of that dynamic entry or again has the dynamic dependent
  18395. * entries of that dynamic entry as dependent entry points.
  18396. *
  18397. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  18398. * complexity with regard to dynamic entries that blew up for very large
  18399. * projects.
  18400. *
  18401. * If we have an efficient way to do Set operations, an alternative approach
  18402. * would be to instead collect already loaded modules per dynamic entry. And as
  18403. * all chunks from the initial grouping would behave the same, we can instead
  18404. * collect already loaded chunks for a performance improvement.
  18405. *
  18406. * To do that efficiently, need
  18407. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  18408. * imports that can be triggered by a dynamic entry
  18409. * - a Map of static dependencies per entry
  18410. * - a Map of already loaded chunks per entry that we initially populate with
  18411. * empty Sets for static entries and Sets containing all entries for dynamic
  18412. * entries
  18413. *
  18414. * For efficient operations, we assign each entry a numerical index and
  18415. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  18416. * bit index. Then the last two maps can be represented as arrays of BigInt
  18417. * values.
  18418. *
  18419. * Then we iterate through each dynamic entry. We set the already loaded modules
  18420. * to the intersection of the previously already loaded modules with the union
  18421. * of the already loaded modules of that chunk with its static dependencies.
  18422. *
  18423. * If the already loaded modules changed, then we use the Map of dynamic imports
  18424. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  18425. * them back into the iteration. As an additional optimization, we note for
  18426. * each dynamic entry which dynamic dependent entries have changed and only
  18427. * intersect those entries again on subsequent interations.
  18428. *
  18429. * Then we remove the dynamic entries from the list of dependent entries for
  18430. * those chunks that are already loaded for that dynamic entry and create
  18431. * another round of chunks.
  18432. */
  18433. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  18434. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  18435. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  18436. // Each chunk is identified by its position in this array
  18437. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  18438. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  18439. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18440. // If we no longer want this, we should make a copy here.
  18441. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  18442. // This mutates the dependentEntries in chunkAtoms
  18443. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry);
  18444. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  18445. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  18446. alias: null,
  18447. modules
  18448. })));
  18449. return chunkDefinitions;
  18450. }
  18451. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  18452. const chunkDefinitions = [];
  18453. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  18454. const manualChunkModulesByAlias = Object.create(null);
  18455. for (const [entry, alias] of manualChunkAliasByEntry) {
  18456. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  18457. }
  18458. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  18459. chunkDefinitions.push({ alias, modules });
  18460. }
  18461. return { chunkDefinitions, modulesInManualChunks };
  18462. }
  18463. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  18464. const modulesToHandle = new Set([entry]);
  18465. for (const module of modulesToHandle) {
  18466. modulesInManualChunks.add(module);
  18467. manualChunkModules.push(module);
  18468. for (const dependency of module.dependencies) {
  18469. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  18470. modulesToHandle.add(dependency);
  18471. }
  18472. }
  18473. }
  18474. }
  18475. function analyzeModuleGraph(entries) {
  18476. const dynamicEntryModules = new Set();
  18477. const dependentEntriesByModule = new Map();
  18478. const dynamicImportModulesByEntry = [];
  18479. const allEntriesSet = new Set(entries);
  18480. let entryIndex = 0;
  18481. for (const currentEntry of allEntriesSet) {
  18482. const dynamicImportsForCurrentEntry = new Set();
  18483. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  18484. const modulesToHandle = new Set([currentEntry]);
  18485. for (const module of modulesToHandle) {
  18486. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  18487. for (const dependency of module.getDependenciesToBeIncluded()) {
  18488. if (!(dependency instanceof ExternalModule)) {
  18489. modulesToHandle.add(dependency);
  18490. }
  18491. }
  18492. for (const { resolution } of module.dynamicImports) {
  18493. if (resolution instanceof Module &&
  18494. resolution.includedDynamicImporters.length > 0 &&
  18495. !allEntriesSet.has(resolution)) {
  18496. dynamicEntryModules.add(resolution);
  18497. allEntriesSet.add(resolution);
  18498. dynamicImportsForCurrentEntry.add(resolution);
  18499. }
  18500. }
  18501. for (const dependency of module.implicitlyLoadedBefore) {
  18502. if (!allEntriesSet.has(dependency)) {
  18503. dynamicEntryModules.add(dependency);
  18504. allEntriesSet.add(dependency);
  18505. }
  18506. }
  18507. }
  18508. entryIndex++;
  18509. }
  18510. const allEntries = [...allEntriesSet];
  18511. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  18512. return {
  18513. allEntries,
  18514. dependentEntriesByModule,
  18515. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  18516. dynamicImportsByEntry
  18517. };
  18518. }
  18519. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  18520. const entryIndexByModule = new Map();
  18521. const dynamicEntries = new Set();
  18522. for (const [entryIndex, entry] of allEntries.entries()) {
  18523. entryIndexByModule.set(entry, entryIndex);
  18524. if (dynamicEntryModules.has(entry)) {
  18525. dynamicEntries.add(entryIndex);
  18526. }
  18527. }
  18528. const dynamicImportsByEntry = [];
  18529. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  18530. const dynamicImports = new Set();
  18531. for (const dynamicEntry of dynamicImportModules) {
  18532. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  18533. }
  18534. dynamicImportsByEntry.push(dynamicImports);
  18535. }
  18536. return { dynamicEntries, dynamicImportsByEntry };
  18537. }
  18538. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  18539. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  18540. for (const dynamicEntryIndex of dynamicEntries) {
  18541. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  18542. const dynamicEntry = allEntries[dynamicEntryIndex];
  18543. for (const importer of concatLazy([
  18544. dynamicEntry.includedDynamicImporters,
  18545. dynamicEntry.implicitlyLoadedAfter
  18546. ])) {
  18547. for (const entry of dependentEntriesByModule.get(importer)) {
  18548. dynamicallyDependentEntries.add(entry);
  18549. }
  18550. }
  18551. }
  18552. return dynamicallyDependentEntriesByDynamicEntry;
  18553. }
  18554. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  18555. const chunkModules = Object.create(null);
  18556. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  18557. let chunkSignature = 0n;
  18558. for (const entryIndex of dependentEntries) {
  18559. chunkSignature |= 1n << BigInt(entryIndex);
  18560. }
  18561. (chunkModules[String(chunkSignature)] ||= {
  18562. dependentEntries: new Set(dependentEntries),
  18563. modules: []
  18564. }).modules.push(...modules);
  18565. }
  18566. return Object.values(chunkModules);
  18567. }
  18568. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  18569. for (const [module, dependentEntries] of dependentEntriesByModule) {
  18570. if (!modulesInManualChunks.has(module)) {
  18571. yield { dependentEntries, modules: [module] };
  18572. }
  18573. }
  18574. }
  18575. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  18576. // The indices correspond to the indices in allEntries. The atoms correspond
  18577. // to bits in the bigint values where chunk 0 is the lowest bit.
  18578. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  18579. // This toggles the bits for each atom that is a dependency of an entry
  18580. let atomMask = 1n;
  18581. for (const { dependentEntries } of chunkAtoms) {
  18582. for (const entryIndex of dependentEntries) {
  18583. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  18584. }
  18585. atomMask <<= 1n;
  18586. }
  18587. return staticDependencyAtomsByEntry;
  18588. }
  18589. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18590. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  18591. // Dynamic entries have all atoms as already loaded initially because we then
  18592. // intersect with the static dependency atoms of all dynamic importers.
  18593. // Static entries cannot have already loaded atoms.
  18594. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  18595. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  18596. // We delete here so that they can be added again if necessary to be handled
  18597. // again by the loop
  18598. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  18599. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  18600. let updatedLoadedAtoms = knownLoadedAtoms;
  18601. for (const entryIndex of dynamicallyDependentEntries) {
  18602. updatedLoadedAtoms &=
  18603. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18604. }
  18605. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  18606. // updated again
  18607. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  18608. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  18609. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  18610. // If this adds an entry that was deleted before, it will be handled
  18611. // again. This is the reason why we delete every entry from this map
  18612. // that we processed.
  18613. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  18614. }
  18615. }
  18616. }
  18617. return alreadyLoadedAtomsByEntry;
  18618. }
  18619. /**
  18620. * This removes all unnecessary dynamic entries from the dependentEntries in its
  18621. * first argument if a chunk is already loaded without that entry.
  18622. */
  18623. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry) {
  18624. // Remove entries from dependent entries if a chunk is already loaded without
  18625. // that entry.
  18626. let chunkMask = 1n;
  18627. for (const { dependentEntries } of chunkAtoms) {
  18628. for (const entryIndex of dependentEntries) {
  18629. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask) {
  18630. dependentEntries.delete(entryIndex);
  18631. }
  18632. }
  18633. chunkMask <<= 1n;
  18634. }
  18635. }
  18636. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  18637. const chunksBySignature = Object.create(null);
  18638. const chunkByModule = new Map();
  18639. const sizeByAtom = [];
  18640. let sideEffectAtoms = 0n;
  18641. let atomMask = 1n;
  18642. for (const { dependentEntries, modules } of chunkAtoms) {
  18643. let chunkSignature = 0n;
  18644. let correlatedAtoms = -1n;
  18645. for (const entryIndex of dependentEntries) {
  18646. chunkSignature |= 1n << BigInt(entryIndex);
  18647. // Correlated atoms are the atoms that are guaranteed to be loaded as
  18648. // well when a given atom is loaded. It is the intersection of the already
  18649. // loaded modules of each chunk merged with its static dependencies.
  18650. correlatedAtoms &=
  18651. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  18652. }
  18653. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  18654. containedAtoms: 0n,
  18655. correlatedAtoms,
  18656. dependencies: new Set(),
  18657. dependentChunks: new Set(),
  18658. dependentEntries: new Set(dependentEntries),
  18659. modules: [],
  18660. pure: true,
  18661. size: 0
  18662. });
  18663. let atomSize = 0;
  18664. let pure = true;
  18665. for (const module of modules) {
  18666. chunkByModule.set(module, chunk);
  18667. // Unfortunately, we cannot take tree-shaking into account here because
  18668. // rendering did not happen yet, but we can detect empty modules
  18669. if (module.isIncluded()) {
  18670. pure &&= !module.hasEffects();
  18671. // we use a trivial size for the default minChunkSize to improve
  18672. // performance
  18673. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  18674. }
  18675. }
  18676. if (!pure) {
  18677. sideEffectAtoms |= atomMask;
  18678. }
  18679. sizeByAtom.push(atomSize);
  18680. chunk.containedAtoms |= atomMask;
  18681. chunk.modules.push(...modules);
  18682. chunk.pure &&= pure;
  18683. chunk.size += atomSize;
  18684. atomMask <<= 1n;
  18685. }
  18686. const chunks = Object.values(chunksBySignature);
  18687. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  18688. return { chunks, sideEffectAtoms, sizeByAtom };
  18689. }
  18690. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  18691. const signatureByExternalModule = new Map();
  18692. let externalSideEffectAtoms = 0n;
  18693. for (const chunk of chunks) {
  18694. const { dependencies, modules } = chunk;
  18695. for (const module of modules) {
  18696. for (const dependency of module.getDependenciesToBeIncluded()) {
  18697. if (dependency instanceof ExternalModule) {
  18698. if (dependency.info.moduleSideEffects) {
  18699. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  18700. const signature = nextAvailableAtomMask;
  18701. nextAvailableAtomMask <<= 1n;
  18702. externalSideEffectAtoms |= signature;
  18703. return signature;
  18704. });
  18705. chunk.containedAtoms |= signature;
  18706. chunk.correlatedAtoms |= signature;
  18707. }
  18708. }
  18709. else {
  18710. const dependencyChunk = chunkByModule.get(dependency);
  18711. if (dependencyChunk && dependencyChunk !== chunk) {
  18712. dependencies.add(dependencyChunk);
  18713. dependencyChunk.dependentChunks.add(chunk);
  18714. }
  18715. }
  18716. }
  18717. }
  18718. }
  18719. return externalSideEffectAtoms;
  18720. }
  18721. /**
  18722. * This function tries to get rid of small chunks by merging them with other
  18723. * chunks.
  18724. *
  18725. * We can only merge chunks safely if after the merge, loading any entry point
  18726. * in any allowed order will not trigger side effects that should not have been
  18727. * triggered. While side effects are usually things like global function calls,
  18728. * global variable mutations or potentially thrown errors, details do not
  18729. * matter here, and we just discern chunks without side effects (pure chunks)
  18730. * from other chunks.
  18731. *
  18732. * As a first step, we assign each pre-generated chunk with side effects a
  18733. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  18734. *
  18735. * Now to determine the side effects of loading a chunk, one also has to take
  18736. * the side effects of its dependencies into account. So if A depends on B
  18737. * (A -> B) and both have side effects, loading A triggers effects AB.
  18738. *
  18739. * Now from the previous step we know that each chunk is uniquely determine by
  18740. * the entry points that depend on it and cause it to load, which we will call
  18741. * its dependent entry points.
  18742. *
  18743. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  18744. * Starting from that idea, we can determine a set of chunks—and thus a set
  18745. * of side effects—that must have been triggered if a certain chunk has been
  18746. * loaded. Basically, it is the intersection of all chunks loaded by the
  18747. * dependent entry points of a given chunk. We call the corresponding side
  18748. * effects the correlated side effects of that chunk.
  18749. *
  18750. * Example:
  18751. * X -> ABC, Y -> ADE, A-> F, B -> D
  18752. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  18753. * The intersection is ADF. So we know that when A is loaded, D and F must also
  18754. * be in memory even though neither D nor A is a dependency of the other.
  18755. * If all have side effects, we call ADF the correlated side effects of A. The
  18756. * correlated side effects need to remain constant when merging chunks.
  18757. *
  18758. * In contrast, we have the dependency side effects of A, which represents
  18759. * the side effects we trigger if we directly load A. In this example, the
  18760. * dependency side effects are AF.
  18761. * For entry chunks, dependency and correlated side effects are the same.
  18762. *
  18763. * With these concepts, merging chunks is allowed if the correlated side
  18764. * effects of each entry do not change. Thus, we are allowed to merge two
  18765. * chunks if
  18766. *
  18767. * a) the dependency side effects of each chunk are a subset of the correlated
  18768. * side effects of the other chunk, so no additional side effects are
  18769. * triggered for any entry, or
  18770. * b) The dependent entry points of chunk A are a subset of the dependent entry
  18771. * points of chunk B while the dependency side effects of A are a subset of
  18772. * the correlated side effects of B. Because in that scenario, whenever A is
  18773. * loaded, B is loaded as well. But there are cases when B is loaded where A
  18774. * is not loaded. So if we merge the chunks, all dependency side effects of
  18775. * A will be added to the correlated side effects of B, and as the latter is
  18776. * not allowed to change, the former need to be a subset of the latter.
  18777. *
  18778. * Another consideration when merging small chunks into other chunks is to
  18779. * avoid
  18780. * that too much additional code is loaded. This is achieved when the dependent
  18781. * entries of the small chunk are a subset of the dependent entries of the
  18782. * other
  18783. * chunk. Because then when the small chunk is loaded, the other chunk was
  18784. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  18785. * additional size of the small chunk is loaded unnecessarily.
  18786. *
  18787. * So the algorithm performs merges in two passes:
  18788. *
  18789. * 1. First we try to merge small chunks A only into other chunks B if the
  18790. * dependent entries of A are a subset of the dependent entries of B and the
  18791. * dependency side effects of A are a subset of the correlated side effects
  18792. * of B.
  18793. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  18794. * following the rule (a), starting with the smallest chunks to look for
  18795. * possible merge targets.
  18796. */
  18797. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  18798. timeStart('optimize chunks', 3);
  18799. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  18800. if (!chunkPartition) {
  18801. timeEnd('optimize chunks', 3);
  18802. return chunks; // the actual modules
  18803. }
  18804. if (minChunkSize > 1) {
  18805. log('info', parseAst_js.logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  18806. }
  18807. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  18808. if (minChunkSize > 1) {
  18809. log('info', parseAst_js.logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  18810. }
  18811. timeEnd('optimize chunks', 3);
  18812. return [...chunkPartition.small, ...chunkPartition.big];
  18813. }
  18814. function getPartitionedChunks(chunks, minChunkSize) {
  18815. const smallChunks = [];
  18816. const bigChunks = [];
  18817. for (const chunk of chunks) {
  18818. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  18819. }
  18820. if (smallChunks.length === 0) {
  18821. return null;
  18822. }
  18823. smallChunks.sort(compareChunkSize);
  18824. bigChunks.sort(compareChunkSize);
  18825. return {
  18826. big: new Set(bigChunks),
  18827. small: new Set(smallChunks)
  18828. };
  18829. }
  18830. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  18831. return sizeA - sizeB;
  18832. }
  18833. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  18834. const { small } = chunkPartition;
  18835. for (const mergedChunk of small) {
  18836. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  18837. // In the default case, we do not accept size increases
  18838. minChunkSize <= 1 ? 1 : Infinity);
  18839. if (bestTargetChunk) {
  18840. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  18841. small.delete(mergedChunk);
  18842. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  18843. bestTargetChunk.modules.push(...modules);
  18844. bestTargetChunk.size += size;
  18845. bestTargetChunk.pure &&= pure;
  18846. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  18847. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  18848. bestTargetChunk.containedAtoms |= containedAtoms;
  18849. for (const entry of mergedChunk.dependentEntries) {
  18850. dependentEntries.add(entry);
  18851. }
  18852. for (const dependency of mergedChunk.dependencies) {
  18853. dependencies.add(dependency);
  18854. dependency.dependentChunks.delete(mergedChunk);
  18855. dependency.dependentChunks.add(bestTargetChunk);
  18856. }
  18857. for (const dependentChunk of mergedChunk.dependentChunks) {
  18858. dependentChunks.add(dependentChunk);
  18859. dependentChunk.dependencies.delete(mergedChunk);
  18860. dependentChunk.dependencies.add(bestTargetChunk);
  18861. }
  18862. dependencies.delete(bestTargetChunk);
  18863. dependentChunks.delete(bestTargetChunk);
  18864. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  18865. }
  18866. }
  18867. }
  18868. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  18869. let bestTargetChunk = null;
  18870. // In the default case, we do not accept size increases
  18871. for (const targetChunk of concatLazy([small, big])) {
  18872. if (mergedChunk === targetChunk)
  18873. continue;
  18874. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  18875. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  18876. bestTargetChunk = targetChunk;
  18877. if (additionalSizeAfterMerge === 0)
  18878. break;
  18879. smallestAdditionalSize = additionalSizeAfterMerge;
  18880. }
  18881. }
  18882. return bestTargetChunk;
  18883. }
  18884. /**
  18885. * Determine the additional unused code size that would be added by merging the
  18886. * two chunks. This is not an exact measurement but rather an upper bound. If
  18887. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  18888. * is returned.
  18889. * Merging will not produce cycles if none of the direct non-merged
  18890. * dependencies of a chunk have the other chunk as a transitive dependency.
  18891. */
  18892. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  18893. // The maximum additional unused code size allowed to be added by the merge,
  18894. // taking dependencies into account, needs to be below this number
  18895. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18896. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  18897. return firstSize < currentAdditionalSize
  18898. ? firstSize +
  18899. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  18900. : Infinity;
  18901. }
  18902. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  18903. const { correlatedAtoms } = dependencyChunk;
  18904. let dependencyAtoms = dependentChunk.containedAtoms;
  18905. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  18906. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  18907. return Infinity;
  18908. }
  18909. const chunksToCheck = new Set(dependentChunk.dependencies);
  18910. for (const { dependencies, containedAtoms } of chunksToCheck) {
  18911. dependencyAtoms |= containedAtoms;
  18912. const containedSideEffects = containedAtoms & sideEffectAtoms;
  18913. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  18914. return Infinity;
  18915. }
  18916. for (const dependency of dependencies) {
  18917. if (dependency === dependencyChunk) {
  18918. return Infinity;
  18919. }
  18920. chunksToCheck.add(dependency);
  18921. }
  18922. }
  18923. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  18924. }
  18925. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  18926. let size = 0;
  18927. let atomIndex = 0;
  18928. let atomSignature = 1n;
  18929. const { length } = sizeByAtom;
  18930. for (; atomIndex < length; atomIndex++) {
  18931. if ((atoms & atomSignature) === atomSignature) {
  18932. size += sizeByAtom[atomIndex];
  18933. }
  18934. atomSignature <<= 1n;
  18935. if (size >= currentAdditionalSize) {
  18936. return Infinity;
  18937. }
  18938. }
  18939. return size;
  18940. }
  18941. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  18942. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  18943. }
  18944. // ported from https://github.com/substack/node-commondir
  18945. function commondir(files) {
  18946. if (files.length === 0)
  18947. return '/';
  18948. if (files.length === 1)
  18949. return path.dirname(files[0]);
  18950. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  18951. const pathSegments = file.split(/\/+|\\+/);
  18952. let index;
  18953. for (index = 0; commonSegments[index] === pathSegments[index] &&
  18954. index < Math.min(commonSegments.length, pathSegments.length); index++)
  18955. ;
  18956. return commonSegments.slice(0, index);
  18957. }, files[0].split(/\/+|\\+/));
  18958. // Windows correctly handles paths with forward-slashes
  18959. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  18960. }
  18961. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  18962. function sortByExecutionOrder(units) {
  18963. units.sort(compareExecIndex);
  18964. }
  18965. // This process is currently faulty in so far as it only takes the first entry
  18966. // module into account and assumes that dynamic imports are imported in a
  18967. // certain order.
  18968. // A better algorithm would follow every possible execution path and mark which
  18969. // modules are executed before or after which other modules. THen the chunking
  18970. // would need to take care that in each chunk, all modules are always executed
  18971. // in the same sequence.
  18972. function analyseModuleExecution(entryModules) {
  18973. let nextExecIndex = 0;
  18974. const cyclePaths = [];
  18975. const analysedModules = new Set();
  18976. const dynamicImports = new Set();
  18977. const parents = new Map();
  18978. const orderedModules = [];
  18979. const analyseModule = (module) => {
  18980. if (module instanceof Module) {
  18981. for (const dependency of module.dependencies) {
  18982. if (parents.has(dependency)) {
  18983. if (!analysedModules.has(dependency)) {
  18984. cyclePaths.push(getCyclePath(dependency, module, parents));
  18985. }
  18986. continue;
  18987. }
  18988. parents.set(dependency, module);
  18989. analyseModule(dependency);
  18990. }
  18991. for (const dependency of module.implicitlyLoadedBefore) {
  18992. dynamicImports.add(dependency);
  18993. }
  18994. for (const { resolution } of module.dynamicImports) {
  18995. if (resolution instanceof Module) {
  18996. dynamicImports.add(resolution);
  18997. }
  18998. }
  18999. orderedModules.push(module);
  19000. }
  19001. module.execIndex = nextExecIndex++;
  19002. analysedModules.add(module);
  19003. };
  19004. for (const currentEntry of entryModules) {
  19005. if (!parents.has(currentEntry)) {
  19006. parents.set(currentEntry, null);
  19007. analyseModule(currentEntry);
  19008. }
  19009. }
  19010. for (const currentEntry of dynamicImports) {
  19011. if (!parents.has(currentEntry)) {
  19012. parents.set(currentEntry, null);
  19013. analyseModule(currentEntry);
  19014. }
  19015. }
  19016. return { cyclePaths, orderedModules };
  19017. }
  19018. function getCyclePath(module, parent, parents) {
  19019. const cycleSymbol = Symbol(module.id);
  19020. const path = [module.id];
  19021. let nextModule = parent;
  19022. module.cycles.add(cycleSymbol);
  19023. while (nextModule !== module) {
  19024. nextModule.cycles.add(cycleSymbol);
  19025. path.push(nextModule.id);
  19026. nextModule = parents.get(nextModule);
  19027. }
  19028. path.push(path[0]);
  19029. path.reverse();
  19030. return path;
  19031. }
  19032. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  19033. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  19034. const cnst = constBindings ? 'const' : 'var';
  19035. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  19036. const getFunctionIntro = arrowFunctions
  19037. ? (parameters, { isAsync, name }) => {
  19038. const singleParameter = parameters.length === 1;
  19039. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  19040. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  19041. }
  19042. : getNonArrowFunctionIntro;
  19043. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  19044. `${getFunctionIntro(parameters, {
  19045. isAsync: false,
  19046. name
  19047. })}${arrowFunctions
  19048. ? lineBreakIndent
  19049. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  19050. : ''
  19051. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  19052. arrowFunctions
  19053. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  19054. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  19055. ];
  19056. const isValidPropertyName = reservedNamesAsProps
  19057. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  19058. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  19059. return {
  19060. _,
  19061. cnst,
  19062. getDirectReturnFunction,
  19063. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  19064. const [left, right] = getDirectReturnFunction(parameters, {
  19065. functionReturn: true,
  19066. lineBreakIndent: null,
  19067. name: null
  19068. });
  19069. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  19070. },
  19071. getFunctionIntro,
  19072. getNonArrowFunctionIntro,
  19073. getObject(fields, { lineBreakIndent }) {
  19074. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  19075. return `{${fields
  19076. .map(([key, value]) => {
  19077. if (key === null)
  19078. return `${prefix}${value}`;
  19079. const keyInObject = stringifyObjectKeyIfNeeded(key);
  19080. return key === value && objectShorthand && key === keyInObject
  19081. ? prefix + key
  19082. : `${prefix}${keyInObject}:${_}${value}`;
  19083. })
  19084. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  19085. },
  19086. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  19087. n,
  19088. s
  19089. };
  19090. }
  19091. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  19092. class Source {
  19093. constructor(filename, content) {
  19094. this.isOriginal = true;
  19095. this.filename = filename;
  19096. this.content = content;
  19097. }
  19098. traceSegment(line, column, name) {
  19099. return { column, line, name, source: this };
  19100. }
  19101. }
  19102. class Link {
  19103. constructor(map, sources) {
  19104. this.sources = sources;
  19105. this.names = map.names;
  19106. this.mappings = map.mappings;
  19107. }
  19108. traceMappings() {
  19109. const sources = [];
  19110. const sourceIndexMap = new Map();
  19111. const sourcesContent = [];
  19112. const names = [];
  19113. const nameIndexMap = new Map();
  19114. const mappings = [];
  19115. for (const line of this.mappings) {
  19116. const tracedLine = [];
  19117. for (const segment of line) {
  19118. if (segment.length === 1)
  19119. continue;
  19120. const source = this.sources[segment[1]];
  19121. if (!source)
  19122. continue;
  19123. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  19124. if (traced) {
  19125. const { column, line, name, source: { content, filename } } = traced;
  19126. let sourceIndex = sourceIndexMap.get(filename);
  19127. if (sourceIndex === undefined) {
  19128. sourceIndex = sources.length;
  19129. sources.push(filename);
  19130. sourceIndexMap.set(filename, sourceIndex);
  19131. sourcesContent[sourceIndex] = content;
  19132. }
  19133. else if (sourcesContent[sourceIndex] == null) {
  19134. sourcesContent[sourceIndex] = content;
  19135. }
  19136. else if (content != null && sourcesContent[sourceIndex] !== content) {
  19137. return parseAst_js.error(parseAst_js.logConflictingSourcemapSources(filename));
  19138. }
  19139. const tracedSegment = [segment[0], sourceIndex, line, column];
  19140. if (name) {
  19141. let nameIndex = nameIndexMap.get(name);
  19142. if (nameIndex === undefined) {
  19143. nameIndex = names.length;
  19144. names.push(name);
  19145. nameIndexMap.set(name, nameIndex);
  19146. }
  19147. tracedSegment[4] = nameIndex;
  19148. }
  19149. tracedLine.push(tracedSegment);
  19150. }
  19151. }
  19152. mappings.push(tracedLine);
  19153. }
  19154. return { mappings, names, sources, sourcesContent };
  19155. }
  19156. traceSegment(line, column, name) {
  19157. const segments = this.mappings[line];
  19158. if (!segments)
  19159. return null;
  19160. // binary search through segments for the given column
  19161. let searchStart = 0;
  19162. let searchEnd = segments.length - 1;
  19163. while (searchStart <= searchEnd) {
  19164. const m = (searchStart + searchEnd) >> 1;
  19165. const segment = segments[m];
  19166. // If a sourcemap does not have sufficient resolution to contain a
  19167. // necessary mapping, e.g. because it only contains line information, we
  19168. // use the best approximation we could find
  19169. if (segment[0] === column || searchStart === searchEnd) {
  19170. if (segment.length == 1)
  19171. return null;
  19172. const source = this.sources[segment[1]];
  19173. if (!source)
  19174. return null;
  19175. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  19176. }
  19177. if (segment[0] > column) {
  19178. searchEnd = m - 1;
  19179. }
  19180. else {
  19181. searchStart = m + 1;
  19182. }
  19183. }
  19184. return null;
  19185. }
  19186. }
  19187. function getLinkMap(log) {
  19188. return function linkMap(source, map) {
  19189. if (!map.missing) {
  19190. return new Link(map, [source]);
  19191. }
  19192. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logSourcemapBroken(map.plugin));
  19193. return new Link({
  19194. mappings: [],
  19195. names: []
  19196. }, [source]);
  19197. };
  19198. }
  19199. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  19200. let source;
  19201. if (originalSourcemap) {
  19202. const sources = originalSourcemap.sources;
  19203. const sourcesContent = originalSourcemap.sourcesContent || [];
  19204. const directory = path.dirname(id) || '.';
  19205. const sourceRoot = originalSourcemap.sourceRoot || '.';
  19206. const baseSources = sources.map((source, index) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  19207. source = new Link(originalSourcemap, baseSources);
  19208. }
  19209. else {
  19210. source = new Source(id, originalCode);
  19211. }
  19212. return sourcemapChain.reduce(linkMap, source);
  19213. }
  19214. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  19215. const linkMap = getLinkMap(log);
  19216. const moduleSources = modules
  19217. .filter(module => !module.excludeFromSourcemap)
  19218. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  19219. const link = new Link(map, moduleSources);
  19220. const source = bundleSourcemapChain.reduce(linkMap, link);
  19221. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  19222. if (file) {
  19223. const directory = path.dirname(file);
  19224. sources = sources.map((source) => path.relative(directory, source));
  19225. file = path.basename(file);
  19226. }
  19227. sourcesContent = (excludeContent ? null : sourcesContent);
  19228. for (const module of modules) {
  19229. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  19230. }
  19231. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  19232. }
  19233. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  19234. if (sourcemapChain.length === 0) {
  19235. return originalSourcemap;
  19236. }
  19237. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  19238. const map = source.traceMappings();
  19239. return decodedSourcemap({ version: 3, ...map });
  19240. }
  19241. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  19242. // this for an actual sourceMappingURL
  19243. let SOURCEMAPPING_URL = 'sourceMa';
  19244. SOURCEMAPPING_URL += 'ppingURL';
  19245. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  19246. timeStart('render chunks', 2);
  19247. reserveEntryChunksInBundle(chunks);
  19248. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  19249. timeEnd('render chunks', 2);
  19250. timeStart('transform chunks', 2);
  19251. const getHash = hasherByType[outputOptions.hashCharacters];
  19252. const chunkGraph = getChunkGraph(chunks);
  19253. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  19254. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  19255. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  19256. timeEnd('transform chunks', 2);
  19257. }
  19258. function reserveEntryChunksInBundle(chunks) {
  19259. for (const chunk of chunks) {
  19260. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  19261. // reserves name in bundle as side effect if it does not contain a hash
  19262. chunk.getPreliminaryFileName();
  19263. }
  19264. }
  19265. }
  19266. function getChunkGraph(chunks) {
  19267. return Object.fromEntries(chunks.map(chunk => {
  19268. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  19269. return [renderedChunkInfo.fileName, renderedChunkInfo];
  19270. }));
  19271. }
  19272. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  19273. let map = null;
  19274. const sourcemapChain = [];
  19275. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  19276. if (result == null)
  19277. return code;
  19278. if (typeof result === 'string')
  19279. result = {
  19280. code: result,
  19281. map: undefined
  19282. };
  19283. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  19284. if (result.map !== null) {
  19285. const map = decodedSourcemap(result.map);
  19286. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  19287. }
  19288. return result.code;
  19289. });
  19290. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  19291. if (!compact && code[code.length - 1] !== '\n')
  19292. code += '\n';
  19293. if (sourcemap) {
  19294. timeStart('sourcemaps', 3);
  19295. let resultingFile;
  19296. if (file)
  19297. resultingFile = path.resolve(sourcemapFile || file);
  19298. else if (dir)
  19299. resultingFile = path.resolve(dir, fileName);
  19300. else
  19301. resultingFile = path.resolve(fileName);
  19302. const decodedMap = magicString.generateDecodedMap({});
  19303. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  19304. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19305. let sourcePath = map.sources[sourcesIndex];
  19306. const sourcemapPath = `${resultingFile}.map`;
  19307. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  19308. if (typeof ignoreList !== 'boolean') {
  19309. parseAst_js.error(parseAst_js.logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  19310. }
  19311. if (ignoreList) {
  19312. if (map.x_google_ignoreList === undefined) {
  19313. map.x_google_ignoreList = [];
  19314. }
  19315. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  19316. map.x_google_ignoreList.push(sourcesIndex);
  19317. }
  19318. }
  19319. if (sourcemapPathTransform) {
  19320. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  19321. if (typeof sourcePath !== 'string') {
  19322. parseAst_js.error(parseAst_js.logFailedValidation(`sourcemapPathTransform function must return a string.`));
  19323. }
  19324. }
  19325. map.sources[sourcesIndex] = parseAst_js.normalize(sourcePath);
  19326. }
  19327. timeEnd('sourcemaps', 3);
  19328. }
  19329. return {
  19330. code,
  19331. map
  19332. };
  19333. }
  19334. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  19335. const nonHashedChunksWithPlaceholders = [];
  19336. const renderedChunksByPlaceholder = new Map();
  19337. const hashDependenciesByPlaceholder = new Map();
  19338. const initialHashesByPlaceholder = new Map();
  19339. const placeholders = new Set();
  19340. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  19341. if (hashPlaceholder)
  19342. placeholders.add(hashPlaceholder);
  19343. }
  19344. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  19345. const transformedChunk = {
  19346. chunk,
  19347. fileName,
  19348. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  19349. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  19350. };
  19351. const { code, map } = transformedChunk;
  19352. if (hashPlaceholder) {
  19353. // To create a reproducible content-only hash, all placeholders are
  19354. // replaced with the same value before hashing
  19355. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  19356. let contentToHash = transformedCode;
  19357. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  19358. if (pluginHash) {
  19359. augmentation += pluginHash;
  19360. }
  19361. return augmentation;
  19362. });
  19363. if (hashAugmentation) {
  19364. contentToHash += hashAugmentation;
  19365. }
  19366. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  19367. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  19368. containedPlaceholders,
  19369. contentHash: getHash(contentToHash)
  19370. });
  19371. }
  19372. else {
  19373. nonHashedChunksWithPlaceholders.push(transformedChunk);
  19374. }
  19375. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  19376. if (map && sourcemapHashPlaceholder) {
  19377. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  19378. }
  19379. }));
  19380. return {
  19381. hashDependenciesByPlaceholder,
  19382. initialHashesByPlaceholder,
  19383. nonHashedChunksWithPlaceholders,
  19384. placeholders,
  19385. renderedChunksByPlaceholder
  19386. };
  19387. }
  19388. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  19389. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  19390. for (const placeholder of placeholders) {
  19391. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  19392. let contentToHash = '';
  19393. const hashDependencyPlaceholders = new Set([placeholder]);
  19394. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  19395. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  19396. contentToHash += contentHash;
  19397. for (const containedPlaceholder of containedPlaceholders) {
  19398. // When looping over a map, setting an entry only causes a new iteration if the key is new
  19399. hashDependencyPlaceholders.add(containedPlaceholder);
  19400. }
  19401. }
  19402. let finalFileName;
  19403. let finalHash;
  19404. do {
  19405. // In case of a hash collision, create a hash of the hash
  19406. if (finalHash) {
  19407. contentToHash = finalHash;
  19408. }
  19409. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  19410. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  19411. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  19412. bundle[finalFileName] = FILE_PLACEHOLDER;
  19413. hashesByPlaceholder.set(placeholder, finalHash);
  19414. }
  19415. return hashesByPlaceholder;
  19416. }
  19417. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  19418. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  19419. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  19420. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  19421. let finalSourcemapFileName = null;
  19422. if (map) {
  19423. finalSourcemapFileName = sourcemapFileName
  19424. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19425. : `${finalFileName}.map`;
  19426. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  19427. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19428. }
  19429. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19430. }
  19431. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  19432. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  19433. let finalSourcemapFileName = null;
  19434. if (map) {
  19435. finalSourcemapFileName = sourcemapFileName
  19436. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19437. : `${fileName}.map`;
  19438. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19439. }
  19440. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19441. }
  19442. }
  19443. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  19444. let url;
  19445. if (sourcemap === 'inline') {
  19446. url = map.toUrl();
  19447. }
  19448. else {
  19449. const sourcemapFileName = path.basename(fileName);
  19450. url = sourcemapBaseUrl
  19451. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  19452. : sourcemapFileName;
  19453. pluginDriver.emitFile({
  19454. fileName,
  19455. originalFileName: null,
  19456. source: map.toString(),
  19457. type: 'asset'
  19458. });
  19459. }
  19460. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19461. }
  19462. class Bundle {
  19463. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  19464. this.outputOptions = outputOptions;
  19465. this.unsetOptions = unsetOptions;
  19466. this.inputOptions = inputOptions;
  19467. this.pluginDriver = pluginDriver;
  19468. this.graph = graph;
  19469. this.facadeChunkByModule = new Map();
  19470. this.includedNamespaces = new Set();
  19471. }
  19472. async generate(isWrite) {
  19473. timeStart('GENERATE', 1);
  19474. const outputBundleBase = Object.create(null);
  19475. const outputBundle = getOutputBundle(outputBundleBase);
  19476. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  19477. try {
  19478. timeStart('initialize render', 2);
  19479. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  19480. timeEnd('initialize render', 2);
  19481. timeStart('generate chunks', 2);
  19482. const getHashPlaceholder = getHashPlaceholderGenerator();
  19483. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  19484. if (chunks.length > 1) {
  19485. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  19486. }
  19487. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  19488. for (const chunk of chunks) {
  19489. chunk.generateExports();
  19490. }
  19491. timeEnd('generate chunks', 2);
  19492. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  19493. }
  19494. catch (error_) {
  19495. await this.pluginDriver.hookParallel('renderError', [error_]);
  19496. throw error_;
  19497. }
  19498. removeUnreferencedAssets(outputBundle);
  19499. timeStart('generate bundle', 2);
  19500. await this.pluginDriver.hookSeq('generateBundle', [
  19501. this.outputOptions,
  19502. outputBundle,
  19503. isWrite
  19504. ]);
  19505. this.finaliseAssets(outputBundle);
  19506. timeEnd('generate bundle', 2);
  19507. timeEnd('GENERATE', 1);
  19508. return outputBundleBase;
  19509. }
  19510. async addManualChunks(manualChunks) {
  19511. const manualChunkAliasByEntry = new Map();
  19512. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  19513. alias,
  19514. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  19515. })));
  19516. for (const { alias, entries } of chunkEntries) {
  19517. for (const entry of entries) {
  19518. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  19519. }
  19520. }
  19521. return manualChunkAliasByEntry;
  19522. }
  19523. assignManualChunks(getManualChunk) {
  19524. const manualChunkAliasesWithEntry = [];
  19525. const manualChunksApi = {
  19526. getModuleIds: () => this.graph.modulesById.keys(),
  19527. getModuleInfo: this.graph.getModuleInfo
  19528. };
  19529. for (const module of this.graph.modulesById.values()) {
  19530. if (module instanceof Module) {
  19531. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  19532. if (typeof manualChunkAlias === 'string') {
  19533. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  19534. }
  19535. }
  19536. }
  19537. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  19538. const manualChunkAliasByEntry = new Map();
  19539. for (const [alias, module] of manualChunkAliasesWithEntry) {
  19540. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  19541. }
  19542. return manualChunkAliasByEntry;
  19543. }
  19544. finaliseAssets(bundle) {
  19545. if (this.outputOptions.validate) {
  19546. for (const file of Object.values(bundle)) {
  19547. if ('code' in file) {
  19548. try {
  19549. parseAst_js.parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  19550. }
  19551. catch (error_) {
  19552. this.inputOptions.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logChunkInvalid(file, error_));
  19553. }
  19554. }
  19555. }
  19556. }
  19557. this.pluginDriver.finaliseAssets();
  19558. }
  19559. async generateChunks(bundle, getHashPlaceholder) {
  19560. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  19561. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  19562. ? await this.addManualChunks(manualChunks)
  19563. : this.assignManualChunks(manualChunks);
  19564. const snippets = getGenerateCodeSnippets(this.outputOptions);
  19565. const includedModules = getIncludedModules(this.graph.modulesById);
  19566. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  19567. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  19568. const chunks = [];
  19569. const chunkByModule = new Map();
  19570. for (const { alias, modules } of inlineDynamicImports
  19571. ? [{ alias: null, modules: includedModules }]
  19572. : preserveModules
  19573. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  19574. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  19575. sortByExecutionOrder(modules);
  19576. 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);
  19577. chunks.push(chunk);
  19578. }
  19579. for (const chunk of chunks) {
  19580. chunk.link();
  19581. }
  19582. const facades = [];
  19583. for (const chunk of chunks) {
  19584. facades.push(...chunk.generateFacades());
  19585. }
  19586. return [...chunks, ...facades];
  19587. }
  19588. }
  19589. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  19590. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  19591. 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));
  19592. if (typeof outputOptions.file === 'string')
  19593. 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'));
  19594. if (outputOptions.sourcemapFile)
  19595. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapFile', parseAst_js.URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  19596. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  19597. 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'));
  19598. }
  19599. function getIncludedModules(modulesById) {
  19600. const includedModules = [];
  19601. for (const module of modulesById.values()) {
  19602. if (module instanceof Module &&
  19603. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  19604. includedModules.push(module);
  19605. }
  19606. }
  19607. return includedModules;
  19608. }
  19609. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  19610. const absoluteEntryModulePaths = [];
  19611. for (const module of includedModules) {
  19612. if ((module.info.isEntry || preserveModules) && parseAst_js.isAbsolute(module.id)) {
  19613. absoluteEntryModulePaths.push(module.id);
  19614. }
  19615. }
  19616. return absoluteEntryModulePaths;
  19617. }
  19618. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  19619. const externalChunkByModule = new Map();
  19620. for (const module of modulesById.values()) {
  19621. if (module instanceof ExternalModule) {
  19622. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  19623. }
  19624. }
  19625. return externalChunkByModule;
  19626. }
  19627. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  19628. const existingAlias = manualChunkAliasByEntry.get(module);
  19629. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  19630. return parseAst_js.error(parseAst_js.logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  19631. }
  19632. manualChunkAliasByEntry.set(module, alias);
  19633. }
  19634. function flru (max) {
  19635. var num, curr, prev;
  19636. var limit = max;
  19637. function keep(key, value) {
  19638. if (++num > limit) {
  19639. prev = curr;
  19640. reset(1);
  19641. ++num;
  19642. }
  19643. curr[key] = value;
  19644. }
  19645. function reset(isPartial) {
  19646. num = 0;
  19647. curr = Object.create(null);
  19648. isPartial || (prev=Object.create(null));
  19649. }
  19650. reset();
  19651. return {
  19652. clear: reset,
  19653. has: function (key) {
  19654. return curr[key] !== void 0 || prev[key] !== void 0;
  19655. },
  19656. get: function (key) {
  19657. var val = curr[key];
  19658. if (val !== void 0) return val;
  19659. if ((val=prev[key]) !== void 0) {
  19660. keep(key, val);
  19661. return val;
  19662. }
  19663. },
  19664. set: function (key, value) {
  19665. if (curr[key] !== void 0) {
  19666. curr[key] = value;
  19667. } else {
  19668. keep(key, value);
  19669. }
  19670. }
  19671. };
  19672. }
  19673. class GlobalScope extends Scope {
  19674. constructor() {
  19675. super();
  19676. this.parent = null;
  19677. this.variables.set('undefined', new UndefinedVariable());
  19678. }
  19679. findVariable(name) {
  19680. let variable = this.variables.get(name);
  19681. if (!variable) {
  19682. variable = new GlobalVariable(name);
  19683. this.variables.set(name, variable);
  19684. }
  19685. return variable;
  19686. }
  19687. }
  19688. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19689. let skipped = null;
  19690. let replaceContext = null;
  19691. if (skip) {
  19692. skipped = new Set();
  19693. for (const skippedCall of skip) {
  19694. if (source === skippedCall.source && importer === skippedCall.importer) {
  19695. skipped.add(skippedCall.plugin);
  19696. }
  19697. }
  19698. replaceContext = (pluginContext, plugin) => ({
  19699. ...pluginContext,
  19700. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = parseAst_js.BLANK) => {
  19701. skipSelf ??= true;
  19702. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || parseAst_js.EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  19703. }
  19704. });
  19705. }
  19706. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  19707. }
  19708. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  19709. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  19710. if (pluginResult != null) {
  19711. const [resolveIdResult, plugin] = pluginResult;
  19712. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  19713. return {
  19714. ...resolveIdResult,
  19715. resolvedBy: plugin.name
  19716. };
  19717. }
  19718. if (typeof resolveIdResult === 'string') {
  19719. return {
  19720. id: resolveIdResult,
  19721. resolvedBy: plugin.name
  19722. };
  19723. }
  19724. return resolveIdResult;
  19725. }
  19726. // external modules (non-entry modules that start with neither '.' or '/')
  19727. // are skipped at this stage.
  19728. if (importer !== undefined && !parseAst_js.isAbsolute(source) && source[0] !== '.')
  19729. return null;
  19730. // `resolve` processes paths from right to left, prepending them until an
  19731. // absolute path is created. Absolute importees therefore shortcircuit the
  19732. // resolve call and require no special handing on our part.
  19733. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  19734. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
  19735. }
  19736. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  19737. return ((await findFile(file, preserveSymlinks)) ??
  19738. (await findFile(file + '.mjs', preserveSymlinks)) ??
  19739. (await findFile(file + '.js', preserveSymlinks)));
  19740. }
  19741. async function findFile(file, preserveSymlinks) {
  19742. try {
  19743. const stats = await promises.lstat(file);
  19744. if (!preserveSymlinks && stats.isSymbolicLink())
  19745. return await findFile(await promises.realpath(file), preserveSymlinks);
  19746. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  19747. // check case
  19748. const name = path.basename(file);
  19749. const files = await promises.readdir(path.dirname(file));
  19750. if (files.includes(name))
  19751. return file;
  19752. }
  19753. }
  19754. catch {
  19755. // suppress
  19756. }
  19757. }
  19758. async function transform(source, module, pluginDriver, log) {
  19759. const id = module.id;
  19760. const sourcemapChain = [];
  19761. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  19762. const originalCode = source.code;
  19763. let ast = source.ast;
  19764. const transformDependencies = [];
  19765. const emittedFiles = [];
  19766. let customTransformCache = false;
  19767. const useCustomTransformCache = () => (customTransformCache = true);
  19768. let pluginName = '';
  19769. let currentSource = source.code;
  19770. function transformReducer(previousCode, result, plugin) {
  19771. let code;
  19772. let map;
  19773. if (typeof result === 'string') {
  19774. code = result;
  19775. }
  19776. else if (result && typeof result === 'object') {
  19777. module.updateOptions(result);
  19778. if (result.code == null) {
  19779. if (result.map || result.ast) {
  19780. log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logNoTransformMapOrAstWithoutCode(plugin.name));
  19781. }
  19782. return previousCode;
  19783. }
  19784. ({ code, map, ast } = result);
  19785. }
  19786. else {
  19787. return previousCode;
  19788. }
  19789. // strict null check allows 'null' maps to not be pushed to the chain,
  19790. // while 'undefined' gets the missing map warning
  19791. if (map !== null) {
  19792. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  19793. missing: true,
  19794. plugin: plugin.name
  19795. });
  19796. }
  19797. currentSource = code;
  19798. return code;
  19799. }
  19800. const getLogHandler = (handler) => (log, pos) => {
  19801. log = normalizeLog(log);
  19802. if (pos)
  19803. parseAst_js.augmentCodeLocation(log, pos, currentSource, id);
  19804. log.id = id;
  19805. log.hook = 'transform';
  19806. handler(log);
  19807. };
  19808. let code;
  19809. try {
  19810. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  19811. pluginName = plugin.name;
  19812. return {
  19813. ...pluginContext,
  19814. addWatchFile(id) {
  19815. transformDependencies.push(id);
  19816. pluginContext.addWatchFile(id);
  19817. },
  19818. cache: customTransformCache
  19819. ? pluginContext.cache
  19820. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  19821. debug: getLogHandler(pluginContext.debug),
  19822. emitFile(emittedFile) {
  19823. emittedFiles.push(emittedFile);
  19824. return pluginDriver.emitFile(emittedFile);
  19825. },
  19826. error(error_, pos) {
  19827. if (typeof error_ === 'string')
  19828. error_ = { message: error_ };
  19829. if (pos)
  19830. parseAst_js.augmentCodeLocation(error_, pos, currentSource, id);
  19831. error_.id = id;
  19832. error_.hook = 'transform';
  19833. return pluginContext.error(error_);
  19834. },
  19835. getCombinedSourcemap() {
  19836. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  19837. if (!combinedMap) {
  19838. const magicString = new MagicString(originalCode);
  19839. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  19840. }
  19841. if (originalSourcemap !== combinedMap) {
  19842. originalSourcemap = combinedMap;
  19843. sourcemapChain.length = 0;
  19844. }
  19845. return new SourceMap({
  19846. ...combinedMap,
  19847. file: null,
  19848. sourcesContent: combinedMap.sourcesContent
  19849. });
  19850. },
  19851. info: getLogHandler(pluginContext.info),
  19852. setAssetSource() {
  19853. return this.error(parseAst_js.logInvalidSetAssetSourceCall());
  19854. },
  19855. warn: getLogHandler(pluginContext.warn)
  19856. };
  19857. });
  19858. }
  19859. catch (error_) {
  19860. return parseAst_js.error(parseAst_js.logPluginError(error_, pluginName, { hook: 'transform', id }));
  19861. }
  19862. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  19863. emittedFiles.length > 0)
  19864. module.transformFiles = emittedFiles;
  19865. return {
  19866. ast,
  19867. code,
  19868. customTransformCache,
  19869. originalCode,
  19870. originalSourcemap,
  19871. sourcemapChain,
  19872. transformDependencies
  19873. };
  19874. }
  19875. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  19876. class ModuleLoader {
  19877. constructor(graph, modulesById, options, pluginDriver) {
  19878. this.graph = graph;
  19879. this.modulesById = modulesById;
  19880. this.options = options;
  19881. this.pluginDriver = pluginDriver;
  19882. this.implicitEntryModules = new Set();
  19883. this.indexedEntryModules = [];
  19884. this.latestLoadModulesPromise = Promise.resolve();
  19885. this.moduleLoadPromises = new Map();
  19886. this.modulesWithLoadedDependencies = new Set();
  19887. this.nextChunkNamePriority = 0;
  19888. this.nextEntryModuleIndex = 0;
  19889. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  19890. ? false
  19891. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  19892. this.hasModuleSideEffects = options.treeshake
  19893. ? options.treeshake.moduleSideEffects
  19894. : () => true;
  19895. }
  19896. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  19897. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  19898. await this.awaitLoadModulesPromise();
  19899. return result;
  19900. }
  19901. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  19902. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  19903. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  19904. const firstChunkNamePriority = this.nextChunkNamePriority;
  19905. this.nextChunkNamePriority += unresolvedEntryModules.length;
  19906. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  19907. for (const [index, entryModule] of entryModules.entries()) {
  19908. entryModule.isUserDefinedEntryPoint =
  19909. entryModule.isUserDefinedEntryPoint || isUserDefined;
  19910. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  19911. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  19912. if (existingIndexedModule) {
  19913. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  19914. }
  19915. else {
  19916. this.indexedEntryModules.push({
  19917. index: firstEntryModuleIndex + index,
  19918. module: entryModule
  19919. });
  19920. }
  19921. }
  19922. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  19923. return entryModules;
  19924. }));
  19925. await this.awaitLoadModulesPromise();
  19926. return {
  19927. entryModules: this.indexedEntryModules.map(({ module }) => module),
  19928. implicitEntryModules: [...this.implicitEntryModules],
  19929. newEntryModules
  19930. };
  19931. }
  19932. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  19933. const unresolvedModule = {
  19934. fileName: fileName || null,
  19935. id,
  19936. importer,
  19937. name: name || null
  19938. };
  19939. const module = implicitlyLoadedAfterOneOf
  19940. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  19941. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  19942. if (preserveSignature != null) {
  19943. module.preserveSignature = preserveSignature;
  19944. }
  19945. return module;
  19946. }
  19947. async preloadModule(resolvedId) {
  19948. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, parseAst_js.EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  19949. return module.info;
  19950. }
  19951. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  19952. const chunkNamePriority = this.nextChunkNamePriority++;
  19953. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  19954. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  19955. if (!entryModule.info.isEntry) {
  19956. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  19957. // We need to check again if this is still an entry module as these
  19958. // changes need to be performed atomically to avoid race conditions
  19959. // if the same module is re-emitted as an entry module.
  19960. // The inverse changes happen in "handleExistingModule"
  19961. if (!entryModule.info.isEntry) {
  19962. this.implicitEntryModules.add(entryModule);
  19963. for (const module of implicitlyLoadedAfterModules) {
  19964. entryModule.implicitlyLoadedAfter.add(module);
  19965. }
  19966. for (const dependant of entryModule.implicitlyLoadedAfter) {
  19967. dependant.implicitlyLoadedBefore.add(entryModule);
  19968. }
  19969. }
  19970. }
  19971. return entryModule;
  19972. }));
  19973. }
  19974. async addModuleSource(id, importer, module) {
  19975. let source;
  19976. try {
  19977. source = await this.graph.fileOperationQueue.run(async () => {
  19978. const content = await this.pluginDriver.hookFirst('load', [id]);
  19979. if (content !== null)
  19980. return content;
  19981. this.graph.watchFiles[id] = true;
  19982. return await promises.readFile(id, 'utf8');
  19983. });
  19984. }
  19985. catch (error_) {
  19986. let message = `Could not load ${id}`;
  19987. if (importer)
  19988. message += ` (imported by ${parseAst_js.relativeId(importer)})`;
  19989. message += `: ${error_.message}`;
  19990. error_.message = message;
  19991. throw error_;
  19992. }
  19993. const sourceDescription = typeof source === 'string'
  19994. ? { code: source }
  19995. : source != null && typeof source === 'object' && typeof source.code === 'string'
  19996. ? source
  19997. : parseAst_js.error(parseAst_js.logBadLoader(id));
  19998. const code = sourceDescription.code;
  19999. if (code.charCodeAt(0) === 0xfe_ff) {
  20000. sourceDescription.code = code.slice(1);
  20001. }
  20002. const cachedModule = this.graph.cachedModules.get(id);
  20003. if (cachedModule &&
  20004. !cachedModule.customTransformCache &&
  20005. cachedModule.originalCode === sourceDescription.code &&
  20006. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20007. {
  20008. ast: cachedModule.ast,
  20009. code: cachedModule.code,
  20010. id: cachedModule.id,
  20011. meta: cachedModule.meta,
  20012. moduleSideEffects: cachedModule.moduleSideEffects,
  20013. resolvedSources: cachedModule.resolvedIds,
  20014. syntheticNamedExports: cachedModule.syntheticNamedExports
  20015. }
  20016. ]))) {
  20017. if (cachedModule.transformFiles) {
  20018. for (const emittedFile of cachedModule.transformFiles)
  20019. this.pluginDriver.emitFile(emittedFile);
  20020. }
  20021. await module.setSource(cachedModule);
  20022. }
  20023. else {
  20024. module.updateOptions(sourceDescription);
  20025. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  20026. }
  20027. }
  20028. async awaitLoadModulesPromise() {
  20029. let startingPromise;
  20030. do {
  20031. startingPromise = this.latestLoadModulesPromise;
  20032. await startingPromise;
  20033. } while (startingPromise !== this.latestLoadModulesPromise);
  20034. }
  20035. extendLoadModulesPromise(loadNewModulesPromise) {
  20036. this.latestLoadModulesPromise = Promise.all([
  20037. loadNewModulesPromise,
  20038. this.latestLoadModulesPromise
  20039. ]);
  20040. this.latestLoadModulesPromise.catch(() => {
  20041. /* Avoid unhandled Promise rejections */
  20042. });
  20043. return loadNewModulesPromise;
  20044. }
  20045. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20046. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20047. if (resolvedId === null)
  20048. return null;
  20049. if (typeof resolvedId === 'string') {
  20050. dynamicImport.resolution = resolvedId;
  20051. return null;
  20052. }
  20053. return (dynamicImport.resolution = await this.fetchResolvedDependency(parseAst_js.relativeId(resolvedId.id), module.id, resolvedId));
  20054. })));
  20055. for (const dependency of dependencies) {
  20056. if (dependency) {
  20057. module.dynamicDependencies.add(dependency);
  20058. dependency.dynamicImporters.push(module.id);
  20059. }
  20060. }
  20061. }
  20062. // If this is a preload, then this method always waits for the dependencies of
  20063. // the module to be resolved.
  20064. // Otherwise, if the module does not exist, it waits for the module and all
  20065. // its dependencies to be loaded.
  20066. // Otherwise, it returns immediately.
  20067. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20068. const existingModule = this.modulesById.get(id);
  20069. if (existingModule instanceof Module) {
  20070. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  20071. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  20072. }
  20073. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20074. return existingModule;
  20075. }
  20076. if (existingModule instanceof ExternalModule) {
  20077. return parseAst_js.error(parseAst_js.logExternalModulesCannotBeTransformedToModules(existingModule.id));
  20078. }
  20079. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  20080. this.modulesById.set(id, module);
  20081. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20082. this.getResolveStaticDependencyPromises(module),
  20083. this.getResolveDynamicImportPromises(module),
  20084. loadAndResolveDependenciesPromise
  20085. ]);
  20086. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20087. loadAndResolveDependenciesPromise.catch(() => {
  20088. /* avoid unhandled promise rejections */
  20089. });
  20090. this.moduleLoadPromises.set(module, loadPromise);
  20091. const resolveDependencyPromises = await loadPromise;
  20092. if (!isPreload) {
  20093. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20094. }
  20095. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20096. await loadAndResolveDependenciesPromise;
  20097. }
  20098. return module;
  20099. }
  20100. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20101. if (this.modulesWithLoadedDependencies.has(module)) {
  20102. return;
  20103. }
  20104. this.modulesWithLoadedDependencies.add(module);
  20105. await Promise.all([
  20106. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20107. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20108. ]);
  20109. module.linkImports();
  20110. // To handle errors when resolving dependencies or in moduleParsed
  20111. await loadAndResolveDependenciesPromise;
  20112. }
  20113. fetchResolvedDependency(source, importer, resolvedId) {
  20114. if (resolvedId.external) {
  20115. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  20116. let externalModule = this.modulesById.get(id);
  20117. if (!externalModule) {
  20118. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && parseAst_js.isAbsolute(id), attributes);
  20119. this.modulesById.set(id, externalModule);
  20120. }
  20121. else if (!(externalModule instanceof ExternalModule)) {
  20122. return parseAst_js.error(parseAst_js.logInternalIdCannotBeExternal(source, importer));
  20123. }
  20124. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  20125. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  20126. }
  20127. return Promise.resolve(externalModule);
  20128. }
  20129. return this.fetchModule(resolvedId, importer, false, false);
  20130. }
  20131. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20132. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20133. module.dependencies.add(dependency);
  20134. dependency.importers.push(module.id);
  20135. }
  20136. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20137. for (const dependency of module.dependencies) {
  20138. if (dependency instanceof Module) {
  20139. dependency.importedFromNotTreeshaken = true;
  20140. }
  20141. }
  20142. }
  20143. }
  20144. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20145. const { makeAbsoluteExternalsRelative } = this.options;
  20146. if (resolveIdResult) {
  20147. if (typeof resolveIdResult === 'object') {
  20148. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20149. return {
  20150. ...resolveIdResult,
  20151. external: external &&
  20152. (external === 'relative' ||
  20153. !parseAst_js.isAbsolute(resolveIdResult.id) ||
  20154. (external === true &&
  20155. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20156. 'absolute')
  20157. };
  20158. }
  20159. const external = this.options.external(resolveIdResult, importer, true);
  20160. return {
  20161. external: external &&
  20162. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20163. 'absolute'),
  20164. id: external && makeAbsoluteExternalsRelative
  20165. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20166. : resolveIdResult
  20167. };
  20168. }
  20169. const id = makeAbsoluteExternalsRelative
  20170. ? normalizeRelativeExternalId(source, importer)
  20171. : source;
  20172. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20173. return null;
  20174. }
  20175. return {
  20176. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20177. id
  20178. };
  20179. }
  20180. getResolveDynamicImportPromises(module) {
  20181. return module.dynamicImports.map(async (dynamicImport) => {
  20182. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  20183. if (resolvedId && typeof resolvedId === 'object') {
  20184. dynamicImport.id = resolvedId.id;
  20185. }
  20186. return [dynamicImport, resolvedId];
  20187. });
  20188. }
  20189. getResolveStaticDependencyPromises(module) {
  20190. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  20191. source,
  20192. (module.resolvedIds[source] =
  20193. module.resolvedIds[source] ||
  20194. this.handleInvalidResolvedId(await this.resolveId(source, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  20195. ]);
  20196. }
  20197. getResolvedIdWithDefaults(resolvedId, attributes) {
  20198. if (!resolvedId) {
  20199. return null;
  20200. }
  20201. const external = resolvedId.external || false;
  20202. return {
  20203. attributes: resolvedId.attributes || attributes,
  20204. external,
  20205. id: resolvedId.id,
  20206. meta: resolvedId.meta || {},
  20207. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  20208. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  20209. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  20210. };
  20211. }
  20212. async handleExistingModule(module, isEntry, isPreload) {
  20213. const loadPromise = this.moduleLoadPromises.get(module);
  20214. if (isPreload) {
  20215. return isPreload === RESOLVE_DEPENDENCIES
  20216. ? waitForDependencyResolution(loadPromise)
  20217. : loadPromise;
  20218. }
  20219. if (isEntry) {
  20220. // This reverts the changes in addEntryWithImplicitDependants and needs to
  20221. // be performed atomically
  20222. module.info.isEntry = true;
  20223. this.implicitEntryModules.delete(module);
  20224. for (const dependant of module.implicitlyLoadedAfter) {
  20225. dependant.implicitlyLoadedBefore.delete(module);
  20226. }
  20227. module.implicitlyLoadedAfter.clear();
  20228. }
  20229. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20230. }
  20231. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  20232. if (resolvedId === null) {
  20233. if (parseAst_js.isRelative(source)) {
  20234. return parseAst_js.error(parseAst_js.logUnresolvedImport(source, importer));
  20235. }
  20236. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logUnresolvedImportTreatedAsExternal(source, importer));
  20237. return {
  20238. attributes,
  20239. external: true,
  20240. id: source,
  20241. meta: {},
  20242. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20243. resolvedBy: 'rollup',
  20244. syntheticNamedExports: false
  20245. };
  20246. }
  20247. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20248. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logExternalSyntheticExports(source, importer));
  20249. }
  20250. return resolvedId;
  20251. }
  20252. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  20253. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, parseAst_js.EMPTY_OBJECT, true, parseAst_js.EMPTY_OBJECT);
  20254. if (resolveIdResult == null) {
  20255. return parseAst_js.error(implicitlyLoadedBefore === null
  20256. ? parseAst_js.logUnresolvedEntry(unresolvedId)
  20257. : parseAst_js.logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20258. }
  20259. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  20260. if (resolveIdResult === false || isExternalModules) {
  20261. return parseAst_js.error(implicitlyLoadedBefore === null
  20262. ? isExternalModules && isLoadForManualChunks
  20263. ? parseAst_js.logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  20264. : parseAst_js.logEntryCannotBeExternal(unresolvedId)
  20265. : parseAst_js.logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20266. }
  20267. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20268. ? resolveIdResult
  20269. : { id: resolveIdResult }, parseAst_js.EMPTY_OBJECT), undefined, isEntry, false);
  20270. }
  20271. async resolveDynamicImport(module, specifier, importer, attributes) {
  20272. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20273. specifier,
  20274. importer,
  20275. { attributes }
  20276. ]);
  20277. if (typeof specifier !== 'string') {
  20278. if (typeof resolution === 'string') {
  20279. return resolution;
  20280. }
  20281. if (!resolution) {
  20282. return null;
  20283. }
  20284. return this.getResolvedIdWithDefaults(resolution, attributes);
  20285. }
  20286. if (resolution == null) {
  20287. const existingResolution = module.resolvedIds[specifier];
  20288. if (existingResolution) {
  20289. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  20290. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  20291. }
  20292. return existingResolution;
  20293. }
  20294. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, parseAst_js.EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  20295. }
  20296. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  20297. }
  20298. }
  20299. function normalizeRelativeExternalId(source, importer) {
  20300. return parseAst_js.isRelative(source)
  20301. ? importer
  20302. ? path.resolve(importer, '..', source)
  20303. : path.resolve(source)
  20304. : source;
  20305. }
  20306. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20307. if (fileName !== null) {
  20308. module.chunkFileNames.add(fileName);
  20309. }
  20310. else if (name !== null) {
  20311. // Always keep chunkNames sorted by priority
  20312. let namePosition = 0;
  20313. while (module.chunkNames[namePosition]?.priority < priority)
  20314. namePosition++;
  20315. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20316. }
  20317. }
  20318. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20319. return (makeAbsoluteExternalsRelative === true ||
  20320. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && parseAst_js.isRelative(source)) ||
  20321. !parseAst_js.isAbsolute(id));
  20322. }
  20323. async function waitForDependencyResolution(loadPromise) {
  20324. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20325. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20326. }
  20327. class Queue {
  20328. constructor(maxParallel) {
  20329. this.maxParallel = maxParallel;
  20330. this.queue = [];
  20331. this.workerCount = 0;
  20332. }
  20333. run(task) {
  20334. return new Promise((resolve, reject) => {
  20335. this.queue.push({ reject, resolve, task });
  20336. this.work();
  20337. });
  20338. }
  20339. async work() {
  20340. if (this.workerCount >= this.maxParallel)
  20341. return;
  20342. this.workerCount++;
  20343. let entry;
  20344. while ((entry = this.queue.shift())) {
  20345. const { reject, resolve, task } = entry;
  20346. try {
  20347. const result = await task();
  20348. resolve(result);
  20349. }
  20350. catch (error) {
  20351. reject(error);
  20352. }
  20353. }
  20354. this.workerCount--;
  20355. }
  20356. }
  20357. function normalizeEntryModules(entryModules) {
  20358. if (Array.isArray(entryModules)) {
  20359. return entryModules.map(id => ({
  20360. fileName: null,
  20361. id,
  20362. implicitlyLoadedAfter: [],
  20363. importer: undefined,
  20364. name: null
  20365. }));
  20366. }
  20367. return Object.entries(entryModules).map(([name, id]) => ({
  20368. fileName: null,
  20369. id,
  20370. implicitlyLoadedAfter: [],
  20371. importer: undefined,
  20372. name
  20373. }));
  20374. }
  20375. class Graph {
  20376. constructor(options, watcher) {
  20377. this.options = options;
  20378. this.astLru = flru(5);
  20379. this.cachedModules = new Map();
  20380. this.deoptimizationTracker = new PathTracker();
  20381. this.entryModules = [];
  20382. this.modulesById = new Map();
  20383. this.needsTreeshakingPass = false;
  20384. this.phase = BuildPhase.LOAD_AND_PARSE;
  20385. this.scope = new GlobalScope();
  20386. this.watchFiles = Object.create(null);
  20387. this.watchMode = false;
  20388. this.externalModules = [];
  20389. this.implicitEntryModules = [];
  20390. this.modules = [];
  20391. this.getModuleInfo = (moduleId) => {
  20392. const foundModule = this.modulesById.get(moduleId);
  20393. if (!foundModule)
  20394. return null;
  20395. return foundModule.info;
  20396. };
  20397. if (options.cache !== false) {
  20398. if (options.cache?.modules) {
  20399. for (const module of options.cache.modules)
  20400. this.cachedModules.set(module.id, module);
  20401. }
  20402. this.pluginCache = options.cache?.plugins || Object.create(null);
  20403. // increment access counter
  20404. for (const name in this.pluginCache) {
  20405. const cache = this.pluginCache[name];
  20406. for (const value of Object.values(cache))
  20407. value[0]++;
  20408. }
  20409. }
  20410. if (watcher) {
  20411. this.watchMode = true;
  20412. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  20413. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  20414. watcher.onCurrentRun('change', handleChange);
  20415. watcher.onCurrentRun('close', handleClose);
  20416. }
  20417. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  20418. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  20419. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  20420. this.pureFunctions = getPureFunctions(options);
  20421. }
  20422. async build() {
  20423. timeStart('generate module graph', 2);
  20424. await this.generateModuleGraph();
  20425. timeEnd('generate module graph', 2);
  20426. timeStart('sort and bind modules', 2);
  20427. this.phase = BuildPhase.ANALYSE;
  20428. this.sortModules();
  20429. timeEnd('sort and bind modules', 2);
  20430. timeStart('mark included statements', 2);
  20431. this.includeStatements();
  20432. timeEnd('mark included statements', 2);
  20433. this.phase = BuildPhase.GENERATE;
  20434. }
  20435. getCache() {
  20436. // handle plugin cache eviction
  20437. for (const name in this.pluginCache) {
  20438. const cache = this.pluginCache[name];
  20439. let allDeleted = true;
  20440. for (const [key, value] of Object.entries(cache)) {
  20441. if (value[0] >= this.options.experimentalCacheExpiry)
  20442. delete cache[key];
  20443. else
  20444. allDeleted = false;
  20445. }
  20446. if (allDeleted)
  20447. delete this.pluginCache[name];
  20448. }
  20449. return {
  20450. modules: this.modules.map(module => module.toJSON()),
  20451. plugins: this.pluginCache
  20452. };
  20453. }
  20454. async generateModuleGraph() {
  20455. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  20456. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  20457. if (this.entryModules.length === 0) {
  20458. throw new Error('You must supply options.input to rollup');
  20459. }
  20460. for (const module of this.modulesById.values()) {
  20461. module.cacheInfoGetters();
  20462. if (module instanceof Module) {
  20463. this.modules.push(module);
  20464. }
  20465. else {
  20466. this.externalModules.push(module);
  20467. }
  20468. }
  20469. }
  20470. includeStatements() {
  20471. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  20472. for (const module of entryModules) {
  20473. markModuleAndImpureDependenciesAsExecuted(module);
  20474. }
  20475. if (this.options.treeshake) {
  20476. let treeshakingPass = 1;
  20477. do {
  20478. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  20479. this.needsTreeshakingPass = false;
  20480. for (const module of this.modules) {
  20481. if (module.isExecuted) {
  20482. module.hasTreeShakingPassStarted = true;
  20483. if (module.info.moduleSideEffects === 'no-treeshake') {
  20484. module.includeAllInBundle();
  20485. }
  20486. else {
  20487. module.include();
  20488. }
  20489. }
  20490. }
  20491. if (treeshakingPass === 1) {
  20492. // We only include exports after the first pass to avoid issues with
  20493. // the TDZ detection logic
  20494. for (const module of entryModules) {
  20495. if (module.preserveSignature !== false) {
  20496. module.includeAllExports(false);
  20497. this.needsTreeshakingPass = true;
  20498. }
  20499. }
  20500. }
  20501. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  20502. } while (this.needsTreeshakingPass);
  20503. }
  20504. else {
  20505. for (const module of this.modules)
  20506. module.includeAllInBundle();
  20507. }
  20508. for (const externalModule of this.externalModules)
  20509. externalModule.warnUnusedImports();
  20510. for (const module of this.implicitEntryModules) {
  20511. for (const dependant of module.implicitlyLoadedAfter) {
  20512. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  20513. parseAst_js.error(parseAst_js.logImplicitDependantIsNotIncluded(dependant));
  20514. }
  20515. }
  20516. }
  20517. }
  20518. sortModules() {
  20519. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  20520. for (const cyclePath of cyclePaths) {
  20521. this.options.onLog(parseAst_js.LOGLEVEL_WARN, parseAst_js.logCircularDependency(cyclePath));
  20522. }
  20523. this.modules = orderedModules;
  20524. for (const module of this.modules) {
  20525. module.bindReferences();
  20526. }
  20527. this.warnForMissingExports();
  20528. }
  20529. warnForMissingExports() {
  20530. for (const module of this.modules) {
  20531. for (const importDescription of module.importDescriptions.values()) {
  20532. if (importDescription.name !== '*' &&
  20533. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  20534. module.log(parseAst_js.LOGLEVEL_WARN, parseAst_js.logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  20535. }
  20536. }
  20537. }
  20538. }
  20539. }
  20540. function formatAction([pluginName, hookName, parameters]) {
  20541. const action = `(${pluginName}) ${hookName}`;
  20542. const s = JSON.stringify;
  20543. switch (hookName) {
  20544. case 'resolveId': {
  20545. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  20546. }
  20547. case 'load': {
  20548. return `${action} ${s(parameters[0])}`;
  20549. }
  20550. case 'transform': {
  20551. return `${action} ${s(parameters[1])}`;
  20552. }
  20553. case 'shouldTransformCachedModule': {
  20554. return `${action} ${s(parameters[0].id)}`;
  20555. }
  20556. case 'moduleParsed': {
  20557. return `${action} ${s(parameters[0].id)}`;
  20558. }
  20559. }
  20560. return action;
  20561. }
  20562. let handleBeforeExit = null;
  20563. const rejectByPluginDriver = new Map();
  20564. async function catchUnfinishedHookActions(pluginDriver, callback) {
  20565. const emptyEventLoopPromise = new Promise((_, reject) => {
  20566. rejectByPluginDriver.set(pluginDriver, reject);
  20567. if (!handleBeforeExit) {
  20568. // We only ever create a single event listener to avoid max listener and
  20569. // other issues
  20570. handleBeforeExit = () => {
  20571. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  20572. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  20573. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  20574. [...unfulfilledActions].map(formatAction).join('\n')));
  20575. }
  20576. };
  20577. process$1.once('beforeExit', handleBeforeExit);
  20578. }
  20579. });
  20580. try {
  20581. return await Promise.race([callback(), emptyEventLoopPromise]);
  20582. }
  20583. finally {
  20584. rejectByPluginDriver.delete(pluginDriver);
  20585. if (rejectByPluginDriver.size === 0) {
  20586. process$1.off('beforeExit', handleBeforeExit);
  20587. handleBeforeExit = null;
  20588. }
  20589. }
  20590. }
  20591. async function initWasm() { }
  20592. async function normalizeInputOptions(config, watchMode) {
  20593. // These are options that may trigger special warnings or behaviour later
  20594. // if the user did not select an explicit value
  20595. const unsetOptions = new Set();
  20596. const context = config.context ?? 'undefined';
  20597. const plugins = await normalizePluginOption(config.plugins);
  20598. const logLevel = config.logLevel || parseAst_js.LOGLEVEL_INFO;
  20599. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  20600. const strictDeprecations = config.strictDeprecations || false;
  20601. const maxParallelFileOps = getMaxParallelFileOps(config);
  20602. const options = {
  20603. cache: getCache(config),
  20604. context,
  20605. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  20606. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  20607. external: getIdMatcher(config.external),
  20608. input: getInput(config),
  20609. jsx: getJsx(config),
  20610. logLevel,
  20611. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  20612. maxParallelFileOps,
  20613. moduleContext: getModuleContext(config, context),
  20614. onLog,
  20615. perf: config.perf || false,
  20616. plugins,
  20617. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  20618. preserveSymlinks: config.preserveSymlinks || false,
  20619. shimMissingExports: config.shimMissingExports || false,
  20620. strictDeprecations,
  20621. treeshake: getTreeshake(config)
  20622. };
  20623. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  20624. return { options, unsetOptions };
  20625. }
  20626. const getCache = (config) => config.cache === true // `true` is the default
  20627. ? undefined
  20628. : config.cache?.cache || config.cache;
  20629. const getIdMatcher = (option) => {
  20630. if (option === true) {
  20631. return () => true;
  20632. }
  20633. if (typeof option === 'function') {
  20634. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  20635. }
  20636. if (option) {
  20637. const ids = new Set();
  20638. const matchers = [];
  20639. for (const value of ensureArray$1(option)) {
  20640. if (value instanceof RegExp) {
  20641. matchers.push(value);
  20642. }
  20643. else {
  20644. ids.add(value);
  20645. }
  20646. }
  20647. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  20648. }
  20649. return () => false;
  20650. };
  20651. const getInput = (config) => {
  20652. const configInput = config.input;
  20653. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  20654. };
  20655. const getJsx = (config) => {
  20656. const configJsx = config.jsx;
  20657. if (!configJsx)
  20658. return false;
  20659. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', parseAst_js.URL_JSX, 'false, ');
  20660. const { factory, importSource, mode } = configWithPreset;
  20661. switch (mode) {
  20662. case 'automatic': {
  20663. return {
  20664. factory: factory || 'React.createElement',
  20665. importSource: importSource || 'react',
  20666. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  20667. mode: 'automatic'
  20668. };
  20669. }
  20670. case 'preserve': {
  20671. if (importSource && !(factory || configWithPreset.fragment)) {
  20672. 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'));
  20673. }
  20674. return {
  20675. factory: factory || null,
  20676. fragment: configWithPreset.fragment || null,
  20677. importSource: importSource || null,
  20678. mode: 'preserve'
  20679. };
  20680. }
  20681. // case 'classic':
  20682. default: {
  20683. if (mode && mode !== 'classic') {
  20684. parseAst_js.error(parseAst_js.logInvalidOption('jsx.mode', parseAst_js.URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  20685. }
  20686. return {
  20687. factory: factory || 'React.createElement',
  20688. fragment: configWithPreset.fragment || 'React.Fragment',
  20689. importSource: importSource || null,
  20690. mode: 'classic'
  20691. };
  20692. }
  20693. }
  20694. };
  20695. const getMaxParallelFileOps = (config) => {
  20696. const maxParallelFileOps = config.maxParallelFileOps;
  20697. if (typeof maxParallelFileOps === 'number') {
  20698. if (maxParallelFileOps <= 0)
  20699. return Infinity;
  20700. return maxParallelFileOps;
  20701. }
  20702. return 20;
  20703. };
  20704. const getModuleContext = (config, context) => {
  20705. const configModuleContext = config.moduleContext;
  20706. if (typeof configModuleContext === 'function') {
  20707. return id => configModuleContext(id) ?? context;
  20708. }
  20709. if (configModuleContext) {
  20710. const contextByModuleId = Object.create(null);
  20711. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  20712. contextByModuleId[path.resolve(key)] = moduleContext;
  20713. }
  20714. return id => contextByModuleId[id] ?? context;
  20715. }
  20716. return () => context;
  20717. };
  20718. const getTreeshake = (config) => {
  20719. const configTreeshake = config.treeshake;
  20720. if (configTreeshake === false) {
  20721. return false;
  20722. }
  20723. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', parseAst_js.URL_TREESHAKE, 'false, true, ');
  20724. return {
  20725. annotations: configWithPreset.annotations !== false,
  20726. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  20727. manualPureFunctions: configWithPreset.manualPureFunctions ?? parseAst_js.EMPTY_ARRAY,
  20728. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  20729. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  20730. ? 'always'
  20731. : configWithPreset.propertyReadSideEffects !== false,
  20732. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  20733. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  20734. };
  20735. };
  20736. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  20737. if (typeof moduleSideEffectsOption === 'boolean') {
  20738. return () => moduleSideEffectsOption;
  20739. }
  20740. if (moduleSideEffectsOption === 'no-external') {
  20741. return (_id, external) => !external;
  20742. }
  20743. if (typeof moduleSideEffectsOption === 'function') {
  20744. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  20745. }
  20746. if (Array.isArray(moduleSideEffectsOption)) {
  20747. const ids = new Set(moduleSideEffectsOption);
  20748. return id => ids.has(id);
  20749. }
  20750. if (moduleSideEffectsOption) {
  20751. 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'));
  20752. }
  20753. return () => true;
  20754. };
  20755. // https://datatracker.ietf.org/doc/html/rfc2396
  20756. // eslint-disable-next-line no-control-regex
  20757. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  20758. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  20759. function sanitizeFileName(name) {
  20760. const match = DRIVE_LETTER_REGEX.exec(name);
  20761. const driveLetter = match ? match[0] : '';
  20762. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  20763. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  20764. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  20765. }
  20766. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  20767. // These are options that may trigger special warnings or behaviour later
  20768. // if the user did not select an explicit value
  20769. const unsetOptions = new Set(unsetInputOptions);
  20770. const compact = config.compact || false;
  20771. const format = getFormat(config);
  20772. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  20773. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  20774. const file = getFile(config, preserveModules, inputOptions);
  20775. const generatedCode = getGeneratedCode(config);
  20776. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  20777. const outputOptions = {
  20778. amd: getAmd(config),
  20779. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  20780. banner: getAddon(config, 'banner'),
  20781. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  20782. compact,
  20783. dir: getDir(config, file),
  20784. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  20785. entryFileNames: getEntryFileNames(config, unsetOptions),
  20786. esModule: config.esModule ?? 'if-default-prop',
  20787. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  20788. exports: getExports(config, unsetOptions),
  20789. extend: config.extend || false,
  20790. externalImportAssertions: externalImportAttributes,
  20791. externalImportAttributes,
  20792. externalLiveBindings: config.externalLiveBindings ?? true,
  20793. file,
  20794. footer: getAddon(config, 'footer'),
  20795. format,
  20796. freeze: config.freeze ?? true,
  20797. generatedCode,
  20798. globals: config.globals || {},
  20799. hashCharacters: config.hashCharacters ?? 'base64',
  20800. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  20801. importAttributesKey: config.importAttributesKey ?? 'assert',
  20802. indent: getIndent(config, compact),
  20803. inlineDynamicImports,
  20804. interop: getInterop(config),
  20805. intro: getAddon(config, 'intro'),
  20806. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  20807. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  20808. name: config.name,
  20809. noConflict: config.noConflict || false,
  20810. outro: getAddon(config, 'outro'),
  20811. paths: config.paths || {},
  20812. plugins: await normalizePluginOption(config.plugins),
  20813. preserveModules,
  20814. preserveModulesRoot: getPreserveModulesRoot(config),
  20815. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  20816. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  20817. ? config.sanitizeFileName
  20818. : config.sanitizeFileName === false
  20819. ? id => id
  20820. : sanitizeFileName,
  20821. sourcemap: config.sourcemap || false,
  20822. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  20823. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  20824. sourcemapFile: config.sourcemapFile,
  20825. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  20826. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  20827. ? config.sourcemapIgnoreList
  20828. : config.sourcemapIgnoreList === false
  20829. ? () => false
  20830. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  20831. sourcemapPathTransform: config.sourcemapPathTransform,
  20832. strict: config.strict ?? true,
  20833. systemNullSetters: config.systemNullSetters ?? true,
  20834. validate: config.validate || false,
  20835. virtualDirname: config.virtualDirname || '_virtual'
  20836. };
  20837. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  20838. return { options: outputOptions, unsetOptions };
  20839. }
  20840. const getFile = (config, preserveModules, inputOptions) => {
  20841. const { file } = config;
  20842. if (typeof file === 'string') {
  20843. if (preserveModules) {
  20844. 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'));
  20845. }
  20846. if (!Array.isArray(inputOptions.input))
  20847. 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'));
  20848. }
  20849. return file;
  20850. };
  20851. const getFormat = (config) => {
  20852. const configFormat = config.format;
  20853. switch (configFormat) {
  20854. case undefined:
  20855. case 'es':
  20856. case 'esm':
  20857. case 'module': {
  20858. return 'es';
  20859. }
  20860. case 'cjs':
  20861. case 'commonjs': {
  20862. return 'cjs';
  20863. }
  20864. case 'system':
  20865. case 'systemjs': {
  20866. return 'system';
  20867. }
  20868. case 'amd':
  20869. case 'iife':
  20870. case 'umd': {
  20871. return configFormat;
  20872. }
  20873. default: {
  20874. 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));
  20875. }
  20876. }
  20877. };
  20878. const getInlineDynamicImports = (config, inputOptions) => {
  20879. const inlineDynamicImports = config.inlineDynamicImports || false;
  20880. const { input } = inputOptions;
  20881. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  20882. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  20883. }
  20884. return inlineDynamicImports;
  20885. };
  20886. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  20887. const preserveModules = config.preserveModules || false;
  20888. if (preserveModules) {
  20889. if (inlineDynamicImports) {
  20890. return parseAst_js.error(parseAst_js.logInvalidOption('output.inlineDynamicImports', parseAst_js.URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  20891. }
  20892. if (inputOptions.preserveEntrySignatures === false) {
  20893. return parseAst_js.error(parseAst_js.logInvalidOption('preserveEntrySignatures', parseAst_js.URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  20894. }
  20895. }
  20896. return preserveModules;
  20897. };
  20898. const getPreserveModulesRoot = (config) => {
  20899. const { preserveModulesRoot } = config;
  20900. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  20901. return undefined;
  20902. }
  20903. return path.resolve(preserveModulesRoot);
  20904. };
  20905. const getAmd = (config) => {
  20906. const mergedOption = {
  20907. autoId: false,
  20908. basePath: '',
  20909. define: 'define',
  20910. forceJsExtensionForImports: false,
  20911. ...config.amd
  20912. };
  20913. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  20914. 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"'));
  20915. }
  20916. if (mergedOption.basePath && !mergedOption.autoId) {
  20917. return parseAst_js.error(parseAst_js.logInvalidOption('output.amd.basePath', parseAst_js.URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  20918. }
  20919. return mergedOption.autoId
  20920. ? {
  20921. autoId: true,
  20922. basePath: mergedOption.basePath,
  20923. define: mergedOption.define,
  20924. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  20925. }
  20926. : {
  20927. autoId: false,
  20928. define: mergedOption.define,
  20929. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  20930. id: mergedOption.id
  20931. };
  20932. };
  20933. const getAddon = (config, name) => {
  20934. const configAddon = config[name];
  20935. if (typeof configAddon === 'function') {
  20936. return configAddon;
  20937. }
  20938. return () => configAddon || '';
  20939. };
  20940. const getDir = (config, file) => {
  20941. const { dir } = config;
  20942. if (typeof dir === 'string' && typeof file === 'string') {
  20943. 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'));
  20944. }
  20945. return dir;
  20946. };
  20947. const getEntryFileNames = (config, unsetOptions) => {
  20948. const configEntryFileNames = config.entryFileNames;
  20949. if (configEntryFileNames == null) {
  20950. unsetOptions.add('entryFileNames');
  20951. }
  20952. return configEntryFileNames ?? '[name].js';
  20953. };
  20954. function getExports(config, unsetOptions) {
  20955. const configExports = config.exports;
  20956. if (configExports == null) {
  20957. unsetOptions.add('exports');
  20958. }
  20959. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  20960. return parseAst_js.error(parseAst_js.logInvalidExportOptionValue(configExports));
  20961. }
  20962. return configExports || 'auto';
  20963. }
  20964. const getExternalImportAttributes = (config, inputOptions) => {
  20965. if (config.externalImportAssertions != undefined) {
  20966. parseAst_js.warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, parseAst_js.URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  20967. }
  20968. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  20969. };
  20970. const getGeneratedCode = (config) => {
  20971. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', parseAst_js.URL_OUTPUT_GENERATEDCODE, '');
  20972. return {
  20973. arrowFunctions: configWithPreset.arrowFunctions === true,
  20974. constBindings: configWithPreset.constBindings === true,
  20975. objectShorthand: configWithPreset.objectShorthand === true,
  20976. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  20977. symbols: configWithPreset.symbols === true
  20978. };
  20979. };
  20980. const getIndent = (config, compact) => {
  20981. if (compact) {
  20982. return '';
  20983. }
  20984. const configIndent = config.indent;
  20985. return configIndent === false ? '' : (configIndent ?? true);
  20986. };
  20987. const ALLOWED_INTEROP_TYPES = new Set([
  20988. 'compat',
  20989. 'auto',
  20990. 'esModule',
  20991. 'default',
  20992. 'defaultOnly'
  20993. ]);
  20994. const getInterop = (config) => {
  20995. const configInterop = config.interop;
  20996. if (typeof configInterop === 'function') {
  20997. const interopPerId = Object.create(null);
  20998. let defaultInterop = null;
  20999. return id => id === null
  21000. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  21001. : id in interopPerId
  21002. ? interopPerId[id]
  21003. : validateInterop((interopPerId[id] = configInterop(id)));
  21004. }
  21005. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  21006. };
  21007. const validateInterop = (interop) => {
  21008. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  21009. 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));
  21010. }
  21011. return interop;
  21012. };
  21013. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  21014. const configManualChunks = config.manualChunks;
  21015. if (configManualChunks) {
  21016. if (inlineDynamicImports) {
  21017. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  21018. }
  21019. if (preserveModules) {
  21020. return parseAst_js.error(parseAst_js.logInvalidOption('output.manualChunks', parseAst_js.URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  21021. }
  21022. }
  21023. return configManualChunks || {};
  21024. };
  21025. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  21026. const getSourcemapFileNames = (config, unsetOptions) => {
  21027. const configSourcemapFileNames = config.sourcemapFileNames;
  21028. if (configSourcemapFileNames == null) {
  21029. unsetOptions.add('sourcemapFileNames');
  21030. }
  21031. return configSourcemapFileNames;
  21032. };
  21033. const getSourcemapBaseUrl = (config) => {
  21034. const { sourcemapBaseUrl } = config;
  21035. if (sourcemapBaseUrl) {
  21036. if (parseAst_js.isValidUrl(sourcemapBaseUrl)) {
  21037. return parseAst_js.addTrailingSlashIfMissed(sourcemapBaseUrl);
  21038. }
  21039. return parseAst_js.error(parseAst_js.logInvalidOption('output.sourcemapBaseUrl', parseAst_js.URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  21040. }
  21041. };
  21042. function rollup(rawInputOptions) {
  21043. return rollupInternal(rawInputOptions, null);
  21044. }
  21045. async function rollupInternal(rawInputOptions, watcher) {
  21046. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  21047. initialiseTimers(inputOptions);
  21048. await initWasm();
  21049. const graph = new Graph(inputOptions, watcher);
  21050. // remove the cache object from the memory after graph creation (cache is not used anymore)
  21051. const useCache = rawInputOptions.cache !== false;
  21052. if (rawInputOptions.cache) {
  21053. inputOptions.cache = undefined;
  21054. rawInputOptions.cache = undefined;
  21055. }
  21056. timeStart('BUILD', 1);
  21057. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  21058. try {
  21059. timeStart('initialize', 2);
  21060. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  21061. timeEnd('initialize', 2);
  21062. await graph.build();
  21063. }
  21064. catch (error_) {
  21065. const watchFiles = Object.keys(graph.watchFiles);
  21066. if (watchFiles.length > 0) {
  21067. error_.watchFiles = watchFiles;
  21068. }
  21069. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  21070. await graph.pluginDriver.hookParallel('closeBundle', []);
  21071. throw error_;
  21072. }
  21073. await graph.pluginDriver.hookParallel('buildEnd', []);
  21074. });
  21075. timeEnd('BUILD', 1);
  21076. const result = {
  21077. cache: useCache ? graph.getCache() : undefined,
  21078. async close() {
  21079. if (result.closed)
  21080. return;
  21081. result.closed = true;
  21082. await graph.pluginDriver.hookParallel('closeBundle', []);
  21083. },
  21084. closed: false,
  21085. async generate(rawOutputOptions) {
  21086. if (result.closed)
  21087. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  21088. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  21089. },
  21090. get watchFiles() {
  21091. return Object.keys(graph.watchFiles);
  21092. },
  21093. async write(rawOutputOptions) {
  21094. if (result.closed)
  21095. return parseAst_js.error(parseAst_js.logAlreadyClosed());
  21096. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  21097. }
  21098. };
  21099. if (inputOptions.perf)
  21100. result.getTimings = getTimings;
  21101. return result;
  21102. }
  21103. async function getInputOptions(initialInputOptions, watchMode) {
  21104. if (!initialInputOptions) {
  21105. throw new Error('You must supply an options object to rollup');
  21106. }
  21107. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  21108. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  21109. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  21110. return { options, unsetOptions };
  21111. }
  21112. async function getProcessedInputOptions(inputOptions, watchMode) {
  21113. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  21114. const logLevel = inputOptions.logLevel || parseAst_js.LOGLEVEL_INFO;
  21115. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  21116. for (const plugin of plugins) {
  21117. const { name, options } = plugin;
  21118. const handler = 'handler' in options ? options.handler : options;
  21119. const processedOptions = await handler.call({
  21120. debug: getLogHandler(parseAst_js.LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  21121. error: (error_) => parseAst_js.error(parseAst_js.logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  21122. info: getLogHandler(parseAst_js.LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  21123. meta: { rollupVersion: version, watchMode },
  21124. warn: getLogHandler(parseAst_js.LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  21125. }, inputOptions);
  21126. if (processedOptions) {
  21127. inputOptions = processedOptions;
  21128. }
  21129. }
  21130. return inputOptions;
  21131. }
  21132. function normalizePlugins(plugins, anonymousPrefix) {
  21133. for (const [index, plugin] of plugins.entries()) {
  21134. if (!plugin.name) {
  21135. plugin.name = `${anonymousPrefix}${index + 1}`;
  21136. }
  21137. }
  21138. }
  21139. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  21140. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  21141. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  21142. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  21143. const generated = await bundle.generate(isWrite);
  21144. if (isWrite) {
  21145. timeStart('WRITE', 1);
  21146. if (!outputOptions.dir && !outputOptions.file) {
  21147. return parseAst_js.error(parseAst_js.logMissingFileOrDirOption());
  21148. }
  21149. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  21150. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  21151. timeEnd('WRITE', 1);
  21152. }
  21153. return createOutput(generated);
  21154. });
  21155. }
  21156. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  21157. if (!rawOutputOptions) {
  21158. throw new Error('You must supply an options object');
  21159. }
  21160. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  21161. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  21162. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  21163. return {
  21164. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  21165. outputPluginDriver
  21166. };
  21167. }
  21168. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  21169. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  21170. const emitError = () => pluginContext.error(parseAst_js.logCannotEmitFromOptionsHook());
  21171. return {
  21172. ...pluginContext,
  21173. emitFile: emitError,
  21174. setAssetSource: emitError
  21175. };
  21176. }), inputOptions, unsetInputOptions);
  21177. }
  21178. function createOutput(outputBundle) {
  21179. return {
  21180. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  21181. };
  21182. }
  21183. var SortingFileType;
  21184. (function (SortingFileType) {
  21185. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  21186. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  21187. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  21188. })(SortingFileType || (SortingFileType = {}));
  21189. function getSortingFileType(file) {
  21190. if (file.type === 'asset') {
  21191. return SortingFileType.ASSET;
  21192. }
  21193. if (file.isEntry) {
  21194. return SortingFileType.ENTRY_CHUNK;
  21195. }
  21196. return SortingFileType.SECONDARY_CHUNK;
  21197. }
  21198. async function writeOutputFile(outputFile, outputOptions) {
  21199. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  21200. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  21201. await promises.mkdir(path.dirname(fileName), { recursive: true });
  21202. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  21203. }
  21204. /**
  21205. * Auxiliary function for defining rollup configuration
  21206. * Mainly to facilitate IDE code prompts, after all, export default does not
  21207. * prompt, even if you add @type annotations, it is not accurate
  21208. * @param options
  21209. */
  21210. function defineConfig(options) {
  21211. return options;
  21212. }
  21213. exports.blue = blue;
  21214. exports.bold = bold;
  21215. exports.commandAliases = commandAliases;
  21216. exports.createFilter = createFilter;
  21217. exports.cyan = cyan$1;
  21218. exports.cyan$1 = cyan;
  21219. exports.defineConfig = defineConfig;
  21220. exports.ensureArray = ensureArray$1;
  21221. exports.getAugmentedNamespace = getAugmentedNamespace;
  21222. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  21223. exports.getNewArray = getNewArray;
  21224. exports.getOrCreate = getOrCreate;
  21225. exports.gray = gray;
  21226. exports.green = green;
  21227. exports.handleError = handleError;
  21228. exports.isWatchEnabled = isWatchEnabled;
  21229. exports.mergeOptions = mergeOptions;
  21230. exports.normalizePluginOption = normalizePluginOption;
  21231. exports.rollup = rollup;
  21232. exports.rollupInternal = rollupInternal;
  21233. exports.stderr = stderr;
  21234. exports.underline = underline;
  21235. exports.version = version;
  21236. exports.yellow = yellow;
  21237. //# sourceMappingURL=rollup.js.map