rollup.js 870 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874
  1. /*
  2. @license
  3. Rollup.js v2.77.3
  4. Thu, 11 Aug 2022 05:48:58 GMT - commit 1165d46685ef3c70617b2f150ab245ff5de5e783
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0, { resolve, basename, extname, dirname, relative as relative$1, win32, posix, isAbsolute as isAbsolute$1 } from 'path';
  9. import process$1 from 'process';
  10. import { performance } from 'perf_hooks';
  11. import { createHash as createHash$1 } from 'crypto';
  12. import { promises } from 'fs';
  13. import { EventEmitter } from 'events';
  14. var version$1 = "2.77.3";
  15. var charToInteger = {};
  16. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  18. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  19. }
  20. function decode(mappings) {
  21. var decoded = [];
  22. var line = [];
  23. var segment = [
  24. 0,
  25. 0,
  26. 0,
  27. 0,
  28. 0,
  29. ];
  30. var j = 0;
  31. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  32. var c = mappings.charCodeAt(i);
  33. if (c === 44) { // ","
  34. segmentify(line, segment, j);
  35. j = 0;
  36. }
  37. else if (c === 59) { // ";"
  38. segmentify(line, segment, j);
  39. j = 0;
  40. decoded.push(line);
  41. line = [];
  42. segment[0] = 0;
  43. }
  44. else {
  45. var integer = charToInteger[c];
  46. if (integer === undefined) {
  47. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  48. }
  49. var hasContinuationBit = integer & 32;
  50. integer &= 31;
  51. value += integer << shift;
  52. if (hasContinuationBit) {
  53. shift += 5;
  54. }
  55. else {
  56. var shouldNegate = value & 1;
  57. value >>>= 1;
  58. if (shouldNegate) {
  59. value = value === 0 ? -0x80000000 : -value;
  60. }
  61. segment[j] += value;
  62. j++;
  63. value = shift = 0; // reset
  64. }
  65. }
  66. }
  67. segmentify(line, segment, j);
  68. decoded.push(line);
  69. return decoded;
  70. }
  71. function segmentify(line, segment, j) {
  72. // This looks ugly, but we're creating specialized arrays with a specific
  73. // length. This is much faster than creating a new array (which v8 expands to
  74. // a capacity of 17 after pushing the first item), or slicing out a subarray
  75. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  76. // length 5 (since not everything will have an associated name), followed by
  77. // length 1 (it's probably rare for a source substring to not have an
  78. // associated segment data).
  79. if (j === 4)
  80. line.push([segment[0], segment[1], segment[2], segment[3]]);
  81. else if (j === 5)
  82. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  83. else if (j === 1)
  84. line.push([segment[0]]);
  85. }
  86. function encode(decoded) {
  87. var sourceFileIndex = 0; // second field
  88. var sourceCodeLine = 0; // third field
  89. var sourceCodeColumn = 0; // fourth field
  90. var nameIndex = 0; // fifth field
  91. var mappings = '';
  92. for (var i = 0; i < decoded.length; i++) {
  93. var line = decoded[i];
  94. if (i > 0)
  95. mappings += ';';
  96. if (line.length === 0)
  97. continue;
  98. var generatedCodeColumn = 0; // first field
  99. var lineMappings = [];
  100. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  101. var segment = line_1[_i];
  102. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  103. generatedCodeColumn = segment[0];
  104. if (segment.length > 1) {
  105. segmentMappings +=
  106. encodeInteger(segment[1] - sourceFileIndex) +
  107. encodeInteger(segment[2] - sourceCodeLine) +
  108. encodeInteger(segment[3] - sourceCodeColumn);
  109. sourceFileIndex = segment[1];
  110. sourceCodeLine = segment[2];
  111. sourceCodeColumn = segment[3];
  112. }
  113. if (segment.length === 5) {
  114. segmentMappings += encodeInteger(segment[4] - nameIndex);
  115. nameIndex = segment[4];
  116. }
  117. lineMappings.push(segmentMappings);
  118. }
  119. mappings += lineMappings.join(',');
  120. }
  121. return mappings;
  122. }
  123. function encodeInteger(num) {
  124. var result = '';
  125. num = num < 0 ? (-num << 1) | 1 : num << 1;
  126. do {
  127. var clamped = num & 31;
  128. num >>>= 5;
  129. if (num > 0) {
  130. clamped |= 32;
  131. }
  132. result += chars$1[clamped];
  133. } while (num > 0);
  134. return result;
  135. }
  136. class BitSet {
  137. constructor(arg) {
  138. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  139. }
  140. add(n) {
  141. this.bits[n >> 5] |= 1 << (n & 31);
  142. }
  143. has(n) {
  144. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  145. }
  146. }
  147. class Chunk$1 {
  148. constructor(start, end, content) {
  149. this.start = start;
  150. this.end = end;
  151. this.original = content;
  152. this.intro = '';
  153. this.outro = '';
  154. this.content = content;
  155. this.storeName = false;
  156. this.edited = false;
  157. // we make these non-enumerable, for sanity while debugging
  158. Object.defineProperties(this, {
  159. previous: { writable: true, value: null },
  160. next: { writable: true, value: null },
  161. });
  162. }
  163. appendLeft(content) {
  164. this.outro += content;
  165. }
  166. appendRight(content) {
  167. this.intro = this.intro + content;
  168. }
  169. clone() {
  170. const chunk = new Chunk$1(this.start, this.end, this.original);
  171. chunk.intro = this.intro;
  172. chunk.outro = this.outro;
  173. chunk.content = this.content;
  174. chunk.storeName = this.storeName;
  175. chunk.edited = this.edited;
  176. return chunk;
  177. }
  178. contains(index) {
  179. return this.start < index && index < this.end;
  180. }
  181. eachNext(fn) {
  182. let chunk = this;
  183. while (chunk) {
  184. fn(chunk);
  185. chunk = chunk.next;
  186. }
  187. }
  188. eachPrevious(fn) {
  189. let chunk = this;
  190. while (chunk) {
  191. fn(chunk);
  192. chunk = chunk.previous;
  193. }
  194. }
  195. edit(content, storeName, contentOnly) {
  196. this.content = content;
  197. if (!contentOnly) {
  198. this.intro = '';
  199. this.outro = '';
  200. }
  201. this.storeName = storeName;
  202. this.edited = true;
  203. return this;
  204. }
  205. prependLeft(content) {
  206. this.outro = content + this.outro;
  207. }
  208. prependRight(content) {
  209. this.intro = content + this.intro;
  210. }
  211. split(index) {
  212. const sliceIndex = index - this.start;
  213. const originalBefore = this.original.slice(0, sliceIndex);
  214. const originalAfter = this.original.slice(sliceIndex);
  215. this.original = originalBefore;
  216. const newChunk = new Chunk$1(index, this.end, originalAfter);
  217. newChunk.outro = this.outro;
  218. this.outro = '';
  219. this.end = index;
  220. if (this.edited) {
  221. // TODO is this block necessary?...
  222. newChunk.edit('', false);
  223. this.content = '';
  224. } else {
  225. this.content = originalBefore;
  226. }
  227. newChunk.next = this.next;
  228. if (newChunk.next) newChunk.next.previous = newChunk;
  229. newChunk.previous = this;
  230. this.next = newChunk;
  231. return newChunk;
  232. }
  233. toString() {
  234. return this.intro + this.content + this.outro;
  235. }
  236. trimEnd(rx) {
  237. this.outro = this.outro.replace(rx, '');
  238. if (this.outro.length) return true;
  239. const trimmed = this.content.replace(rx, '');
  240. if (trimmed.length) {
  241. if (trimmed !== this.content) {
  242. this.split(this.start + trimmed.length).edit('', undefined, true);
  243. }
  244. return true;
  245. } else {
  246. this.edit('', undefined, true);
  247. this.intro = this.intro.replace(rx, '');
  248. if (this.intro.length) return true;
  249. }
  250. }
  251. trimStart(rx) {
  252. this.intro = this.intro.replace(rx, '');
  253. if (this.intro.length) return true;
  254. const trimmed = this.content.replace(rx, '');
  255. if (trimmed.length) {
  256. if (trimmed !== this.content) {
  257. this.split(this.end - trimmed.length);
  258. this.edit('', undefined, true);
  259. }
  260. return true;
  261. } else {
  262. this.edit('', undefined, true);
  263. this.outro = this.outro.replace(rx, '');
  264. if (this.outro.length) return true;
  265. }
  266. }
  267. }
  268. let btoa = () => {
  269. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  270. };
  271. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  272. btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
  273. } else if (typeof Buffer === 'function') {
  274. btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
  275. }
  276. class SourceMap {
  277. constructor(properties) {
  278. this.version = 3;
  279. this.file = properties.file;
  280. this.sources = properties.sources;
  281. this.sourcesContent = properties.sourcesContent;
  282. this.names = properties.names;
  283. this.mappings = encode(properties.mappings);
  284. }
  285. toString() {
  286. return JSON.stringify(this);
  287. }
  288. toUrl() {
  289. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  290. }
  291. }
  292. function guessIndent(code) {
  293. const lines = code.split('\n');
  294. const tabbed = lines.filter((line) => /^\t+/.test(line));
  295. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  296. if (tabbed.length === 0 && spaced.length === 0) {
  297. return null;
  298. }
  299. // More lines tabbed than spaced? Assume tabs, and
  300. // default to tabs in the case of a tie (or nothing
  301. // to go on)
  302. if (tabbed.length >= spaced.length) {
  303. return '\t';
  304. }
  305. // Otherwise, we need to guess the multiple
  306. const min = spaced.reduce((previous, current) => {
  307. const numSpaces = /^ +/.exec(current)[0].length;
  308. return Math.min(numSpaces, previous);
  309. }, Infinity);
  310. return new Array(min + 1).join(' ');
  311. }
  312. function getRelativePath(from, to) {
  313. const fromParts = from.split(/[/\\]/);
  314. const toParts = to.split(/[/\\]/);
  315. fromParts.pop(); // get dirname
  316. while (fromParts[0] === toParts[0]) {
  317. fromParts.shift();
  318. toParts.shift();
  319. }
  320. if (fromParts.length) {
  321. let i = fromParts.length;
  322. while (i--) fromParts[i] = '..';
  323. }
  324. return fromParts.concat(toParts).join('/');
  325. }
  326. const toString$1 = Object.prototype.toString;
  327. function isObject$1(thing) {
  328. return toString$1.call(thing) === '[object Object]';
  329. }
  330. function getLocator$1(source) {
  331. const originalLines = source.split('\n');
  332. const lineOffsets = [];
  333. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  334. lineOffsets.push(pos);
  335. pos += originalLines[i].length + 1;
  336. }
  337. return function locate(index) {
  338. let i = 0;
  339. let j = lineOffsets.length;
  340. while (i < j) {
  341. const m = (i + j) >> 1;
  342. if (index < lineOffsets[m]) {
  343. j = m;
  344. } else {
  345. i = m + 1;
  346. }
  347. }
  348. const line = i - 1;
  349. const column = index - lineOffsets[line];
  350. return { line, column };
  351. };
  352. }
  353. class Mappings {
  354. constructor(hires) {
  355. this.hires = hires;
  356. this.generatedCodeLine = 0;
  357. this.generatedCodeColumn = 0;
  358. this.raw = [];
  359. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  360. this.pending = null;
  361. }
  362. addEdit(sourceIndex, content, loc, nameIndex) {
  363. if (content.length) {
  364. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  365. if (nameIndex >= 0) {
  366. segment.push(nameIndex);
  367. }
  368. this.rawSegments.push(segment);
  369. } else if (this.pending) {
  370. this.rawSegments.push(this.pending);
  371. }
  372. this.advance(content);
  373. this.pending = null;
  374. }
  375. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  376. let originalCharIndex = chunk.start;
  377. let first = true;
  378. while (originalCharIndex < chunk.end) {
  379. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  380. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  381. }
  382. if (original[originalCharIndex] === '\n') {
  383. loc.line += 1;
  384. loc.column = 0;
  385. this.generatedCodeLine += 1;
  386. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  387. this.generatedCodeColumn = 0;
  388. first = true;
  389. } else {
  390. loc.column += 1;
  391. this.generatedCodeColumn += 1;
  392. first = false;
  393. }
  394. originalCharIndex += 1;
  395. }
  396. this.pending = null;
  397. }
  398. advance(str) {
  399. if (!str) return;
  400. const lines = str.split('\n');
  401. if (lines.length > 1) {
  402. for (let i = 0; i < lines.length - 1; i++) {
  403. this.generatedCodeLine++;
  404. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  405. }
  406. this.generatedCodeColumn = 0;
  407. }
  408. this.generatedCodeColumn += lines[lines.length - 1].length;
  409. }
  410. }
  411. const n = '\n';
  412. const warned = {
  413. insertLeft: false,
  414. insertRight: false,
  415. storeName: false,
  416. };
  417. class MagicString {
  418. constructor(string, options = {}) {
  419. const chunk = new Chunk$1(0, string.length, string);
  420. Object.defineProperties(this, {
  421. original: { writable: true, value: string },
  422. outro: { writable: true, value: '' },
  423. intro: { writable: true, value: '' },
  424. firstChunk: { writable: true, value: chunk },
  425. lastChunk: { writable: true, value: chunk },
  426. lastSearchedChunk: { writable: true, value: chunk },
  427. byStart: { writable: true, value: {} },
  428. byEnd: { writable: true, value: {} },
  429. filename: { writable: true, value: options.filename },
  430. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  431. sourcemapLocations: { writable: true, value: new BitSet() },
  432. storedNames: { writable: true, value: {} },
  433. indentStr: { writable: true, value: guessIndent(string) },
  434. });
  435. this.byStart[0] = chunk;
  436. this.byEnd[string.length] = chunk;
  437. }
  438. addSourcemapLocation(char) {
  439. this.sourcemapLocations.add(char);
  440. }
  441. append(content) {
  442. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  443. this.outro += content;
  444. return this;
  445. }
  446. appendLeft(index, content) {
  447. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  448. this._split(index);
  449. const chunk = this.byEnd[index];
  450. if (chunk) {
  451. chunk.appendLeft(content);
  452. } else {
  453. this.intro += content;
  454. }
  455. return this;
  456. }
  457. appendRight(index, content) {
  458. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  459. this._split(index);
  460. const chunk = this.byStart[index];
  461. if (chunk) {
  462. chunk.appendRight(content);
  463. } else {
  464. this.outro += content;
  465. }
  466. return this;
  467. }
  468. clone() {
  469. const cloned = new MagicString(this.original, { filename: this.filename });
  470. let originalChunk = this.firstChunk;
  471. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  472. while (originalChunk) {
  473. cloned.byStart[clonedChunk.start] = clonedChunk;
  474. cloned.byEnd[clonedChunk.end] = clonedChunk;
  475. const nextOriginalChunk = originalChunk.next;
  476. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  477. if (nextClonedChunk) {
  478. clonedChunk.next = nextClonedChunk;
  479. nextClonedChunk.previous = clonedChunk;
  480. clonedChunk = nextClonedChunk;
  481. }
  482. originalChunk = nextOriginalChunk;
  483. }
  484. cloned.lastChunk = clonedChunk;
  485. if (this.indentExclusionRanges) {
  486. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  487. }
  488. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  489. cloned.intro = this.intro;
  490. cloned.outro = this.outro;
  491. return cloned;
  492. }
  493. generateDecodedMap(options) {
  494. options = options || {};
  495. const sourceIndex = 0;
  496. const names = Object.keys(this.storedNames);
  497. const mappings = new Mappings(options.hires);
  498. const locate = getLocator$1(this.original);
  499. if (this.intro) {
  500. mappings.advance(this.intro);
  501. }
  502. this.firstChunk.eachNext((chunk) => {
  503. const loc = locate(chunk.start);
  504. if (chunk.intro.length) mappings.advance(chunk.intro);
  505. if (chunk.edited) {
  506. mappings.addEdit(
  507. sourceIndex,
  508. chunk.content,
  509. loc,
  510. chunk.storeName ? names.indexOf(chunk.original) : -1
  511. );
  512. } else {
  513. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  514. }
  515. if (chunk.outro.length) mappings.advance(chunk.outro);
  516. });
  517. return {
  518. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  519. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  520. sourcesContent: options.includeContent ? [this.original] : [null],
  521. names,
  522. mappings: mappings.raw,
  523. };
  524. }
  525. generateMap(options) {
  526. return new SourceMap(this.generateDecodedMap(options));
  527. }
  528. getIndentString() {
  529. return this.indentStr === null ? '\t' : this.indentStr;
  530. }
  531. indent(indentStr, options) {
  532. const pattern = /^[^\r\n]/gm;
  533. if (isObject$1(indentStr)) {
  534. options = indentStr;
  535. indentStr = undefined;
  536. }
  537. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  538. if (indentStr === '') return this; // noop
  539. options = options || {};
  540. // Process exclusion ranges
  541. const isExcluded = {};
  542. if (options.exclude) {
  543. const exclusions =
  544. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  545. exclusions.forEach((exclusion) => {
  546. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  547. isExcluded[i] = true;
  548. }
  549. });
  550. }
  551. let shouldIndentNextCharacter = options.indentStart !== false;
  552. const replacer = (match) => {
  553. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  554. shouldIndentNextCharacter = true;
  555. return match;
  556. };
  557. this.intro = this.intro.replace(pattern, replacer);
  558. let charIndex = 0;
  559. let chunk = this.firstChunk;
  560. while (chunk) {
  561. const end = chunk.end;
  562. if (chunk.edited) {
  563. if (!isExcluded[charIndex]) {
  564. chunk.content = chunk.content.replace(pattern, replacer);
  565. if (chunk.content.length) {
  566. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  567. }
  568. }
  569. } else {
  570. charIndex = chunk.start;
  571. while (charIndex < end) {
  572. if (!isExcluded[charIndex]) {
  573. const char = this.original[charIndex];
  574. if (char === '\n') {
  575. shouldIndentNextCharacter = true;
  576. } else if (char !== '\r' && shouldIndentNextCharacter) {
  577. shouldIndentNextCharacter = false;
  578. if (charIndex === chunk.start) {
  579. chunk.prependRight(indentStr);
  580. } else {
  581. this._splitChunk(chunk, charIndex);
  582. chunk = chunk.next;
  583. chunk.prependRight(indentStr);
  584. }
  585. }
  586. }
  587. charIndex += 1;
  588. }
  589. }
  590. charIndex = chunk.end;
  591. chunk = chunk.next;
  592. }
  593. this.outro = this.outro.replace(pattern, replacer);
  594. return this;
  595. }
  596. insert() {
  597. throw new Error(
  598. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  599. );
  600. }
  601. insertLeft(index, content) {
  602. if (!warned.insertLeft) {
  603. console.warn(
  604. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  605. ); // eslint-disable-line no-console
  606. warned.insertLeft = true;
  607. }
  608. return this.appendLeft(index, content);
  609. }
  610. insertRight(index, content) {
  611. if (!warned.insertRight) {
  612. console.warn(
  613. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  614. ); // eslint-disable-line no-console
  615. warned.insertRight = true;
  616. }
  617. return this.prependRight(index, content);
  618. }
  619. move(start, end, index) {
  620. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  621. this._split(start);
  622. this._split(end);
  623. this._split(index);
  624. const first = this.byStart[start];
  625. const last = this.byEnd[end];
  626. const oldLeft = first.previous;
  627. const oldRight = last.next;
  628. const newRight = this.byStart[index];
  629. if (!newRight && last === this.lastChunk) return this;
  630. const newLeft = newRight ? newRight.previous : this.lastChunk;
  631. if (oldLeft) oldLeft.next = oldRight;
  632. if (oldRight) oldRight.previous = oldLeft;
  633. if (newLeft) newLeft.next = first;
  634. if (newRight) newRight.previous = last;
  635. if (!first.previous) this.firstChunk = last.next;
  636. if (!last.next) {
  637. this.lastChunk = first.previous;
  638. this.lastChunk.next = null;
  639. }
  640. first.previous = newLeft;
  641. last.next = newRight || null;
  642. if (!newLeft) this.firstChunk = first;
  643. if (!newRight) this.lastChunk = last;
  644. return this;
  645. }
  646. overwrite(start, end, content, options) {
  647. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  648. while (start < 0) start += this.original.length;
  649. while (end < 0) end += this.original.length;
  650. if (end > this.original.length) throw new Error('end is out of bounds');
  651. if (start === end)
  652. throw new Error(
  653. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  654. );
  655. this._split(start);
  656. this._split(end);
  657. if (options === true) {
  658. if (!warned.storeName) {
  659. console.warn(
  660. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  661. ); // eslint-disable-line no-console
  662. warned.storeName = true;
  663. }
  664. options = { storeName: true };
  665. }
  666. const storeName = options !== undefined ? options.storeName : false;
  667. const contentOnly = options !== undefined ? options.contentOnly : false;
  668. if (storeName) {
  669. const original = this.original.slice(start, end);
  670. Object.defineProperty(this.storedNames, original, {
  671. writable: true,
  672. value: true,
  673. enumerable: true,
  674. });
  675. }
  676. const first = this.byStart[start];
  677. const last = this.byEnd[end];
  678. if (first) {
  679. let chunk = first;
  680. while (chunk !== last) {
  681. if (chunk.next !== this.byStart[chunk.end]) {
  682. throw new Error('Cannot overwrite across a split point');
  683. }
  684. chunk = chunk.next;
  685. chunk.edit('', false);
  686. }
  687. first.edit(content, storeName, contentOnly);
  688. } else {
  689. // must be inserting at the end
  690. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  691. // TODO last chunk in the array may not be the last chunk, if it's moved...
  692. last.next = newChunk;
  693. newChunk.previous = last;
  694. }
  695. return this;
  696. }
  697. prepend(content) {
  698. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  699. this.intro = content + this.intro;
  700. return this;
  701. }
  702. prependLeft(index, content) {
  703. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  704. this._split(index);
  705. const chunk = this.byEnd[index];
  706. if (chunk) {
  707. chunk.prependLeft(content);
  708. } else {
  709. this.intro = content + this.intro;
  710. }
  711. return this;
  712. }
  713. prependRight(index, content) {
  714. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  715. this._split(index);
  716. const chunk = this.byStart[index];
  717. if (chunk) {
  718. chunk.prependRight(content);
  719. } else {
  720. this.outro = content + this.outro;
  721. }
  722. return this;
  723. }
  724. remove(start, end) {
  725. while (start < 0) start += this.original.length;
  726. while (end < 0) end += this.original.length;
  727. if (start === end) return this;
  728. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  729. if (start > end) throw new Error('end must be greater than start');
  730. this._split(start);
  731. this._split(end);
  732. let chunk = this.byStart[start];
  733. while (chunk) {
  734. chunk.intro = '';
  735. chunk.outro = '';
  736. chunk.edit('');
  737. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  738. }
  739. return this;
  740. }
  741. lastChar() {
  742. if (this.outro.length) return this.outro[this.outro.length - 1];
  743. let chunk = this.lastChunk;
  744. do {
  745. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  746. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  747. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  748. } while ((chunk = chunk.previous));
  749. if (this.intro.length) return this.intro[this.intro.length - 1];
  750. return '';
  751. }
  752. lastLine() {
  753. let lineIndex = this.outro.lastIndexOf(n);
  754. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  755. let lineStr = this.outro;
  756. let chunk = this.lastChunk;
  757. do {
  758. if (chunk.outro.length > 0) {
  759. lineIndex = chunk.outro.lastIndexOf(n);
  760. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  761. lineStr = chunk.outro + lineStr;
  762. }
  763. if (chunk.content.length > 0) {
  764. lineIndex = chunk.content.lastIndexOf(n);
  765. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  766. lineStr = chunk.content + lineStr;
  767. }
  768. if (chunk.intro.length > 0) {
  769. lineIndex = chunk.intro.lastIndexOf(n);
  770. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  771. lineStr = chunk.intro + lineStr;
  772. }
  773. } while ((chunk = chunk.previous));
  774. lineIndex = this.intro.lastIndexOf(n);
  775. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  776. return this.intro + lineStr;
  777. }
  778. slice(start = 0, end = this.original.length) {
  779. while (start < 0) start += this.original.length;
  780. while (end < 0) end += this.original.length;
  781. let result = '';
  782. // find start chunk
  783. let chunk = this.firstChunk;
  784. while (chunk && (chunk.start > start || chunk.end <= start)) {
  785. // found end chunk before start
  786. if (chunk.start < end && chunk.end >= end) {
  787. return result;
  788. }
  789. chunk = chunk.next;
  790. }
  791. if (chunk && chunk.edited && chunk.start !== start)
  792. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  793. const startChunk = chunk;
  794. while (chunk) {
  795. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  796. result += chunk.intro;
  797. }
  798. const containsEnd = chunk.start < end && chunk.end >= end;
  799. if (containsEnd && chunk.edited && chunk.end !== end)
  800. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  801. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  802. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  803. result += chunk.content.slice(sliceStart, sliceEnd);
  804. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  805. result += chunk.outro;
  806. }
  807. if (containsEnd) {
  808. break;
  809. }
  810. chunk = chunk.next;
  811. }
  812. return result;
  813. }
  814. // TODO deprecate this? not really very useful
  815. snip(start, end) {
  816. const clone = this.clone();
  817. clone.remove(0, start);
  818. clone.remove(end, clone.original.length);
  819. return clone;
  820. }
  821. _split(index) {
  822. if (this.byStart[index] || this.byEnd[index]) return;
  823. let chunk = this.lastSearchedChunk;
  824. const searchForward = index > chunk.end;
  825. while (chunk) {
  826. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  827. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  828. }
  829. }
  830. _splitChunk(chunk, index) {
  831. if (chunk.edited && chunk.content.length) {
  832. // zero-length edited chunks are a special case (overlapping replacements)
  833. const loc = getLocator$1(this.original)(index);
  834. throw new Error(
  835. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  836. );
  837. }
  838. const newChunk = chunk.split(index);
  839. this.byEnd[index] = chunk;
  840. this.byStart[index] = newChunk;
  841. this.byEnd[newChunk.end] = newChunk;
  842. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  843. this.lastSearchedChunk = chunk;
  844. return true;
  845. }
  846. toString() {
  847. let str = this.intro;
  848. let chunk = this.firstChunk;
  849. while (chunk) {
  850. str += chunk.toString();
  851. chunk = chunk.next;
  852. }
  853. return str + this.outro;
  854. }
  855. isEmpty() {
  856. let chunk = this.firstChunk;
  857. do {
  858. if (
  859. (chunk.intro.length && chunk.intro.trim()) ||
  860. (chunk.content.length && chunk.content.trim()) ||
  861. (chunk.outro.length && chunk.outro.trim())
  862. )
  863. return false;
  864. } while ((chunk = chunk.next));
  865. return true;
  866. }
  867. length() {
  868. let chunk = this.firstChunk;
  869. let length = 0;
  870. do {
  871. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  872. } while ((chunk = chunk.next));
  873. return length;
  874. }
  875. trimLines() {
  876. return this.trim('[\\r\\n]');
  877. }
  878. trim(charType) {
  879. return this.trimStart(charType).trimEnd(charType);
  880. }
  881. trimEndAborted(charType) {
  882. const rx = new RegExp((charType || '\\s') + '+$');
  883. this.outro = this.outro.replace(rx, '');
  884. if (this.outro.length) return true;
  885. let chunk = this.lastChunk;
  886. do {
  887. const end = chunk.end;
  888. const aborted = chunk.trimEnd(rx);
  889. // if chunk was trimmed, we have a new lastChunk
  890. if (chunk.end !== end) {
  891. if (this.lastChunk === chunk) {
  892. this.lastChunk = chunk.next;
  893. }
  894. this.byEnd[chunk.end] = chunk;
  895. this.byStart[chunk.next.start] = chunk.next;
  896. this.byEnd[chunk.next.end] = chunk.next;
  897. }
  898. if (aborted) return true;
  899. chunk = chunk.previous;
  900. } while (chunk);
  901. return false;
  902. }
  903. trimEnd(charType) {
  904. this.trimEndAborted(charType);
  905. return this;
  906. }
  907. trimStartAborted(charType) {
  908. const rx = new RegExp('^' + (charType || '\\s') + '+');
  909. this.intro = this.intro.replace(rx, '');
  910. if (this.intro.length) return true;
  911. let chunk = this.firstChunk;
  912. do {
  913. const end = chunk.end;
  914. const aborted = chunk.trimStart(rx);
  915. if (chunk.end !== end) {
  916. // special case...
  917. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  918. this.byEnd[chunk.end] = chunk;
  919. this.byStart[chunk.next.start] = chunk.next;
  920. this.byEnd[chunk.next.end] = chunk.next;
  921. }
  922. if (aborted) return true;
  923. chunk = chunk.next;
  924. } while (chunk);
  925. return false;
  926. }
  927. trimStart(charType) {
  928. this.trimStartAborted(charType);
  929. return this;
  930. }
  931. hasChanged() {
  932. return this.original !== this.toString();
  933. }
  934. replace(searchValue, replacement) {
  935. function getReplacement(match, str) {
  936. if (typeof replacement === 'string') {
  937. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  938. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  939. if (i === '$') return '$';
  940. if (i === '&') return match[0];
  941. const num = +i;
  942. if (num < match.length) return match[+i];
  943. return `$${i}`;
  944. });
  945. } else {
  946. return replacement(...match, match.index, str, match.groups);
  947. }
  948. }
  949. function matchAll(re, str) {
  950. let match;
  951. const matches = [];
  952. while ((match = re.exec(str))) {
  953. matches.push(match);
  954. }
  955. return matches;
  956. }
  957. if (typeof searchValue !== 'string' && searchValue.global) {
  958. const matches = matchAll(searchValue, this.original);
  959. matches.forEach((match) => {
  960. if (match.index != null)
  961. this.overwrite(
  962. match.index,
  963. match.index + match[0].length,
  964. getReplacement(match, this.original)
  965. );
  966. });
  967. } else {
  968. const match = this.original.match(searchValue);
  969. if (match && match.index != null)
  970. this.overwrite(
  971. match.index,
  972. match.index + match[0].length,
  973. getReplacement(match, this.original)
  974. );
  975. }
  976. return this;
  977. }
  978. }
  979. const hasOwnProp = Object.prototype.hasOwnProperty;
  980. class Bundle$1 {
  981. constructor(options = {}) {
  982. this.intro = options.intro || '';
  983. this.separator = options.separator !== undefined ? options.separator : '\n';
  984. this.sources = [];
  985. this.uniqueSources = [];
  986. this.uniqueSourceIndexByFilename = {};
  987. }
  988. addSource(source) {
  989. if (source instanceof MagicString) {
  990. return this.addSource({
  991. content: source,
  992. filename: source.filename,
  993. separator: this.separator,
  994. });
  995. }
  996. if (!isObject$1(source) || !source.content) {
  997. throw new Error(
  998. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  999. );
  1000. }
  1001. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1002. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1003. });
  1004. if (source.separator === undefined) {
  1005. // TODO there's a bunch of this sort of thing, needs cleaning up
  1006. source.separator = this.separator;
  1007. }
  1008. if (source.filename) {
  1009. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1010. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1011. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1012. } else {
  1013. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1014. if (source.content.original !== uniqueSource.content) {
  1015. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1016. }
  1017. }
  1018. }
  1019. this.sources.push(source);
  1020. return this;
  1021. }
  1022. append(str, options) {
  1023. this.addSource({
  1024. content: new MagicString(str),
  1025. separator: (options && options.separator) || '',
  1026. });
  1027. return this;
  1028. }
  1029. clone() {
  1030. const bundle = new Bundle$1({
  1031. intro: this.intro,
  1032. separator: this.separator,
  1033. });
  1034. this.sources.forEach((source) => {
  1035. bundle.addSource({
  1036. filename: source.filename,
  1037. content: source.content.clone(),
  1038. separator: source.separator,
  1039. });
  1040. });
  1041. return bundle;
  1042. }
  1043. generateDecodedMap(options = {}) {
  1044. const names = [];
  1045. this.sources.forEach((source) => {
  1046. Object.keys(source.content.storedNames).forEach((name) => {
  1047. if (!~names.indexOf(name)) names.push(name);
  1048. });
  1049. });
  1050. const mappings = new Mappings(options.hires);
  1051. if (this.intro) {
  1052. mappings.advance(this.intro);
  1053. }
  1054. this.sources.forEach((source, i) => {
  1055. if (i > 0) {
  1056. mappings.advance(this.separator);
  1057. }
  1058. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1059. const magicString = source.content;
  1060. const locate = getLocator$1(magicString.original);
  1061. if (magicString.intro) {
  1062. mappings.advance(magicString.intro);
  1063. }
  1064. magicString.firstChunk.eachNext((chunk) => {
  1065. const loc = locate(chunk.start);
  1066. if (chunk.intro.length) mappings.advance(chunk.intro);
  1067. if (source.filename) {
  1068. if (chunk.edited) {
  1069. mappings.addEdit(
  1070. sourceIndex,
  1071. chunk.content,
  1072. loc,
  1073. chunk.storeName ? names.indexOf(chunk.original) : -1
  1074. );
  1075. } else {
  1076. mappings.addUneditedChunk(
  1077. sourceIndex,
  1078. chunk,
  1079. magicString.original,
  1080. loc,
  1081. magicString.sourcemapLocations
  1082. );
  1083. }
  1084. } else {
  1085. mappings.advance(chunk.content);
  1086. }
  1087. if (chunk.outro.length) mappings.advance(chunk.outro);
  1088. });
  1089. if (magicString.outro) {
  1090. mappings.advance(magicString.outro);
  1091. }
  1092. });
  1093. return {
  1094. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1095. sources: this.uniqueSources.map((source) => {
  1096. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1097. }),
  1098. sourcesContent: this.uniqueSources.map((source) => {
  1099. return options.includeContent ? source.content : null;
  1100. }),
  1101. names,
  1102. mappings: mappings.raw,
  1103. };
  1104. }
  1105. generateMap(options) {
  1106. return new SourceMap(this.generateDecodedMap(options));
  1107. }
  1108. getIndentString() {
  1109. const indentStringCounts = {};
  1110. this.sources.forEach((source) => {
  1111. const indentStr = source.content.indentStr;
  1112. if (indentStr === null) return;
  1113. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1114. indentStringCounts[indentStr] += 1;
  1115. });
  1116. return (
  1117. Object.keys(indentStringCounts).sort((a, b) => {
  1118. return indentStringCounts[a] - indentStringCounts[b];
  1119. })[0] || '\t'
  1120. );
  1121. }
  1122. indent(indentStr) {
  1123. if (!arguments.length) {
  1124. indentStr = this.getIndentString();
  1125. }
  1126. if (indentStr === '') return this; // noop
  1127. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1128. this.sources.forEach((source, i) => {
  1129. const separator = source.separator !== undefined ? source.separator : this.separator;
  1130. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1131. source.content.indent(indentStr, {
  1132. exclude: source.indentExclusionRanges,
  1133. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1134. });
  1135. trailingNewline = source.content.lastChar() === '\n';
  1136. });
  1137. if (this.intro) {
  1138. this.intro =
  1139. indentStr +
  1140. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1141. return index > 0 ? indentStr + match : match;
  1142. });
  1143. }
  1144. return this;
  1145. }
  1146. prepend(str) {
  1147. this.intro = str + this.intro;
  1148. return this;
  1149. }
  1150. toString() {
  1151. const body = this.sources
  1152. .map((source, i) => {
  1153. const separator = source.separator !== undefined ? source.separator : this.separator;
  1154. const str = (i > 0 ? separator : '') + source.content.toString();
  1155. return str;
  1156. })
  1157. .join('');
  1158. return this.intro + body;
  1159. }
  1160. isEmpty() {
  1161. if (this.intro.length && this.intro.trim()) return false;
  1162. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1163. return true;
  1164. }
  1165. length() {
  1166. return this.sources.reduce(
  1167. (length, source) => length + source.content.length(),
  1168. this.intro.length
  1169. );
  1170. }
  1171. trimLines() {
  1172. return this.trim('[\\r\\n]');
  1173. }
  1174. trim(charType) {
  1175. return this.trimStart(charType).trimEnd(charType);
  1176. }
  1177. trimStart(charType) {
  1178. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1179. this.intro = this.intro.replace(rx, '');
  1180. if (!this.intro) {
  1181. let source;
  1182. let i = 0;
  1183. do {
  1184. source = this.sources[i++];
  1185. if (!source) {
  1186. break;
  1187. }
  1188. } while (!source.content.trimStartAborted(charType));
  1189. }
  1190. return this;
  1191. }
  1192. trimEnd(charType) {
  1193. const rx = new RegExp((charType || '\\s') + '+$');
  1194. let source;
  1195. let i = this.sources.length - 1;
  1196. do {
  1197. source = this.sources[i--];
  1198. if (!source) {
  1199. this.intro = this.intro.replace(rx, '');
  1200. break;
  1201. }
  1202. } while (!source.content.trimEndAborted(charType));
  1203. return this;
  1204. }
  1205. }
  1206. const ANY_SLASH_REGEX = /[/\\]/;
  1207. function relative(from, to) {
  1208. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  1209. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  1210. if (fromParts[0] === '.')
  1211. fromParts.shift();
  1212. if (toParts[0] === '.')
  1213. toParts.shift();
  1214. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1215. fromParts.shift();
  1216. toParts.shift();
  1217. }
  1218. while (toParts[0] === '..' && fromParts.length > 0) {
  1219. toParts.shift();
  1220. fromParts.pop();
  1221. }
  1222. while (fromParts.pop()) {
  1223. toParts.unshift('..');
  1224. }
  1225. return toParts.join('/');
  1226. }
  1227. function getOrCreate(map, key, init) {
  1228. const existing = map.get(key);
  1229. if (existing) {
  1230. return existing;
  1231. }
  1232. const value = init();
  1233. map.set(key, value);
  1234. return value;
  1235. }
  1236. const UnknownKey = Symbol('Unknown Key');
  1237. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1238. const UnknownInteger = Symbol('Unknown Integer');
  1239. const EMPTY_PATH = [];
  1240. const UNKNOWN_PATH = [UnknownKey];
  1241. // For deoptimizations, this means we are modifying an unknown property but did
  1242. // not lose track of the object or are creating a setter/getter;
  1243. // For assignment effects it means we do not check for setter/getter effects
  1244. // but only if something is mutated that is included, which is relevant for
  1245. // Object.defineProperty
  1246. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1247. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1248. const EntitiesKey = Symbol('Entities');
  1249. class PathTracker {
  1250. constructor() {
  1251. this.entityPaths = Object.create(null, {
  1252. [EntitiesKey]: { value: new Set() }
  1253. });
  1254. }
  1255. trackEntityAtPathAndGetIfTracked(path, entity) {
  1256. const trackedEntities = this.getEntities(path);
  1257. if (trackedEntities.has(entity))
  1258. return true;
  1259. trackedEntities.add(entity);
  1260. return false;
  1261. }
  1262. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1263. const trackedEntities = this.getEntities(path);
  1264. if (trackedEntities.has(entity))
  1265. return returnIfTracked;
  1266. trackedEntities.add(entity);
  1267. const result = onUntracked();
  1268. trackedEntities.delete(entity);
  1269. return result;
  1270. }
  1271. getEntities(path) {
  1272. let currentPaths = this.entityPaths;
  1273. for (const pathSegment of path) {
  1274. currentPaths = currentPaths[pathSegment] =
  1275. currentPaths[pathSegment] ||
  1276. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1277. }
  1278. return currentPaths[EntitiesKey];
  1279. }
  1280. }
  1281. const SHARED_RECURSION_TRACKER = new PathTracker();
  1282. class DiscriminatedPathTracker {
  1283. constructor() {
  1284. this.entityPaths = Object.create(null, {
  1285. [EntitiesKey]: { value: new Map() }
  1286. });
  1287. }
  1288. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1289. let currentPaths = this.entityPaths;
  1290. for (const pathSegment of path) {
  1291. currentPaths = currentPaths[pathSegment] =
  1292. currentPaths[pathSegment] ||
  1293. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1294. }
  1295. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1296. if (trackedEntities.has(entity))
  1297. return true;
  1298. trackedEntities.add(entity);
  1299. return false;
  1300. }
  1301. }
  1302. const UnknownValue = Symbol('Unknown Value');
  1303. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1304. class ExpressionEntity {
  1305. constructor() {
  1306. this.included = false;
  1307. }
  1308. deoptimizePath(_path) { }
  1309. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  1310. thisArg.deoptimizePath(UNKNOWN_PATH);
  1311. }
  1312. /**
  1313. * If possible it returns a stringifyable literal value for this node that can be used
  1314. * for inlining or comparing values.
  1315. * Otherwise it should return UnknownValue.
  1316. */
  1317. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1318. return UnknownValue;
  1319. }
  1320. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1321. return UNKNOWN_EXPRESSION;
  1322. }
  1323. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1324. return true;
  1325. }
  1326. include(_context, _includeChildrenRecursively, _options) {
  1327. this.included = true;
  1328. }
  1329. includeCallArguments(context, args) {
  1330. for (const arg of args) {
  1331. arg.include(context, false);
  1332. }
  1333. }
  1334. shouldBeIncluded(_context) {
  1335. return true;
  1336. }
  1337. }
  1338. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1339. })();
  1340. const INTERACTION_ACCESSED = 0;
  1341. const INTERACTION_ASSIGNED = 1;
  1342. const INTERACTION_CALLED = 2;
  1343. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1344. thisArg: null,
  1345. type: INTERACTION_ACCESSED
  1346. };
  1347. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  1348. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1349. args: UNKNOWN_ARG,
  1350. thisArg: null,
  1351. type: INTERACTION_ASSIGNED
  1352. };
  1353. const NO_ARGS = [];
  1354. // While this is technically a call without arguments, we can compare against
  1355. // this reference in places where precise values or thisArg would make a
  1356. // difference
  1357. const NODE_INTERACTION_UNKNOWN_CALL = {
  1358. args: NO_ARGS,
  1359. thisArg: null,
  1360. type: INTERACTION_CALLED,
  1361. withNew: false
  1362. };
  1363. class Variable extends ExpressionEntity {
  1364. constructor(name) {
  1365. super();
  1366. this.name = name;
  1367. this.alwaysRendered = false;
  1368. this.initReached = false;
  1369. this.isId = false;
  1370. this.isReassigned = false;
  1371. this.kind = null;
  1372. this.renderBaseName = null;
  1373. this.renderName = null;
  1374. }
  1375. /**
  1376. * Binds identifiers that reference this variable to this variable.
  1377. * Necessary to be able to change variable names.
  1378. */
  1379. addReference(_identifier) { }
  1380. getBaseVariableName() {
  1381. return this.renderBaseName || this.renderName || this.name;
  1382. }
  1383. getName(getPropertyAccess) {
  1384. const name = this.renderName || this.name;
  1385. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1386. }
  1387. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1388. return type !== INTERACTION_ACCESSED || path.length > 0;
  1389. }
  1390. /**
  1391. * Marks this variable as being part of the bundle, which is usually the case when one of
  1392. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1393. * previously.
  1394. * Once a variable is included, it should take care all its declarations are included.
  1395. */
  1396. include() {
  1397. this.included = true;
  1398. }
  1399. markCalledFromTryStatement() { }
  1400. setRenderNames(baseName, name) {
  1401. this.renderBaseName = baseName;
  1402. this.renderName = name;
  1403. }
  1404. }
  1405. class ExternalVariable extends Variable {
  1406. constructor(module, name) {
  1407. super(name);
  1408. this.referenced = false;
  1409. this.module = module;
  1410. this.isNamespace = name === '*';
  1411. }
  1412. addReference(identifier) {
  1413. this.referenced = true;
  1414. if (this.name === 'default' || this.name === '*') {
  1415. this.module.suggestName(identifier.name);
  1416. }
  1417. }
  1418. hasEffectsOnInteractionAtPath(path, { type }) {
  1419. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1420. }
  1421. include() {
  1422. if (!this.included) {
  1423. this.included = true;
  1424. this.module.used = true;
  1425. }
  1426. }
  1427. }
  1428. const BLANK = Object.freeze(Object.create(null));
  1429. const EMPTY_OBJECT = Object.freeze({});
  1430. const EMPTY_ARRAY = Object.freeze([]);
  1431. function getLocator(source, options) {
  1432. if (options === void 0) { options = {}; }
  1433. var offsetLine = options.offsetLine || 0;
  1434. var offsetColumn = options.offsetColumn || 0;
  1435. var originalLines = source.split('\n');
  1436. var start = 0;
  1437. var lineRanges = originalLines.map(function (line, i) {
  1438. var end = start + line.length + 1;
  1439. var range = { start: start, end: end, line: i };
  1440. start = end;
  1441. return range;
  1442. });
  1443. var i = 0;
  1444. function rangeContains(range, index) {
  1445. return range.start <= index && index < range.end;
  1446. }
  1447. function getLocation(range, index) {
  1448. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  1449. }
  1450. function locate(search, startIndex) {
  1451. if (typeof search === 'string') {
  1452. search = source.indexOf(search, startIndex || 0);
  1453. }
  1454. var range = lineRanges[i];
  1455. var d = search >= range.end ? 1 : -1;
  1456. while (range) {
  1457. if (rangeContains(range, search))
  1458. return getLocation(range, search);
  1459. i += d;
  1460. range = lineRanges[i];
  1461. }
  1462. }
  1463. return locate;
  1464. }
  1465. function locate(source, search, options) {
  1466. if (typeof options === 'number') {
  1467. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  1468. }
  1469. return getLocator(source, options)(search, options && options.startIndex);
  1470. }
  1471. function spaces(i) {
  1472. let result = '';
  1473. while (i--)
  1474. result += ' ';
  1475. return result;
  1476. }
  1477. function tabsToSpaces(str) {
  1478. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  1479. }
  1480. function getCodeFrame(source, line, column) {
  1481. let lines = source.split('\n');
  1482. const frameStart = Math.max(0, line - 3);
  1483. let frameEnd = Math.min(line + 2, lines.length);
  1484. lines = lines.slice(frameStart, frameEnd);
  1485. while (!/\S/.test(lines[lines.length - 1])) {
  1486. lines.pop();
  1487. frameEnd -= 1;
  1488. }
  1489. const digits = String(frameEnd).length;
  1490. return lines
  1491. .map((str, i) => {
  1492. const isErrorLine = frameStart + i + 1 === line;
  1493. let lineNum = String(i + frameStart + 1);
  1494. while (lineNum.length < digits)
  1495. lineNum = ` ${lineNum}`;
  1496. if (isErrorLine) {
  1497. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  1498. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  1499. }
  1500. return `${lineNum}: ${tabsToSpaces(str)}`;
  1501. })
  1502. .join('\n');
  1503. }
  1504. function printQuotedStringList(list, verbs) {
  1505. const isSingleItem = list.length <= 1;
  1506. const quotedList = list.map(item => `"${item}"`);
  1507. let output = isSingleItem
  1508. ? quotedList[0]
  1509. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  1510. if (verbs) {
  1511. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  1512. }
  1513. return output;
  1514. }
  1515. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  1516. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  1517. function isAbsolute(path) {
  1518. return ABSOLUTE_PATH_REGEX.test(path);
  1519. }
  1520. function isRelative(path) {
  1521. return RELATIVE_PATH_REGEX.test(path);
  1522. }
  1523. const BACKSLASH_REGEX = /\\/g;
  1524. function normalize(path) {
  1525. return path.replace(BACKSLASH_REGEX, '/');
  1526. }
  1527. function getAliasName(id) {
  1528. const base = basename(id);
  1529. return base.substring(0, base.length - extname(id).length);
  1530. }
  1531. function relativeId(id) {
  1532. if (!isAbsolute(id))
  1533. return id;
  1534. return relative(resolve(), id);
  1535. }
  1536. function isPathFragment(name) {
  1537. // starting with "/", "./", "../", "C:/"
  1538. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  1539. }
  1540. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  1541. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  1542. let relativePath = normalize(relative(dirname(importerId), targetPath));
  1543. if (stripJsExtension && relativePath.endsWith('.js')) {
  1544. relativePath = relativePath.slice(0, -3);
  1545. }
  1546. if (ensureFileName) {
  1547. if (relativePath === '')
  1548. return '../' + basename(targetPath);
  1549. if (UPPER_DIR_REGEX.test(relativePath)) {
  1550. return relativePath
  1551. .split('/')
  1552. .concat(['..', basename(targetPath)])
  1553. .join('/');
  1554. }
  1555. }
  1556. return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
  1557. }
  1558. function error(base) {
  1559. if (!(base instanceof Error))
  1560. base = Object.assign(new Error(base.message), base);
  1561. throw base;
  1562. }
  1563. function augmentCodeLocation(props, pos, source, id) {
  1564. if (typeof pos === 'object') {
  1565. const { line, column } = pos;
  1566. props.loc = { column, file: id, line };
  1567. }
  1568. else {
  1569. props.pos = pos;
  1570. const { line, column } = locate(source, pos, { offsetLine: 1 });
  1571. props.loc = { column, file: id, line };
  1572. }
  1573. if (props.frame === undefined) {
  1574. const { line, column } = props.loc;
  1575. props.frame = getCodeFrame(source, line, column);
  1576. }
  1577. }
  1578. var Errors;
  1579. (function (Errors) {
  1580. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  1581. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  1582. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  1583. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  1584. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  1585. Errors["BAD_LOADER"] = "BAD_LOADER";
  1586. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  1587. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  1588. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  1589. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  1590. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  1591. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  1592. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  1593. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  1594. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  1595. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  1596. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  1597. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  1598. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  1599. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  1600. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  1601. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  1602. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  1603. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  1604. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  1605. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  1606. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  1607. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  1608. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  1609. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  1610. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  1611. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  1612. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  1613. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  1614. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  1615. })(Errors || (Errors = {}));
  1616. function errAssetNotFinalisedForFileName(name) {
  1617. return {
  1618. code: Errors.ASSET_NOT_FINALISED,
  1619. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  1620. };
  1621. }
  1622. function errCannotEmitFromOptionsHook() {
  1623. return {
  1624. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  1625. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  1626. };
  1627. }
  1628. function errChunkNotGeneratedForFileName(name) {
  1629. return {
  1630. code: Errors.CHUNK_NOT_GENERATED,
  1631. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  1632. };
  1633. }
  1634. function errChunkInvalid({ fileName, code }, exception) {
  1635. const errorProps = {
  1636. code: Errors.CHUNK_INVALID,
  1637. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  1638. };
  1639. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  1640. return errorProps;
  1641. }
  1642. function errCircularReexport(exportName, importedModule) {
  1643. return {
  1644. code: Errors.CIRCULAR_REEXPORT,
  1645. id: importedModule,
  1646. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  1647. };
  1648. }
  1649. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  1650. return {
  1651. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  1652. exporter,
  1653. importer,
  1654. message: `Export "${exportName}" of module ${relativeId(exporter)} was reexported through module ${relativeId(reexporter)} while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in ${relativeId(importer)} to point directly to the exporting module or do not use "preserveModules" to ensure these modules end up in the same chunk.`,
  1655. reexporter
  1656. };
  1657. }
  1658. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  1659. return {
  1660. code: Errors.ASSET_NOT_FOUND,
  1661. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  1662. };
  1663. }
  1664. function errAssetSourceAlreadySet(name) {
  1665. return {
  1666. code: Errors.ASSET_SOURCE_ALREADY_SET,
  1667. message: `Unable to set the source for asset "${name}", source already set.`
  1668. };
  1669. }
  1670. function errNoAssetSourceSet(assetName) {
  1671. return {
  1672. code: Errors.ASSET_SOURCE_MISSING,
  1673. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  1674. };
  1675. }
  1676. function errBadLoader(id) {
  1677. return {
  1678. code: Errors.BAD_LOADER,
  1679. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  1680. };
  1681. }
  1682. function errDeprecation(deprecation) {
  1683. return {
  1684. code: Errors.DEPRECATED_FEATURE,
  1685. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  1686. };
  1687. }
  1688. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  1689. return {
  1690. code: Errors.FILE_NOT_FOUND,
  1691. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  1692. };
  1693. }
  1694. function errFileNameConflict(fileName) {
  1695. return {
  1696. code: Errors.FILE_NAME_CONFLICT,
  1697. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  1698. };
  1699. }
  1700. function errInputHookInOutputPlugin(pluginName, hookName) {
  1701. return {
  1702. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  1703. message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
  1704. };
  1705. }
  1706. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  1707. return {
  1708. code: Errors.INVALID_CHUNK,
  1709. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  1710. };
  1711. }
  1712. function errInvalidExportOptionValue(optionValue) {
  1713. return {
  1714. code: Errors.INVALID_EXPORT_OPTION,
  1715. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  1716. url: `https://rollupjs.org/guide/en/#outputexports`
  1717. };
  1718. }
  1719. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  1720. return {
  1721. code: 'INVALID_EXPORT_OPTION',
  1722. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  1723. };
  1724. }
  1725. function errInternalIdCannotBeExternal(source, importer) {
  1726. return {
  1727. code: Errors.INVALID_EXTERNAL_ID,
  1728. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  1729. };
  1730. }
  1731. function errInvalidOption(option, urlHash, explanation, value) {
  1732. return {
  1733. code: Errors.INVALID_OPTION,
  1734. message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
  1735. url: `https://rollupjs.org/guide/en/#${urlHash}`
  1736. };
  1737. }
  1738. function errInvalidRollupPhaseForAddWatchFile() {
  1739. return {
  1740. code: Errors.INVALID_ROLLUP_PHASE,
  1741. message: `Cannot call addWatchFile after the build has finished.`
  1742. };
  1743. }
  1744. function errInvalidRollupPhaseForChunkEmission() {
  1745. return {
  1746. code: Errors.INVALID_ROLLUP_PHASE,
  1747. message: `Cannot emit chunks after module loading has finished.`
  1748. };
  1749. }
  1750. function errMissingExport(exportName, importingModule, importedModule) {
  1751. return {
  1752. code: Errors.MISSING_EXPORT,
  1753. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  1754. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  1755. };
  1756. }
  1757. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  1758. return {
  1759. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1760. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  1761. };
  1762. }
  1763. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  1764. return {
  1765. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1766. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  1767. };
  1768. }
  1769. function errImplicitDependantIsNotIncluded(module) {
  1770. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  1771. return {
  1772. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1773. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
  1774. };
  1775. }
  1776. function errMixedExport(facadeModuleId, name) {
  1777. return {
  1778. code: Errors.MIXED_EXPORTS,
  1779. id: facadeModuleId,
  1780. message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}["default"]\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning`,
  1781. url: `https://rollupjs.org/guide/en/#outputexports`
  1782. };
  1783. }
  1784. function errNamespaceConflict(name, reexportingModuleId, sources) {
  1785. return {
  1786. code: Errors.NAMESPACE_CONFLICT,
  1787. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
  1788. name,
  1789. reexporter: reexportingModuleId,
  1790. sources
  1791. };
  1792. }
  1793. function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
  1794. return {
  1795. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  1796. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
  1797. name,
  1798. reexporter: reexportingModule,
  1799. sources
  1800. };
  1801. }
  1802. function errNoTransformMapOrAstWithoutCode(pluginName) {
  1803. return {
  1804. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  1805. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  1806. 'a "code". This will be ignored.'
  1807. };
  1808. }
  1809. function errPreferNamedExports(facadeModuleId) {
  1810. const file = relativeId(facadeModuleId);
  1811. return {
  1812. code: Errors.PREFER_NAMED_EXPORTS,
  1813. id: facadeModuleId,
  1814. message: `Entry module "${file}" is implicitly using "default" export mode, which means for CommonJS output that its default export is assigned to "module.exports". For many tools, such CommonJS output will not be interchangeable with the original ES module. If this is intended, explicitly set "output.exports" to either "auto" or "default", otherwise you might want to consider changing the signature of "${file}" to use named exports only.`,
  1815. url: `https://rollupjs.org/guide/en/#outputexports`
  1816. };
  1817. }
  1818. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  1819. return {
  1820. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  1821. id,
  1822. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  1823. ? `an explicit export named "${syntheticNamedExportsOption}"`
  1824. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  1825. };
  1826. }
  1827. function errUnexpectedNamedImport(id, imported, isReexport) {
  1828. const importType = isReexport ? 'reexport' : 'import';
  1829. return {
  1830. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1831. id,
  1832. message: `The named export "${imported}" was ${importType}ed from the external module ${relativeId(id)} even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
  1833. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1834. };
  1835. }
  1836. function errUnexpectedNamespaceReexport(id) {
  1837. return {
  1838. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1839. id,
  1840. message: `There was a namespace "*" reexport from the external module ${relativeId(id)} even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
  1841. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1842. };
  1843. }
  1844. function errEntryCannotBeExternal(unresolvedId) {
  1845. return {
  1846. code: Errors.UNRESOLVED_ENTRY,
  1847. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  1848. };
  1849. }
  1850. function errUnresolvedEntry(unresolvedId) {
  1851. return {
  1852. code: Errors.UNRESOLVED_ENTRY,
  1853. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  1854. };
  1855. }
  1856. function errUnresolvedImport(source, importer) {
  1857. return {
  1858. code: Errors.UNRESOLVED_IMPORT,
  1859. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  1860. };
  1861. }
  1862. function errUnresolvedImportTreatedAsExternal(source, importer) {
  1863. return {
  1864. code: Errors.UNRESOLVED_IMPORT,
  1865. importer: relativeId(importer),
  1866. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  1867. source,
  1868. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  1869. };
  1870. }
  1871. function errExternalSyntheticExports(source, importer) {
  1872. return {
  1873. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  1874. importer: relativeId(importer),
  1875. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  1876. source
  1877. };
  1878. }
  1879. function errFailedValidation(message) {
  1880. return {
  1881. code: Errors.VALIDATION_ERROR,
  1882. message
  1883. };
  1884. }
  1885. function errAlreadyClosed() {
  1886. return {
  1887. code: Errors.ALREADY_CLOSED,
  1888. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  1889. };
  1890. }
  1891. function warnDeprecation(deprecation, activeDeprecation, options) {
  1892. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  1893. }
  1894. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  1895. if (activeDeprecation || strictDeprecations) {
  1896. const warning = errDeprecation(deprecation);
  1897. if (strictDeprecations) {
  1898. return error(warning);
  1899. }
  1900. warn(warning);
  1901. }
  1902. }
  1903. const RESERVED_NAMES = new Set([
  1904. 'await',
  1905. 'break',
  1906. 'case',
  1907. 'catch',
  1908. 'class',
  1909. 'const',
  1910. 'continue',
  1911. 'debugger',
  1912. 'default',
  1913. 'delete',
  1914. 'do',
  1915. 'else',
  1916. 'enum',
  1917. 'eval',
  1918. 'export',
  1919. 'extends',
  1920. 'false',
  1921. 'finally',
  1922. 'for',
  1923. 'function',
  1924. 'if',
  1925. 'implements',
  1926. 'import',
  1927. 'in',
  1928. 'instanceof',
  1929. 'interface',
  1930. 'let',
  1931. 'NaN',
  1932. 'new',
  1933. 'null',
  1934. 'package',
  1935. 'private',
  1936. 'protected',
  1937. 'public',
  1938. 'return',
  1939. 'static',
  1940. 'super',
  1941. 'switch',
  1942. 'this',
  1943. 'throw',
  1944. 'true',
  1945. 'try',
  1946. 'typeof',
  1947. 'undefined',
  1948. 'var',
  1949. 'void',
  1950. 'while',
  1951. 'with',
  1952. 'yield'
  1953. ]);
  1954. const RESERVED_NAMES$1 = RESERVED_NAMES;
  1955. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1956. const startsWithDigit = (str) => /\d/.test(str[0]);
  1957. function isLegal(str) {
  1958. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str)) {
  1959. return false;
  1960. }
  1961. return !illegalCharacters.test(str);
  1962. }
  1963. function makeLegal(str) {
  1964. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1965. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str))
  1966. str = `_${str}`;
  1967. return str || '_';
  1968. }
  1969. class ExternalModule {
  1970. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
  1971. this.options = options;
  1972. this.id = id;
  1973. this.renormalizeRenderPath = renormalizeRenderPath;
  1974. this.declarations = new Map();
  1975. this.defaultVariableName = '';
  1976. this.dynamicImporters = [];
  1977. this.execIndex = Infinity;
  1978. this.exportedVariables = new Map();
  1979. this.importers = [];
  1980. this.mostCommonSuggestion = 0;
  1981. this.nameSuggestions = new Map();
  1982. this.namespaceVariableName = '';
  1983. this.reexported = false;
  1984. this.renderPath = undefined;
  1985. this.used = false;
  1986. this.variableName = '';
  1987. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  1988. const { importers, dynamicImporters } = this;
  1989. const info = (this.info = {
  1990. ast: null,
  1991. code: null,
  1992. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  1993. dynamicallyImportedIds: EMPTY_ARRAY,
  1994. get dynamicImporters() {
  1995. return dynamicImporters.sort();
  1996. },
  1997. hasDefaultExport: null,
  1998. get hasModuleSideEffects() {
  1999. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  2000. return info.moduleSideEffects;
  2001. },
  2002. id,
  2003. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2004. implicitlyLoadedBefore: EMPTY_ARRAY,
  2005. importedIdResolutions: EMPTY_ARRAY,
  2006. importedIds: EMPTY_ARRAY,
  2007. get importers() {
  2008. return importers.sort();
  2009. },
  2010. isEntry: false,
  2011. isExternal: true,
  2012. isIncluded: null,
  2013. meta,
  2014. moduleSideEffects,
  2015. syntheticNamedExports: false
  2016. });
  2017. // Hide the deprecated key so that it only warns when accessed explicitly
  2018. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2019. enumerable: false
  2020. });
  2021. }
  2022. getVariableForExportName(name) {
  2023. const declaration = this.declarations.get(name);
  2024. if (declaration)
  2025. return [declaration];
  2026. const externalVariable = new ExternalVariable(this, name);
  2027. this.declarations.set(name, externalVariable);
  2028. this.exportedVariables.set(externalVariable, name);
  2029. return [externalVariable];
  2030. }
  2031. setRenderPath(options, inputBase) {
  2032. this.renderPath =
  2033. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2034. if (!this.renderPath) {
  2035. this.renderPath = this.renormalizeRenderPath
  2036. ? normalize(relative$1(inputBase, this.id))
  2037. : this.id;
  2038. }
  2039. }
  2040. suggestName(name) {
  2041. var _a;
  2042. const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
  2043. this.nameSuggestions.set(name, value);
  2044. if (value > this.mostCommonSuggestion) {
  2045. this.mostCommonSuggestion = value;
  2046. this.suggestedVariableName = name;
  2047. }
  2048. }
  2049. warnUnusedImports() {
  2050. const unused = Array.from(this.declarations)
  2051. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2052. .map(([name]) => name);
  2053. if (unused.length === 0)
  2054. return;
  2055. const importersSet = new Set();
  2056. for (const name of unused) {
  2057. for (const importer of this.declarations.get(name).module.importers) {
  2058. importersSet.add(importer);
  2059. }
  2060. }
  2061. const importersArray = [...importersSet];
  2062. this.options.onwarn({
  2063. code: 'UNUSED_EXTERNAL_IMPORT',
  2064. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2065. names: unused,
  2066. source: this.id,
  2067. sources: importersArray
  2068. });
  2069. }
  2070. }
  2071. function getDefaultExportFromCjs (x) {
  2072. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2073. }
  2074. function getAugmentedNamespace(n) {
  2075. var f = n.default;
  2076. if (typeof f == "function") {
  2077. var a = function () {
  2078. return f.apply(this, arguments);
  2079. };
  2080. a.prototype = f.prototype;
  2081. } else a = {};
  2082. Object.defineProperty(a, '__esModule', {value: true});
  2083. Object.keys(n).forEach(function (k) {
  2084. var d = Object.getOwnPropertyDescriptor(n, k);
  2085. Object.defineProperty(a, k, d.get ? d : {
  2086. enumerable: true,
  2087. get: function () {
  2088. return n[k];
  2089. }
  2090. });
  2091. });
  2092. return a;
  2093. }
  2094. var picomatch$1 = {exports: {}};
  2095. var utils$3 = {};
  2096. const path$1 = require$$0;
  2097. const WIN_SLASH = '\\\\/';
  2098. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2099. /**
  2100. * Posix glob regex
  2101. */
  2102. const DOT_LITERAL = '\\.';
  2103. const PLUS_LITERAL = '\\+';
  2104. const QMARK_LITERAL = '\\?';
  2105. const SLASH_LITERAL = '\\/';
  2106. const ONE_CHAR = '(?=.)';
  2107. const QMARK = '[^/]';
  2108. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2109. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2110. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2111. const NO_DOT = `(?!${DOT_LITERAL})`;
  2112. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2113. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2114. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2115. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2116. const STAR = `${QMARK}*?`;
  2117. const POSIX_CHARS = {
  2118. DOT_LITERAL,
  2119. PLUS_LITERAL,
  2120. QMARK_LITERAL,
  2121. SLASH_LITERAL,
  2122. ONE_CHAR,
  2123. QMARK,
  2124. END_ANCHOR,
  2125. DOTS_SLASH,
  2126. NO_DOT,
  2127. NO_DOTS,
  2128. NO_DOT_SLASH,
  2129. NO_DOTS_SLASH,
  2130. QMARK_NO_DOT,
  2131. STAR,
  2132. START_ANCHOR
  2133. };
  2134. /**
  2135. * Windows glob regex
  2136. */
  2137. const WINDOWS_CHARS = {
  2138. ...POSIX_CHARS,
  2139. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2140. QMARK: WIN_NO_SLASH,
  2141. STAR: `${WIN_NO_SLASH}*?`,
  2142. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2143. NO_DOT: `(?!${DOT_LITERAL})`,
  2144. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2145. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2146. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2147. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2148. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2149. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2150. };
  2151. /**
  2152. * POSIX Bracket Regex
  2153. */
  2154. const POSIX_REGEX_SOURCE$1 = {
  2155. alnum: 'a-zA-Z0-9',
  2156. alpha: 'a-zA-Z',
  2157. ascii: '\\x00-\\x7F',
  2158. blank: ' \\t',
  2159. cntrl: '\\x00-\\x1F\\x7F',
  2160. digit: '0-9',
  2161. graph: '\\x21-\\x7E',
  2162. lower: 'a-z',
  2163. print: '\\x20-\\x7E ',
  2164. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2165. space: ' \\t\\r\\n\\v\\f',
  2166. upper: 'A-Z',
  2167. word: 'A-Za-z0-9_',
  2168. xdigit: 'A-Fa-f0-9'
  2169. };
  2170. var constants$2 = {
  2171. MAX_LENGTH: 1024 * 64,
  2172. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2173. // regular expressions
  2174. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2175. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2176. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2177. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2178. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2179. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2180. // Replace globs with equivalent patterns to reduce parsing time.
  2181. REPLACEMENTS: {
  2182. '***': '*',
  2183. '**/**': '**',
  2184. '**/**/**': '**'
  2185. },
  2186. // Digits
  2187. CHAR_0: 48, /* 0 */
  2188. CHAR_9: 57, /* 9 */
  2189. // Alphabet chars.
  2190. CHAR_UPPERCASE_A: 65, /* A */
  2191. CHAR_LOWERCASE_A: 97, /* a */
  2192. CHAR_UPPERCASE_Z: 90, /* Z */
  2193. CHAR_LOWERCASE_Z: 122, /* z */
  2194. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2195. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2196. CHAR_ASTERISK: 42, /* * */
  2197. // Non-alphabetic chars.
  2198. CHAR_AMPERSAND: 38, /* & */
  2199. CHAR_AT: 64, /* @ */
  2200. CHAR_BACKWARD_SLASH: 92, /* \ */
  2201. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2202. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2203. CHAR_COLON: 58, /* : */
  2204. CHAR_COMMA: 44, /* , */
  2205. CHAR_DOT: 46, /* . */
  2206. CHAR_DOUBLE_QUOTE: 34, /* " */
  2207. CHAR_EQUAL: 61, /* = */
  2208. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2209. CHAR_FORM_FEED: 12, /* \f */
  2210. CHAR_FORWARD_SLASH: 47, /* / */
  2211. CHAR_GRAVE_ACCENT: 96, /* ` */
  2212. CHAR_HASH: 35, /* # */
  2213. CHAR_HYPHEN_MINUS: 45, /* - */
  2214. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2215. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2216. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2217. CHAR_LINE_FEED: 10, /* \n */
  2218. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2219. CHAR_PERCENT: 37, /* % */
  2220. CHAR_PLUS: 43, /* + */
  2221. CHAR_QUESTION_MARK: 63, /* ? */
  2222. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2223. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2224. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2225. CHAR_SEMICOLON: 59, /* ; */
  2226. CHAR_SINGLE_QUOTE: 39, /* ' */
  2227. CHAR_SPACE: 32, /* */
  2228. CHAR_TAB: 9, /* \t */
  2229. CHAR_UNDERSCORE: 95, /* _ */
  2230. CHAR_VERTICAL_LINE: 124, /* | */
  2231. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2232. SEP: path$1.sep,
  2233. /**
  2234. * Create EXTGLOB_CHARS
  2235. */
  2236. extglobChars(chars) {
  2237. return {
  2238. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2239. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2240. '+': { type: 'plus', open: '(?:', close: ')+' },
  2241. '*': { type: 'star', open: '(?:', close: ')*' },
  2242. '@': { type: 'at', open: '(?:', close: ')' }
  2243. };
  2244. },
  2245. /**
  2246. * Create GLOB_CHARS
  2247. */
  2248. globChars(win32) {
  2249. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2250. }
  2251. };
  2252. (function (exports) {
  2253. const path = require$$0;
  2254. const win32 = process.platform === 'win32';
  2255. const {
  2256. REGEX_BACKSLASH,
  2257. REGEX_REMOVE_BACKSLASH,
  2258. REGEX_SPECIAL_CHARS,
  2259. REGEX_SPECIAL_CHARS_GLOBAL
  2260. } = constants$2;
  2261. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2262. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2263. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2264. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2265. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2266. exports.removeBackslashes = str => {
  2267. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2268. return match === '\\' ? '' : match;
  2269. });
  2270. };
  2271. exports.supportsLookbehinds = () => {
  2272. const segs = process.version.slice(1).split('.').map(Number);
  2273. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2274. return true;
  2275. }
  2276. return false;
  2277. };
  2278. exports.isWindows = options => {
  2279. if (options && typeof options.windows === 'boolean') {
  2280. return options.windows;
  2281. }
  2282. return win32 === true || path.sep === '\\';
  2283. };
  2284. exports.escapeLast = (input, char, lastIdx) => {
  2285. const idx = input.lastIndexOf(char, lastIdx);
  2286. if (idx === -1) return input;
  2287. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2288. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2289. };
  2290. exports.removePrefix = (input, state = {}) => {
  2291. let output = input;
  2292. if (output.startsWith('./')) {
  2293. output = output.slice(2);
  2294. state.prefix = './';
  2295. }
  2296. return output;
  2297. };
  2298. exports.wrapOutput = (input, state = {}, options = {}) => {
  2299. const prepend = options.contains ? '' : '^';
  2300. const append = options.contains ? '' : '$';
  2301. let output = `${prepend}(?:${input})${append}`;
  2302. if (state.negated === true) {
  2303. output = `(?:^(?!${output}).*$)`;
  2304. }
  2305. return output;
  2306. };
  2307. } (utils$3));
  2308. const utils$2 = utils$3;
  2309. const {
  2310. CHAR_ASTERISK, /* * */
  2311. CHAR_AT, /* @ */
  2312. CHAR_BACKWARD_SLASH, /* \ */
  2313. CHAR_COMMA, /* , */
  2314. CHAR_DOT, /* . */
  2315. CHAR_EXCLAMATION_MARK, /* ! */
  2316. CHAR_FORWARD_SLASH, /* / */
  2317. CHAR_LEFT_CURLY_BRACE, /* { */
  2318. CHAR_LEFT_PARENTHESES, /* ( */
  2319. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2320. CHAR_PLUS, /* + */
  2321. CHAR_QUESTION_MARK, /* ? */
  2322. CHAR_RIGHT_CURLY_BRACE, /* } */
  2323. CHAR_RIGHT_PARENTHESES, /* ) */
  2324. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2325. } = constants$2;
  2326. const isPathSeparator = code => {
  2327. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2328. };
  2329. const depth = token => {
  2330. if (token.isPrefix !== true) {
  2331. token.depth = token.isGlobstar ? Infinity : 1;
  2332. }
  2333. };
  2334. /**
  2335. * Quickly scans a glob pattern and returns an object with a handful of
  2336. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2337. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2338. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2339. *
  2340. * ```js
  2341. * const pm = require('picomatch');
  2342. * console.log(pm.scan('foo/bar/*.js'));
  2343. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2344. * ```
  2345. * @param {String} `str`
  2346. * @param {Object} `options`
  2347. * @return {Object} Returns an object with tokens and regex source string.
  2348. * @api public
  2349. */
  2350. const scan$1 = (input, options) => {
  2351. const opts = options || {};
  2352. const length = input.length - 1;
  2353. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2354. const slashes = [];
  2355. const tokens = [];
  2356. const parts = [];
  2357. let str = input;
  2358. let index = -1;
  2359. let start = 0;
  2360. let lastIndex = 0;
  2361. let isBrace = false;
  2362. let isBracket = false;
  2363. let isGlob = false;
  2364. let isExtglob = false;
  2365. let isGlobstar = false;
  2366. let braceEscaped = false;
  2367. let backslashes = false;
  2368. let negated = false;
  2369. let negatedExtglob = false;
  2370. let finished = false;
  2371. let braces = 0;
  2372. let prev;
  2373. let code;
  2374. let token = { value: '', depth: 0, isGlob: false };
  2375. const eos = () => index >= length;
  2376. const peek = () => str.charCodeAt(index + 1);
  2377. const advance = () => {
  2378. prev = code;
  2379. return str.charCodeAt(++index);
  2380. };
  2381. while (index < length) {
  2382. code = advance();
  2383. let next;
  2384. if (code === CHAR_BACKWARD_SLASH) {
  2385. backslashes = token.backslashes = true;
  2386. code = advance();
  2387. if (code === CHAR_LEFT_CURLY_BRACE) {
  2388. braceEscaped = true;
  2389. }
  2390. continue;
  2391. }
  2392. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2393. braces++;
  2394. while (eos() !== true && (code = advance())) {
  2395. if (code === CHAR_BACKWARD_SLASH) {
  2396. backslashes = token.backslashes = true;
  2397. advance();
  2398. continue;
  2399. }
  2400. if (code === CHAR_LEFT_CURLY_BRACE) {
  2401. braces++;
  2402. continue;
  2403. }
  2404. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2405. isBrace = token.isBrace = true;
  2406. isGlob = token.isGlob = true;
  2407. finished = true;
  2408. if (scanToEnd === true) {
  2409. continue;
  2410. }
  2411. break;
  2412. }
  2413. if (braceEscaped !== true && code === CHAR_COMMA) {
  2414. isBrace = token.isBrace = true;
  2415. isGlob = token.isGlob = true;
  2416. finished = true;
  2417. if (scanToEnd === true) {
  2418. continue;
  2419. }
  2420. break;
  2421. }
  2422. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2423. braces--;
  2424. if (braces === 0) {
  2425. braceEscaped = false;
  2426. isBrace = token.isBrace = true;
  2427. finished = true;
  2428. break;
  2429. }
  2430. }
  2431. }
  2432. if (scanToEnd === true) {
  2433. continue;
  2434. }
  2435. break;
  2436. }
  2437. if (code === CHAR_FORWARD_SLASH) {
  2438. slashes.push(index);
  2439. tokens.push(token);
  2440. token = { value: '', depth: 0, isGlob: false };
  2441. if (finished === true) continue;
  2442. if (prev === CHAR_DOT && index === (start + 1)) {
  2443. start += 2;
  2444. continue;
  2445. }
  2446. lastIndex = index + 1;
  2447. continue;
  2448. }
  2449. if (opts.noext !== true) {
  2450. const isExtglobChar = code === CHAR_PLUS
  2451. || code === CHAR_AT
  2452. || code === CHAR_ASTERISK
  2453. || code === CHAR_QUESTION_MARK
  2454. || code === CHAR_EXCLAMATION_MARK;
  2455. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2456. isGlob = token.isGlob = true;
  2457. isExtglob = token.isExtglob = true;
  2458. finished = true;
  2459. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2460. negatedExtglob = true;
  2461. }
  2462. if (scanToEnd === true) {
  2463. while (eos() !== true && (code = advance())) {
  2464. if (code === CHAR_BACKWARD_SLASH) {
  2465. backslashes = token.backslashes = true;
  2466. code = advance();
  2467. continue;
  2468. }
  2469. if (code === CHAR_RIGHT_PARENTHESES) {
  2470. isGlob = token.isGlob = true;
  2471. finished = true;
  2472. break;
  2473. }
  2474. }
  2475. continue;
  2476. }
  2477. break;
  2478. }
  2479. }
  2480. if (code === CHAR_ASTERISK) {
  2481. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2482. isGlob = token.isGlob = true;
  2483. finished = true;
  2484. if (scanToEnd === true) {
  2485. continue;
  2486. }
  2487. break;
  2488. }
  2489. if (code === CHAR_QUESTION_MARK) {
  2490. isGlob = token.isGlob = true;
  2491. finished = true;
  2492. if (scanToEnd === true) {
  2493. continue;
  2494. }
  2495. break;
  2496. }
  2497. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2498. while (eos() !== true && (next = advance())) {
  2499. if (next === CHAR_BACKWARD_SLASH) {
  2500. backslashes = token.backslashes = true;
  2501. advance();
  2502. continue;
  2503. }
  2504. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2505. isBracket = token.isBracket = true;
  2506. isGlob = token.isGlob = true;
  2507. finished = true;
  2508. break;
  2509. }
  2510. }
  2511. if (scanToEnd === true) {
  2512. continue;
  2513. }
  2514. break;
  2515. }
  2516. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2517. negated = token.negated = true;
  2518. start++;
  2519. continue;
  2520. }
  2521. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2522. isGlob = token.isGlob = true;
  2523. if (scanToEnd === true) {
  2524. while (eos() !== true && (code = advance())) {
  2525. if (code === CHAR_LEFT_PARENTHESES) {
  2526. backslashes = token.backslashes = true;
  2527. code = advance();
  2528. continue;
  2529. }
  2530. if (code === CHAR_RIGHT_PARENTHESES) {
  2531. finished = true;
  2532. break;
  2533. }
  2534. }
  2535. continue;
  2536. }
  2537. break;
  2538. }
  2539. if (isGlob === true) {
  2540. finished = true;
  2541. if (scanToEnd === true) {
  2542. continue;
  2543. }
  2544. break;
  2545. }
  2546. }
  2547. if (opts.noext === true) {
  2548. isExtglob = false;
  2549. isGlob = false;
  2550. }
  2551. let base = str;
  2552. let prefix = '';
  2553. let glob = '';
  2554. if (start > 0) {
  2555. prefix = str.slice(0, start);
  2556. str = str.slice(start);
  2557. lastIndex -= start;
  2558. }
  2559. if (base && isGlob === true && lastIndex > 0) {
  2560. base = str.slice(0, lastIndex);
  2561. glob = str.slice(lastIndex);
  2562. } else if (isGlob === true) {
  2563. base = '';
  2564. glob = str;
  2565. } else {
  2566. base = str;
  2567. }
  2568. if (base && base !== '' && base !== '/' && base !== str) {
  2569. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2570. base = base.slice(0, -1);
  2571. }
  2572. }
  2573. if (opts.unescape === true) {
  2574. if (glob) glob = utils$2.removeBackslashes(glob);
  2575. if (base && backslashes === true) {
  2576. base = utils$2.removeBackslashes(base);
  2577. }
  2578. }
  2579. const state = {
  2580. prefix,
  2581. input,
  2582. start,
  2583. base,
  2584. glob,
  2585. isBrace,
  2586. isBracket,
  2587. isGlob,
  2588. isExtglob,
  2589. isGlobstar,
  2590. negated,
  2591. negatedExtglob
  2592. };
  2593. if (opts.tokens === true) {
  2594. state.maxDepth = 0;
  2595. if (!isPathSeparator(code)) {
  2596. tokens.push(token);
  2597. }
  2598. state.tokens = tokens;
  2599. }
  2600. if (opts.parts === true || opts.tokens === true) {
  2601. let prevIndex;
  2602. for (let idx = 0; idx < slashes.length; idx++) {
  2603. const n = prevIndex ? prevIndex + 1 : start;
  2604. const i = slashes[idx];
  2605. const value = input.slice(n, i);
  2606. if (opts.tokens) {
  2607. if (idx === 0 && start !== 0) {
  2608. tokens[idx].isPrefix = true;
  2609. tokens[idx].value = prefix;
  2610. } else {
  2611. tokens[idx].value = value;
  2612. }
  2613. depth(tokens[idx]);
  2614. state.maxDepth += tokens[idx].depth;
  2615. }
  2616. if (idx !== 0 || value !== '') {
  2617. parts.push(value);
  2618. }
  2619. prevIndex = i;
  2620. }
  2621. if (prevIndex && prevIndex + 1 < input.length) {
  2622. const value = input.slice(prevIndex + 1);
  2623. parts.push(value);
  2624. if (opts.tokens) {
  2625. tokens[tokens.length - 1].value = value;
  2626. depth(tokens[tokens.length - 1]);
  2627. state.maxDepth += tokens[tokens.length - 1].depth;
  2628. }
  2629. }
  2630. state.slashes = slashes;
  2631. state.parts = parts;
  2632. }
  2633. return state;
  2634. };
  2635. var scan_1 = scan$1;
  2636. const constants$1 = constants$2;
  2637. const utils$1 = utils$3;
  2638. /**
  2639. * Constants
  2640. */
  2641. const {
  2642. MAX_LENGTH,
  2643. POSIX_REGEX_SOURCE,
  2644. REGEX_NON_SPECIAL_CHARS,
  2645. REGEX_SPECIAL_CHARS_BACKREF,
  2646. REPLACEMENTS
  2647. } = constants$1;
  2648. /**
  2649. * Helpers
  2650. */
  2651. const expandRange = (args, options) => {
  2652. if (typeof options.expandRange === 'function') {
  2653. return options.expandRange(...args, options);
  2654. }
  2655. args.sort();
  2656. const value = `[${args.join('-')}]`;
  2657. return value;
  2658. };
  2659. /**
  2660. * Create the message for a syntax error
  2661. */
  2662. const syntaxError = (type, char) => {
  2663. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2664. };
  2665. /**
  2666. * Parse the given input string.
  2667. * @param {String} input
  2668. * @param {Object} options
  2669. * @return {Object}
  2670. */
  2671. const parse$1 = (input, options) => {
  2672. if (typeof input !== 'string') {
  2673. throw new TypeError('Expected a string');
  2674. }
  2675. input = REPLACEMENTS[input] || input;
  2676. const opts = { ...options };
  2677. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2678. let len = input.length;
  2679. if (len > max) {
  2680. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2681. }
  2682. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2683. const tokens = [bos];
  2684. const capture = opts.capture ? '' : '?:';
  2685. const win32 = utils$1.isWindows(options);
  2686. // create constants based on platform, for windows or posix
  2687. const PLATFORM_CHARS = constants$1.globChars(win32);
  2688. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2689. const {
  2690. DOT_LITERAL,
  2691. PLUS_LITERAL,
  2692. SLASH_LITERAL,
  2693. ONE_CHAR,
  2694. DOTS_SLASH,
  2695. NO_DOT,
  2696. NO_DOT_SLASH,
  2697. NO_DOTS_SLASH,
  2698. QMARK,
  2699. QMARK_NO_DOT,
  2700. STAR,
  2701. START_ANCHOR
  2702. } = PLATFORM_CHARS;
  2703. const globstar = opts => {
  2704. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2705. };
  2706. const nodot = opts.dot ? '' : NO_DOT;
  2707. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2708. let star = opts.bash === true ? globstar(opts) : STAR;
  2709. if (opts.capture) {
  2710. star = `(${star})`;
  2711. }
  2712. // minimatch options support
  2713. if (typeof opts.noext === 'boolean') {
  2714. opts.noextglob = opts.noext;
  2715. }
  2716. const state = {
  2717. input,
  2718. index: -1,
  2719. start: 0,
  2720. dot: opts.dot === true,
  2721. consumed: '',
  2722. output: '',
  2723. prefix: '',
  2724. backtrack: false,
  2725. negated: false,
  2726. brackets: 0,
  2727. braces: 0,
  2728. parens: 0,
  2729. quotes: 0,
  2730. globstar: false,
  2731. tokens
  2732. };
  2733. input = utils$1.removePrefix(input, state);
  2734. len = input.length;
  2735. const extglobs = [];
  2736. const braces = [];
  2737. const stack = [];
  2738. let prev = bos;
  2739. let value;
  2740. /**
  2741. * Tokenizing helpers
  2742. */
  2743. const eos = () => state.index === len - 1;
  2744. const peek = state.peek = (n = 1) => input[state.index + n];
  2745. const advance = state.advance = () => input[++state.index] || '';
  2746. const remaining = () => input.slice(state.index + 1);
  2747. const consume = (value = '', num = 0) => {
  2748. state.consumed += value;
  2749. state.index += num;
  2750. };
  2751. const append = token => {
  2752. state.output += token.output != null ? token.output : token.value;
  2753. consume(token.value);
  2754. };
  2755. const negate = () => {
  2756. let count = 1;
  2757. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2758. advance();
  2759. state.start++;
  2760. count++;
  2761. }
  2762. if (count % 2 === 0) {
  2763. return false;
  2764. }
  2765. state.negated = true;
  2766. state.start++;
  2767. return true;
  2768. };
  2769. const increment = type => {
  2770. state[type]++;
  2771. stack.push(type);
  2772. };
  2773. const decrement = type => {
  2774. state[type]--;
  2775. stack.pop();
  2776. };
  2777. /**
  2778. * Push tokens onto the tokens array. This helper speeds up
  2779. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2780. * and 2) helping us avoid creating extra tokens when consecutive
  2781. * characters are plain text. This improves performance and simplifies
  2782. * lookbehinds.
  2783. */
  2784. const push = tok => {
  2785. if (prev.type === 'globstar') {
  2786. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2787. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2788. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2789. state.output = state.output.slice(0, -prev.output.length);
  2790. prev.type = 'star';
  2791. prev.value = '*';
  2792. prev.output = star;
  2793. state.output += prev.output;
  2794. }
  2795. }
  2796. if (extglobs.length && tok.type !== 'paren') {
  2797. extglobs[extglobs.length - 1].inner += tok.value;
  2798. }
  2799. if (tok.value || tok.output) append(tok);
  2800. if (prev && prev.type === 'text' && tok.type === 'text') {
  2801. prev.value += tok.value;
  2802. prev.output = (prev.output || '') + tok.value;
  2803. return;
  2804. }
  2805. tok.prev = prev;
  2806. tokens.push(tok);
  2807. prev = tok;
  2808. };
  2809. const extglobOpen = (type, value) => {
  2810. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2811. token.prev = prev;
  2812. token.parens = state.parens;
  2813. token.output = state.output;
  2814. const output = (opts.capture ? '(' : '') + token.open;
  2815. increment('parens');
  2816. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2817. push({ type: 'paren', extglob: true, value: advance(), output });
  2818. extglobs.push(token);
  2819. };
  2820. const extglobClose = token => {
  2821. let output = token.close + (opts.capture ? ')' : '');
  2822. let rest;
  2823. if (token.type === 'negate') {
  2824. let extglobStar = star;
  2825. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2826. extglobStar = globstar(opts);
  2827. }
  2828. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2829. output = token.close = `)$))${extglobStar}`;
  2830. }
  2831. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2832. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2833. // In this case, we need to parse the string and use it in the output of the original pattern.
  2834. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2835. //
  2836. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2837. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2838. output = token.close = `)${expression})${extglobStar})`;
  2839. }
  2840. if (token.prev.type === 'bos') {
  2841. state.negatedExtglob = true;
  2842. }
  2843. }
  2844. push({ type: 'paren', extglob: true, value, output });
  2845. decrement('parens');
  2846. };
  2847. /**
  2848. * Fast paths
  2849. */
  2850. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2851. let backslashes = false;
  2852. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2853. if (first === '\\') {
  2854. backslashes = true;
  2855. return m;
  2856. }
  2857. if (first === '?') {
  2858. if (esc) {
  2859. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2860. }
  2861. if (index === 0) {
  2862. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2863. }
  2864. return QMARK.repeat(chars.length);
  2865. }
  2866. if (first === '.') {
  2867. return DOT_LITERAL.repeat(chars.length);
  2868. }
  2869. if (first === '*') {
  2870. if (esc) {
  2871. return esc + first + (rest ? star : '');
  2872. }
  2873. return star;
  2874. }
  2875. return esc ? m : `\\${m}`;
  2876. });
  2877. if (backslashes === true) {
  2878. if (opts.unescape === true) {
  2879. output = output.replace(/\\/g, '');
  2880. } else {
  2881. output = output.replace(/\\+/g, m => {
  2882. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2883. });
  2884. }
  2885. }
  2886. if (output === input && opts.contains === true) {
  2887. state.output = input;
  2888. return state;
  2889. }
  2890. state.output = utils$1.wrapOutput(output, state, options);
  2891. return state;
  2892. }
  2893. /**
  2894. * Tokenize input until we reach end-of-string
  2895. */
  2896. while (!eos()) {
  2897. value = advance();
  2898. if (value === '\u0000') {
  2899. continue;
  2900. }
  2901. /**
  2902. * Escaped characters
  2903. */
  2904. if (value === '\\') {
  2905. const next = peek();
  2906. if (next === '/' && opts.bash !== true) {
  2907. continue;
  2908. }
  2909. if (next === '.' || next === ';') {
  2910. continue;
  2911. }
  2912. if (!next) {
  2913. value += '\\';
  2914. push({ type: 'text', value });
  2915. continue;
  2916. }
  2917. // collapse slashes to reduce potential for exploits
  2918. const match = /^\\+/.exec(remaining());
  2919. let slashes = 0;
  2920. if (match && match[0].length > 2) {
  2921. slashes = match[0].length;
  2922. state.index += slashes;
  2923. if (slashes % 2 !== 0) {
  2924. value += '\\';
  2925. }
  2926. }
  2927. if (opts.unescape === true) {
  2928. value = advance();
  2929. } else {
  2930. value += advance();
  2931. }
  2932. if (state.brackets === 0) {
  2933. push({ type: 'text', value });
  2934. continue;
  2935. }
  2936. }
  2937. /**
  2938. * If we're inside a regex character class, continue
  2939. * until we reach the closing bracket.
  2940. */
  2941. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2942. if (opts.posix !== false && value === ':') {
  2943. const inner = prev.value.slice(1);
  2944. if (inner.includes('[')) {
  2945. prev.posix = true;
  2946. if (inner.includes(':')) {
  2947. const idx = prev.value.lastIndexOf('[');
  2948. const pre = prev.value.slice(0, idx);
  2949. const rest = prev.value.slice(idx + 2);
  2950. const posix = POSIX_REGEX_SOURCE[rest];
  2951. if (posix) {
  2952. prev.value = pre + posix;
  2953. state.backtrack = true;
  2954. advance();
  2955. if (!bos.output && tokens.indexOf(prev) === 1) {
  2956. bos.output = ONE_CHAR;
  2957. }
  2958. continue;
  2959. }
  2960. }
  2961. }
  2962. }
  2963. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2964. value = `\\${value}`;
  2965. }
  2966. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2967. value = `\\${value}`;
  2968. }
  2969. if (opts.posix === true && value === '!' && prev.value === '[') {
  2970. value = '^';
  2971. }
  2972. prev.value += value;
  2973. append({ value });
  2974. continue;
  2975. }
  2976. /**
  2977. * If we're inside a quoted string, continue
  2978. * until we reach the closing double quote.
  2979. */
  2980. if (state.quotes === 1 && value !== '"') {
  2981. value = utils$1.escapeRegex(value);
  2982. prev.value += value;
  2983. append({ value });
  2984. continue;
  2985. }
  2986. /**
  2987. * Double quotes
  2988. */
  2989. if (value === '"') {
  2990. state.quotes = state.quotes === 1 ? 0 : 1;
  2991. if (opts.keepQuotes === true) {
  2992. push({ type: 'text', value });
  2993. }
  2994. continue;
  2995. }
  2996. /**
  2997. * Parentheses
  2998. */
  2999. if (value === '(') {
  3000. increment('parens');
  3001. push({ type: 'paren', value });
  3002. continue;
  3003. }
  3004. if (value === ')') {
  3005. if (state.parens === 0 && opts.strictBrackets === true) {
  3006. throw new SyntaxError(syntaxError('opening', '('));
  3007. }
  3008. const extglob = extglobs[extglobs.length - 1];
  3009. if (extglob && state.parens === extglob.parens + 1) {
  3010. extglobClose(extglobs.pop());
  3011. continue;
  3012. }
  3013. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3014. decrement('parens');
  3015. continue;
  3016. }
  3017. /**
  3018. * Square brackets
  3019. */
  3020. if (value === '[') {
  3021. if (opts.nobracket === true || !remaining().includes(']')) {
  3022. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3023. throw new SyntaxError(syntaxError('closing', ']'));
  3024. }
  3025. value = `\\${value}`;
  3026. } else {
  3027. increment('brackets');
  3028. }
  3029. push({ type: 'bracket', value });
  3030. continue;
  3031. }
  3032. if (value === ']') {
  3033. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3034. push({ type: 'text', value, output: `\\${value}` });
  3035. continue;
  3036. }
  3037. if (state.brackets === 0) {
  3038. if (opts.strictBrackets === true) {
  3039. throw new SyntaxError(syntaxError('opening', '['));
  3040. }
  3041. push({ type: 'text', value, output: `\\${value}` });
  3042. continue;
  3043. }
  3044. decrement('brackets');
  3045. const prevValue = prev.value.slice(1);
  3046. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3047. value = `/${value}`;
  3048. }
  3049. prev.value += value;
  3050. append({ value });
  3051. // when literal brackets are explicitly disabled
  3052. // assume we should match with a regex character class
  3053. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3054. continue;
  3055. }
  3056. const escaped = utils$1.escapeRegex(prev.value);
  3057. state.output = state.output.slice(0, -prev.value.length);
  3058. // when literal brackets are explicitly enabled
  3059. // assume we should escape the brackets to match literal characters
  3060. if (opts.literalBrackets === true) {
  3061. state.output += escaped;
  3062. prev.value = escaped;
  3063. continue;
  3064. }
  3065. // when the user specifies nothing, try to match both
  3066. prev.value = `(${capture}${escaped}|${prev.value})`;
  3067. state.output += prev.value;
  3068. continue;
  3069. }
  3070. /**
  3071. * Braces
  3072. */
  3073. if (value === '{' && opts.nobrace !== true) {
  3074. increment('braces');
  3075. const open = {
  3076. type: 'brace',
  3077. value,
  3078. output: '(',
  3079. outputIndex: state.output.length,
  3080. tokensIndex: state.tokens.length
  3081. };
  3082. braces.push(open);
  3083. push(open);
  3084. continue;
  3085. }
  3086. if (value === '}') {
  3087. const brace = braces[braces.length - 1];
  3088. if (opts.nobrace === true || !brace) {
  3089. push({ type: 'text', value, output: value });
  3090. continue;
  3091. }
  3092. let output = ')';
  3093. if (brace.dots === true) {
  3094. const arr = tokens.slice();
  3095. const range = [];
  3096. for (let i = arr.length - 1; i >= 0; i--) {
  3097. tokens.pop();
  3098. if (arr[i].type === 'brace') {
  3099. break;
  3100. }
  3101. if (arr[i].type !== 'dots') {
  3102. range.unshift(arr[i].value);
  3103. }
  3104. }
  3105. output = expandRange(range, opts);
  3106. state.backtrack = true;
  3107. }
  3108. if (brace.comma !== true && brace.dots !== true) {
  3109. const out = state.output.slice(0, brace.outputIndex);
  3110. const toks = state.tokens.slice(brace.tokensIndex);
  3111. brace.value = brace.output = '\\{';
  3112. value = output = '\\}';
  3113. state.output = out;
  3114. for (const t of toks) {
  3115. state.output += (t.output || t.value);
  3116. }
  3117. }
  3118. push({ type: 'brace', value, output });
  3119. decrement('braces');
  3120. braces.pop();
  3121. continue;
  3122. }
  3123. /**
  3124. * Pipes
  3125. */
  3126. if (value === '|') {
  3127. if (extglobs.length > 0) {
  3128. extglobs[extglobs.length - 1].conditions++;
  3129. }
  3130. push({ type: 'text', value });
  3131. continue;
  3132. }
  3133. /**
  3134. * Commas
  3135. */
  3136. if (value === ',') {
  3137. let output = value;
  3138. const brace = braces[braces.length - 1];
  3139. if (brace && stack[stack.length - 1] === 'braces') {
  3140. brace.comma = true;
  3141. output = '|';
  3142. }
  3143. push({ type: 'comma', value, output });
  3144. continue;
  3145. }
  3146. /**
  3147. * Slashes
  3148. */
  3149. if (value === '/') {
  3150. // if the beginning of the glob is "./", advance the start
  3151. // to the current index, and don't add the "./" characters
  3152. // to the state. This greatly simplifies lookbehinds when
  3153. // checking for BOS characters like "!" and "." (not "./")
  3154. if (prev.type === 'dot' && state.index === state.start + 1) {
  3155. state.start = state.index + 1;
  3156. state.consumed = '';
  3157. state.output = '';
  3158. tokens.pop();
  3159. prev = bos; // reset "prev" to the first token
  3160. continue;
  3161. }
  3162. push({ type: 'slash', value, output: SLASH_LITERAL });
  3163. continue;
  3164. }
  3165. /**
  3166. * Dots
  3167. */
  3168. if (value === '.') {
  3169. if (state.braces > 0 && prev.type === 'dot') {
  3170. if (prev.value === '.') prev.output = DOT_LITERAL;
  3171. const brace = braces[braces.length - 1];
  3172. prev.type = 'dots';
  3173. prev.output += value;
  3174. prev.value += value;
  3175. brace.dots = true;
  3176. continue;
  3177. }
  3178. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3179. push({ type: 'text', value, output: DOT_LITERAL });
  3180. continue;
  3181. }
  3182. push({ type: 'dot', value, output: DOT_LITERAL });
  3183. continue;
  3184. }
  3185. /**
  3186. * Question marks
  3187. */
  3188. if (value === '?') {
  3189. const isGroup = prev && prev.value === '(';
  3190. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3191. extglobOpen('qmark', value);
  3192. continue;
  3193. }
  3194. if (prev && prev.type === 'paren') {
  3195. const next = peek();
  3196. let output = value;
  3197. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3198. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3199. }
  3200. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3201. output = `\\${value}`;
  3202. }
  3203. push({ type: 'text', value, output });
  3204. continue;
  3205. }
  3206. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3207. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3208. continue;
  3209. }
  3210. push({ type: 'qmark', value, output: QMARK });
  3211. continue;
  3212. }
  3213. /**
  3214. * Exclamation
  3215. */
  3216. if (value === '!') {
  3217. if (opts.noextglob !== true && peek() === '(') {
  3218. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3219. extglobOpen('negate', value);
  3220. continue;
  3221. }
  3222. }
  3223. if (opts.nonegate !== true && state.index === 0) {
  3224. negate();
  3225. continue;
  3226. }
  3227. }
  3228. /**
  3229. * Plus
  3230. */
  3231. if (value === '+') {
  3232. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3233. extglobOpen('plus', value);
  3234. continue;
  3235. }
  3236. if ((prev && prev.value === '(') || opts.regex === false) {
  3237. push({ type: 'plus', value, output: PLUS_LITERAL });
  3238. continue;
  3239. }
  3240. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3241. push({ type: 'plus', value });
  3242. continue;
  3243. }
  3244. push({ type: 'plus', value: PLUS_LITERAL });
  3245. continue;
  3246. }
  3247. /**
  3248. * Plain text
  3249. */
  3250. if (value === '@') {
  3251. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3252. push({ type: 'at', extglob: true, value, output: '' });
  3253. continue;
  3254. }
  3255. push({ type: 'text', value });
  3256. continue;
  3257. }
  3258. /**
  3259. * Plain text
  3260. */
  3261. if (value !== '*') {
  3262. if (value === '$' || value === '^') {
  3263. value = `\\${value}`;
  3264. }
  3265. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3266. if (match) {
  3267. value += match[0];
  3268. state.index += match[0].length;
  3269. }
  3270. push({ type: 'text', value });
  3271. continue;
  3272. }
  3273. /**
  3274. * Stars
  3275. */
  3276. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3277. prev.type = 'star';
  3278. prev.star = true;
  3279. prev.value += value;
  3280. prev.output = star;
  3281. state.backtrack = true;
  3282. state.globstar = true;
  3283. consume(value);
  3284. continue;
  3285. }
  3286. let rest = remaining();
  3287. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3288. extglobOpen('star', value);
  3289. continue;
  3290. }
  3291. if (prev.type === 'star') {
  3292. if (opts.noglobstar === true) {
  3293. consume(value);
  3294. continue;
  3295. }
  3296. const prior = prev.prev;
  3297. const before = prior.prev;
  3298. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3299. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3300. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3301. push({ type: 'star', value, output: '' });
  3302. continue;
  3303. }
  3304. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3305. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3306. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3307. push({ type: 'star', value, output: '' });
  3308. continue;
  3309. }
  3310. // strip consecutive `/**/`
  3311. while (rest.slice(0, 3) === '/**') {
  3312. const after = input[state.index + 4];
  3313. if (after && after !== '/') {
  3314. break;
  3315. }
  3316. rest = rest.slice(3);
  3317. consume('/**', 3);
  3318. }
  3319. if (prior.type === 'bos' && eos()) {
  3320. prev.type = 'globstar';
  3321. prev.value += value;
  3322. prev.output = globstar(opts);
  3323. state.output = prev.output;
  3324. state.globstar = true;
  3325. consume(value);
  3326. continue;
  3327. }
  3328. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3329. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3330. prior.output = `(?:${prior.output}`;
  3331. prev.type = 'globstar';
  3332. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3333. prev.value += value;
  3334. state.globstar = true;
  3335. state.output += prior.output + prev.output;
  3336. consume(value);
  3337. continue;
  3338. }
  3339. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3340. const end = rest[1] !== void 0 ? '|$' : '';
  3341. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3342. prior.output = `(?:${prior.output}`;
  3343. prev.type = 'globstar';
  3344. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3345. prev.value += value;
  3346. state.output += prior.output + prev.output;
  3347. state.globstar = true;
  3348. consume(value + advance());
  3349. push({ type: 'slash', value: '/', output: '' });
  3350. continue;
  3351. }
  3352. if (prior.type === 'bos' && rest[0] === '/') {
  3353. prev.type = 'globstar';
  3354. prev.value += value;
  3355. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3356. state.output = prev.output;
  3357. state.globstar = true;
  3358. consume(value + advance());
  3359. push({ type: 'slash', value: '/', output: '' });
  3360. continue;
  3361. }
  3362. // remove single star from output
  3363. state.output = state.output.slice(0, -prev.output.length);
  3364. // reset previous token to globstar
  3365. prev.type = 'globstar';
  3366. prev.output = globstar(opts);
  3367. prev.value += value;
  3368. // reset output with globstar
  3369. state.output += prev.output;
  3370. state.globstar = true;
  3371. consume(value);
  3372. continue;
  3373. }
  3374. const token = { type: 'star', value, output: star };
  3375. if (opts.bash === true) {
  3376. token.output = '.*?';
  3377. if (prev.type === 'bos' || prev.type === 'slash') {
  3378. token.output = nodot + token.output;
  3379. }
  3380. push(token);
  3381. continue;
  3382. }
  3383. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3384. token.output = value;
  3385. push(token);
  3386. continue;
  3387. }
  3388. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3389. if (prev.type === 'dot') {
  3390. state.output += NO_DOT_SLASH;
  3391. prev.output += NO_DOT_SLASH;
  3392. } else if (opts.dot === true) {
  3393. state.output += NO_DOTS_SLASH;
  3394. prev.output += NO_DOTS_SLASH;
  3395. } else {
  3396. state.output += nodot;
  3397. prev.output += nodot;
  3398. }
  3399. if (peek() !== '*') {
  3400. state.output += ONE_CHAR;
  3401. prev.output += ONE_CHAR;
  3402. }
  3403. }
  3404. push(token);
  3405. }
  3406. while (state.brackets > 0) {
  3407. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3408. state.output = utils$1.escapeLast(state.output, '[');
  3409. decrement('brackets');
  3410. }
  3411. while (state.parens > 0) {
  3412. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3413. state.output = utils$1.escapeLast(state.output, '(');
  3414. decrement('parens');
  3415. }
  3416. while (state.braces > 0) {
  3417. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3418. state.output = utils$1.escapeLast(state.output, '{');
  3419. decrement('braces');
  3420. }
  3421. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3422. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3423. }
  3424. // rebuild the output if we had to backtrack at any point
  3425. if (state.backtrack === true) {
  3426. state.output = '';
  3427. for (const token of state.tokens) {
  3428. state.output += token.output != null ? token.output : token.value;
  3429. if (token.suffix) {
  3430. state.output += token.suffix;
  3431. }
  3432. }
  3433. }
  3434. return state;
  3435. };
  3436. /**
  3437. * Fast paths for creating regular expressions for common glob patterns.
  3438. * This can significantly speed up processing and has very little downside
  3439. * impact when none of the fast paths match.
  3440. */
  3441. parse$1.fastpaths = (input, options) => {
  3442. const opts = { ...options };
  3443. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3444. const len = input.length;
  3445. if (len > max) {
  3446. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3447. }
  3448. input = REPLACEMENTS[input] || input;
  3449. const win32 = utils$1.isWindows(options);
  3450. // create constants based on platform, for windows or posix
  3451. const {
  3452. DOT_LITERAL,
  3453. SLASH_LITERAL,
  3454. ONE_CHAR,
  3455. DOTS_SLASH,
  3456. NO_DOT,
  3457. NO_DOTS,
  3458. NO_DOTS_SLASH,
  3459. STAR,
  3460. START_ANCHOR
  3461. } = constants$1.globChars(win32);
  3462. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3463. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3464. const capture = opts.capture ? '' : '?:';
  3465. const state = { negated: false, prefix: '' };
  3466. let star = opts.bash === true ? '.*?' : STAR;
  3467. if (opts.capture) {
  3468. star = `(${star})`;
  3469. }
  3470. const globstar = opts => {
  3471. if (opts.noglobstar === true) return star;
  3472. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3473. };
  3474. const create = str => {
  3475. switch (str) {
  3476. case '*':
  3477. return `${nodot}${ONE_CHAR}${star}`;
  3478. case '.*':
  3479. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3480. case '*.*':
  3481. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3482. case '*/*':
  3483. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3484. case '**':
  3485. return nodot + globstar(opts);
  3486. case '**/*':
  3487. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3488. case '**/*.*':
  3489. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3490. case '**/.*':
  3491. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3492. default: {
  3493. const match = /^(.*?)\.(\w+)$/.exec(str);
  3494. if (!match) return;
  3495. const source = create(match[1]);
  3496. if (!source) return;
  3497. return source + DOT_LITERAL + match[2];
  3498. }
  3499. }
  3500. };
  3501. const output = utils$1.removePrefix(input, state);
  3502. let source = create(output);
  3503. if (source && opts.strictSlashes !== true) {
  3504. source += `${SLASH_LITERAL}?`;
  3505. }
  3506. return source;
  3507. };
  3508. var parse_1 = parse$1;
  3509. const path = require$$0;
  3510. const scan = scan_1;
  3511. const parse = parse_1;
  3512. const utils = utils$3;
  3513. const constants = constants$2;
  3514. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3515. /**
  3516. * Creates a matcher function from one or more glob patterns. The
  3517. * returned function takes a string to match as its first argument,
  3518. * and returns true if the string is a match. The returned matcher
  3519. * function also takes a boolean as the second argument that, when true,
  3520. * returns an object with additional information.
  3521. *
  3522. * ```js
  3523. * const picomatch = require('picomatch');
  3524. * // picomatch(glob[, options]);
  3525. *
  3526. * const isMatch = picomatch('*.!(*a)');
  3527. * console.log(isMatch('a.a')); //=> false
  3528. * console.log(isMatch('a.b')); //=> true
  3529. * ```
  3530. * @name picomatch
  3531. * @param {String|Array} `globs` One or more glob patterns.
  3532. * @param {Object=} `options`
  3533. * @return {Function=} Returns a matcher function.
  3534. * @api public
  3535. */
  3536. const picomatch = (glob, options, returnState = false) => {
  3537. if (Array.isArray(glob)) {
  3538. const fns = glob.map(input => picomatch(input, options, returnState));
  3539. const arrayMatcher = str => {
  3540. for (const isMatch of fns) {
  3541. const state = isMatch(str);
  3542. if (state) return state;
  3543. }
  3544. return false;
  3545. };
  3546. return arrayMatcher;
  3547. }
  3548. const isState = isObject(glob) && glob.tokens && glob.input;
  3549. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3550. throw new TypeError('Expected pattern to be a non-empty string');
  3551. }
  3552. const opts = options || {};
  3553. const posix = utils.isWindows(options);
  3554. const regex = isState
  3555. ? picomatch.compileRe(glob, options)
  3556. : picomatch.makeRe(glob, options, false, true);
  3557. const state = regex.state;
  3558. delete regex.state;
  3559. let isIgnored = () => false;
  3560. if (opts.ignore) {
  3561. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3562. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3563. }
  3564. const matcher = (input, returnObject = false) => {
  3565. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3566. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3567. if (typeof opts.onResult === 'function') {
  3568. opts.onResult(result);
  3569. }
  3570. if (isMatch === false) {
  3571. result.isMatch = false;
  3572. return returnObject ? result : false;
  3573. }
  3574. if (isIgnored(input)) {
  3575. if (typeof opts.onIgnore === 'function') {
  3576. opts.onIgnore(result);
  3577. }
  3578. result.isMatch = false;
  3579. return returnObject ? result : false;
  3580. }
  3581. if (typeof opts.onMatch === 'function') {
  3582. opts.onMatch(result);
  3583. }
  3584. return returnObject ? result : true;
  3585. };
  3586. if (returnState) {
  3587. matcher.state = state;
  3588. }
  3589. return matcher;
  3590. };
  3591. /**
  3592. * Test `input` with the given `regex`. This is used by the main
  3593. * `picomatch()` function to test the input string.
  3594. *
  3595. * ```js
  3596. * const picomatch = require('picomatch');
  3597. * // picomatch.test(input, regex[, options]);
  3598. *
  3599. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3600. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3601. * ```
  3602. * @param {String} `input` String to test.
  3603. * @param {RegExp} `regex`
  3604. * @return {Object} Returns an object with matching info.
  3605. * @api public
  3606. */
  3607. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3608. if (typeof input !== 'string') {
  3609. throw new TypeError('Expected input to be a string');
  3610. }
  3611. if (input === '') {
  3612. return { isMatch: false, output: '' };
  3613. }
  3614. const opts = options || {};
  3615. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3616. let match = input === glob;
  3617. let output = (match && format) ? format(input) : input;
  3618. if (match === false) {
  3619. output = format ? format(input) : input;
  3620. match = output === glob;
  3621. }
  3622. if (match === false || opts.capture === true) {
  3623. if (opts.matchBase === true || opts.basename === true) {
  3624. match = picomatch.matchBase(input, regex, options, posix);
  3625. } else {
  3626. match = regex.exec(output);
  3627. }
  3628. }
  3629. return { isMatch: Boolean(match), match, output };
  3630. };
  3631. /**
  3632. * Match the basename of a filepath.
  3633. *
  3634. * ```js
  3635. * const picomatch = require('picomatch');
  3636. * // picomatch.matchBase(input, glob[, options]);
  3637. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3638. * ```
  3639. * @param {String} `input` String to test.
  3640. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3641. * @return {Boolean}
  3642. * @api public
  3643. */
  3644. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3645. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3646. return regex.test(path.basename(input));
  3647. };
  3648. /**
  3649. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3650. *
  3651. * ```js
  3652. * const picomatch = require('picomatch');
  3653. * // picomatch.isMatch(string, patterns[, options]);
  3654. *
  3655. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3656. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3657. * ```
  3658. * @param {String|Array} str The string to test.
  3659. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3660. * @param {Object} [options] See available [options](#options).
  3661. * @return {Boolean} Returns true if any patterns match `str`
  3662. * @api public
  3663. */
  3664. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3665. /**
  3666. * Parse a glob pattern to create the source string for a regular
  3667. * expression.
  3668. *
  3669. * ```js
  3670. * const picomatch = require('picomatch');
  3671. * const result = picomatch.parse(pattern[, options]);
  3672. * ```
  3673. * @param {String} `pattern`
  3674. * @param {Object} `options`
  3675. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3676. * @api public
  3677. */
  3678. picomatch.parse = (pattern, options) => {
  3679. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3680. return parse(pattern, { ...options, fastpaths: false });
  3681. };
  3682. /**
  3683. * Scan a glob pattern to separate the pattern into segments.
  3684. *
  3685. * ```js
  3686. * const picomatch = require('picomatch');
  3687. * // picomatch.scan(input[, options]);
  3688. *
  3689. * const result = picomatch.scan('!./foo/*.js');
  3690. * console.log(result);
  3691. * { prefix: '!./',
  3692. * input: '!./foo/*.js',
  3693. * start: 3,
  3694. * base: 'foo',
  3695. * glob: '*.js',
  3696. * isBrace: false,
  3697. * isBracket: false,
  3698. * isGlob: true,
  3699. * isExtglob: false,
  3700. * isGlobstar: false,
  3701. * negated: true }
  3702. * ```
  3703. * @param {String} `input` Glob pattern to scan.
  3704. * @param {Object} `options`
  3705. * @return {Object} Returns an object with
  3706. * @api public
  3707. */
  3708. picomatch.scan = (input, options) => scan(input, options);
  3709. /**
  3710. * Compile a regular expression from the `state` object returned by the
  3711. * [parse()](#parse) method.
  3712. *
  3713. * @param {Object} `state`
  3714. * @param {Object} `options`
  3715. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3716. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3717. * @return {RegExp}
  3718. * @api public
  3719. */
  3720. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3721. if (returnOutput === true) {
  3722. return state.output;
  3723. }
  3724. const opts = options || {};
  3725. const prepend = opts.contains ? '' : '^';
  3726. const append = opts.contains ? '' : '$';
  3727. let source = `${prepend}(?:${state.output})${append}`;
  3728. if (state && state.negated === true) {
  3729. source = `^(?!${source}).*$`;
  3730. }
  3731. const regex = picomatch.toRegex(source, options);
  3732. if (returnState === true) {
  3733. regex.state = state;
  3734. }
  3735. return regex;
  3736. };
  3737. /**
  3738. * Create a regular expression from a parsed glob pattern.
  3739. *
  3740. * ```js
  3741. * const picomatch = require('picomatch');
  3742. * const state = picomatch.parse('*.js');
  3743. * // picomatch.compileRe(state[, options]);
  3744. *
  3745. * console.log(picomatch.compileRe(state));
  3746. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3747. * ```
  3748. * @param {String} `state` The object returned from the `.parse` method.
  3749. * @param {Object} `options`
  3750. * @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.
  3751. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3752. * @return {RegExp} Returns a regex created from the given pattern.
  3753. * @api public
  3754. */
  3755. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3756. if (!input || typeof input !== 'string') {
  3757. throw new TypeError('Expected a non-empty string');
  3758. }
  3759. let parsed = { negated: false, fastpaths: true };
  3760. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3761. parsed.output = parse.fastpaths(input, options);
  3762. }
  3763. if (!parsed.output) {
  3764. parsed = parse(input, options);
  3765. }
  3766. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3767. };
  3768. /**
  3769. * Create a regular expression from the given regex source string.
  3770. *
  3771. * ```js
  3772. * const picomatch = require('picomatch');
  3773. * // picomatch.toRegex(source[, options]);
  3774. *
  3775. * const { output } = picomatch.parse('*.js');
  3776. * console.log(picomatch.toRegex(output));
  3777. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3778. * ```
  3779. * @param {String} `source` Regular expression source string.
  3780. * @param {Object} `options`
  3781. * @return {RegExp}
  3782. * @api public
  3783. */
  3784. picomatch.toRegex = (source, options) => {
  3785. try {
  3786. const opts = options || {};
  3787. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3788. } catch (err) {
  3789. if (options && options.debug === true) throw err;
  3790. return /$^/;
  3791. }
  3792. };
  3793. /**
  3794. * Picomatch constants.
  3795. * @return {Object}
  3796. */
  3797. picomatch.constants = constants;
  3798. /**
  3799. * Expose "picomatch"
  3800. */
  3801. var picomatch_1 = picomatch;
  3802. (function (module) {
  3803. module.exports = picomatch_1;
  3804. } (picomatch$1));
  3805. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
  3806. const extractors = {
  3807. ArrayPattern(names, param) {
  3808. for (const element of param.elements) {
  3809. if (element)
  3810. extractors[element.type](names, element);
  3811. }
  3812. },
  3813. AssignmentPattern(names, param) {
  3814. extractors[param.left.type](names, param.left);
  3815. },
  3816. Identifier(names, param) {
  3817. names.push(param.name);
  3818. },
  3819. MemberExpression() { },
  3820. ObjectPattern(names, param) {
  3821. for (const prop of param.properties) {
  3822. // @ts-ignore Typescript reports that this is not a valid type
  3823. if (prop.type === 'RestElement') {
  3824. extractors.RestElement(names, prop);
  3825. }
  3826. else {
  3827. extractors[prop.value.type](names, prop.value);
  3828. }
  3829. }
  3830. },
  3831. RestElement(names, param) {
  3832. extractors[param.argument.type](names, param.argument);
  3833. }
  3834. };
  3835. const extractAssignedNames = function extractAssignedNames(param) {
  3836. const names = [];
  3837. extractors[param.type](names, param);
  3838. return names;
  3839. };
  3840. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3841. function isArray$1(arg) {
  3842. return Array.isArray(arg);
  3843. }
  3844. function ensureArray$1(thing) {
  3845. if (isArray$1(thing))
  3846. return thing;
  3847. if (thing == null)
  3848. return [];
  3849. return [thing];
  3850. }
  3851. const normalizePath = function normalizePath(filename) {
  3852. return filename.split(win32.sep).join(posix.sep);
  3853. };
  3854. function getMatcherString(id, resolutionBase) {
  3855. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
  3856. return normalizePath(id);
  3857. }
  3858. // resolve('') is valid and will default to process.cwd()
  3859. const basePath = normalizePath(resolve(resolutionBase || ''))
  3860. // escape all possible (posix + win) path characters that might interfere with regex
  3861. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  3862. // Note that we use posix.join because:
  3863. // 1. the basePath has been normalized to use /
  3864. // 2. the incoming glob (id) matcher, also uses /
  3865. // otherwise Node will force backslash (\) on windows
  3866. return posix.join(basePath, normalizePath(id));
  3867. }
  3868. const createFilter = function createFilter(include, exclude, options) {
  3869. const resolutionBase = options && options.resolve;
  3870. const getMatcher = (id) => id instanceof RegExp
  3871. ? id
  3872. : {
  3873. test: (what) => {
  3874. // this refactor is a tad overly verbose but makes for easy debugging
  3875. const pattern = getMatcherString(id, resolutionBase);
  3876. const fn = pm(pattern, { dot: true });
  3877. const result = fn(what);
  3878. return result;
  3879. }
  3880. };
  3881. const includeMatchers = ensureArray$1(include).map(getMatcher);
  3882. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  3883. return function result(id) {
  3884. if (typeof id !== 'string')
  3885. return false;
  3886. if (/\0/.test(id))
  3887. return false;
  3888. const pathId = normalizePath(id);
  3889. for (let i = 0; i < excludeMatchers.length; ++i) {
  3890. const matcher = excludeMatchers[i];
  3891. if (matcher.test(pathId))
  3892. return false;
  3893. }
  3894. for (let i = 0; i < includeMatchers.length; ++i) {
  3895. const matcher = includeMatchers[i];
  3896. if (matcher.test(pathId))
  3897. return true;
  3898. }
  3899. return !includeMatchers.length;
  3900. };
  3901. };
  3902. const reservedWords$1 = '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';
  3903. const builtins$1 = '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';
  3904. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  3905. forbiddenIdentifiers.add('');
  3906. const BROKEN_FLOW_NONE = 0;
  3907. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  3908. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  3909. function createInclusionContext() {
  3910. return {
  3911. brokenFlow: BROKEN_FLOW_NONE,
  3912. includedCallArguments: new Set(),
  3913. includedLabels: new Set()
  3914. };
  3915. }
  3916. function createHasEffectsContext() {
  3917. return {
  3918. accessed: new PathTracker(),
  3919. assigned: new PathTracker(),
  3920. brokenFlow: BROKEN_FLOW_NONE,
  3921. called: new DiscriminatedPathTracker(),
  3922. ignore: {
  3923. breaks: false,
  3924. continues: false,
  3925. labels: new Set(),
  3926. returnYield: false
  3927. },
  3928. includedLabels: new Set(),
  3929. instantiated: new DiscriminatedPathTracker(),
  3930. replacedVariableInits: new Map()
  3931. };
  3932. }
  3933. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  3934. return Object.create(inheritedDescriptions, memberDescriptions);
  3935. }
  3936. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  3937. getLiteralValueAtPath() {
  3938. return undefined;
  3939. }
  3940. })();
  3941. const returnsUnknown = {
  3942. value: {
  3943. hasEffectsWhenCalled: null,
  3944. returns: UNKNOWN_EXPRESSION
  3945. }
  3946. };
  3947. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  3948. getReturnExpressionWhenCalledAtPath(path) {
  3949. if (path.length === 1) {
  3950. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  3951. }
  3952. return UNKNOWN_EXPRESSION;
  3953. }
  3954. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3955. if (interaction.type === INTERACTION_ACCESSED) {
  3956. return path.length > 1;
  3957. }
  3958. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3959. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  3960. }
  3961. return true;
  3962. }
  3963. })();
  3964. const returnsBoolean = {
  3965. value: {
  3966. hasEffectsWhenCalled: null,
  3967. returns: UNKNOWN_LITERAL_BOOLEAN
  3968. }
  3969. };
  3970. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  3971. getReturnExpressionWhenCalledAtPath(path) {
  3972. if (path.length === 1) {
  3973. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  3974. }
  3975. return UNKNOWN_EXPRESSION;
  3976. }
  3977. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3978. if (interaction.type === INTERACTION_ACCESSED) {
  3979. return path.length > 1;
  3980. }
  3981. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3982. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  3983. }
  3984. return true;
  3985. }
  3986. })();
  3987. const returnsNumber = {
  3988. value: {
  3989. hasEffectsWhenCalled: null,
  3990. returns: UNKNOWN_LITERAL_NUMBER
  3991. }
  3992. };
  3993. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  3994. getReturnExpressionWhenCalledAtPath(path) {
  3995. if (path.length === 1) {
  3996. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  3997. }
  3998. return UNKNOWN_EXPRESSION;
  3999. }
  4000. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4001. if (interaction.type === INTERACTION_ACCESSED) {
  4002. return path.length > 1;
  4003. }
  4004. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4005. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4006. }
  4007. return true;
  4008. }
  4009. })();
  4010. const returnsString = {
  4011. value: {
  4012. hasEffectsWhenCalled: null,
  4013. returns: UNKNOWN_LITERAL_STRING
  4014. }
  4015. };
  4016. const stringReplace = {
  4017. value: {
  4018. hasEffectsWhenCalled({ args }, context) {
  4019. const arg1 = args[1];
  4020. return (args.length < 2 ||
  4021. (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4022. deoptimizeCache() { }
  4023. }) === 'symbol' &&
  4024. arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4025. },
  4026. returns: UNKNOWN_LITERAL_STRING
  4027. }
  4028. };
  4029. const objectMembers = assembleMemberDescriptions({
  4030. hasOwnProperty: returnsBoolean,
  4031. isPrototypeOf: returnsBoolean,
  4032. propertyIsEnumerable: returnsBoolean,
  4033. toLocaleString: returnsString,
  4034. toString: returnsString,
  4035. valueOf: returnsUnknown
  4036. });
  4037. const literalBooleanMembers = assembleMemberDescriptions({
  4038. valueOf: returnsBoolean
  4039. }, objectMembers);
  4040. const literalNumberMembers = assembleMemberDescriptions({
  4041. toExponential: returnsString,
  4042. toFixed: returnsString,
  4043. toLocaleString: returnsString,
  4044. toPrecision: returnsString,
  4045. valueOf: returnsNumber
  4046. }, objectMembers);
  4047. const literalStringMembers = assembleMemberDescriptions({
  4048. anchor: returnsString,
  4049. at: returnsUnknown,
  4050. big: returnsString,
  4051. blink: returnsString,
  4052. bold: returnsString,
  4053. charAt: returnsString,
  4054. charCodeAt: returnsNumber,
  4055. codePointAt: returnsUnknown,
  4056. concat: returnsString,
  4057. endsWith: returnsBoolean,
  4058. fixed: returnsString,
  4059. fontcolor: returnsString,
  4060. fontsize: returnsString,
  4061. includes: returnsBoolean,
  4062. indexOf: returnsNumber,
  4063. italics: returnsString,
  4064. lastIndexOf: returnsNumber,
  4065. link: returnsString,
  4066. localeCompare: returnsNumber,
  4067. match: returnsUnknown,
  4068. matchAll: returnsUnknown,
  4069. normalize: returnsString,
  4070. padEnd: returnsString,
  4071. padStart: returnsString,
  4072. repeat: returnsString,
  4073. replace: stringReplace,
  4074. replaceAll: stringReplace,
  4075. search: returnsNumber,
  4076. slice: returnsString,
  4077. small: returnsString,
  4078. split: returnsUnknown,
  4079. startsWith: returnsBoolean,
  4080. strike: returnsString,
  4081. sub: returnsString,
  4082. substr: returnsString,
  4083. substring: returnsString,
  4084. sup: returnsString,
  4085. toLocaleLowerCase: returnsString,
  4086. toLocaleUpperCase: returnsString,
  4087. toLowerCase: returnsString,
  4088. toString: returnsString,
  4089. toUpperCase: returnsString,
  4090. trim: returnsString,
  4091. trimEnd: returnsString,
  4092. trimLeft: returnsString,
  4093. trimRight: returnsString,
  4094. trimStart: returnsString,
  4095. valueOf: returnsString
  4096. }, objectMembers);
  4097. function getLiteralMembersForValue(value) {
  4098. switch (typeof value) {
  4099. case 'boolean':
  4100. return literalBooleanMembers;
  4101. case 'number':
  4102. return literalNumberMembers;
  4103. case 'string':
  4104. return literalStringMembers;
  4105. }
  4106. return Object.create(null);
  4107. }
  4108. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4109. var _a, _b;
  4110. if (typeof memberName !== 'string' || !members[memberName]) {
  4111. return true;
  4112. }
  4113. return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
  4114. }
  4115. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4116. if (typeof memberName !== 'string' || !members[memberName])
  4117. return UNKNOWN_EXPRESSION;
  4118. return members[memberName].returns;
  4119. }
  4120. // AST walker module for Mozilla Parser API compatible trees
  4121. function skipThrough(node, st, c) { c(node, st); }
  4122. function ignore(_node, _st, _c) {}
  4123. // Node walkers.
  4124. var base$1 = {};
  4125. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4126. for (var i = 0, list = node.body; i < list.length; i += 1)
  4127. {
  4128. var stmt = list[i];
  4129. c(stmt, st, "Statement");
  4130. }
  4131. };
  4132. base$1.Statement = skipThrough;
  4133. base$1.EmptyStatement = ignore;
  4134. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4135. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4136. base$1.IfStatement = function (node, st, c) {
  4137. c(node.test, st, "Expression");
  4138. c(node.consequent, st, "Statement");
  4139. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4140. };
  4141. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4142. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4143. base$1.WithStatement = function (node, st, c) {
  4144. c(node.object, st, "Expression");
  4145. c(node.body, st, "Statement");
  4146. };
  4147. base$1.SwitchStatement = function (node, st, c) {
  4148. c(node.discriminant, st, "Expression");
  4149. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4150. var cs = list$1[i$1];
  4151. if (cs.test) { c(cs.test, st, "Expression"); }
  4152. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4153. {
  4154. var cons = list[i];
  4155. c(cons, st, "Statement");
  4156. }
  4157. }
  4158. };
  4159. base$1.SwitchCase = function (node, st, c) {
  4160. if (node.test) { c(node.test, st, "Expression"); }
  4161. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4162. {
  4163. var cons = list[i];
  4164. c(cons, st, "Statement");
  4165. }
  4166. };
  4167. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4168. if (node.argument) { c(node.argument, st, "Expression"); }
  4169. };
  4170. base$1.ThrowStatement = base$1.SpreadElement =
  4171. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4172. base$1.TryStatement = function (node, st, c) {
  4173. c(node.block, st, "Statement");
  4174. if (node.handler) { c(node.handler, st); }
  4175. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4176. };
  4177. base$1.CatchClause = function (node, st, c) {
  4178. if (node.param) { c(node.param, st, "Pattern"); }
  4179. c(node.body, st, "Statement");
  4180. };
  4181. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4182. c(node.test, st, "Expression");
  4183. c(node.body, st, "Statement");
  4184. };
  4185. base$1.ForStatement = function (node, st, c) {
  4186. if (node.init) { c(node.init, st, "ForInit"); }
  4187. if (node.test) { c(node.test, st, "Expression"); }
  4188. if (node.update) { c(node.update, st, "Expression"); }
  4189. c(node.body, st, "Statement");
  4190. };
  4191. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4192. c(node.left, st, "ForInit");
  4193. c(node.right, st, "Expression");
  4194. c(node.body, st, "Statement");
  4195. };
  4196. base$1.ForInit = function (node, st, c) {
  4197. if (node.type === "VariableDeclaration") { c(node, st); }
  4198. else { c(node, st, "Expression"); }
  4199. };
  4200. base$1.DebuggerStatement = ignore;
  4201. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4202. base$1.VariableDeclaration = function (node, st, c) {
  4203. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4204. {
  4205. var decl = list[i];
  4206. c(decl, st);
  4207. }
  4208. };
  4209. base$1.VariableDeclarator = function (node, st, c) {
  4210. c(node.id, st, "Pattern");
  4211. if (node.init) { c(node.init, st, "Expression"); }
  4212. };
  4213. base$1.Function = function (node, st, c) {
  4214. if (node.id) { c(node.id, st, "Pattern"); }
  4215. for (var i = 0, list = node.params; i < list.length; i += 1)
  4216. {
  4217. var param = list[i];
  4218. c(param, st, "Pattern");
  4219. }
  4220. c(node.body, st, node.expression ? "Expression" : "Statement");
  4221. };
  4222. base$1.Pattern = function (node, st, c) {
  4223. if (node.type === "Identifier")
  4224. { c(node, st, "VariablePattern"); }
  4225. else if (node.type === "MemberExpression")
  4226. { c(node, st, "MemberPattern"); }
  4227. else
  4228. { c(node, st); }
  4229. };
  4230. base$1.VariablePattern = ignore;
  4231. base$1.MemberPattern = skipThrough;
  4232. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4233. base$1.ArrayPattern = function (node, st, c) {
  4234. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4235. var elt = list[i];
  4236. if (elt) { c(elt, st, "Pattern"); }
  4237. }
  4238. };
  4239. base$1.ObjectPattern = function (node, st, c) {
  4240. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4241. var prop = list[i];
  4242. if (prop.type === "Property") {
  4243. if (prop.computed) { c(prop.key, st, "Expression"); }
  4244. c(prop.value, st, "Pattern");
  4245. } else if (prop.type === "RestElement") {
  4246. c(prop.argument, st, "Pattern");
  4247. }
  4248. }
  4249. };
  4250. base$1.Expression = skipThrough;
  4251. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4252. base$1.ArrayExpression = function (node, st, c) {
  4253. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4254. var elt = list[i];
  4255. if (elt) { c(elt, st, "Expression"); }
  4256. }
  4257. };
  4258. base$1.ObjectExpression = function (node, st, c) {
  4259. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4260. {
  4261. var prop = list[i];
  4262. c(prop, st);
  4263. }
  4264. };
  4265. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4266. base$1.SequenceExpression = function (node, st, c) {
  4267. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4268. {
  4269. var expr = list[i];
  4270. c(expr, st, "Expression");
  4271. }
  4272. };
  4273. base$1.TemplateLiteral = function (node, st, c) {
  4274. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4275. {
  4276. var quasi = list[i];
  4277. c(quasi, st);
  4278. }
  4279. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4280. {
  4281. var expr = list$1[i$1];
  4282. c(expr, st, "Expression");
  4283. }
  4284. };
  4285. base$1.TemplateElement = ignore;
  4286. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4287. c(node.argument, st, "Expression");
  4288. };
  4289. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4290. c(node.left, st, "Expression");
  4291. c(node.right, st, "Expression");
  4292. };
  4293. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4294. c(node.left, st, "Pattern");
  4295. c(node.right, st, "Expression");
  4296. };
  4297. base$1.ConditionalExpression = function (node, st, c) {
  4298. c(node.test, st, "Expression");
  4299. c(node.consequent, st, "Expression");
  4300. c(node.alternate, st, "Expression");
  4301. };
  4302. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4303. c(node.callee, st, "Expression");
  4304. if (node.arguments)
  4305. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4306. {
  4307. var arg = list[i];
  4308. c(arg, st, "Expression");
  4309. } }
  4310. };
  4311. base$1.MemberExpression = function (node, st, c) {
  4312. c(node.object, st, "Expression");
  4313. if (node.computed) { c(node.property, st, "Expression"); }
  4314. };
  4315. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4316. if (node.declaration)
  4317. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4318. if (node.source) { c(node.source, st, "Expression"); }
  4319. };
  4320. base$1.ExportAllDeclaration = function (node, st, c) {
  4321. if (node.exported)
  4322. { c(node.exported, st); }
  4323. c(node.source, st, "Expression");
  4324. };
  4325. base$1.ImportDeclaration = function (node, st, c) {
  4326. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4327. {
  4328. var spec = list[i];
  4329. c(spec, st);
  4330. }
  4331. c(node.source, st, "Expression");
  4332. };
  4333. base$1.ImportExpression = function (node, st, c) {
  4334. c(node.source, st, "Expression");
  4335. };
  4336. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4337. base$1.TaggedTemplateExpression = function (node, st, c) {
  4338. c(node.tag, st, "Expression");
  4339. c(node.quasi, st, "Expression");
  4340. };
  4341. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4342. base$1.Class = function (node, st, c) {
  4343. if (node.id) { c(node.id, st, "Pattern"); }
  4344. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4345. c(node.body, st);
  4346. };
  4347. base$1.ClassBody = function (node, st, c) {
  4348. for (var i = 0, list = node.body; i < list.length; i += 1)
  4349. {
  4350. var elt = list[i];
  4351. c(elt, st);
  4352. }
  4353. };
  4354. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4355. if (node.computed) { c(node.key, st, "Expression"); }
  4356. if (node.value) { c(node.value, st, "Expression"); }
  4357. };
  4358. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4359. const BinaryExpression$1 = 'BinaryExpression';
  4360. const BlockStatement$1 = 'BlockStatement';
  4361. const CallExpression$1 = 'CallExpression';
  4362. const ChainExpression$1 = 'ChainExpression';
  4363. const ConditionalExpression$1 = 'ConditionalExpression';
  4364. const ExpressionStatement$1 = 'ExpressionStatement';
  4365. const Identifier$1 = 'Identifier';
  4366. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  4367. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  4368. const LogicalExpression$1 = 'LogicalExpression';
  4369. const NewExpression$1 = 'NewExpression';
  4370. const Program$1 = 'Program';
  4371. const Property$1 = 'Property';
  4372. const ReturnStatement$1 = 'ReturnStatement';
  4373. const SequenceExpression$1 = 'SequenceExpression';
  4374. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4375. // this for an actual sourceMappingURL
  4376. let SOURCEMAPPING_URL = 'sourceMa';
  4377. SOURCEMAPPING_URL += 'ppingURL';
  4378. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4379. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  4380. const ANNOTATION_KEY = '_rollupAnnotations';
  4381. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4382. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4383. const { annotations } = state;
  4384. let comment = annotations[state.annotationIndex];
  4385. while (comment && node.start >= comment.end) {
  4386. markPureNode(node, comment, state.code);
  4387. comment = annotations[++state.annotationIndex];
  4388. }
  4389. if (comment && comment.end <= node.end) {
  4390. base$1[type](node, state, handlePureAnnotationsOfNode);
  4391. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4392. ++state.annotationIndex;
  4393. annotateNode(node, comment, false);
  4394. }
  4395. }
  4396. }
  4397. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4398. const noWhitespace = /\S/g;
  4399. function markPureNode(node, comment, code) {
  4400. const annotatedNodes = [];
  4401. let invalidAnnotation;
  4402. const codeInBetween = code.slice(comment.end, node.start);
  4403. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4404. const parentStart = node.start;
  4405. while (true) {
  4406. annotatedNodes.push(node);
  4407. switch (node.type) {
  4408. case ExpressionStatement$1:
  4409. case ChainExpression$1:
  4410. node = node.expression;
  4411. continue;
  4412. case SequenceExpression$1:
  4413. // if there are parentheses, the annotation would apply to the entire expression
  4414. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4415. node = node.expressions[0];
  4416. continue;
  4417. }
  4418. invalidAnnotation = true;
  4419. break;
  4420. case ConditionalExpression$1:
  4421. // if there are parentheses, the annotation would apply to the entire expression
  4422. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4423. node = node.test;
  4424. continue;
  4425. }
  4426. invalidAnnotation = true;
  4427. break;
  4428. case LogicalExpression$1:
  4429. case BinaryExpression$1:
  4430. // if there are parentheses, the annotation would apply to the entire expression
  4431. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4432. node = node.left;
  4433. continue;
  4434. }
  4435. invalidAnnotation = true;
  4436. break;
  4437. case CallExpression$1:
  4438. case NewExpression$1:
  4439. break;
  4440. default:
  4441. invalidAnnotation = true;
  4442. }
  4443. break;
  4444. }
  4445. }
  4446. else {
  4447. invalidAnnotation = true;
  4448. }
  4449. if (invalidAnnotation) {
  4450. annotateNode(node, comment, false);
  4451. }
  4452. else {
  4453. for (const node of annotatedNodes) {
  4454. annotateNode(node, comment, true);
  4455. }
  4456. }
  4457. }
  4458. function doesNotMatchOutsideComment(code, forbiddenChars) {
  4459. let nextMatch;
  4460. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  4461. if (nextMatch[0] === '/') {
  4462. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  4463. if (charCodeAfterSlash === 42 /*"*"*/) {
  4464. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  4465. continue;
  4466. }
  4467. else if (charCodeAfterSlash === 47 /*"/"*/) {
  4468. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  4469. continue;
  4470. }
  4471. }
  4472. forbiddenChars.lastIndex = 0;
  4473. return false;
  4474. }
  4475. return true;
  4476. }
  4477. const pureCommentRegex = /[@#]__PURE__/;
  4478. function addAnnotations(comments, esTreeAst, code) {
  4479. const annotations = [];
  4480. const sourceMappingComments = [];
  4481. for (const comment of comments) {
  4482. if (pureCommentRegex.test(comment.value)) {
  4483. annotations.push(comment);
  4484. }
  4485. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  4486. sourceMappingComments.push(comment);
  4487. }
  4488. }
  4489. for (const comment of sourceMappingComments) {
  4490. annotateNode(esTreeAst, comment, false);
  4491. }
  4492. handlePureAnnotationsOfNode(esTreeAst, {
  4493. annotationIndex: 0,
  4494. annotations,
  4495. code
  4496. });
  4497. }
  4498. function annotateNode(node, comment, valid) {
  4499. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  4500. const property = node[key];
  4501. if (property) {
  4502. property.push(comment);
  4503. }
  4504. else {
  4505. node[key] = [comment];
  4506. }
  4507. }
  4508. const keys = {
  4509. Literal: [],
  4510. Program: ['body']
  4511. };
  4512. function getAndCreateKeys(esTreeNode) {
  4513. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4514. return keys[esTreeNode.type];
  4515. }
  4516. const INCLUDE_PARAMETERS = 'variables';
  4517. class NodeBase extends ExpressionEntity {
  4518. constructor(esTreeNode, parent, parentScope) {
  4519. super();
  4520. /**
  4521. * Nodes can apply custom deoptimizations once they become part of the
  4522. * executed code. To do this, they must initialize this as false, implement
  4523. * applyDeoptimizations and call this from include and hasEffects if they have
  4524. * custom handlers
  4525. */
  4526. this.deoptimized = false;
  4527. this.esTreeNode = esTreeNode;
  4528. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  4529. this.parent = parent;
  4530. this.context = parent.context;
  4531. this.createScope(parentScope);
  4532. this.parseNode(esTreeNode);
  4533. this.initialise();
  4534. this.context.magicString.addSourcemapLocation(this.start);
  4535. this.context.magicString.addSourcemapLocation(this.end);
  4536. }
  4537. addExportedVariables(_variables, _exportNamesByVariable) { }
  4538. /**
  4539. * Override this to bind assignments to variables and do any initialisations that
  4540. * require the scopes to be populated with variables.
  4541. */
  4542. bind() {
  4543. for (const key of this.keys) {
  4544. const value = this[key];
  4545. if (value === null)
  4546. continue;
  4547. if (Array.isArray(value)) {
  4548. for (const child of value) {
  4549. child === null || child === void 0 ? void 0 : child.bind();
  4550. }
  4551. }
  4552. else {
  4553. value.bind();
  4554. }
  4555. }
  4556. }
  4557. /**
  4558. * Override if this node should receive a different scope than the parent scope.
  4559. */
  4560. createScope(parentScope) {
  4561. this.scope = parentScope;
  4562. }
  4563. hasEffects(context) {
  4564. if (!this.deoptimized)
  4565. this.applyDeoptimizations();
  4566. for (const key of this.keys) {
  4567. const value = this[key];
  4568. if (value === null)
  4569. continue;
  4570. if (Array.isArray(value)) {
  4571. for (const child of value) {
  4572. if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
  4573. return true;
  4574. }
  4575. }
  4576. else if (value.hasEffects(context))
  4577. return true;
  4578. }
  4579. return false;
  4580. }
  4581. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4582. return (this.hasEffects(context) ||
  4583. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4584. }
  4585. include(context, includeChildrenRecursively, _options) {
  4586. if (!this.deoptimized)
  4587. this.applyDeoptimizations();
  4588. this.included = true;
  4589. for (const key of this.keys) {
  4590. const value = this[key];
  4591. if (value === null)
  4592. continue;
  4593. if (Array.isArray(value)) {
  4594. for (const child of value) {
  4595. child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
  4596. }
  4597. }
  4598. else {
  4599. value.include(context, includeChildrenRecursively);
  4600. }
  4601. }
  4602. }
  4603. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4604. this.include(context, includeChildrenRecursively);
  4605. }
  4606. /**
  4607. * Override to perform special initialisation steps after the scope is initialised
  4608. */
  4609. initialise() { }
  4610. insertSemicolon(code) {
  4611. if (code.original[this.end - 1] !== ';') {
  4612. code.appendLeft(this.end, ';');
  4613. }
  4614. }
  4615. parseNode(esTreeNode) {
  4616. for (const [key, value] of Object.entries(esTreeNode)) {
  4617. // That way, we can override this function to add custom initialisation and then call super.parseNode
  4618. if (this.hasOwnProperty(key))
  4619. continue;
  4620. if (key.charCodeAt(0) === 95 /* _ */) {
  4621. if (key === ANNOTATION_KEY) {
  4622. this.annotations = value;
  4623. }
  4624. else if (key === INVALID_COMMENT_KEY) {
  4625. for (const { start, end } of value)
  4626. this.context.magicString.remove(start, end);
  4627. }
  4628. }
  4629. else if (typeof value !== 'object' || value === null) {
  4630. this[key] = value;
  4631. }
  4632. else if (Array.isArray(value)) {
  4633. this[key] = [];
  4634. for (const child of value) {
  4635. this[key].push(child === null
  4636. ? null
  4637. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
  4638. }
  4639. }
  4640. else {
  4641. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
  4642. }
  4643. }
  4644. }
  4645. render(code, options) {
  4646. for (const key of this.keys) {
  4647. const value = this[key];
  4648. if (value === null)
  4649. continue;
  4650. if (Array.isArray(value)) {
  4651. for (const child of value) {
  4652. child === null || child === void 0 ? void 0 : child.render(code, options);
  4653. }
  4654. }
  4655. else {
  4656. value.render(code, options);
  4657. }
  4658. }
  4659. }
  4660. setAssignedValue(value) {
  4661. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  4662. }
  4663. shouldBeIncluded(context) {
  4664. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4665. }
  4666. /**
  4667. * Just deoptimize everything by default so that when e.g. we do not track
  4668. * something properly, it is deoptimized.
  4669. * @protected
  4670. */
  4671. applyDeoptimizations() {
  4672. this.deoptimized = true;
  4673. for (const key of this.keys) {
  4674. const value = this[key];
  4675. if (value === null)
  4676. continue;
  4677. if (Array.isArray(value)) {
  4678. for (const child of value) {
  4679. child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
  4680. }
  4681. }
  4682. else {
  4683. value.deoptimizePath(UNKNOWN_PATH);
  4684. }
  4685. }
  4686. this.context.requestTreeshakingPass();
  4687. }
  4688. }
  4689. class SpreadElement extends NodeBase {
  4690. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4691. if (path.length > 0) {
  4692. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4693. }
  4694. }
  4695. hasEffects(context) {
  4696. if (!this.deoptimized)
  4697. this.applyDeoptimizations();
  4698. const { propertyReadSideEffects } = this.context.options
  4699. .treeshake;
  4700. return (this.argument.hasEffects(context) ||
  4701. (propertyReadSideEffects &&
  4702. (propertyReadSideEffects === 'always' ||
  4703. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4704. }
  4705. applyDeoptimizations() {
  4706. this.deoptimized = true;
  4707. // Only properties of properties of the argument could become subject to reassignment
  4708. // This will also reassign the return values of iterators
  4709. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4710. this.context.requestTreeshakingPass();
  4711. }
  4712. }
  4713. class Method extends ExpressionEntity {
  4714. constructor(description) {
  4715. super();
  4716. this.description = description;
  4717. }
  4718. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  4719. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4720. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4721. }
  4722. }
  4723. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  4724. if (path.length > 0) {
  4725. return UNKNOWN_EXPRESSION;
  4726. }
  4727. return (this.description.returnsPrimitive ||
  4728. (this.description.returns === 'self'
  4729. ? thisArg || UNKNOWN_EXPRESSION
  4730. : this.description.returns()));
  4731. }
  4732. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4733. var _a, _b;
  4734. const { type } = interaction;
  4735. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4736. return true;
  4737. }
  4738. if (type === INTERACTION_CALLED) {
  4739. if (this.description.mutatesSelfAsArray === true &&
  4740. ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
  4741. return true;
  4742. }
  4743. if (this.description.callsArgs) {
  4744. for (const argIndex of this.description.callsArgs) {
  4745. if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4746. return true;
  4747. }
  4748. }
  4749. }
  4750. }
  4751. return false;
  4752. }
  4753. }
  4754. const METHOD_RETURNS_BOOLEAN = [
  4755. new Method({
  4756. callsArgs: null,
  4757. mutatesSelfAsArray: false,
  4758. returns: null,
  4759. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4760. })
  4761. ];
  4762. const METHOD_RETURNS_STRING = [
  4763. new Method({
  4764. callsArgs: null,
  4765. mutatesSelfAsArray: false,
  4766. returns: null,
  4767. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4768. })
  4769. ];
  4770. const METHOD_RETURNS_NUMBER = [
  4771. new Method({
  4772. callsArgs: null,
  4773. mutatesSelfAsArray: false,
  4774. returns: null,
  4775. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4776. })
  4777. ];
  4778. const METHOD_RETURNS_UNKNOWN = [
  4779. new Method({
  4780. callsArgs: null,
  4781. mutatesSelfAsArray: false,
  4782. returns: null,
  4783. returnsPrimitive: UNKNOWN_EXPRESSION
  4784. })
  4785. ];
  4786. const INTEGER_REG_EXP = /^\d+$/;
  4787. class ObjectEntity extends ExpressionEntity {
  4788. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4789. // and we assume there are no setters or getters
  4790. constructor(properties, prototypeExpression, immutable = false) {
  4791. super();
  4792. this.prototypeExpression = prototypeExpression;
  4793. this.immutable = immutable;
  4794. this.allProperties = [];
  4795. this.deoptimizedPaths = Object.create(null);
  4796. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4797. this.gettersByKey = Object.create(null);
  4798. this.hasLostTrack = false;
  4799. this.hasUnknownDeoptimizedInteger = false;
  4800. this.hasUnknownDeoptimizedProperty = false;
  4801. this.propertiesAndGettersByKey = Object.create(null);
  4802. this.propertiesAndSettersByKey = Object.create(null);
  4803. this.settersByKey = Object.create(null);
  4804. this.thisParametersToBeDeoptimized = new Set();
  4805. this.unknownIntegerProps = [];
  4806. this.unmatchableGetters = [];
  4807. this.unmatchablePropertiesAndGetters = [];
  4808. this.unmatchableSetters = [];
  4809. if (Array.isArray(properties)) {
  4810. this.buildPropertyMaps(properties);
  4811. }
  4812. else {
  4813. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4814. for (const propertiesForKey of Object.values(properties)) {
  4815. this.allProperties.push(...propertiesForKey);
  4816. }
  4817. }
  4818. }
  4819. deoptimizeAllProperties(noAccessors) {
  4820. var _a;
  4821. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4822. if (noAccessors) {
  4823. this.hasUnknownDeoptimizedProperty = true;
  4824. }
  4825. else {
  4826. this.hasLostTrack = true;
  4827. }
  4828. if (isDeoptimized) {
  4829. return;
  4830. }
  4831. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4832. for (const property of properties) {
  4833. property.deoptimizePath(UNKNOWN_PATH);
  4834. }
  4835. }
  4836. // While the prototype itself cannot be mutated, each property can
  4837. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4838. this.deoptimizeCachedEntities();
  4839. }
  4840. deoptimizeIntegerProperties() {
  4841. if (this.hasLostTrack ||
  4842. this.hasUnknownDeoptimizedProperty ||
  4843. this.hasUnknownDeoptimizedInteger) {
  4844. return;
  4845. }
  4846. this.hasUnknownDeoptimizedInteger = true;
  4847. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4848. if (INTEGER_REG_EXP.test(key)) {
  4849. for (const property of propertiesAndGetters) {
  4850. property.deoptimizePath(UNKNOWN_PATH);
  4851. }
  4852. }
  4853. }
  4854. this.deoptimizeCachedIntegerEntities();
  4855. }
  4856. // Assumption: If only a specific path is deoptimized, no accessors are created
  4857. deoptimizePath(path) {
  4858. var _a;
  4859. if (this.hasLostTrack || this.immutable) {
  4860. return;
  4861. }
  4862. const key = path[0];
  4863. if (path.length === 1) {
  4864. if (typeof key !== 'string') {
  4865. if (key === UnknownInteger) {
  4866. return this.deoptimizeIntegerProperties();
  4867. }
  4868. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4869. }
  4870. if (!this.deoptimizedPaths[key]) {
  4871. this.deoptimizedPaths[key] = true;
  4872. // we only deoptimizeCache exact matches as in all other cases,
  4873. // we do not return a literal value or return expression
  4874. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4875. if (expressionsToBeDeoptimized) {
  4876. for (const expression of expressionsToBeDeoptimized) {
  4877. expression.deoptimizeCache();
  4878. }
  4879. }
  4880. }
  4881. }
  4882. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4883. for (const property of typeof key === 'string'
  4884. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  4885. : this.allProperties) {
  4886. property.deoptimizePath(subPath);
  4887. }
  4888. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  4889. }
  4890. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4891. var _a;
  4892. const [key, ...subPath] = path;
  4893. if (this.hasLostTrack ||
  4894. // single paths that are deoptimized will not become getters or setters
  4895. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  4896. (this.hasUnknownDeoptimizedProperty ||
  4897. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4898. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  4899. return;
  4900. }
  4901. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  4902. ? [
  4903. this.propertiesAndGettersByKey,
  4904. this.propertiesAndGettersByKey,
  4905. this.unmatchablePropertiesAndGetters
  4906. ]
  4907. : interaction.type === INTERACTION_ACCESSED
  4908. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4909. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4910. if (typeof key === 'string') {
  4911. if (propertiesForExactMatchByKey[key]) {
  4912. const properties = relevantPropertiesByKey[key];
  4913. if (properties) {
  4914. for (const property of properties) {
  4915. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4916. }
  4917. }
  4918. if (!this.immutable) {
  4919. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4920. }
  4921. return;
  4922. }
  4923. for (const property of relevantUnmatchableProperties) {
  4924. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4925. }
  4926. if (INTEGER_REG_EXP.test(key)) {
  4927. for (const property of this.unknownIntegerProps) {
  4928. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4929. }
  4930. }
  4931. }
  4932. else {
  4933. for (const properties of Object.values(relevantPropertiesByKey).concat([
  4934. relevantUnmatchableProperties
  4935. ])) {
  4936. for (const property of properties) {
  4937. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4938. }
  4939. }
  4940. for (const property of this.unknownIntegerProps) {
  4941. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4942. }
  4943. }
  4944. if (!this.immutable) {
  4945. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4946. }
  4947. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  4948. }
  4949. getLiteralValueAtPath(path, recursionTracker, origin) {
  4950. if (path.length === 0) {
  4951. return UnknownTruthyValue;
  4952. }
  4953. const key = path[0];
  4954. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4955. if (expressionAtPath) {
  4956. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4957. }
  4958. if (this.prototypeExpression) {
  4959. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4960. }
  4961. if (path.length === 1) {
  4962. return undefined;
  4963. }
  4964. return UnknownValue;
  4965. }
  4966. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4967. if (path.length === 0) {
  4968. return UNKNOWN_EXPRESSION;
  4969. }
  4970. const [key, ...subPath] = path;
  4971. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4972. if (expressionAtPath) {
  4973. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4974. }
  4975. if (this.prototypeExpression) {
  4976. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4977. }
  4978. return UNKNOWN_EXPRESSION;
  4979. }
  4980. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4981. const [key, ...subPath] = path;
  4982. if (subPath.length || interaction.type === INTERACTION_CALLED) {
  4983. const expressionAtPath = this.getMemberExpression(key);
  4984. if (expressionAtPath) {
  4985. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  4986. }
  4987. if (this.prototypeExpression) {
  4988. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  4989. }
  4990. return true;
  4991. }
  4992. if (key === UnknownNonAccessorKey)
  4993. return false;
  4994. if (this.hasLostTrack)
  4995. return true;
  4996. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  4997. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4998. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4999. if (typeof key === 'string') {
  5000. if (propertiesAndAccessorsByKey[key]) {
  5001. const accessors = accessorsByKey[key];
  5002. if (accessors) {
  5003. for (const accessor of accessors) {
  5004. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5005. return true;
  5006. }
  5007. }
  5008. return false;
  5009. }
  5010. for (const accessor of unmatchableAccessors) {
  5011. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5012. return true;
  5013. }
  5014. }
  5015. }
  5016. else {
  5017. for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
  5018. for (const accessor of accessors) {
  5019. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5020. return true;
  5021. }
  5022. }
  5023. }
  5024. if (this.prototypeExpression) {
  5025. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5026. }
  5027. return false;
  5028. }
  5029. buildPropertyMaps(properties) {
  5030. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5031. const unmatchablePropertiesAndSetters = [];
  5032. for (let index = properties.length - 1; index >= 0; index--) {
  5033. const { key, kind, property } = properties[index];
  5034. allProperties.push(property);
  5035. if (typeof key !== 'string') {
  5036. if (key === UnknownInteger) {
  5037. unknownIntegerProps.push(property);
  5038. continue;
  5039. }
  5040. if (kind === 'set')
  5041. unmatchableSetters.push(property);
  5042. if (kind === 'get')
  5043. unmatchableGetters.push(property);
  5044. if (kind !== 'get')
  5045. unmatchablePropertiesAndSetters.push(property);
  5046. if (kind !== 'set')
  5047. unmatchablePropertiesAndGetters.push(property);
  5048. }
  5049. else {
  5050. if (kind === 'set') {
  5051. if (!propertiesAndSettersByKey[key]) {
  5052. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5053. settersByKey[key] = [property, ...unmatchableSetters];
  5054. }
  5055. }
  5056. else if (kind === 'get') {
  5057. if (!propertiesAndGettersByKey[key]) {
  5058. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5059. gettersByKey[key] = [property, ...unmatchableGetters];
  5060. }
  5061. }
  5062. else {
  5063. if (!propertiesAndSettersByKey[key]) {
  5064. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5065. }
  5066. if (!propertiesAndGettersByKey[key]) {
  5067. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5068. }
  5069. }
  5070. }
  5071. }
  5072. }
  5073. deoptimizeCachedEntities() {
  5074. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5075. for (const expression of expressionsToBeDeoptimized) {
  5076. expression.deoptimizeCache();
  5077. }
  5078. }
  5079. for (const expression of this.thisParametersToBeDeoptimized) {
  5080. expression.deoptimizePath(UNKNOWN_PATH);
  5081. }
  5082. }
  5083. deoptimizeCachedIntegerEntities() {
  5084. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5085. if (INTEGER_REG_EXP.test(key)) {
  5086. for (const expression of expressionsToBeDeoptimized) {
  5087. expression.deoptimizeCache();
  5088. }
  5089. }
  5090. }
  5091. for (const expression of this.thisParametersToBeDeoptimized) {
  5092. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5093. }
  5094. }
  5095. getMemberExpression(key) {
  5096. if (this.hasLostTrack ||
  5097. this.hasUnknownDeoptimizedProperty ||
  5098. typeof key !== 'string' ||
  5099. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5100. this.deoptimizedPaths[key]) {
  5101. return UNKNOWN_EXPRESSION;
  5102. }
  5103. const properties = this.propertiesAndGettersByKey[key];
  5104. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  5105. return properties[0];
  5106. }
  5107. if (properties ||
  5108. this.unmatchablePropertiesAndGetters.length > 0 ||
  5109. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  5110. return UNKNOWN_EXPRESSION;
  5111. }
  5112. return null;
  5113. }
  5114. getMemberExpressionAndTrackDeopt(key, origin) {
  5115. if (typeof key !== 'string') {
  5116. return UNKNOWN_EXPRESSION;
  5117. }
  5118. const expression = this.getMemberExpression(key);
  5119. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5120. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5121. this.expressionsToBeDeoptimizedByKey[key] || []);
  5122. expressionsToBeDeoptimized.push(origin);
  5123. }
  5124. return expression;
  5125. }
  5126. }
  5127. const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
  5128. // This makes sure unknown properties are not handled as "undefined" but as
  5129. // "unknown" but without access side effects. An exception is done for numeric
  5130. // properties as we do not expect new builtin properties to be numbers, this
  5131. // will improve tree-shaking for out-of-bounds array properties
  5132. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5133. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5134. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5135. thisArg.deoptimizePath(UNKNOWN_PATH);
  5136. }
  5137. }
  5138. getLiteralValueAtPath(path) {
  5139. // We ignore number properties as we do not expect new properties to be
  5140. // numbers and also want to keep handling out-of-bound array elements as
  5141. // "undefined"
  5142. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5143. }
  5144. hasEffectsOnInteractionAtPath(path, { type }) {
  5145. return path.length > 1 || type === INTERACTION_CALLED;
  5146. }
  5147. })();
  5148. const OBJECT_PROTOTYPE = new ObjectEntity({
  5149. __proto__: null,
  5150. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5151. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5152. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5153. toLocaleString: METHOD_RETURNS_STRING,
  5154. toString: METHOD_RETURNS_STRING,
  5155. valueOf: METHOD_RETURNS_UNKNOWN
  5156. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5157. const NEW_ARRAY_PROPERTIES = [
  5158. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5159. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5160. ];
  5161. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5162. new Method({
  5163. callsArgs: [0],
  5164. mutatesSelfAsArray: 'deopt-only',
  5165. returns: null,
  5166. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5167. })
  5168. ];
  5169. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5170. new Method({
  5171. callsArgs: [0],
  5172. mutatesSelfAsArray: 'deopt-only',
  5173. returns: null,
  5174. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5175. })
  5176. ];
  5177. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5178. new Method({
  5179. callsArgs: null,
  5180. mutatesSelfAsArray: true,
  5181. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5182. returnsPrimitive: null
  5183. })
  5184. ];
  5185. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5186. new Method({
  5187. callsArgs: null,
  5188. mutatesSelfAsArray: 'deopt-only',
  5189. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5190. returnsPrimitive: null
  5191. })
  5192. ];
  5193. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5194. new Method({
  5195. callsArgs: [0],
  5196. mutatesSelfAsArray: 'deopt-only',
  5197. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5198. returnsPrimitive: null
  5199. })
  5200. ];
  5201. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5202. new Method({
  5203. callsArgs: null,
  5204. mutatesSelfAsArray: true,
  5205. returns: null,
  5206. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5207. })
  5208. ];
  5209. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5210. new Method({
  5211. callsArgs: null,
  5212. mutatesSelfAsArray: true,
  5213. returns: null,
  5214. returnsPrimitive: UNKNOWN_EXPRESSION
  5215. })
  5216. ];
  5217. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5218. new Method({
  5219. callsArgs: null,
  5220. mutatesSelfAsArray: 'deopt-only',
  5221. returns: null,
  5222. returnsPrimitive: UNKNOWN_EXPRESSION
  5223. })
  5224. ];
  5225. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5226. new Method({
  5227. callsArgs: [0],
  5228. mutatesSelfAsArray: 'deopt-only',
  5229. returns: null,
  5230. returnsPrimitive: UNKNOWN_EXPRESSION
  5231. })
  5232. ];
  5233. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5234. new Method({
  5235. callsArgs: null,
  5236. mutatesSelfAsArray: true,
  5237. returns: 'self',
  5238. returnsPrimitive: null
  5239. })
  5240. ];
  5241. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5242. new Method({
  5243. callsArgs: [0],
  5244. mutatesSelfAsArray: true,
  5245. returns: 'self',
  5246. returnsPrimitive: null
  5247. })
  5248. ];
  5249. const ARRAY_PROTOTYPE = new ObjectEntity({
  5250. __proto__: null,
  5251. // We assume that accessors have effects as we do not track the accessed value afterwards
  5252. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5253. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5254. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5255. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5256. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5257. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5258. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5259. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5260. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5261. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5262. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5263. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5264. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5265. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5266. group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5267. groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5268. includes: METHOD_RETURNS_BOOLEAN,
  5269. indexOf: METHOD_RETURNS_NUMBER,
  5270. join: METHOD_RETURNS_STRING,
  5271. keys: METHOD_RETURNS_UNKNOWN,
  5272. lastIndexOf: METHOD_RETURNS_NUMBER,
  5273. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5274. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5275. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5276. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5277. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5278. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5279. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5280. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5281. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5282. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5283. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5284. toLocaleString: METHOD_RETURNS_STRING,
  5285. toString: METHOD_RETURNS_STRING,
  5286. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5287. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5288. }, OBJECT_PROTOTYPE, true);
  5289. class ArrayExpression extends NodeBase {
  5290. constructor() {
  5291. super(...arguments);
  5292. this.objectEntity = null;
  5293. }
  5294. deoptimizePath(path) {
  5295. this.getObjectEntity().deoptimizePath(path);
  5296. }
  5297. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5298. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5299. }
  5300. getLiteralValueAtPath(path, recursionTracker, origin) {
  5301. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5302. }
  5303. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5304. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5305. }
  5306. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5307. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5308. }
  5309. applyDeoptimizations() {
  5310. this.deoptimized = true;
  5311. let hasSpread = false;
  5312. for (let index = 0; index < this.elements.length; index++) {
  5313. const element = this.elements[index];
  5314. if (element) {
  5315. if (hasSpread || element instanceof SpreadElement) {
  5316. hasSpread = true;
  5317. element.deoptimizePath(UNKNOWN_PATH);
  5318. }
  5319. }
  5320. }
  5321. this.context.requestTreeshakingPass();
  5322. }
  5323. getObjectEntity() {
  5324. if (this.objectEntity !== null) {
  5325. return this.objectEntity;
  5326. }
  5327. const properties = [
  5328. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5329. ];
  5330. let hasSpread = false;
  5331. for (let index = 0; index < this.elements.length; index++) {
  5332. const element = this.elements[index];
  5333. if (hasSpread || element instanceof SpreadElement) {
  5334. if (element) {
  5335. hasSpread = true;
  5336. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5337. }
  5338. }
  5339. else if (!element) {
  5340. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5341. }
  5342. else {
  5343. properties.push({ key: String(index), kind: 'init', property: element });
  5344. }
  5345. }
  5346. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5347. }
  5348. }
  5349. class ArrayPattern extends NodeBase {
  5350. addExportedVariables(variables, exportNamesByVariable) {
  5351. for (const element of this.elements) {
  5352. element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
  5353. }
  5354. }
  5355. declare(kind) {
  5356. const variables = [];
  5357. for (const element of this.elements) {
  5358. if (element !== null) {
  5359. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5360. }
  5361. }
  5362. return variables;
  5363. }
  5364. // Patterns can only be deoptimized at the empty path at the moment
  5365. deoptimizePath() {
  5366. for (const element of this.elements) {
  5367. element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
  5368. }
  5369. }
  5370. // Patterns are only checked at the emtpy path at the moment
  5371. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5372. for (const element of this.elements) {
  5373. if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5374. return true;
  5375. }
  5376. return false;
  5377. }
  5378. markDeclarationReached() {
  5379. for (const element of this.elements) {
  5380. element === null || element === void 0 ? void 0 : element.markDeclarationReached();
  5381. }
  5382. }
  5383. }
  5384. class LocalVariable extends Variable {
  5385. constructor(name, declarator, init, context) {
  5386. super(name);
  5387. this.calledFromTryStatement = false;
  5388. this.additionalInitializers = null;
  5389. this.expressionsToBeDeoptimized = [];
  5390. this.declarations = declarator ? [declarator] : [];
  5391. this.init = init;
  5392. this.deoptimizationTracker = context.deoptimizationTracker;
  5393. this.module = context.module;
  5394. }
  5395. addDeclaration(identifier, init) {
  5396. this.declarations.push(identifier);
  5397. const additionalInitializers = this.markInitializersForDeoptimization();
  5398. if (init !== null) {
  5399. additionalInitializers.push(init);
  5400. }
  5401. }
  5402. consolidateInitializers() {
  5403. if (this.additionalInitializers !== null) {
  5404. for (const initializer of this.additionalInitializers) {
  5405. initializer.deoptimizePath(UNKNOWN_PATH);
  5406. }
  5407. this.additionalInitializers = null;
  5408. }
  5409. }
  5410. deoptimizePath(path) {
  5411. var _a, _b;
  5412. if (this.isReassigned ||
  5413. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5414. return;
  5415. }
  5416. if (path.length === 0) {
  5417. if (!this.isReassigned) {
  5418. this.isReassigned = true;
  5419. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5420. this.expressionsToBeDeoptimized = [];
  5421. for (const expression of expressionsToBeDeoptimized) {
  5422. expression.deoptimizeCache();
  5423. }
  5424. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  5425. }
  5426. }
  5427. else {
  5428. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  5429. }
  5430. }
  5431. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5432. if (this.isReassigned || !this.init) {
  5433. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5434. }
  5435. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5436. }
  5437. getLiteralValueAtPath(path, recursionTracker, origin) {
  5438. if (this.isReassigned || !this.init) {
  5439. return UnknownValue;
  5440. }
  5441. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5442. this.expressionsToBeDeoptimized.push(origin);
  5443. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5444. }, UnknownValue);
  5445. }
  5446. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5447. if (this.isReassigned || !this.init) {
  5448. return UNKNOWN_EXPRESSION;
  5449. }
  5450. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5451. this.expressionsToBeDeoptimized.push(origin);
  5452. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5453. }, UNKNOWN_EXPRESSION);
  5454. }
  5455. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5456. switch (interaction.type) {
  5457. case INTERACTION_ACCESSED:
  5458. if (this.isReassigned)
  5459. return true;
  5460. return (this.init &&
  5461. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5462. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5463. case INTERACTION_ASSIGNED:
  5464. if (this.included)
  5465. return true;
  5466. if (path.length === 0)
  5467. return false;
  5468. if (this.isReassigned)
  5469. return true;
  5470. return (this.init &&
  5471. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5472. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5473. case INTERACTION_CALLED:
  5474. if (this.isReassigned)
  5475. return true;
  5476. return (this.init &&
  5477. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5478. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5479. }
  5480. }
  5481. include() {
  5482. if (!this.included) {
  5483. this.included = true;
  5484. for (const declaration of this.declarations) {
  5485. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5486. if (!declaration.included)
  5487. declaration.include(createInclusionContext(), false);
  5488. let node = declaration.parent;
  5489. while (!node.included) {
  5490. // We do not want to properly include parents in case they are part of a dead branch
  5491. // in which case .include() might pull in more dead code
  5492. node.included = true;
  5493. if (node.type === Program$1)
  5494. break;
  5495. node = node.parent;
  5496. }
  5497. }
  5498. }
  5499. }
  5500. includeCallArguments(context, args) {
  5501. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  5502. for (const arg of args) {
  5503. arg.include(context, false);
  5504. }
  5505. }
  5506. else if (this.init) {
  5507. context.includedCallArguments.add(this.init);
  5508. this.init.includeCallArguments(context, args);
  5509. context.includedCallArguments.delete(this.init);
  5510. }
  5511. }
  5512. markCalledFromTryStatement() {
  5513. this.calledFromTryStatement = true;
  5514. }
  5515. markInitializersForDeoptimization() {
  5516. if (this.additionalInitializers === null) {
  5517. this.additionalInitializers = this.init === null ? [] : [this.init];
  5518. this.init = UNKNOWN_EXPRESSION;
  5519. this.isReassigned = true;
  5520. }
  5521. return this.additionalInitializers;
  5522. }
  5523. }
  5524. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5525. const base = 64;
  5526. function toBase64(num) {
  5527. let outStr = '';
  5528. do {
  5529. const curDigit = num % base;
  5530. num = Math.floor(num / base);
  5531. outStr = chars[curDigit] + outStr;
  5532. } while (num !== 0);
  5533. return outStr;
  5534. }
  5535. function getSafeName(baseName, usedNames) {
  5536. let safeName = baseName;
  5537. let count = 1;
  5538. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
  5539. safeName = `${baseName}$${toBase64(count++)}`;
  5540. }
  5541. usedNames.add(safeName);
  5542. return safeName;
  5543. }
  5544. class Scope$1 {
  5545. constructor() {
  5546. this.children = [];
  5547. this.variables = new Map();
  5548. }
  5549. addDeclaration(identifier, context, init, _isHoisted) {
  5550. const name = identifier.name;
  5551. let variable = this.variables.get(name);
  5552. if (variable) {
  5553. variable.addDeclaration(identifier, init);
  5554. }
  5555. else {
  5556. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  5557. this.variables.set(name, variable);
  5558. }
  5559. return variable;
  5560. }
  5561. contains(name) {
  5562. return this.variables.has(name);
  5563. }
  5564. findVariable(_name) {
  5565. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5566. }
  5567. }
  5568. class ChildScope extends Scope$1 {
  5569. constructor(parent) {
  5570. super();
  5571. this.accessedOutsideVariables = new Map();
  5572. this.parent = parent;
  5573. parent.children.push(this);
  5574. }
  5575. addAccessedDynamicImport(importExpression) {
  5576. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5577. if (this.parent instanceof ChildScope) {
  5578. this.parent.addAccessedDynamicImport(importExpression);
  5579. }
  5580. }
  5581. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5582. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5583. for (const name of globals) {
  5584. accessedGlobals.add(name);
  5585. }
  5586. accessedGlobalsByScope.set(this, accessedGlobals);
  5587. if (this.parent instanceof ChildScope) {
  5588. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5589. }
  5590. }
  5591. addNamespaceMemberAccess(name, variable) {
  5592. this.accessedOutsideVariables.set(name, variable);
  5593. this.parent.addNamespaceMemberAccess(name, variable);
  5594. }
  5595. addReturnExpression(expression) {
  5596. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5597. }
  5598. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5599. for (const variable of this.accessedOutsideVariables.values()) {
  5600. if (variable.included) {
  5601. usedNames.add(variable.getBaseVariableName());
  5602. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5603. usedNames.add('exports');
  5604. }
  5605. }
  5606. }
  5607. const accessedGlobals = accessedGlobalsByScope.get(this);
  5608. if (accessedGlobals) {
  5609. for (const name of accessedGlobals) {
  5610. usedNames.add(name);
  5611. }
  5612. }
  5613. }
  5614. contains(name) {
  5615. return this.variables.has(name) || this.parent.contains(name);
  5616. }
  5617. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5618. const usedNames = new Set();
  5619. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5620. if (this.accessedDynamicImports) {
  5621. for (const importExpression of this.accessedDynamicImports) {
  5622. if (importExpression.inlineNamespace) {
  5623. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5624. }
  5625. }
  5626. }
  5627. for (const [name, variable] of this.variables) {
  5628. if (variable.included || variable.alwaysRendered) {
  5629. variable.setRenderNames(null, getSafeName(name, usedNames));
  5630. }
  5631. }
  5632. for (const scope of this.children) {
  5633. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5634. }
  5635. }
  5636. findLexicalBoundary() {
  5637. return this.parent.findLexicalBoundary();
  5638. }
  5639. findVariable(name) {
  5640. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5641. if (knownVariable) {
  5642. return knownVariable;
  5643. }
  5644. const variable = this.parent.findVariable(name);
  5645. this.accessedOutsideVariables.set(name, variable);
  5646. return variable;
  5647. }
  5648. }
  5649. class ParameterScope extends ChildScope {
  5650. constructor(parent, context) {
  5651. super(parent);
  5652. this.parameters = [];
  5653. this.hasRest = false;
  5654. this.context = context;
  5655. this.hoistedBodyVarScope = new ChildScope(this);
  5656. }
  5657. /**
  5658. * Adds a parameter to this scope. Parameters must be added in the correct
  5659. * order, e.g. from left to right.
  5660. */
  5661. addParameterDeclaration(identifier) {
  5662. const name = identifier.name;
  5663. let variable = this.hoistedBodyVarScope.variables.get(name);
  5664. if (variable) {
  5665. variable.addDeclaration(identifier, null);
  5666. }
  5667. else {
  5668. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5669. }
  5670. this.variables.set(name, variable);
  5671. return variable;
  5672. }
  5673. addParameterVariables(parameters, hasRest) {
  5674. this.parameters = parameters;
  5675. for (const parameterList of parameters) {
  5676. for (const parameter of parameterList) {
  5677. parameter.alwaysRendered = true;
  5678. }
  5679. }
  5680. this.hasRest = hasRest;
  5681. }
  5682. includeCallArguments(context, args) {
  5683. let calledFromTryStatement = false;
  5684. let argIncluded = false;
  5685. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5686. for (const checkedArg of args) {
  5687. if (checkedArg instanceof SpreadElement) {
  5688. for (const arg of args) {
  5689. arg.include(context, false);
  5690. }
  5691. break;
  5692. }
  5693. }
  5694. for (let index = args.length - 1; index >= 0; index--) {
  5695. const paramVars = this.parameters[index] || restParam;
  5696. const arg = args[index];
  5697. if (paramVars) {
  5698. calledFromTryStatement = false;
  5699. if (paramVars.length === 0) {
  5700. // handle empty destructuring
  5701. argIncluded = true;
  5702. }
  5703. else {
  5704. for (const variable of paramVars) {
  5705. if (variable.included) {
  5706. argIncluded = true;
  5707. }
  5708. if (variable.calledFromTryStatement) {
  5709. calledFromTryStatement = true;
  5710. }
  5711. }
  5712. }
  5713. }
  5714. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5715. argIncluded = true;
  5716. }
  5717. if (argIncluded) {
  5718. arg.include(context, calledFromTryStatement);
  5719. }
  5720. }
  5721. }
  5722. }
  5723. class ReturnValueScope extends ParameterScope {
  5724. constructor() {
  5725. super(...arguments);
  5726. this.returnExpression = null;
  5727. this.returnExpressions = [];
  5728. }
  5729. addReturnExpression(expression) {
  5730. this.returnExpressions.push(expression);
  5731. }
  5732. getReturnExpression() {
  5733. if (this.returnExpression === null)
  5734. this.updateReturnExpression();
  5735. return this.returnExpression;
  5736. }
  5737. updateReturnExpression() {
  5738. if (this.returnExpressions.length === 1) {
  5739. this.returnExpression = this.returnExpressions[0];
  5740. }
  5741. else {
  5742. this.returnExpression = UNKNOWN_EXPRESSION;
  5743. for (const expression of this.returnExpressions) {
  5744. expression.deoptimizePath(UNKNOWN_PATH);
  5745. }
  5746. }
  5747. }
  5748. }
  5749. //@ts-check
  5750. /** @typedef { import('estree').Node} Node */
  5751. /** @typedef {Node | {
  5752. * type: 'PropertyDefinition';
  5753. * computed: boolean;
  5754. * value: Node
  5755. * }} NodeWithPropertyDefinition */
  5756. /**
  5757. *
  5758. * @param {NodeWithPropertyDefinition} node
  5759. * @param {NodeWithPropertyDefinition} parent
  5760. * @returns boolean
  5761. */
  5762. function is_reference (node, parent) {
  5763. if (node.type === 'MemberExpression') {
  5764. return !node.computed && is_reference(node.object, node);
  5765. }
  5766. if (node.type === 'Identifier') {
  5767. if (!parent) return true;
  5768. switch (parent.type) {
  5769. // disregard `bar` in `foo.bar`
  5770. case 'MemberExpression': return parent.computed || node === parent.object;
  5771. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5772. case 'MethodDefinition': return parent.computed;
  5773. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5774. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5775. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5776. case 'Property': return parent.computed || node === parent.value;
  5777. // disregard the `bar` in `export { foo as bar }` or
  5778. // the foo in `import { foo as bar }`
  5779. case 'ExportSpecifier':
  5780. case 'ImportSpecifier': return node === parent.local;
  5781. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5782. case 'LabeledStatement':
  5783. case 'BreakStatement':
  5784. case 'ContinueStatement': return false;
  5785. default: return true;
  5786. }
  5787. }
  5788. return false;
  5789. }
  5790. /* eslint sort-keys: "off" */
  5791. const ValueProperties = Symbol('Value Properties');
  5792. const PURE = {
  5793. hasEffectsWhenCalled() {
  5794. return false;
  5795. }
  5796. };
  5797. const IMPURE = {
  5798. hasEffectsWhenCalled() {
  5799. return true;
  5800. }
  5801. };
  5802. // We use shortened variables to reduce file size here
  5803. /* OBJECT */
  5804. const O = {
  5805. __proto__: null,
  5806. [ValueProperties]: IMPURE
  5807. };
  5808. /* PURE FUNCTION */
  5809. const PF = {
  5810. __proto__: null,
  5811. [ValueProperties]: PURE
  5812. };
  5813. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5814. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5815. __proto__: null,
  5816. [ValueProperties]: {
  5817. hasEffectsWhenCalled({ args }, context) {
  5818. return (!args.length ||
  5819. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5820. }
  5821. }
  5822. };
  5823. /* CONSTRUCTOR */
  5824. const C = {
  5825. __proto__: null,
  5826. [ValueProperties]: IMPURE,
  5827. prototype: O
  5828. };
  5829. /* PURE CONSTRUCTOR */
  5830. const PC = {
  5831. __proto__: null,
  5832. [ValueProperties]: PURE,
  5833. prototype: O
  5834. };
  5835. const ARRAY_TYPE = {
  5836. __proto__: null,
  5837. [ValueProperties]: PURE,
  5838. from: PF,
  5839. of: PF,
  5840. prototype: O
  5841. };
  5842. const INTL_MEMBER = {
  5843. __proto__: null,
  5844. [ValueProperties]: PURE,
  5845. supportedLocalesOf: PC
  5846. };
  5847. const knownGlobals = {
  5848. // Placeholders for global objects to avoid shape mutations
  5849. global: O,
  5850. globalThis: O,
  5851. self: O,
  5852. window: O,
  5853. // Common globals
  5854. __proto__: null,
  5855. [ValueProperties]: IMPURE,
  5856. Array: {
  5857. __proto__: null,
  5858. [ValueProperties]: IMPURE,
  5859. from: O,
  5860. isArray: PF,
  5861. of: PF,
  5862. prototype: O
  5863. },
  5864. ArrayBuffer: {
  5865. __proto__: null,
  5866. [ValueProperties]: PURE,
  5867. isView: PF,
  5868. prototype: O
  5869. },
  5870. Atomics: O,
  5871. BigInt: C,
  5872. BigInt64Array: C,
  5873. BigUint64Array: C,
  5874. Boolean: PC,
  5875. constructor: C,
  5876. DataView: PC,
  5877. Date: {
  5878. __proto__: null,
  5879. [ValueProperties]: PURE,
  5880. now: PF,
  5881. parse: PF,
  5882. prototype: O,
  5883. UTC: PF
  5884. },
  5885. decodeURI: PF,
  5886. decodeURIComponent: PF,
  5887. encodeURI: PF,
  5888. encodeURIComponent: PF,
  5889. Error: PC,
  5890. escape: PF,
  5891. eval: O,
  5892. EvalError: PC,
  5893. Float32Array: ARRAY_TYPE,
  5894. Float64Array: ARRAY_TYPE,
  5895. Function: C,
  5896. hasOwnProperty: O,
  5897. Infinity: O,
  5898. Int16Array: ARRAY_TYPE,
  5899. Int32Array: ARRAY_TYPE,
  5900. Int8Array: ARRAY_TYPE,
  5901. isFinite: PF,
  5902. isNaN: PF,
  5903. isPrototypeOf: O,
  5904. JSON: O,
  5905. Map: PC,
  5906. Math: {
  5907. __proto__: null,
  5908. [ValueProperties]: IMPURE,
  5909. abs: PF,
  5910. acos: PF,
  5911. acosh: PF,
  5912. asin: PF,
  5913. asinh: PF,
  5914. atan: PF,
  5915. atan2: PF,
  5916. atanh: PF,
  5917. cbrt: PF,
  5918. ceil: PF,
  5919. clz32: PF,
  5920. cos: PF,
  5921. cosh: PF,
  5922. exp: PF,
  5923. expm1: PF,
  5924. floor: PF,
  5925. fround: PF,
  5926. hypot: PF,
  5927. imul: PF,
  5928. log: PF,
  5929. log10: PF,
  5930. log1p: PF,
  5931. log2: PF,
  5932. max: PF,
  5933. min: PF,
  5934. pow: PF,
  5935. random: PF,
  5936. round: PF,
  5937. sign: PF,
  5938. sin: PF,
  5939. sinh: PF,
  5940. sqrt: PF,
  5941. tan: PF,
  5942. tanh: PF,
  5943. trunc: PF
  5944. },
  5945. NaN: O,
  5946. Number: {
  5947. __proto__: null,
  5948. [ValueProperties]: PURE,
  5949. isFinite: PF,
  5950. isInteger: PF,
  5951. isNaN: PF,
  5952. isSafeInteger: PF,
  5953. parseFloat: PF,
  5954. parseInt: PF,
  5955. prototype: O
  5956. },
  5957. Object: {
  5958. __proto__: null,
  5959. [ValueProperties]: PURE,
  5960. create: PF,
  5961. // Technically those can throw in certain situations, but we ignore this as
  5962. // code that relies on this will hopefully wrap this in a try-catch, which
  5963. // deoptimizes everything anyway
  5964. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5965. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5966. getOwnPropertyDescriptor: PF,
  5967. getOwnPropertyNames: PF,
  5968. getOwnPropertySymbols: PF,
  5969. getPrototypeOf: PF,
  5970. hasOwn: PF,
  5971. is: PF,
  5972. isExtensible: PF,
  5973. isFrozen: PF,
  5974. isSealed: PF,
  5975. keys: PF,
  5976. fromEntries: PF,
  5977. entries: PF,
  5978. prototype: O
  5979. },
  5980. parseFloat: PF,
  5981. parseInt: PF,
  5982. Promise: {
  5983. __proto__: null,
  5984. [ValueProperties]: IMPURE,
  5985. all: O,
  5986. prototype: O,
  5987. race: O,
  5988. reject: O,
  5989. resolve: O
  5990. },
  5991. propertyIsEnumerable: O,
  5992. Proxy: O,
  5993. RangeError: PC,
  5994. ReferenceError: PC,
  5995. Reflect: O,
  5996. RegExp: PC,
  5997. Set: PC,
  5998. SharedArrayBuffer: C,
  5999. String: {
  6000. __proto__: null,
  6001. [ValueProperties]: PURE,
  6002. fromCharCode: PF,
  6003. fromCodePoint: PF,
  6004. prototype: O,
  6005. raw: PF
  6006. },
  6007. Symbol: {
  6008. __proto__: null,
  6009. [ValueProperties]: PURE,
  6010. for: PF,
  6011. keyFor: PF,
  6012. prototype: O
  6013. },
  6014. SyntaxError: PC,
  6015. toLocaleString: O,
  6016. toString: O,
  6017. TypeError: PC,
  6018. Uint16Array: ARRAY_TYPE,
  6019. Uint32Array: ARRAY_TYPE,
  6020. Uint8Array: ARRAY_TYPE,
  6021. Uint8ClampedArray: ARRAY_TYPE,
  6022. // Technically, this is a global, but it needs special handling
  6023. // undefined: ?,
  6024. unescape: PF,
  6025. URIError: PC,
  6026. valueOf: O,
  6027. WeakMap: PC,
  6028. WeakSet: PC,
  6029. // Additional globals shared by Node and Browser that are not strictly part of the language
  6030. clearInterval: C,
  6031. clearTimeout: C,
  6032. console: O,
  6033. Intl: {
  6034. __proto__: null,
  6035. [ValueProperties]: IMPURE,
  6036. Collator: INTL_MEMBER,
  6037. DateTimeFormat: INTL_MEMBER,
  6038. ListFormat: INTL_MEMBER,
  6039. NumberFormat: INTL_MEMBER,
  6040. PluralRules: INTL_MEMBER,
  6041. RelativeTimeFormat: INTL_MEMBER
  6042. },
  6043. setInterval: C,
  6044. setTimeout: C,
  6045. TextDecoder: C,
  6046. TextEncoder: C,
  6047. URL: C,
  6048. URLSearchParams: C,
  6049. // Browser specific globals
  6050. AbortController: C,
  6051. AbortSignal: C,
  6052. addEventListener: O,
  6053. alert: O,
  6054. AnalyserNode: C,
  6055. Animation: C,
  6056. AnimationEvent: C,
  6057. applicationCache: O,
  6058. ApplicationCache: C,
  6059. ApplicationCacheErrorEvent: C,
  6060. atob: O,
  6061. Attr: C,
  6062. Audio: C,
  6063. AudioBuffer: C,
  6064. AudioBufferSourceNode: C,
  6065. AudioContext: C,
  6066. AudioDestinationNode: C,
  6067. AudioListener: C,
  6068. AudioNode: C,
  6069. AudioParam: C,
  6070. AudioProcessingEvent: C,
  6071. AudioScheduledSourceNode: C,
  6072. AudioWorkletNode: C,
  6073. BarProp: C,
  6074. BaseAudioContext: C,
  6075. BatteryManager: C,
  6076. BeforeUnloadEvent: C,
  6077. BiquadFilterNode: C,
  6078. Blob: C,
  6079. BlobEvent: C,
  6080. blur: O,
  6081. BroadcastChannel: C,
  6082. btoa: O,
  6083. ByteLengthQueuingStrategy: C,
  6084. Cache: C,
  6085. caches: O,
  6086. CacheStorage: C,
  6087. cancelAnimationFrame: O,
  6088. cancelIdleCallback: O,
  6089. CanvasCaptureMediaStreamTrack: C,
  6090. CanvasGradient: C,
  6091. CanvasPattern: C,
  6092. CanvasRenderingContext2D: C,
  6093. ChannelMergerNode: C,
  6094. ChannelSplitterNode: C,
  6095. CharacterData: C,
  6096. clientInformation: O,
  6097. ClipboardEvent: C,
  6098. close: O,
  6099. closed: O,
  6100. CloseEvent: C,
  6101. Comment: C,
  6102. CompositionEvent: C,
  6103. confirm: O,
  6104. ConstantSourceNode: C,
  6105. ConvolverNode: C,
  6106. CountQueuingStrategy: C,
  6107. createImageBitmap: O,
  6108. Credential: C,
  6109. CredentialsContainer: C,
  6110. crypto: O,
  6111. Crypto: C,
  6112. CryptoKey: C,
  6113. CSS: C,
  6114. CSSConditionRule: C,
  6115. CSSFontFaceRule: C,
  6116. CSSGroupingRule: C,
  6117. CSSImportRule: C,
  6118. CSSKeyframeRule: C,
  6119. CSSKeyframesRule: C,
  6120. CSSMediaRule: C,
  6121. CSSNamespaceRule: C,
  6122. CSSPageRule: C,
  6123. CSSRule: C,
  6124. CSSRuleList: C,
  6125. CSSStyleDeclaration: C,
  6126. CSSStyleRule: C,
  6127. CSSStyleSheet: C,
  6128. CSSSupportsRule: C,
  6129. CustomElementRegistry: C,
  6130. customElements: O,
  6131. CustomEvent: C,
  6132. DataTransfer: C,
  6133. DataTransferItem: C,
  6134. DataTransferItemList: C,
  6135. defaultstatus: O,
  6136. defaultStatus: O,
  6137. DelayNode: C,
  6138. DeviceMotionEvent: C,
  6139. DeviceOrientationEvent: C,
  6140. devicePixelRatio: O,
  6141. dispatchEvent: O,
  6142. document: O,
  6143. Document: C,
  6144. DocumentFragment: C,
  6145. DocumentType: C,
  6146. DOMError: C,
  6147. DOMException: C,
  6148. DOMImplementation: C,
  6149. DOMMatrix: C,
  6150. DOMMatrixReadOnly: C,
  6151. DOMParser: C,
  6152. DOMPoint: C,
  6153. DOMPointReadOnly: C,
  6154. DOMQuad: C,
  6155. DOMRect: C,
  6156. DOMRectReadOnly: C,
  6157. DOMStringList: C,
  6158. DOMStringMap: C,
  6159. DOMTokenList: C,
  6160. DragEvent: C,
  6161. DynamicsCompressorNode: C,
  6162. Element: C,
  6163. ErrorEvent: C,
  6164. Event: C,
  6165. EventSource: C,
  6166. EventTarget: C,
  6167. external: O,
  6168. fetch: O,
  6169. File: C,
  6170. FileList: C,
  6171. FileReader: C,
  6172. find: O,
  6173. focus: O,
  6174. FocusEvent: C,
  6175. FontFace: C,
  6176. FontFaceSetLoadEvent: C,
  6177. FormData: C,
  6178. frames: O,
  6179. GainNode: C,
  6180. Gamepad: C,
  6181. GamepadButton: C,
  6182. GamepadEvent: C,
  6183. getComputedStyle: O,
  6184. getSelection: O,
  6185. HashChangeEvent: C,
  6186. Headers: C,
  6187. history: O,
  6188. History: C,
  6189. HTMLAllCollection: C,
  6190. HTMLAnchorElement: C,
  6191. HTMLAreaElement: C,
  6192. HTMLAudioElement: C,
  6193. HTMLBaseElement: C,
  6194. HTMLBodyElement: C,
  6195. HTMLBRElement: C,
  6196. HTMLButtonElement: C,
  6197. HTMLCanvasElement: C,
  6198. HTMLCollection: C,
  6199. HTMLContentElement: C,
  6200. HTMLDataElement: C,
  6201. HTMLDataListElement: C,
  6202. HTMLDetailsElement: C,
  6203. HTMLDialogElement: C,
  6204. HTMLDirectoryElement: C,
  6205. HTMLDivElement: C,
  6206. HTMLDListElement: C,
  6207. HTMLDocument: C,
  6208. HTMLElement: C,
  6209. HTMLEmbedElement: C,
  6210. HTMLFieldSetElement: C,
  6211. HTMLFontElement: C,
  6212. HTMLFormControlsCollection: C,
  6213. HTMLFormElement: C,
  6214. HTMLFrameElement: C,
  6215. HTMLFrameSetElement: C,
  6216. HTMLHeadElement: C,
  6217. HTMLHeadingElement: C,
  6218. HTMLHRElement: C,
  6219. HTMLHtmlElement: C,
  6220. HTMLIFrameElement: C,
  6221. HTMLImageElement: C,
  6222. HTMLInputElement: C,
  6223. HTMLLabelElement: C,
  6224. HTMLLegendElement: C,
  6225. HTMLLIElement: C,
  6226. HTMLLinkElement: C,
  6227. HTMLMapElement: C,
  6228. HTMLMarqueeElement: C,
  6229. HTMLMediaElement: C,
  6230. HTMLMenuElement: C,
  6231. HTMLMetaElement: C,
  6232. HTMLMeterElement: C,
  6233. HTMLModElement: C,
  6234. HTMLObjectElement: C,
  6235. HTMLOListElement: C,
  6236. HTMLOptGroupElement: C,
  6237. HTMLOptionElement: C,
  6238. HTMLOptionsCollection: C,
  6239. HTMLOutputElement: C,
  6240. HTMLParagraphElement: C,
  6241. HTMLParamElement: C,
  6242. HTMLPictureElement: C,
  6243. HTMLPreElement: C,
  6244. HTMLProgressElement: C,
  6245. HTMLQuoteElement: C,
  6246. HTMLScriptElement: C,
  6247. HTMLSelectElement: C,
  6248. HTMLShadowElement: C,
  6249. HTMLSlotElement: C,
  6250. HTMLSourceElement: C,
  6251. HTMLSpanElement: C,
  6252. HTMLStyleElement: C,
  6253. HTMLTableCaptionElement: C,
  6254. HTMLTableCellElement: C,
  6255. HTMLTableColElement: C,
  6256. HTMLTableElement: C,
  6257. HTMLTableRowElement: C,
  6258. HTMLTableSectionElement: C,
  6259. HTMLTemplateElement: C,
  6260. HTMLTextAreaElement: C,
  6261. HTMLTimeElement: C,
  6262. HTMLTitleElement: C,
  6263. HTMLTrackElement: C,
  6264. HTMLUListElement: C,
  6265. HTMLUnknownElement: C,
  6266. HTMLVideoElement: C,
  6267. IDBCursor: C,
  6268. IDBCursorWithValue: C,
  6269. IDBDatabase: C,
  6270. IDBFactory: C,
  6271. IDBIndex: C,
  6272. IDBKeyRange: C,
  6273. IDBObjectStore: C,
  6274. IDBOpenDBRequest: C,
  6275. IDBRequest: C,
  6276. IDBTransaction: C,
  6277. IDBVersionChangeEvent: C,
  6278. IdleDeadline: C,
  6279. IIRFilterNode: C,
  6280. Image: C,
  6281. ImageBitmap: C,
  6282. ImageBitmapRenderingContext: C,
  6283. ImageCapture: C,
  6284. ImageData: C,
  6285. indexedDB: O,
  6286. innerHeight: O,
  6287. innerWidth: O,
  6288. InputEvent: C,
  6289. IntersectionObserver: C,
  6290. IntersectionObserverEntry: C,
  6291. isSecureContext: O,
  6292. KeyboardEvent: C,
  6293. KeyframeEffect: C,
  6294. length: O,
  6295. localStorage: O,
  6296. location: O,
  6297. Location: C,
  6298. locationbar: O,
  6299. matchMedia: O,
  6300. MediaDeviceInfo: C,
  6301. MediaDevices: C,
  6302. MediaElementAudioSourceNode: C,
  6303. MediaEncryptedEvent: C,
  6304. MediaError: C,
  6305. MediaKeyMessageEvent: C,
  6306. MediaKeySession: C,
  6307. MediaKeyStatusMap: C,
  6308. MediaKeySystemAccess: C,
  6309. MediaList: C,
  6310. MediaQueryList: C,
  6311. MediaQueryListEvent: C,
  6312. MediaRecorder: C,
  6313. MediaSettingsRange: C,
  6314. MediaSource: C,
  6315. MediaStream: C,
  6316. MediaStreamAudioDestinationNode: C,
  6317. MediaStreamAudioSourceNode: C,
  6318. MediaStreamEvent: C,
  6319. MediaStreamTrack: C,
  6320. MediaStreamTrackEvent: C,
  6321. menubar: O,
  6322. MessageChannel: C,
  6323. MessageEvent: C,
  6324. MessagePort: C,
  6325. MIDIAccess: C,
  6326. MIDIConnectionEvent: C,
  6327. MIDIInput: C,
  6328. MIDIInputMap: C,
  6329. MIDIMessageEvent: C,
  6330. MIDIOutput: C,
  6331. MIDIOutputMap: C,
  6332. MIDIPort: C,
  6333. MimeType: C,
  6334. MimeTypeArray: C,
  6335. MouseEvent: C,
  6336. moveBy: O,
  6337. moveTo: O,
  6338. MutationEvent: C,
  6339. MutationObserver: C,
  6340. MutationRecord: C,
  6341. name: O,
  6342. NamedNodeMap: C,
  6343. NavigationPreloadManager: C,
  6344. navigator: O,
  6345. Navigator: C,
  6346. NetworkInformation: C,
  6347. Node: C,
  6348. NodeFilter: O,
  6349. NodeIterator: C,
  6350. NodeList: C,
  6351. Notification: C,
  6352. OfflineAudioCompletionEvent: C,
  6353. OfflineAudioContext: C,
  6354. offscreenBuffering: O,
  6355. OffscreenCanvas: C,
  6356. open: O,
  6357. openDatabase: O,
  6358. Option: C,
  6359. origin: O,
  6360. OscillatorNode: C,
  6361. outerHeight: O,
  6362. outerWidth: O,
  6363. PageTransitionEvent: C,
  6364. pageXOffset: O,
  6365. pageYOffset: O,
  6366. PannerNode: C,
  6367. parent: O,
  6368. Path2D: C,
  6369. PaymentAddress: C,
  6370. PaymentRequest: C,
  6371. PaymentRequestUpdateEvent: C,
  6372. PaymentResponse: C,
  6373. performance: O,
  6374. Performance: C,
  6375. PerformanceEntry: C,
  6376. PerformanceLongTaskTiming: C,
  6377. PerformanceMark: C,
  6378. PerformanceMeasure: C,
  6379. PerformanceNavigation: C,
  6380. PerformanceNavigationTiming: C,
  6381. PerformanceObserver: C,
  6382. PerformanceObserverEntryList: C,
  6383. PerformancePaintTiming: C,
  6384. PerformanceResourceTiming: C,
  6385. PerformanceTiming: C,
  6386. PeriodicWave: C,
  6387. Permissions: C,
  6388. PermissionStatus: C,
  6389. personalbar: O,
  6390. PhotoCapabilities: C,
  6391. Plugin: C,
  6392. PluginArray: C,
  6393. PointerEvent: C,
  6394. PopStateEvent: C,
  6395. postMessage: O,
  6396. Presentation: C,
  6397. PresentationAvailability: C,
  6398. PresentationConnection: C,
  6399. PresentationConnectionAvailableEvent: C,
  6400. PresentationConnectionCloseEvent: C,
  6401. PresentationConnectionList: C,
  6402. PresentationReceiver: C,
  6403. PresentationRequest: C,
  6404. print: O,
  6405. ProcessingInstruction: C,
  6406. ProgressEvent: C,
  6407. PromiseRejectionEvent: C,
  6408. prompt: O,
  6409. PushManager: C,
  6410. PushSubscription: C,
  6411. PushSubscriptionOptions: C,
  6412. queueMicrotask: O,
  6413. RadioNodeList: C,
  6414. Range: C,
  6415. ReadableStream: C,
  6416. RemotePlayback: C,
  6417. removeEventListener: O,
  6418. Request: C,
  6419. requestAnimationFrame: O,
  6420. requestIdleCallback: O,
  6421. resizeBy: O,
  6422. ResizeObserver: C,
  6423. ResizeObserverEntry: C,
  6424. resizeTo: O,
  6425. Response: C,
  6426. RTCCertificate: C,
  6427. RTCDataChannel: C,
  6428. RTCDataChannelEvent: C,
  6429. RTCDtlsTransport: C,
  6430. RTCIceCandidate: C,
  6431. RTCIceTransport: C,
  6432. RTCPeerConnection: C,
  6433. RTCPeerConnectionIceEvent: C,
  6434. RTCRtpReceiver: C,
  6435. RTCRtpSender: C,
  6436. RTCSctpTransport: C,
  6437. RTCSessionDescription: C,
  6438. RTCStatsReport: C,
  6439. RTCTrackEvent: C,
  6440. screen: O,
  6441. Screen: C,
  6442. screenLeft: O,
  6443. ScreenOrientation: C,
  6444. screenTop: O,
  6445. screenX: O,
  6446. screenY: O,
  6447. ScriptProcessorNode: C,
  6448. scroll: O,
  6449. scrollbars: O,
  6450. scrollBy: O,
  6451. scrollTo: O,
  6452. scrollX: O,
  6453. scrollY: O,
  6454. SecurityPolicyViolationEvent: C,
  6455. Selection: C,
  6456. ServiceWorker: C,
  6457. ServiceWorkerContainer: C,
  6458. ServiceWorkerRegistration: C,
  6459. sessionStorage: O,
  6460. ShadowRoot: C,
  6461. SharedWorker: C,
  6462. SourceBuffer: C,
  6463. SourceBufferList: C,
  6464. speechSynthesis: O,
  6465. SpeechSynthesisEvent: C,
  6466. SpeechSynthesisUtterance: C,
  6467. StaticRange: C,
  6468. status: O,
  6469. statusbar: O,
  6470. StereoPannerNode: C,
  6471. stop: O,
  6472. Storage: C,
  6473. StorageEvent: C,
  6474. StorageManager: C,
  6475. styleMedia: O,
  6476. StyleSheet: C,
  6477. StyleSheetList: C,
  6478. SubtleCrypto: C,
  6479. SVGAElement: C,
  6480. SVGAngle: C,
  6481. SVGAnimatedAngle: C,
  6482. SVGAnimatedBoolean: C,
  6483. SVGAnimatedEnumeration: C,
  6484. SVGAnimatedInteger: C,
  6485. SVGAnimatedLength: C,
  6486. SVGAnimatedLengthList: C,
  6487. SVGAnimatedNumber: C,
  6488. SVGAnimatedNumberList: C,
  6489. SVGAnimatedPreserveAspectRatio: C,
  6490. SVGAnimatedRect: C,
  6491. SVGAnimatedString: C,
  6492. SVGAnimatedTransformList: C,
  6493. SVGAnimateElement: C,
  6494. SVGAnimateMotionElement: C,
  6495. SVGAnimateTransformElement: C,
  6496. SVGAnimationElement: C,
  6497. SVGCircleElement: C,
  6498. SVGClipPathElement: C,
  6499. SVGComponentTransferFunctionElement: C,
  6500. SVGDefsElement: C,
  6501. SVGDescElement: C,
  6502. SVGDiscardElement: C,
  6503. SVGElement: C,
  6504. SVGEllipseElement: C,
  6505. SVGFEBlendElement: C,
  6506. SVGFEColorMatrixElement: C,
  6507. SVGFEComponentTransferElement: C,
  6508. SVGFECompositeElement: C,
  6509. SVGFEConvolveMatrixElement: C,
  6510. SVGFEDiffuseLightingElement: C,
  6511. SVGFEDisplacementMapElement: C,
  6512. SVGFEDistantLightElement: C,
  6513. SVGFEDropShadowElement: C,
  6514. SVGFEFloodElement: C,
  6515. SVGFEFuncAElement: C,
  6516. SVGFEFuncBElement: C,
  6517. SVGFEFuncGElement: C,
  6518. SVGFEFuncRElement: C,
  6519. SVGFEGaussianBlurElement: C,
  6520. SVGFEImageElement: C,
  6521. SVGFEMergeElement: C,
  6522. SVGFEMergeNodeElement: C,
  6523. SVGFEMorphologyElement: C,
  6524. SVGFEOffsetElement: C,
  6525. SVGFEPointLightElement: C,
  6526. SVGFESpecularLightingElement: C,
  6527. SVGFESpotLightElement: C,
  6528. SVGFETileElement: C,
  6529. SVGFETurbulenceElement: C,
  6530. SVGFilterElement: C,
  6531. SVGForeignObjectElement: C,
  6532. SVGGElement: C,
  6533. SVGGeometryElement: C,
  6534. SVGGradientElement: C,
  6535. SVGGraphicsElement: C,
  6536. SVGImageElement: C,
  6537. SVGLength: C,
  6538. SVGLengthList: C,
  6539. SVGLinearGradientElement: C,
  6540. SVGLineElement: C,
  6541. SVGMarkerElement: C,
  6542. SVGMaskElement: C,
  6543. SVGMatrix: C,
  6544. SVGMetadataElement: C,
  6545. SVGMPathElement: C,
  6546. SVGNumber: C,
  6547. SVGNumberList: C,
  6548. SVGPathElement: C,
  6549. SVGPatternElement: C,
  6550. SVGPoint: C,
  6551. SVGPointList: C,
  6552. SVGPolygonElement: C,
  6553. SVGPolylineElement: C,
  6554. SVGPreserveAspectRatio: C,
  6555. SVGRadialGradientElement: C,
  6556. SVGRect: C,
  6557. SVGRectElement: C,
  6558. SVGScriptElement: C,
  6559. SVGSetElement: C,
  6560. SVGStopElement: C,
  6561. SVGStringList: C,
  6562. SVGStyleElement: C,
  6563. SVGSVGElement: C,
  6564. SVGSwitchElement: C,
  6565. SVGSymbolElement: C,
  6566. SVGTextContentElement: C,
  6567. SVGTextElement: C,
  6568. SVGTextPathElement: C,
  6569. SVGTextPositioningElement: C,
  6570. SVGTitleElement: C,
  6571. SVGTransform: C,
  6572. SVGTransformList: C,
  6573. SVGTSpanElement: C,
  6574. SVGUnitTypes: C,
  6575. SVGUseElement: C,
  6576. SVGViewElement: C,
  6577. TaskAttributionTiming: C,
  6578. Text: C,
  6579. TextEvent: C,
  6580. TextMetrics: C,
  6581. TextTrack: C,
  6582. TextTrackCue: C,
  6583. TextTrackCueList: C,
  6584. TextTrackList: C,
  6585. TimeRanges: C,
  6586. toolbar: O,
  6587. top: O,
  6588. Touch: C,
  6589. TouchEvent: C,
  6590. TouchList: C,
  6591. TrackEvent: C,
  6592. TransitionEvent: C,
  6593. TreeWalker: C,
  6594. UIEvent: C,
  6595. ValidityState: C,
  6596. visualViewport: O,
  6597. VisualViewport: C,
  6598. VTTCue: C,
  6599. WaveShaperNode: C,
  6600. WebAssembly: O,
  6601. WebGL2RenderingContext: C,
  6602. WebGLActiveInfo: C,
  6603. WebGLBuffer: C,
  6604. WebGLContextEvent: C,
  6605. WebGLFramebuffer: C,
  6606. WebGLProgram: C,
  6607. WebGLQuery: C,
  6608. WebGLRenderbuffer: C,
  6609. WebGLRenderingContext: C,
  6610. WebGLSampler: C,
  6611. WebGLShader: C,
  6612. WebGLShaderPrecisionFormat: C,
  6613. WebGLSync: C,
  6614. WebGLTexture: C,
  6615. WebGLTransformFeedback: C,
  6616. WebGLUniformLocation: C,
  6617. WebGLVertexArrayObject: C,
  6618. WebSocket: C,
  6619. WheelEvent: C,
  6620. Window: C,
  6621. Worker: C,
  6622. WritableStream: C,
  6623. XMLDocument: C,
  6624. XMLHttpRequest: C,
  6625. XMLHttpRequestEventTarget: C,
  6626. XMLHttpRequestUpload: C,
  6627. XMLSerializer: C,
  6628. XPathEvaluator: C,
  6629. XPathExpression: C,
  6630. XPathResult: C,
  6631. XSLTProcessor: C
  6632. };
  6633. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6634. knownGlobals[global] = knownGlobals;
  6635. }
  6636. function getGlobalAtPath(path) {
  6637. let currentGlobal = knownGlobals;
  6638. for (const pathSegment of path) {
  6639. if (typeof pathSegment !== 'string') {
  6640. return null;
  6641. }
  6642. currentGlobal = currentGlobal[pathSegment];
  6643. if (!currentGlobal) {
  6644. return null;
  6645. }
  6646. }
  6647. return currentGlobal[ValueProperties];
  6648. }
  6649. class GlobalVariable extends Variable {
  6650. constructor() {
  6651. super(...arguments);
  6652. // Ensure we use live-bindings for globals as we do not know if they have
  6653. // been reassigned
  6654. this.isReassigned = true;
  6655. }
  6656. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6657. return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
  6658. }
  6659. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6660. switch (interaction.type) {
  6661. case INTERACTION_ACCESSED:
  6662. if (path.length === 0) {
  6663. // Technically, "undefined" is a global variable of sorts
  6664. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6665. }
  6666. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6667. case INTERACTION_ASSIGNED:
  6668. return true;
  6669. case INTERACTION_CALLED: {
  6670. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6671. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6672. }
  6673. }
  6674. }
  6675. }
  6676. const tdzVariableKinds = {
  6677. __proto__: null,
  6678. class: true,
  6679. const: true,
  6680. let: true,
  6681. var: true
  6682. };
  6683. class Identifier extends NodeBase {
  6684. constructor() {
  6685. super(...arguments);
  6686. this.variable = null;
  6687. this.isTDZAccess = null;
  6688. }
  6689. addExportedVariables(variables, exportNamesByVariable) {
  6690. if (exportNamesByVariable.has(this.variable)) {
  6691. variables.push(this.variable);
  6692. }
  6693. }
  6694. bind() {
  6695. if (!this.variable && is_reference(this, this.parent)) {
  6696. this.variable = this.scope.findVariable(this.name);
  6697. this.variable.addReference(this);
  6698. }
  6699. }
  6700. declare(kind, init) {
  6701. let variable;
  6702. const { treeshake } = this.context.options;
  6703. switch (kind) {
  6704. case 'var':
  6705. variable = this.scope.addDeclaration(this, this.context, init, true);
  6706. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6707. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6708. variable.markInitializersForDeoptimization();
  6709. }
  6710. break;
  6711. case 'function':
  6712. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6713. variable = this.scope.addDeclaration(this, this.context, init, false);
  6714. break;
  6715. case 'let':
  6716. case 'const':
  6717. case 'class':
  6718. variable = this.scope.addDeclaration(this, this.context, init, false);
  6719. break;
  6720. case 'parameter':
  6721. variable = this.scope.addParameterDeclaration(this);
  6722. break;
  6723. /* istanbul ignore next */
  6724. default:
  6725. /* istanbul ignore next */
  6726. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6727. }
  6728. variable.kind = kind;
  6729. return [(this.variable = variable)];
  6730. }
  6731. deoptimizePath(path) {
  6732. var _a;
  6733. if (path.length === 0 && !this.scope.contains(this.name)) {
  6734. this.disallowImportReassignment();
  6735. }
  6736. // We keep conditional chaining because an unknown Node could have an
  6737. // Identifier as property that might be deoptimized by default
  6738. (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  6739. }
  6740. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6741. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6742. }
  6743. getLiteralValueAtPath(path, recursionTracker, origin) {
  6744. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6745. }
  6746. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6747. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6748. }
  6749. hasEffects(context) {
  6750. if (!this.deoptimized)
  6751. this.applyDeoptimizations();
  6752. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6753. return true;
  6754. }
  6755. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  6756. this.variable instanceof GlobalVariable &&
  6757. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6758. }
  6759. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6760. switch (interaction.type) {
  6761. case INTERACTION_ACCESSED:
  6762. return (this.variable !== null &&
  6763. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6764. case INTERACTION_ASSIGNED:
  6765. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6766. case INTERACTION_CALLED:
  6767. return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
  6768. }
  6769. }
  6770. include() {
  6771. if (!this.deoptimized)
  6772. this.applyDeoptimizations();
  6773. if (!this.included) {
  6774. this.included = true;
  6775. if (this.variable !== null) {
  6776. this.context.includeVariableInModule(this.variable);
  6777. }
  6778. }
  6779. }
  6780. includeCallArguments(context, args) {
  6781. this.variable.includeCallArguments(context, args);
  6782. }
  6783. isPossibleTDZ() {
  6784. // return cached value to avoid issues with the next tree-shaking pass
  6785. if (this.isTDZAccess !== null)
  6786. return this.isTDZAccess;
  6787. if (!(this.variable instanceof LocalVariable) ||
  6788. !this.variable.kind ||
  6789. !(this.variable.kind in tdzVariableKinds)) {
  6790. return (this.isTDZAccess = false);
  6791. }
  6792. let decl_id;
  6793. if (this.variable.declarations &&
  6794. this.variable.declarations.length === 1 &&
  6795. (decl_id = this.variable.declarations[0]) &&
  6796. this.start < decl_id.start &&
  6797. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6798. // a variable accessed before its declaration
  6799. // in the same function or at top level of module
  6800. return (this.isTDZAccess = true);
  6801. }
  6802. if (!this.variable.initReached) {
  6803. // Either a const/let TDZ violation or
  6804. // var use before declaration was encountered.
  6805. return (this.isTDZAccess = true);
  6806. }
  6807. return (this.isTDZAccess = false);
  6808. }
  6809. markDeclarationReached() {
  6810. this.variable.initReached = true;
  6811. }
  6812. render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6813. if (this.variable) {
  6814. const name = this.variable.getName(getPropertyAccess);
  6815. if (name !== this.name) {
  6816. code.overwrite(this.start, this.end, name, {
  6817. contentOnly: true,
  6818. storeName: true
  6819. });
  6820. if (isShorthandProperty) {
  6821. code.prependRight(this.start, `${this.name}: `);
  6822. }
  6823. }
  6824. // In strict mode, any variable named "eval" must be the actual "eval" function
  6825. if (name === 'eval' &&
  6826. renderedParentType === CallExpression$1 &&
  6827. isCalleeOfRenderedParent) {
  6828. code.appendRight(this.start, '0, ');
  6829. }
  6830. }
  6831. }
  6832. applyDeoptimizations() {
  6833. this.deoptimized = true;
  6834. if (this.variable instanceof LocalVariable) {
  6835. this.variable.consolidateInitializers();
  6836. this.context.requestTreeshakingPass();
  6837. }
  6838. }
  6839. disallowImportReassignment() {
  6840. return this.context.error({
  6841. code: 'ILLEGAL_REASSIGNMENT',
  6842. message: `Illegal reassignment to import '${this.name}'`
  6843. }, this.start);
  6844. }
  6845. getVariableRespectingTDZ() {
  6846. if (this.isPossibleTDZ()) {
  6847. return UNKNOWN_EXPRESSION;
  6848. }
  6849. return this.variable;
  6850. }
  6851. }
  6852. function closestParentFunctionOrProgram(node) {
  6853. while (node && !/^Program|Function/.test(node.type)) {
  6854. node = node.parent;
  6855. }
  6856. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6857. return node;
  6858. }
  6859. function treeshakeNode(node, code, start, end) {
  6860. code.remove(start, end);
  6861. if (node.annotations) {
  6862. for (const annotation of node.annotations) {
  6863. if (annotation.start < start) {
  6864. code.remove(annotation.start, annotation.end);
  6865. }
  6866. else {
  6867. return;
  6868. }
  6869. }
  6870. }
  6871. }
  6872. function removeAnnotations(node, code) {
  6873. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  6874. node = node.parent;
  6875. }
  6876. if (node.annotations) {
  6877. for (const annotation of node.annotations) {
  6878. code.remove(annotation.start, annotation.end);
  6879. }
  6880. }
  6881. }
  6882. const NO_SEMICOLON = { isNoStatement: true };
  6883. // This assumes there are only white-space and comments between start and the string we are looking for
  6884. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  6885. let searchPos, charCodeAfterSlash;
  6886. searchPos = code.indexOf(searchString, start);
  6887. while (true) {
  6888. start = code.indexOf('/', start);
  6889. if (start === -1 || start >= searchPos)
  6890. return searchPos;
  6891. charCodeAfterSlash = code.charCodeAt(++start);
  6892. ++start;
  6893. // With our assumption, '/' always starts a comment. Determine comment type:
  6894. start =
  6895. charCodeAfterSlash === 47 /*"/"*/
  6896. ? code.indexOf('\n', start) + 1
  6897. : code.indexOf('*/', start) + 2;
  6898. if (start > searchPos) {
  6899. searchPos = code.indexOf(searchString, start);
  6900. }
  6901. }
  6902. }
  6903. const NON_WHITESPACE = /\S/g;
  6904. function findNonWhiteSpace(code, index) {
  6905. NON_WHITESPACE.lastIndex = index;
  6906. const result = NON_WHITESPACE.exec(code);
  6907. return result.index;
  6908. }
  6909. // This assumes "code" only contains white-space and comments
  6910. // Returns position of line-comment if applicable
  6911. function findFirstLineBreakOutsideComment(code) {
  6912. let lineBreakPos, charCodeAfterSlash, start = 0;
  6913. lineBreakPos = code.indexOf('\n', start);
  6914. while (true) {
  6915. start = code.indexOf('/', start);
  6916. if (start === -1 || start > lineBreakPos)
  6917. return [lineBreakPos, lineBreakPos + 1];
  6918. // With our assumption, '/' always starts a comment. Determine comment type:
  6919. charCodeAfterSlash = code.charCodeAt(start + 1);
  6920. if (charCodeAfterSlash === 47 /*"/"*/)
  6921. return [start, lineBreakPos + 1];
  6922. start = code.indexOf('*/', start + 3) + 2;
  6923. if (start > lineBreakPos) {
  6924. lineBreakPos = code.indexOf('\n', start);
  6925. }
  6926. }
  6927. }
  6928. function renderStatementList(statements, code, start, end, options) {
  6929. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  6930. let nextNode = statements[0];
  6931. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  6932. if (nextNodeNeedsBoundaries) {
  6933. nextNodeStart =
  6934. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  6935. }
  6936. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  6937. currentNode = nextNode;
  6938. currentNodeStart = nextNodeStart;
  6939. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  6940. nextNode = statements[nextIndex];
  6941. nextNodeNeedsBoundaries =
  6942. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  6943. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  6944. nextNodeStart =
  6945. currentNode.end +
  6946. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  6947. if (currentNode.included) {
  6948. currentNodeNeedsBoundaries
  6949. ? currentNode.render(code, options, {
  6950. end: nextNodeStart,
  6951. start: currentNodeStart
  6952. })
  6953. : currentNode.render(code, options);
  6954. }
  6955. else {
  6956. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  6957. }
  6958. }
  6959. else {
  6960. currentNode.render(code, options);
  6961. }
  6962. }
  6963. }
  6964. // This assumes that the first character is not part of the first node
  6965. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  6966. const splitUpNodes = [];
  6967. let node, nextNode, nextNodeStart, contentEnd, char;
  6968. let separator = start - 1;
  6969. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  6970. nextNode = nodes[nextIndex];
  6971. if (node !== undefined) {
  6972. separator =
  6973. node.end +
  6974. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  6975. }
  6976. nextNodeStart = contentEnd =
  6977. separator +
  6978. 1 +
  6979. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  6980. while (((char = code.original.charCodeAt(nextNodeStart)),
  6981. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  6982. nextNodeStart++;
  6983. if (node !== undefined) {
  6984. splitUpNodes.push({
  6985. contentEnd,
  6986. end: nextNodeStart,
  6987. node,
  6988. separator,
  6989. start
  6990. });
  6991. }
  6992. node = nextNode;
  6993. start = nextNodeStart;
  6994. }
  6995. splitUpNodes.push({
  6996. contentEnd: end,
  6997. end,
  6998. node: node,
  6999. separator: null,
  7000. start
  7001. });
  7002. return splitUpNodes;
  7003. }
  7004. // This assumes there are only white-space and comments between start and end
  7005. function removeLineBreaks(code, start, end) {
  7006. while (true) {
  7007. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7008. if (removeStart === -1) {
  7009. break;
  7010. }
  7011. code.remove(start + removeStart, (start += removeEnd));
  7012. }
  7013. }
  7014. class BlockScope extends ChildScope {
  7015. addDeclaration(identifier, context, init, isHoisted) {
  7016. if (isHoisted) {
  7017. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7018. // Necessary to make sure the init is deoptimized for conditional declarations.
  7019. // We cannot call deoptimizePath here.
  7020. variable.markInitializersForDeoptimization();
  7021. return variable;
  7022. }
  7023. else {
  7024. return super.addDeclaration(identifier, context, init, false);
  7025. }
  7026. }
  7027. }
  7028. class ExpressionStatement extends NodeBase {
  7029. initialise() {
  7030. if (this.directive &&
  7031. this.directive !== 'use strict' &&
  7032. this.parent.type === Program$1) {
  7033. this.context.warn(
  7034. // This is necessary, because either way (deleting or not) can lead to errors.
  7035. {
  7036. code: 'MODULE_LEVEL_DIRECTIVE',
  7037. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  7038. }, this.start);
  7039. }
  7040. }
  7041. render(code, options) {
  7042. super.render(code, options);
  7043. if (this.included)
  7044. this.insertSemicolon(code);
  7045. }
  7046. shouldBeIncluded(context) {
  7047. if (this.directive && this.directive !== 'use strict')
  7048. return this.parent.type !== Program$1;
  7049. return super.shouldBeIncluded(context);
  7050. }
  7051. applyDeoptimizations() { }
  7052. }
  7053. class BlockStatement extends NodeBase {
  7054. constructor() {
  7055. super(...arguments);
  7056. this.directlyIncluded = false;
  7057. }
  7058. addImplicitReturnExpressionToScope() {
  7059. const lastStatement = this.body[this.body.length - 1];
  7060. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7061. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7062. }
  7063. }
  7064. createScope(parentScope) {
  7065. this.scope = this.parent.preventChildBlockScope
  7066. ? parentScope
  7067. : new BlockScope(parentScope);
  7068. }
  7069. hasEffects(context) {
  7070. if (this.deoptimizeBody)
  7071. return true;
  7072. for (const node of this.body) {
  7073. if (context.brokenFlow)
  7074. break;
  7075. if (node.hasEffects(context))
  7076. return true;
  7077. }
  7078. return false;
  7079. }
  7080. include(context, includeChildrenRecursively) {
  7081. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7082. this.included = true;
  7083. this.directlyIncluded = true;
  7084. if (this.deoptimizeBody)
  7085. includeChildrenRecursively = true;
  7086. for (const node of this.body) {
  7087. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7088. node.include(context, includeChildrenRecursively);
  7089. }
  7090. }
  7091. }
  7092. initialise() {
  7093. const firstBodyStatement = this.body[0];
  7094. this.deoptimizeBody =
  7095. firstBodyStatement instanceof ExpressionStatement &&
  7096. firstBodyStatement.directive === 'use asm';
  7097. }
  7098. render(code, options) {
  7099. if (this.body.length) {
  7100. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7101. }
  7102. else {
  7103. super.render(code, options);
  7104. }
  7105. }
  7106. }
  7107. class RestElement extends NodeBase {
  7108. constructor() {
  7109. super(...arguments);
  7110. this.declarationInit = null;
  7111. }
  7112. addExportedVariables(variables, exportNamesByVariable) {
  7113. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7114. }
  7115. declare(kind, init) {
  7116. this.declarationInit = init;
  7117. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7118. }
  7119. deoptimizePath(path) {
  7120. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7121. }
  7122. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7123. return (path.length > 0 ||
  7124. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7125. }
  7126. markDeclarationReached() {
  7127. this.argument.markDeclarationReached();
  7128. }
  7129. applyDeoptimizations() {
  7130. this.deoptimized = true;
  7131. if (this.declarationInit !== null) {
  7132. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7133. this.context.requestTreeshakingPass();
  7134. }
  7135. }
  7136. }
  7137. class FunctionBase extends NodeBase {
  7138. constructor() {
  7139. super(...arguments);
  7140. this.objectEntity = null;
  7141. this.deoptimizedReturn = false;
  7142. }
  7143. deoptimizePath(path) {
  7144. this.getObjectEntity().deoptimizePath(path);
  7145. if (path.length === 1 && path[0] === UnknownKey) {
  7146. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7147. // which means the return expression needs to be reassigned
  7148. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7149. }
  7150. }
  7151. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7152. if (path.length > 0) {
  7153. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7154. }
  7155. }
  7156. getLiteralValueAtPath(path, recursionTracker, origin) {
  7157. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7158. }
  7159. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7160. if (path.length > 0) {
  7161. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7162. }
  7163. if (this.async) {
  7164. if (!this.deoptimizedReturn) {
  7165. this.deoptimizedReturn = true;
  7166. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7167. this.context.requestTreeshakingPass();
  7168. }
  7169. return UNKNOWN_EXPRESSION;
  7170. }
  7171. return this.scope.getReturnExpression();
  7172. }
  7173. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7174. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7175. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7176. }
  7177. if (this.async) {
  7178. const { propertyReadSideEffects } = this.context.options
  7179. .treeshake;
  7180. const returnExpression = this.scope.getReturnExpression();
  7181. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7182. (propertyReadSideEffects &&
  7183. (propertyReadSideEffects === 'always' ||
  7184. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7185. return true;
  7186. }
  7187. }
  7188. for (const param of this.params) {
  7189. if (param.hasEffects(context))
  7190. return true;
  7191. }
  7192. return false;
  7193. }
  7194. include(context, includeChildrenRecursively) {
  7195. if (!this.deoptimized)
  7196. this.applyDeoptimizations();
  7197. this.included = true;
  7198. const { brokenFlow } = context;
  7199. context.brokenFlow = BROKEN_FLOW_NONE;
  7200. this.body.include(context, includeChildrenRecursively);
  7201. context.brokenFlow = brokenFlow;
  7202. }
  7203. includeCallArguments(context, args) {
  7204. this.scope.includeCallArguments(context, args);
  7205. }
  7206. initialise() {
  7207. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  7208. if (this.body instanceof BlockStatement) {
  7209. this.body.addImplicitReturnExpressionToScope();
  7210. }
  7211. else {
  7212. this.scope.addReturnExpression(this.body);
  7213. }
  7214. }
  7215. parseNode(esTreeNode) {
  7216. if (esTreeNode.body.type === BlockStatement$1) {
  7217. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  7218. }
  7219. super.parseNode(esTreeNode);
  7220. }
  7221. applyDeoptimizations() { }
  7222. }
  7223. FunctionBase.prototype.preventChildBlockScope = true;
  7224. class ArrowFunctionExpression extends FunctionBase {
  7225. constructor() {
  7226. super(...arguments);
  7227. this.objectEntity = null;
  7228. }
  7229. createScope(parentScope) {
  7230. this.scope = new ReturnValueScope(parentScope, this.context);
  7231. }
  7232. hasEffects() {
  7233. if (!this.deoptimized)
  7234. this.applyDeoptimizations();
  7235. return false;
  7236. }
  7237. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7238. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7239. return true;
  7240. if (interaction.type === INTERACTION_CALLED) {
  7241. const { ignore, brokenFlow } = context;
  7242. context.ignore = {
  7243. breaks: false,
  7244. continues: false,
  7245. labels: new Set(),
  7246. returnYield: true
  7247. };
  7248. if (this.body.hasEffects(context))
  7249. return true;
  7250. context.ignore = ignore;
  7251. context.brokenFlow = brokenFlow;
  7252. }
  7253. return false;
  7254. }
  7255. include(context, includeChildrenRecursively) {
  7256. super.include(context, includeChildrenRecursively);
  7257. for (const param of this.params) {
  7258. if (!(param instanceof Identifier)) {
  7259. param.include(context, includeChildrenRecursively);
  7260. }
  7261. }
  7262. }
  7263. getObjectEntity() {
  7264. if (this.objectEntity !== null) {
  7265. return this.objectEntity;
  7266. }
  7267. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7268. }
  7269. }
  7270. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7271. if (exportedVariables.length === 1 &&
  7272. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7273. const variable = exportedVariables[0];
  7274. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7275. }
  7276. else {
  7277. const fields = [];
  7278. for (const variable of exportedVariables) {
  7279. for (const exportName of exportNamesByVariable.get(variable)) {
  7280. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7281. }
  7282. }
  7283. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7284. }
  7285. }
  7286. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7287. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  7288. code.appendLeft(expressionEnd, ')');
  7289. }
  7290. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7291. const { _, getDirectReturnIifeLeft } = options.snippets;
  7292. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7293. code.appendLeft(expressionEnd, ')');
  7294. }
  7295. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7296. const { _, getPropertyAccess } = options.snippets;
  7297. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7298. if (needsParens) {
  7299. code.prependRight(expressionStart, '(');
  7300. code.appendLeft(expressionEnd, ')');
  7301. }
  7302. }
  7303. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7304. const { _ } = options.snippets;
  7305. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7306. if (needsParens) {
  7307. code.prependRight(expressionStart, '(');
  7308. code.appendLeft(expressionEnd, ')');
  7309. }
  7310. }
  7311. class ObjectPattern extends NodeBase {
  7312. addExportedVariables(variables, exportNamesByVariable) {
  7313. for (const property of this.properties) {
  7314. if (property.type === Property$1) {
  7315. property.value.addExportedVariables(variables, exportNamesByVariable);
  7316. }
  7317. else {
  7318. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7319. }
  7320. }
  7321. }
  7322. declare(kind, init) {
  7323. const variables = [];
  7324. for (const property of this.properties) {
  7325. variables.push(...property.declare(kind, init));
  7326. }
  7327. return variables;
  7328. }
  7329. deoptimizePath(path) {
  7330. if (path.length === 0) {
  7331. for (const property of this.properties) {
  7332. property.deoptimizePath(path);
  7333. }
  7334. }
  7335. }
  7336. hasEffectsOnInteractionAtPath(
  7337. // At the moment, this is only triggered for assignment left-hand sides,
  7338. // where the path is empty
  7339. _path, interaction, context) {
  7340. for (const property of this.properties) {
  7341. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7342. return true;
  7343. }
  7344. return false;
  7345. }
  7346. markDeclarationReached() {
  7347. for (const property of this.properties) {
  7348. property.markDeclarationReached();
  7349. }
  7350. }
  7351. }
  7352. class AssignmentExpression extends NodeBase {
  7353. hasEffects(context) {
  7354. const { deoptimized, left, right } = this;
  7355. if (!deoptimized)
  7356. this.applyDeoptimizations();
  7357. // MemberExpressions do not access the property before assignments if the
  7358. // operator is '='.
  7359. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
  7360. }
  7361. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7362. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7363. }
  7364. include(context, includeChildrenRecursively) {
  7365. const { deoptimized, left, right, operator } = this;
  7366. if (!deoptimized)
  7367. this.applyDeoptimizations();
  7368. this.included = true;
  7369. if (includeChildrenRecursively ||
  7370. operator !== '=' ||
  7371. left.included ||
  7372. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7373. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7374. }
  7375. right.include(context, includeChildrenRecursively);
  7376. }
  7377. initialise() {
  7378. this.left.setAssignedValue(this.right);
  7379. }
  7380. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7381. const { left, right, start, end, parent } = this;
  7382. if (left.included) {
  7383. left.render(code, options);
  7384. right.render(code, options);
  7385. }
  7386. else {
  7387. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7388. code.remove(start, inclusionStart);
  7389. if (preventASI) {
  7390. removeLineBreaks(code, inclusionStart, right.start);
  7391. }
  7392. right.render(code, options, {
  7393. renderedParentType: renderedParentType || parent.type,
  7394. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7395. });
  7396. }
  7397. if (options.format === 'system') {
  7398. if (left instanceof Identifier) {
  7399. const variable = left.variable;
  7400. const exportNames = options.exportNamesByVariable.get(variable);
  7401. if (exportNames) {
  7402. if (exportNames.length === 1) {
  7403. renderSystemExportExpression(variable, start, end, code, options);
  7404. }
  7405. else {
  7406. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7407. }
  7408. return;
  7409. }
  7410. }
  7411. else {
  7412. const systemPatternExports = [];
  7413. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7414. if (systemPatternExports.length > 0) {
  7415. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7416. return;
  7417. }
  7418. }
  7419. }
  7420. if (left.included &&
  7421. left instanceof ObjectPattern &&
  7422. (renderedSurroundingElement === ExpressionStatement$1 ||
  7423. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7424. code.appendRight(start, '(');
  7425. code.prependLeft(end, ')');
  7426. }
  7427. }
  7428. applyDeoptimizations() {
  7429. this.deoptimized = true;
  7430. this.left.deoptimizePath(EMPTY_PATH);
  7431. this.right.deoptimizePath(UNKNOWN_PATH);
  7432. this.context.requestTreeshakingPass();
  7433. }
  7434. }
  7435. class AssignmentPattern extends NodeBase {
  7436. addExportedVariables(variables, exportNamesByVariable) {
  7437. this.left.addExportedVariables(variables, exportNamesByVariable);
  7438. }
  7439. declare(kind, init) {
  7440. return this.left.declare(kind, init);
  7441. }
  7442. deoptimizePath(path) {
  7443. path.length === 0 && this.left.deoptimizePath(path);
  7444. }
  7445. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7446. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7447. }
  7448. markDeclarationReached() {
  7449. this.left.markDeclarationReached();
  7450. }
  7451. render(code, options, { isShorthandProperty } = BLANK) {
  7452. this.left.render(code, options, { isShorthandProperty });
  7453. this.right.render(code, options);
  7454. }
  7455. applyDeoptimizations() {
  7456. this.deoptimized = true;
  7457. this.left.deoptimizePath(EMPTY_PATH);
  7458. this.right.deoptimizePath(UNKNOWN_PATH);
  7459. this.context.requestTreeshakingPass();
  7460. }
  7461. }
  7462. class ArgumentsVariable extends LocalVariable {
  7463. constructor(context) {
  7464. super('arguments', null, UNKNOWN_EXPRESSION, context);
  7465. }
  7466. hasEffectsOnInteractionAtPath(path, { type }) {
  7467. return type !== INTERACTION_ACCESSED || path.length > 1;
  7468. }
  7469. }
  7470. class ThisVariable extends LocalVariable {
  7471. constructor(context) {
  7472. super('this', null, null, context);
  7473. this.deoptimizedPaths = [];
  7474. this.entitiesToBeDeoptimized = new Set();
  7475. this.thisDeoptimizationList = [];
  7476. this.thisDeoptimizations = new DiscriminatedPathTracker();
  7477. }
  7478. addEntityToBeDeoptimized(entity) {
  7479. for (const path of this.deoptimizedPaths) {
  7480. entity.deoptimizePath(path);
  7481. }
  7482. for (const { interaction, path } of this.thisDeoptimizationList) {
  7483. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7484. }
  7485. this.entitiesToBeDeoptimized.add(entity);
  7486. }
  7487. deoptimizePath(path) {
  7488. if (path.length === 0 ||
  7489. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7490. return;
  7491. }
  7492. this.deoptimizedPaths.push(path);
  7493. for (const entity of this.entitiesToBeDeoptimized) {
  7494. entity.deoptimizePath(path);
  7495. }
  7496. }
  7497. deoptimizeThisOnInteractionAtPath(interaction, path) {
  7498. const thisDeoptimization = {
  7499. interaction,
  7500. path
  7501. };
  7502. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  7503. for (const entity of this.entitiesToBeDeoptimized) {
  7504. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7505. }
  7506. this.thisDeoptimizationList.push(thisDeoptimization);
  7507. }
  7508. }
  7509. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7510. return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
  7511. super.hasEffectsOnInteractionAtPath(path, interaction, context));
  7512. }
  7513. getInit(context) {
  7514. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  7515. }
  7516. }
  7517. class FunctionScope extends ReturnValueScope {
  7518. constructor(parent, context) {
  7519. super(parent, context);
  7520. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7521. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7522. }
  7523. findLexicalBoundary() {
  7524. return this;
  7525. }
  7526. includeCallArguments(context, args) {
  7527. super.includeCallArguments(context, args);
  7528. if (this.argumentsVariable.included) {
  7529. for (const arg of args) {
  7530. if (!arg.included) {
  7531. arg.include(context, false);
  7532. }
  7533. }
  7534. }
  7535. }
  7536. }
  7537. class FunctionNode extends FunctionBase {
  7538. constructor() {
  7539. super(...arguments);
  7540. this.objectEntity = null;
  7541. }
  7542. createScope(parentScope) {
  7543. this.scope = new FunctionScope(parentScope, this.context);
  7544. }
  7545. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7546. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7547. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7548. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  7549. }
  7550. }
  7551. hasEffects(context) {
  7552. var _a;
  7553. if (!this.deoptimized)
  7554. this.applyDeoptimizations();
  7555. return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  7556. }
  7557. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7558. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7559. return true;
  7560. if (interaction.type === INTERACTION_CALLED) {
  7561. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7562. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
  7563. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  7564. : UNKNOWN_EXPRESSION);
  7565. const { brokenFlow, ignore } = context;
  7566. context.ignore = {
  7567. breaks: false,
  7568. continues: false,
  7569. labels: new Set(),
  7570. returnYield: true
  7571. };
  7572. if (this.body.hasEffects(context))
  7573. return true;
  7574. context.brokenFlow = brokenFlow;
  7575. if (thisInit) {
  7576. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7577. }
  7578. else {
  7579. context.replacedVariableInits.delete(this.scope.thisVariable);
  7580. }
  7581. context.ignore = ignore;
  7582. }
  7583. return false;
  7584. }
  7585. include(context, includeChildrenRecursively) {
  7586. var _a;
  7587. super.include(context, includeChildrenRecursively);
  7588. (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
  7589. const hasArguments = this.scope.argumentsVariable.included;
  7590. for (const param of this.params) {
  7591. if (!(param instanceof Identifier) || hasArguments) {
  7592. param.include(context, includeChildrenRecursively);
  7593. }
  7594. }
  7595. }
  7596. initialise() {
  7597. var _a;
  7598. super.initialise();
  7599. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
  7600. }
  7601. getObjectEntity() {
  7602. if (this.objectEntity !== null) {
  7603. return this.objectEntity;
  7604. }
  7605. return (this.objectEntity = new ObjectEntity([
  7606. {
  7607. key: 'prototype',
  7608. kind: 'init',
  7609. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7610. }
  7611. ], OBJECT_PROTOTYPE));
  7612. }
  7613. }
  7614. class AwaitExpression extends NodeBase {
  7615. hasEffects() {
  7616. if (!this.deoptimized)
  7617. this.applyDeoptimizations();
  7618. return true;
  7619. }
  7620. include(context, includeChildrenRecursively) {
  7621. if (!this.deoptimized)
  7622. this.applyDeoptimizations();
  7623. if (!this.included) {
  7624. this.included = true;
  7625. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  7626. let parent = this.parent;
  7627. do {
  7628. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7629. break checkTopLevelAwait;
  7630. } while ((parent = parent.parent));
  7631. this.context.usesTopLevelAwait = true;
  7632. }
  7633. }
  7634. this.argument.include(context, includeChildrenRecursively);
  7635. }
  7636. }
  7637. const binaryOperators = {
  7638. '!=': (left, right) => left != right,
  7639. '!==': (left, right) => left !== right,
  7640. '%': (left, right) => left % right,
  7641. '&': (left, right) => left & right,
  7642. '*': (left, right) => left * right,
  7643. // At the moment, "**" will be transpiled to Math.pow
  7644. '**': (left, right) => left ** right,
  7645. '+': (left, right) => left + right,
  7646. '-': (left, right) => left - right,
  7647. '/': (left, right) => left / right,
  7648. '<': (left, right) => left < right,
  7649. '<<': (left, right) => left << right,
  7650. '<=': (left, right) => left <= right,
  7651. '==': (left, right) => left == right,
  7652. '===': (left, right) => left === right,
  7653. '>': (left, right) => left > right,
  7654. '>=': (left, right) => left >= right,
  7655. '>>': (left, right) => left >> right,
  7656. '>>>': (left, right) => left >>> right,
  7657. '^': (left, right) => left ^ right,
  7658. '|': (left, right) => left | right
  7659. // We use the fallback for cases where we return something unknown
  7660. // in: () => UnknownValue,
  7661. // instanceof: () => UnknownValue,
  7662. };
  7663. class BinaryExpression extends NodeBase {
  7664. deoptimizeCache() { }
  7665. getLiteralValueAtPath(path, recursionTracker, origin) {
  7666. if (path.length > 0)
  7667. return UnknownValue;
  7668. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7669. if (typeof leftValue === 'symbol')
  7670. return UnknownValue;
  7671. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7672. if (typeof rightValue === 'symbol')
  7673. return UnknownValue;
  7674. const operatorFn = binaryOperators[this.operator];
  7675. if (!operatorFn)
  7676. return UnknownValue;
  7677. return operatorFn(leftValue, rightValue);
  7678. }
  7679. hasEffects(context) {
  7680. // support some implicit type coercion runtime errors
  7681. if (this.operator === '+' &&
  7682. this.parent instanceof ExpressionStatement &&
  7683. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7684. return true;
  7685. }
  7686. return super.hasEffects(context);
  7687. }
  7688. hasEffectsOnInteractionAtPath(path, { type }) {
  7689. return type !== INTERACTION_ACCESSED || path.length > 1;
  7690. }
  7691. render(code, options, { renderedSurroundingElement } = BLANK) {
  7692. this.left.render(code, options, { renderedSurroundingElement });
  7693. this.right.render(code, options);
  7694. }
  7695. }
  7696. class BreakStatement extends NodeBase {
  7697. hasEffects(context) {
  7698. if (this.label) {
  7699. if (!context.ignore.labels.has(this.label.name))
  7700. return true;
  7701. context.includedLabels.add(this.label.name);
  7702. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7703. }
  7704. else {
  7705. if (!context.ignore.breaks)
  7706. return true;
  7707. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7708. }
  7709. return false;
  7710. }
  7711. include(context) {
  7712. this.included = true;
  7713. if (this.label) {
  7714. this.label.include();
  7715. context.includedLabels.add(this.label.name);
  7716. }
  7717. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7718. }
  7719. }
  7720. function renderCallArguments(code, options, node) {
  7721. if (node.arguments.length > 0) {
  7722. if (node.arguments[node.arguments.length - 1].included) {
  7723. for (const arg of node.arguments) {
  7724. arg.render(code, options);
  7725. }
  7726. }
  7727. else {
  7728. let lastIncludedIndex = node.arguments.length - 2;
  7729. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7730. lastIncludedIndex--;
  7731. }
  7732. if (lastIncludedIndex >= 0) {
  7733. for (let index = 0; index <= lastIncludedIndex; index++) {
  7734. node.arguments[index].render(code, options);
  7735. }
  7736. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7737. }
  7738. else {
  7739. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7740. }
  7741. }
  7742. }
  7743. }
  7744. class Literal extends NodeBase {
  7745. deoptimizeThisOnInteractionAtPath() { }
  7746. getLiteralValueAtPath(path) {
  7747. if (path.length > 0 ||
  7748. // unknown literals can also be null but do not start with an "n"
  7749. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  7750. typeof this.value === 'bigint' ||
  7751. // to support shims for regular expressions
  7752. this.context.code.charCodeAt(this.start) === 47) {
  7753. return UnknownValue;
  7754. }
  7755. return this.value;
  7756. }
  7757. getReturnExpressionWhenCalledAtPath(path) {
  7758. if (path.length !== 1)
  7759. return UNKNOWN_EXPRESSION;
  7760. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7761. }
  7762. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7763. switch (interaction.type) {
  7764. case INTERACTION_ACCESSED:
  7765. return path.length > (this.value === null ? 0 : 1);
  7766. case INTERACTION_ASSIGNED:
  7767. return true;
  7768. case INTERACTION_CALLED:
  7769. return (path.length !== 1 ||
  7770. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7771. }
  7772. }
  7773. initialise() {
  7774. this.members = getLiteralMembersForValue(this.value);
  7775. }
  7776. parseNode(esTreeNode) {
  7777. this.value = esTreeNode.value;
  7778. this.regex = esTreeNode.regex;
  7779. super.parseNode(esTreeNode);
  7780. }
  7781. render(code) {
  7782. if (typeof this.value === 'string') {
  7783. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7784. }
  7785. }
  7786. }
  7787. // To avoid infinite recursions
  7788. const MAX_PATH_DEPTH = 7;
  7789. function getResolvablePropertyKey(memberExpression) {
  7790. return memberExpression.computed
  7791. ? getResolvableComputedPropertyKey(memberExpression.property)
  7792. : memberExpression.property.name;
  7793. }
  7794. function getResolvableComputedPropertyKey(propertyKey) {
  7795. if (propertyKey instanceof Literal) {
  7796. return String(propertyKey.value);
  7797. }
  7798. return null;
  7799. }
  7800. function getPathIfNotComputed(memberExpression) {
  7801. const nextPathKey = memberExpression.propertyKey;
  7802. const object = memberExpression.object;
  7803. if (typeof nextPathKey === 'string') {
  7804. if (object instanceof Identifier) {
  7805. return [
  7806. { key: object.name, pos: object.start },
  7807. { key: nextPathKey, pos: memberExpression.property.start }
  7808. ];
  7809. }
  7810. if (object instanceof MemberExpression) {
  7811. const parentPath = getPathIfNotComputed(object);
  7812. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7813. }
  7814. }
  7815. return null;
  7816. }
  7817. function getStringFromPath(path) {
  7818. let pathString = path[0].key;
  7819. for (let index = 1; index < path.length; index++) {
  7820. pathString += '.' + path[index].key;
  7821. }
  7822. return pathString;
  7823. }
  7824. class MemberExpression extends NodeBase {
  7825. constructor() {
  7826. super(...arguments);
  7827. this.variable = null;
  7828. this.assignmentDeoptimized = false;
  7829. this.bound = false;
  7830. this.expressionsToBeDeoptimized = [];
  7831. this.replacement = null;
  7832. }
  7833. bind() {
  7834. this.bound = true;
  7835. const path = getPathIfNotComputed(this);
  7836. const baseVariable = path && this.scope.findVariable(path[0].key);
  7837. if (baseVariable && baseVariable.isNamespace) {
  7838. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  7839. if (!resolvedVariable) {
  7840. super.bind();
  7841. }
  7842. else if (typeof resolvedVariable === 'string') {
  7843. this.replacement = resolvedVariable;
  7844. }
  7845. else {
  7846. this.variable = resolvedVariable;
  7847. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7848. }
  7849. }
  7850. else {
  7851. super.bind();
  7852. }
  7853. }
  7854. deoptimizeCache() {
  7855. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7856. this.expressionsToBeDeoptimized = [];
  7857. this.propertyKey = UnknownKey;
  7858. this.object.deoptimizePath(UNKNOWN_PATH);
  7859. for (const expression of expressionsToBeDeoptimized) {
  7860. expression.deoptimizeCache();
  7861. }
  7862. }
  7863. deoptimizePath(path) {
  7864. if (path.length === 0)
  7865. this.disallowNamespaceReassignment();
  7866. if (this.variable) {
  7867. this.variable.deoptimizePath(path);
  7868. }
  7869. else if (!this.replacement) {
  7870. if (path.length < MAX_PATH_DEPTH) {
  7871. const propertyKey = this.getPropertyKey();
  7872. this.object.deoptimizePath([
  7873. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7874. ...path
  7875. ]);
  7876. }
  7877. }
  7878. }
  7879. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7880. if (this.variable) {
  7881. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7882. }
  7883. else if (!this.replacement) {
  7884. if (path.length < MAX_PATH_DEPTH) {
  7885. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  7886. }
  7887. else {
  7888. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  7889. }
  7890. }
  7891. }
  7892. getLiteralValueAtPath(path, recursionTracker, origin) {
  7893. if (this.variable) {
  7894. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7895. }
  7896. if (this.replacement) {
  7897. return UnknownValue;
  7898. }
  7899. this.expressionsToBeDeoptimized.push(origin);
  7900. if (path.length < MAX_PATH_DEPTH) {
  7901. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  7902. }
  7903. return UnknownValue;
  7904. }
  7905. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7906. if (this.variable) {
  7907. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7908. }
  7909. if (this.replacement) {
  7910. return UNKNOWN_EXPRESSION;
  7911. }
  7912. this.expressionsToBeDeoptimized.push(origin);
  7913. if (path.length < MAX_PATH_DEPTH) {
  7914. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  7915. }
  7916. return UNKNOWN_EXPRESSION;
  7917. }
  7918. hasEffects(context) {
  7919. if (!this.deoptimized)
  7920. this.applyDeoptimizations();
  7921. return (this.property.hasEffects(context) ||
  7922. this.object.hasEffects(context) ||
  7923. this.hasAccessEffect(context));
  7924. }
  7925. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7926. if (checkAccess && !this.deoptimized)
  7927. this.applyDeoptimizations();
  7928. if (!this.assignmentDeoptimized)
  7929. this.applyAssignmentDeoptimization();
  7930. return (this.property.hasEffects(context) ||
  7931. this.object.hasEffects(context) ||
  7932. (checkAccess && this.hasAccessEffect(context)) ||
  7933. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7934. }
  7935. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7936. if (this.variable) {
  7937. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7938. }
  7939. if (this.replacement) {
  7940. return true;
  7941. }
  7942. if (path.length < MAX_PATH_DEPTH) {
  7943. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  7944. }
  7945. return true;
  7946. }
  7947. include(context, includeChildrenRecursively) {
  7948. if (!this.deoptimized)
  7949. this.applyDeoptimizations();
  7950. this.includeProperties(context, includeChildrenRecursively);
  7951. }
  7952. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7953. if (!this.assignmentDeoptimized)
  7954. this.applyAssignmentDeoptimization();
  7955. if (deoptimizeAccess) {
  7956. this.include(context, includeChildrenRecursively);
  7957. }
  7958. else {
  7959. this.includeProperties(context, includeChildrenRecursively);
  7960. }
  7961. }
  7962. includeCallArguments(context, args) {
  7963. if (this.variable) {
  7964. this.variable.includeCallArguments(context, args);
  7965. }
  7966. else {
  7967. super.includeCallArguments(context, args);
  7968. }
  7969. }
  7970. initialise() {
  7971. this.propertyKey = getResolvablePropertyKey(this);
  7972. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  7973. }
  7974. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7975. if (this.variable || this.replacement) {
  7976. const { snippets: { getPropertyAccess } } = options;
  7977. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
  7978. if (renderedParentType && isCalleeOfRenderedParent)
  7979. replacement = '0, ' + replacement;
  7980. code.overwrite(this.start, this.end, replacement, {
  7981. contentOnly: true,
  7982. storeName: true
  7983. });
  7984. }
  7985. else {
  7986. if (renderedParentType && isCalleeOfRenderedParent) {
  7987. code.appendRight(this.start, '0, ');
  7988. }
  7989. this.object.render(code, options, { renderedSurroundingElement });
  7990. this.property.render(code, options);
  7991. }
  7992. }
  7993. setAssignedValue(value) {
  7994. this.assignmentInteraction = {
  7995. args: [value],
  7996. thisArg: this.object,
  7997. type: INTERACTION_ASSIGNED
  7998. };
  7999. }
  8000. applyDeoptimizations() {
  8001. this.deoptimized = true;
  8002. const { propertyReadSideEffects } = this.context.options
  8003. .treeshake;
  8004. if (
  8005. // Namespaces are not bound and should not be deoptimized
  8006. this.bound &&
  8007. propertyReadSideEffects &&
  8008. !(this.variable || this.replacement)) {
  8009. const propertyKey = this.getPropertyKey();
  8010. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8011. this.context.requestTreeshakingPass();
  8012. }
  8013. }
  8014. applyAssignmentDeoptimization() {
  8015. this.assignmentDeoptimized = true;
  8016. const { propertyReadSideEffects } = this.context.options
  8017. .treeshake;
  8018. if (
  8019. // Namespaces are not bound and should not be deoptimized
  8020. this.bound &&
  8021. propertyReadSideEffects &&
  8022. !(this.variable || this.replacement)) {
  8023. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8024. this.context.requestTreeshakingPass();
  8025. }
  8026. }
  8027. disallowNamespaceReassignment() {
  8028. if (this.object instanceof Identifier) {
  8029. const variable = this.scope.findVariable(this.object.name);
  8030. if (variable.isNamespace) {
  8031. if (this.variable) {
  8032. this.context.includeVariableInModule(this.variable);
  8033. }
  8034. this.context.warn({
  8035. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  8036. message: `Illegal reassignment to import '${this.object.name}'`
  8037. }, this.start);
  8038. }
  8039. }
  8040. }
  8041. getPropertyKey() {
  8042. if (this.propertyKey === null) {
  8043. this.propertyKey = UnknownKey;
  8044. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8045. return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
  8046. }
  8047. return this.propertyKey;
  8048. }
  8049. hasAccessEffect(context) {
  8050. const { propertyReadSideEffects } = this.context.options
  8051. .treeshake;
  8052. return (!(this.variable || this.replacement) &&
  8053. propertyReadSideEffects &&
  8054. (propertyReadSideEffects === 'always' ||
  8055. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8056. }
  8057. includeProperties(context, includeChildrenRecursively) {
  8058. if (!this.included) {
  8059. this.included = true;
  8060. if (this.variable) {
  8061. this.context.includeVariableInModule(this.variable);
  8062. }
  8063. }
  8064. this.object.include(context, includeChildrenRecursively);
  8065. this.property.include(context, includeChildrenRecursively);
  8066. }
  8067. }
  8068. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8069. if (path.length === 0)
  8070. return baseVariable;
  8071. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8072. return null;
  8073. const exportName = path[0].key;
  8074. const variable = baseVariable.context.traceExport(exportName);
  8075. if (!variable) {
  8076. const fileName = baseVariable.context.fileName;
  8077. astContext.warn({
  8078. code: 'MISSING_EXPORT',
  8079. exporter: relativeId(fileName),
  8080. importer: relativeId(astContext.fileName),
  8081. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  8082. missing: exportName,
  8083. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  8084. }, path[0].pos);
  8085. return 'undefined';
  8086. }
  8087. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8088. }
  8089. class CallExpressionBase extends NodeBase {
  8090. constructor() {
  8091. super(...arguments);
  8092. this.returnExpression = null;
  8093. this.deoptimizableDependentExpressions = [];
  8094. this.expressionsToBeDeoptimized = new Set();
  8095. }
  8096. deoptimizeCache() {
  8097. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  8098. this.returnExpression = UNKNOWN_EXPRESSION;
  8099. for (const expression of this.deoptimizableDependentExpressions) {
  8100. expression.deoptimizeCache();
  8101. }
  8102. for (const expression of this.expressionsToBeDeoptimized) {
  8103. expression.deoptimizePath(UNKNOWN_PATH);
  8104. }
  8105. }
  8106. }
  8107. deoptimizePath(path) {
  8108. if (path.length === 0 ||
  8109. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8110. return;
  8111. }
  8112. const returnExpression = this.getReturnExpression();
  8113. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8114. returnExpression.deoptimizePath(path);
  8115. }
  8116. }
  8117. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8118. const returnExpression = this.getReturnExpression(recursionTracker);
  8119. if (returnExpression === UNKNOWN_EXPRESSION) {
  8120. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8121. }
  8122. else {
  8123. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8124. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  8125. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8126. }, undefined);
  8127. }
  8128. }
  8129. getLiteralValueAtPath(path, recursionTracker, origin) {
  8130. const returnExpression = this.getReturnExpression(recursionTracker);
  8131. if (returnExpression === UNKNOWN_EXPRESSION) {
  8132. return UnknownValue;
  8133. }
  8134. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8135. this.deoptimizableDependentExpressions.push(origin);
  8136. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8137. }, UnknownValue);
  8138. }
  8139. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8140. const returnExpression = this.getReturnExpression(recursionTracker);
  8141. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  8142. return UNKNOWN_EXPRESSION;
  8143. }
  8144. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8145. this.deoptimizableDependentExpressions.push(origin);
  8146. return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8147. }, UNKNOWN_EXPRESSION);
  8148. }
  8149. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8150. const { type } = interaction;
  8151. if (type === INTERACTION_CALLED) {
  8152. if ((interaction.withNew
  8153. ? context.instantiated
  8154. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
  8155. return false;
  8156. }
  8157. }
  8158. else if ((type === INTERACTION_ASSIGNED
  8159. ? context.assigned
  8160. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8161. return false;
  8162. }
  8163. return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
  8164. }
  8165. }
  8166. class CallExpression extends CallExpressionBase {
  8167. bind() {
  8168. super.bind();
  8169. if (this.callee instanceof Identifier) {
  8170. const variable = this.scope.findVariable(this.callee.name);
  8171. if (variable.isNamespace) {
  8172. this.context.warn({
  8173. code: 'CANNOT_CALL_NAMESPACE',
  8174. message: `Cannot call a namespace ('${this.callee.name}')`
  8175. }, this.start);
  8176. }
  8177. if (this.callee.name === 'eval') {
  8178. this.context.warn({
  8179. code: 'EVAL',
  8180. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8181. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8182. }, this.start);
  8183. }
  8184. }
  8185. this.interaction = {
  8186. args: this.arguments,
  8187. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  8188. ? this.callee.object
  8189. : null,
  8190. type: INTERACTION_CALLED,
  8191. withNew: false
  8192. };
  8193. }
  8194. hasEffects(context) {
  8195. try {
  8196. for (const argument of this.arguments) {
  8197. if (argument.hasEffects(context))
  8198. return true;
  8199. }
  8200. if (this.context.options.treeshake.annotations &&
  8201. this.annotations)
  8202. return false;
  8203. return (this.callee.hasEffects(context) ||
  8204. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8205. }
  8206. finally {
  8207. if (!this.deoptimized)
  8208. this.applyDeoptimizations();
  8209. }
  8210. }
  8211. include(context, includeChildrenRecursively) {
  8212. if (!this.deoptimized)
  8213. this.applyDeoptimizations();
  8214. if (includeChildrenRecursively) {
  8215. super.include(context, includeChildrenRecursively);
  8216. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8217. this.callee instanceof Identifier &&
  8218. this.callee.variable) {
  8219. this.callee.variable.markCalledFromTryStatement();
  8220. }
  8221. }
  8222. else {
  8223. this.included = true;
  8224. this.callee.include(context, false);
  8225. }
  8226. this.callee.includeCallArguments(context, this.arguments);
  8227. }
  8228. render(code, options, { renderedSurroundingElement } = BLANK) {
  8229. this.callee.render(code, options, {
  8230. isCalleeOfRenderedParent: true,
  8231. renderedSurroundingElement
  8232. });
  8233. renderCallArguments(code, options, this);
  8234. }
  8235. applyDeoptimizations() {
  8236. this.deoptimized = true;
  8237. if (this.interaction.thisArg) {
  8238. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8239. }
  8240. for (const argument of this.arguments) {
  8241. // This will make sure all properties of parameters behave as "unknown"
  8242. argument.deoptimizePath(UNKNOWN_PATH);
  8243. }
  8244. this.context.requestTreeshakingPass();
  8245. }
  8246. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8247. if (this.returnExpression === null) {
  8248. this.returnExpression = UNKNOWN_EXPRESSION;
  8249. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8250. }
  8251. return this.returnExpression;
  8252. }
  8253. }
  8254. class CatchScope extends ParameterScope {
  8255. addDeclaration(identifier, context, init, isHoisted) {
  8256. const existingParameter = this.variables.get(identifier.name);
  8257. if (existingParameter) {
  8258. // While we still create a hoisted declaration, the initializer goes to
  8259. // the parameter. Note that technically, the declaration now belongs to
  8260. // two variables, which is not correct but should not cause issues.
  8261. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  8262. existingParameter.addDeclaration(identifier, init);
  8263. return existingParameter;
  8264. }
  8265. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  8266. }
  8267. }
  8268. class CatchClause extends NodeBase {
  8269. createScope(parentScope) {
  8270. this.scope = new CatchScope(parentScope, this.context);
  8271. }
  8272. parseNode(esTreeNode) {
  8273. // Parameters need to be declared first as the logic is that initializers
  8274. // of hoisted body variables are associated with parameters of the same
  8275. // name instead of the variable
  8276. const { param } = esTreeNode;
  8277. if (param) {
  8278. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  8279. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8280. }
  8281. super.parseNode(esTreeNode);
  8282. }
  8283. }
  8284. class ChainExpression extends NodeBase {
  8285. }
  8286. class ClassBodyScope extends ChildScope {
  8287. constructor(parent, classNode, context) {
  8288. super(parent);
  8289. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  8290. this.instanceScope = new ChildScope(this);
  8291. this.instanceScope.variables.set('this', new ThisVariable(context));
  8292. }
  8293. findLexicalBoundary() {
  8294. return this;
  8295. }
  8296. }
  8297. class ClassBody extends NodeBase {
  8298. createScope(parentScope) {
  8299. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  8300. }
  8301. include(context, includeChildrenRecursively) {
  8302. this.included = true;
  8303. this.context.includeVariableInModule(this.scope.thisVariable);
  8304. for (const definition of this.body) {
  8305. definition.include(context, includeChildrenRecursively);
  8306. }
  8307. }
  8308. parseNode(esTreeNode) {
  8309. const body = (this.body = []);
  8310. for (const definition of esTreeNode.body) {
  8311. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  8312. }
  8313. super.parseNode(esTreeNode);
  8314. }
  8315. applyDeoptimizations() { }
  8316. }
  8317. class MethodBase extends NodeBase {
  8318. constructor() {
  8319. super(...arguments);
  8320. this.accessedValue = null;
  8321. }
  8322. // As getter properties directly receive their values from fixed function
  8323. // expressions, there is no known situation where a getter is deoptimized.
  8324. deoptimizeCache() { }
  8325. deoptimizePath(path) {
  8326. this.getAccessedValue().deoptimizePath(path);
  8327. }
  8328. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8329. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8330. return this.value.deoptimizeThisOnInteractionAtPath({
  8331. args: NO_ARGS,
  8332. thisArg: interaction.thisArg,
  8333. type: INTERACTION_CALLED,
  8334. withNew: false
  8335. }, EMPTY_PATH, recursionTracker);
  8336. }
  8337. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8338. return this.value.deoptimizeThisOnInteractionAtPath({
  8339. args: interaction.args,
  8340. thisArg: interaction.thisArg,
  8341. type: INTERACTION_CALLED,
  8342. withNew: false
  8343. }, EMPTY_PATH, recursionTracker);
  8344. }
  8345. this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8346. }
  8347. getLiteralValueAtPath(path, recursionTracker, origin) {
  8348. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  8349. }
  8350. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8351. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8352. }
  8353. hasEffects(context) {
  8354. return this.key.hasEffects(context);
  8355. }
  8356. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8357. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8358. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8359. args: NO_ARGS,
  8360. thisArg: interaction.thisArg,
  8361. type: INTERACTION_CALLED,
  8362. withNew: false
  8363. }, context);
  8364. }
  8365. // setters are only called for empty paths
  8366. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8367. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8368. args: interaction.args,
  8369. thisArg: interaction.thisArg,
  8370. type: INTERACTION_CALLED,
  8371. withNew: false
  8372. }, context);
  8373. }
  8374. return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
  8375. }
  8376. applyDeoptimizations() { }
  8377. getAccessedValue() {
  8378. if (this.accessedValue === null) {
  8379. if (this.kind === 'get') {
  8380. this.accessedValue = UNKNOWN_EXPRESSION;
  8381. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8382. }
  8383. else {
  8384. return (this.accessedValue = this.value);
  8385. }
  8386. }
  8387. return this.accessedValue;
  8388. }
  8389. }
  8390. class MethodDefinition extends MethodBase {
  8391. applyDeoptimizations() { }
  8392. }
  8393. class ObjectMember extends ExpressionEntity {
  8394. constructor(object, key) {
  8395. super();
  8396. this.object = object;
  8397. this.key = key;
  8398. }
  8399. deoptimizePath(path) {
  8400. this.object.deoptimizePath([this.key, ...path]);
  8401. }
  8402. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8403. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8404. }
  8405. getLiteralValueAtPath(path, recursionTracker, origin) {
  8406. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8407. }
  8408. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8409. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8410. }
  8411. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8412. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8413. }
  8414. }
  8415. class ClassNode extends NodeBase {
  8416. constructor() {
  8417. super(...arguments);
  8418. this.objectEntity = null;
  8419. }
  8420. createScope(parentScope) {
  8421. this.scope = new ChildScope(parentScope);
  8422. }
  8423. deoptimizeCache() {
  8424. this.getObjectEntity().deoptimizeAllProperties();
  8425. }
  8426. deoptimizePath(path) {
  8427. this.getObjectEntity().deoptimizePath(path);
  8428. }
  8429. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8430. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8431. }
  8432. getLiteralValueAtPath(path, recursionTracker, origin) {
  8433. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8434. }
  8435. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8436. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8437. }
  8438. hasEffects(context) {
  8439. var _a, _b;
  8440. if (!this.deoptimized)
  8441. this.applyDeoptimizations();
  8442. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  8443. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  8444. return initEffect || super.hasEffects(context);
  8445. }
  8446. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8447. var _a;
  8448. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8449. return (!interaction.withNew ||
  8450. (this.classConstructor !== null
  8451. ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
  8452. : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8453. false);
  8454. }
  8455. else {
  8456. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8457. }
  8458. }
  8459. include(context, includeChildrenRecursively) {
  8460. var _a;
  8461. if (!this.deoptimized)
  8462. this.applyDeoptimizations();
  8463. this.included = true;
  8464. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  8465. this.body.include(context, includeChildrenRecursively);
  8466. if (this.id) {
  8467. this.id.markDeclarationReached();
  8468. this.id.include();
  8469. }
  8470. }
  8471. initialise() {
  8472. var _a;
  8473. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  8474. for (const method of this.body.body) {
  8475. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8476. this.classConstructor = method;
  8477. return;
  8478. }
  8479. }
  8480. this.classConstructor = null;
  8481. }
  8482. applyDeoptimizations() {
  8483. this.deoptimized = true;
  8484. for (const definition of this.body.body) {
  8485. if (!(definition.static ||
  8486. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8487. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8488. definition.deoptimizePath(UNKNOWN_PATH);
  8489. }
  8490. }
  8491. this.context.requestTreeshakingPass();
  8492. }
  8493. getObjectEntity() {
  8494. if (this.objectEntity !== null) {
  8495. return this.objectEntity;
  8496. }
  8497. const staticProperties = [];
  8498. const dynamicMethods = [];
  8499. for (const definition of this.body.body) {
  8500. const properties = definition.static ? staticProperties : dynamicMethods;
  8501. const definitionKind = definition.kind;
  8502. // Note that class fields do not end up on the prototype
  8503. if (properties === dynamicMethods && !definitionKind)
  8504. continue;
  8505. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8506. let key;
  8507. if (definition.computed) {
  8508. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8509. if (typeof keyValue === 'symbol') {
  8510. properties.push({ key: UnknownKey, kind, property: definition });
  8511. continue;
  8512. }
  8513. else {
  8514. key = String(keyValue);
  8515. }
  8516. }
  8517. else {
  8518. key =
  8519. definition.key instanceof Identifier
  8520. ? definition.key.name
  8521. : String(definition.key.value);
  8522. }
  8523. properties.push({ key, kind, property: definition });
  8524. }
  8525. staticProperties.unshift({
  8526. key: 'prototype',
  8527. kind: 'init',
  8528. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8529. });
  8530. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8531. }
  8532. }
  8533. class ClassDeclaration extends ClassNode {
  8534. initialise() {
  8535. super.initialise();
  8536. if (this.id !== null) {
  8537. this.id.variable.isId = true;
  8538. }
  8539. }
  8540. parseNode(esTreeNode) {
  8541. if (esTreeNode.id !== null) {
  8542. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8543. }
  8544. super.parseNode(esTreeNode);
  8545. }
  8546. render(code, options) {
  8547. const { exportNamesByVariable, format, snippets: { _ } } = options;
  8548. if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
  8549. code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
  8550. }
  8551. super.render(code, options);
  8552. }
  8553. }
  8554. class ClassExpression extends ClassNode {
  8555. render(code, options, { renderedSurroundingElement } = BLANK) {
  8556. super.render(code, options);
  8557. if (renderedSurroundingElement === ExpressionStatement$1) {
  8558. code.appendRight(this.start, '(');
  8559. code.prependLeft(this.end, ')');
  8560. }
  8561. }
  8562. }
  8563. class MultiExpression extends ExpressionEntity {
  8564. constructor(expressions) {
  8565. super();
  8566. this.expressions = expressions;
  8567. this.included = false;
  8568. }
  8569. deoptimizePath(path) {
  8570. for (const expression of this.expressions) {
  8571. expression.deoptimizePath(path);
  8572. }
  8573. }
  8574. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8575. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
  8576. }
  8577. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8578. for (const expression of this.expressions) {
  8579. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8580. return true;
  8581. }
  8582. return false;
  8583. }
  8584. }
  8585. class ConditionalExpression extends NodeBase {
  8586. constructor() {
  8587. super(...arguments);
  8588. this.expressionsToBeDeoptimized = [];
  8589. this.isBranchResolutionAnalysed = false;
  8590. this.usedBranch = null;
  8591. }
  8592. deoptimizeCache() {
  8593. if (this.usedBranch !== null) {
  8594. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8595. this.usedBranch = null;
  8596. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8597. for (const expression of this.expressionsToBeDeoptimized) {
  8598. expression.deoptimizeCache();
  8599. }
  8600. }
  8601. }
  8602. deoptimizePath(path) {
  8603. const usedBranch = this.getUsedBranch();
  8604. if (!usedBranch) {
  8605. this.consequent.deoptimizePath(path);
  8606. this.alternate.deoptimizePath(path);
  8607. }
  8608. else {
  8609. usedBranch.deoptimizePath(path);
  8610. }
  8611. }
  8612. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8613. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8614. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8615. }
  8616. getLiteralValueAtPath(path, recursionTracker, origin) {
  8617. const usedBranch = this.getUsedBranch();
  8618. if (!usedBranch)
  8619. return UnknownValue;
  8620. this.expressionsToBeDeoptimized.push(origin);
  8621. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8622. }
  8623. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8624. const usedBranch = this.getUsedBranch();
  8625. if (!usedBranch)
  8626. return new MultiExpression([
  8627. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  8628. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  8629. ]);
  8630. this.expressionsToBeDeoptimized.push(origin);
  8631. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8632. }
  8633. hasEffects(context) {
  8634. if (this.test.hasEffects(context))
  8635. return true;
  8636. const usedBranch = this.getUsedBranch();
  8637. if (!usedBranch) {
  8638. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8639. }
  8640. return usedBranch.hasEffects(context);
  8641. }
  8642. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8643. const usedBranch = this.getUsedBranch();
  8644. if (!usedBranch) {
  8645. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8646. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8647. }
  8648. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8649. }
  8650. include(context, includeChildrenRecursively) {
  8651. this.included = true;
  8652. const usedBranch = this.getUsedBranch();
  8653. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8654. this.test.include(context, includeChildrenRecursively);
  8655. this.consequent.include(context, includeChildrenRecursively);
  8656. this.alternate.include(context, includeChildrenRecursively);
  8657. }
  8658. else {
  8659. usedBranch.include(context, includeChildrenRecursively);
  8660. }
  8661. }
  8662. includeCallArguments(context, args) {
  8663. const usedBranch = this.getUsedBranch();
  8664. if (!usedBranch) {
  8665. this.consequent.includeCallArguments(context, args);
  8666. this.alternate.includeCallArguments(context, args);
  8667. }
  8668. else {
  8669. usedBranch.includeCallArguments(context, args);
  8670. }
  8671. }
  8672. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8673. const usedBranch = this.getUsedBranch();
  8674. if (!this.test.included) {
  8675. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8676. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8677. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8678. : colonPos) + 1);
  8679. if (preventASI) {
  8680. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8681. }
  8682. code.remove(this.start, inclusionStart);
  8683. if (this.consequent.included) {
  8684. code.remove(colonPos, this.end);
  8685. }
  8686. removeAnnotations(this, code);
  8687. usedBranch.render(code, options, {
  8688. isCalleeOfRenderedParent,
  8689. preventASI: true,
  8690. renderedParentType: renderedParentType || this.parent.type,
  8691. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8692. });
  8693. }
  8694. else {
  8695. this.test.render(code, options, { renderedSurroundingElement });
  8696. this.consequent.render(code, options);
  8697. this.alternate.render(code, options);
  8698. }
  8699. }
  8700. getUsedBranch() {
  8701. if (this.isBranchResolutionAnalysed) {
  8702. return this.usedBranch;
  8703. }
  8704. this.isBranchResolutionAnalysed = true;
  8705. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8706. return typeof testValue === 'symbol'
  8707. ? null
  8708. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8709. }
  8710. }
  8711. class ContinueStatement extends NodeBase {
  8712. hasEffects(context) {
  8713. if (this.label) {
  8714. if (!context.ignore.labels.has(this.label.name))
  8715. return true;
  8716. context.includedLabels.add(this.label.name);
  8717. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8718. }
  8719. else {
  8720. if (!context.ignore.continues)
  8721. return true;
  8722. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8723. }
  8724. return false;
  8725. }
  8726. include(context) {
  8727. this.included = true;
  8728. if (this.label) {
  8729. this.label.include();
  8730. context.includedLabels.add(this.label.name);
  8731. }
  8732. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8733. }
  8734. }
  8735. class DoWhileStatement extends NodeBase {
  8736. hasEffects(context) {
  8737. if (this.test.hasEffects(context))
  8738. return true;
  8739. const { brokenFlow, ignore: { breaks, continues } } = context;
  8740. context.ignore.breaks = true;
  8741. context.ignore.continues = true;
  8742. if (this.body.hasEffects(context))
  8743. return true;
  8744. context.ignore.breaks = breaks;
  8745. context.ignore.continues = continues;
  8746. context.brokenFlow = brokenFlow;
  8747. return false;
  8748. }
  8749. include(context, includeChildrenRecursively) {
  8750. this.included = true;
  8751. this.test.include(context, includeChildrenRecursively);
  8752. const { brokenFlow } = context;
  8753. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8754. context.brokenFlow = brokenFlow;
  8755. }
  8756. }
  8757. class EmptyStatement extends NodeBase {
  8758. hasEffects() {
  8759. return false;
  8760. }
  8761. }
  8762. class ExportAllDeclaration extends NodeBase {
  8763. hasEffects() {
  8764. return false;
  8765. }
  8766. initialise() {
  8767. this.context.addExport(this);
  8768. }
  8769. render(code, _options, nodeRenderOptions) {
  8770. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8771. }
  8772. applyDeoptimizations() { }
  8773. }
  8774. ExportAllDeclaration.prototype.needsBoundaries = true;
  8775. class FunctionDeclaration extends FunctionNode {
  8776. initialise() {
  8777. super.initialise();
  8778. if (this.id !== null) {
  8779. this.id.variable.isId = true;
  8780. }
  8781. }
  8782. parseNode(esTreeNode) {
  8783. if (esTreeNode.id !== null) {
  8784. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8785. }
  8786. super.parseNode(esTreeNode);
  8787. }
  8788. }
  8789. // The header ends at the first non-white-space after "default"
  8790. function getDeclarationStart(code, start) {
  8791. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8792. }
  8793. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  8794. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  8795. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  8796. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8797. if (generatorStarPos === -1) {
  8798. return declarationEnd;
  8799. }
  8800. return declarationEnd + generatorStarPos + 1;
  8801. }
  8802. class ExportDefaultDeclaration extends NodeBase {
  8803. include(context, includeChildrenRecursively) {
  8804. super.include(context, includeChildrenRecursively);
  8805. if (includeChildrenRecursively) {
  8806. this.context.includeVariableInModule(this.variable);
  8807. }
  8808. }
  8809. initialise() {
  8810. const declaration = this.declaration;
  8811. this.declarationName =
  8812. (declaration.id && declaration.id.name) || this.declaration.name;
  8813. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  8814. this.context.addExport(this);
  8815. }
  8816. render(code, options, nodeRenderOptions) {
  8817. const { start, end } = nodeRenderOptions;
  8818. const declarationStart = getDeclarationStart(code.original, this.start);
  8819. if (this.declaration instanceof FunctionDeclaration) {
  8820. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  8821. }
  8822. else if (this.declaration instanceof ClassDeclaration) {
  8823. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  8824. }
  8825. else if (this.variable.getOriginalVariable() !== this.variable) {
  8826. // Remove altogether to prevent re-declaring the same variable
  8827. treeshakeNode(this, code, start, end);
  8828. return;
  8829. }
  8830. else if (this.variable.included) {
  8831. this.renderVariableDeclaration(code, declarationStart, options);
  8832. }
  8833. else {
  8834. code.remove(this.start, declarationStart);
  8835. this.declaration.render(code, options, {
  8836. renderedSurroundingElement: ExpressionStatement$1
  8837. });
  8838. if (code.original[this.end - 1] !== ';') {
  8839. code.appendLeft(this.end, ';');
  8840. }
  8841. return;
  8842. }
  8843. this.declaration.render(code, options);
  8844. }
  8845. applyDeoptimizations() { }
  8846. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  8847. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8848. const name = this.variable.getName(getPropertyAccess);
  8849. // Remove `export default`
  8850. code.remove(this.start, declarationStart);
  8851. if (needsId) {
  8852. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  8853. }
  8854. if (format === 'system' &&
  8855. this.declaration instanceof ClassDeclaration &&
  8856. exportNamesByVariable.has(this.variable)) {
  8857. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8858. }
  8859. }
  8860. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  8861. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  8862. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  8863. if (systemExportNames) {
  8864. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  8865. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  8866. }
  8867. else {
  8868. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  8869. if (!hasTrailingSemicolon) {
  8870. code.appendLeft(this.end, ';');
  8871. }
  8872. }
  8873. }
  8874. }
  8875. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  8876. class ExportNamedDeclaration extends NodeBase {
  8877. bind() {
  8878. var _a;
  8879. // Do not bind specifiers
  8880. (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
  8881. }
  8882. hasEffects(context) {
  8883. var _a;
  8884. return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  8885. }
  8886. initialise() {
  8887. this.context.addExport(this);
  8888. }
  8889. render(code, options, nodeRenderOptions) {
  8890. const { start, end } = nodeRenderOptions;
  8891. if (this.declaration === null) {
  8892. code.remove(start, end);
  8893. }
  8894. else {
  8895. code.remove(this.start, this.declaration.start);
  8896. this.declaration.render(code, options, { end, start });
  8897. }
  8898. }
  8899. applyDeoptimizations() { }
  8900. }
  8901. ExportNamedDeclaration.prototype.needsBoundaries = true;
  8902. class ExportSpecifier extends NodeBase {
  8903. applyDeoptimizations() { }
  8904. }
  8905. class ForInStatement extends NodeBase {
  8906. createScope(parentScope) {
  8907. this.scope = new BlockScope(parentScope);
  8908. }
  8909. hasEffects(context) {
  8910. const { deoptimized, left, right } = this;
  8911. if (!deoptimized)
  8912. this.applyDeoptimizations();
  8913. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  8914. return true;
  8915. const { brokenFlow, ignore: { breaks, continues } } = context;
  8916. context.ignore.breaks = true;
  8917. context.ignore.continues = true;
  8918. if (this.body.hasEffects(context))
  8919. return true;
  8920. context.ignore.breaks = breaks;
  8921. context.ignore.continues = continues;
  8922. context.brokenFlow = brokenFlow;
  8923. return false;
  8924. }
  8925. include(context, includeChildrenRecursively) {
  8926. const { body, deoptimized, left, right } = this;
  8927. if (!deoptimized)
  8928. this.applyDeoptimizations();
  8929. this.included = true;
  8930. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8931. right.include(context, includeChildrenRecursively);
  8932. const { brokenFlow } = context;
  8933. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8934. context.brokenFlow = brokenFlow;
  8935. }
  8936. initialise() {
  8937. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8938. }
  8939. render(code, options) {
  8940. this.left.render(code, options, NO_SEMICOLON);
  8941. this.right.render(code, options, NO_SEMICOLON);
  8942. // handle no space between "in" and the right side
  8943. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  8944. code.prependLeft(this.right.start, ' ');
  8945. }
  8946. this.body.render(code, options);
  8947. }
  8948. applyDeoptimizations() {
  8949. this.deoptimized = true;
  8950. this.left.deoptimizePath(EMPTY_PATH);
  8951. this.context.requestTreeshakingPass();
  8952. }
  8953. }
  8954. class ForOfStatement extends NodeBase {
  8955. createScope(parentScope) {
  8956. this.scope = new BlockScope(parentScope);
  8957. }
  8958. hasEffects() {
  8959. if (!this.deoptimized)
  8960. this.applyDeoptimizations();
  8961. // Placeholder until proper Symbol.Iterator support
  8962. return true;
  8963. }
  8964. include(context, includeChildrenRecursively) {
  8965. const { body, deoptimized, left, right } = this;
  8966. if (!deoptimized)
  8967. this.applyDeoptimizations();
  8968. this.included = true;
  8969. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8970. right.include(context, includeChildrenRecursively);
  8971. const { brokenFlow } = context;
  8972. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8973. context.brokenFlow = brokenFlow;
  8974. }
  8975. initialise() {
  8976. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8977. }
  8978. render(code, options) {
  8979. this.left.render(code, options, NO_SEMICOLON);
  8980. this.right.render(code, options, NO_SEMICOLON);
  8981. // handle no space between "of" and the right side
  8982. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  8983. code.prependLeft(this.right.start, ' ');
  8984. }
  8985. this.body.render(code, options);
  8986. }
  8987. applyDeoptimizations() {
  8988. this.deoptimized = true;
  8989. this.left.deoptimizePath(EMPTY_PATH);
  8990. this.context.requestTreeshakingPass();
  8991. }
  8992. }
  8993. class ForStatement extends NodeBase {
  8994. createScope(parentScope) {
  8995. this.scope = new BlockScope(parentScope);
  8996. }
  8997. hasEffects(context) {
  8998. var _a, _b, _c;
  8999. if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
  9000. ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
  9001. ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
  9002. return true;
  9003. const { brokenFlow, ignore: { breaks, continues } } = context;
  9004. context.ignore.breaks = true;
  9005. context.ignore.continues = true;
  9006. if (this.body.hasEffects(context))
  9007. return true;
  9008. context.ignore.breaks = breaks;
  9009. context.ignore.continues = continues;
  9010. context.brokenFlow = brokenFlow;
  9011. return false;
  9012. }
  9013. include(context, includeChildrenRecursively) {
  9014. var _a, _b, _c;
  9015. this.included = true;
  9016. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9017. (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  9018. const { brokenFlow } = context;
  9019. (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
  9020. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9021. context.brokenFlow = brokenFlow;
  9022. }
  9023. render(code, options) {
  9024. var _a, _b, _c;
  9025. (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
  9026. (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
  9027. (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
  9028. this.body.render(code, options);
  9029. }
  9030. }
  9031. class FunctionExpression extends FunctionNode {
  9032. render(code, options, { renderedSurroundingElement } = BLANK) {
  9033. super.render(code, options);
  9034. if (renderedSurroundingElement === ExpressionStatement$1) {
  9035. code.appendRight(this.start, '(');
  9036. code.prependLeft(this.end, ')');
  9037. }
  9038. }
  9039. }
  9040. class TrackingScope extends BlockScope {
  9041. constructor() {
  9042. super(...arguments);
  9043. this.hoistedDeclarations = [];
  9044. }
  9045. addDeclaration(identifier, context, init, isHoisted) {
  9046. this.hoistedDeclarations.push(identifier);
  9047. return super.addDeclaration(identifier, context, init, isHoisted);
  9048. }
  9049. }
  9050. const unset = Symbol('unset');
  9051. class IfStatement extends NodeBase {
  9052. constructor() {
  9053. super(...arguments);
  9054. this.testValue = unset;
  9055. }
  9056. deoptimizeCache() {
  9057. this.testValue = UnknownValue;
  9058. }
  9059. hasEffects(context) {
  9060. var _a;
  9061. if (this.test.hasEffects(context)) {
  9062. return true;
  9063. }
  9064. const testValue = this.getTestValue();
  9065. if (typeof testValue === 'symbol') {
  9066. const { brokenFlow } = context;
  9067. if (this.consequent.hasEffects(context))
  9068. return true;
  9069. const consequentBrokenFlow = context.brokenFlow;
  9070. context.brokenFlow = brokenFlow;
  9071. if (this.alternate === null)
  9072. return false;
  9073. if (this.alternate.hasEffects(context))
  9074. return true;
  9075. context.brokenFlow =
  9076. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9077. return false;
  9078. }
  9079. return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9080. }
  9081. include(context, includeChildrenRecursively) {
  9082. this.included = true;
  9083. if (includeChildrenRecursively) {
  9084. this.includeRecursively(includeChildrenRecursively, context);
  9085. }
  9086. else {
  9087. const testValue = this.getTestValue();
  9088. if (typeof testValue === 'symbol') {
  9089. this.includeUnknownTest(context);
  9090. }
  9091. else {
  9092. this.includeKnownTest(context, testValue);
  9093. }
  9094. }
  9095. }
  9096. parseNode(esTreeNode) {
  9097. this.consequentScope = new TrackingScope(this.scope);
  9098. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  9099. if (esTreeNode.alternate) {
  9100. this.alternateScope = new TrackingScope(this.scope);
  9101. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  9102. }
  9103. super.parseNode(esTreeNode);
  9104. }
  9105. render(code, options) {
  9106. const { snippets: { getPropertyAccess } } = options;
  9107. // Note that unknown test values are always included
  9108. const testValue = this.getTestValue();
  9109. const hoistedDeclarations = [];
  9110. const includesIfElse = this.test.included;
  9111. const noTreeshake = !this.context.options.treeshake;
  9112. if (includesIfElse) {
  9113. this.test.render(code, options);
  9114. }
  9115. else {
  9116. code.remove(this.start, this.consequent.start);
  9117. }
  9118. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9119. this.consequent.render(code, options);
  9120. }
  9121. else {
  9122. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9123. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9124. }
  9125. if (this.alternate) {
  9126. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9127. if (includesIfElse) {
  9128. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9129. code.prependLeft(this.alternate.start, ' ');
  9130. }
  9131. }
  9132. else {
  9133. code.remove(this.consequent.end, this.alternate.start);
  9134. }
  9135. this.alternate.render(code, options);
  9136. }
  9137. else {
  9138. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9139. code.overwrite(this.alternate.start, this.end, ';');
  9140. }
  9141. else {
  9142. code.remove(this.consequent.end, this.end);
  9143. }
  9144. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9145. }
  9146. }
  9147. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9148. }
  9149. applyDeoptimizations() { }
  9150. getTestValue() {
  9151. if (this.testValue === unset) {
  9152. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9153. }
  9154. return this.testValue;
  9155. }
  9156. includeKnownTest(context, testValue) {
  9157. var _a;
  9158. if (this.test.shouldBeIncluded(context)) {
  9159. this.test.include(context, false);
  9160. }
  9161. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9162. this.consequent.include(context, false, { asSingleStatement: true });
  9163. }
  9164. if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
  9165. this.alternate.include(context, false, { asSingleStatement: true });
  9166. }
  9167. }
  9168. includeRecursively(includeChildrenRecursively, context) {
  9169. var _a;
  9170. this.test.include(context, includeChildrenRecursively);
  9171. this.consequent.include(context, includeChildrenRecursively);
  9172. (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  9173. }
  9174. includeUnknownTest(context) {
  9175. var _a;
  9176. this.test.include(context, false);
  9177. const { brokenFlow } = context;
  9178. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  9179. if (this.consequent.shouldBeIncluded(context)) {
  9180. this.consequent.include(context, false, { asSingleStatement: true });
  9181. consequentBrokenFlow = context.brokenFlow;
  9182. context.brokenFlow = brokenFlow;
  9183. }
  9184. if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
  9185. this.alternate.include(context, false, { asSingleStatement: true });
  9186. context.brokenFlow =
  9187. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9188. }
  9189. }
  9190. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9191. const hoistedVars = [
  9192. ...new Set(hoistedDeclarations.map(identifier => {
  9193. const variable = identifier.variable;
  9194. return variable.included ? variable.getName(getPropertyAccess) : '';
  9195. }))
  9196. ]
  9197. .filter(Boolean)
  9198. .join(', ');
  9199. if (hoistedVars) {
  9200. const parentType = this.parent.type;
  9201. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9202. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  9203. if (needsBraces) {
  9204. code.appendLeft(this.end, ` }`);
  9205. }
  9206. }
  9207. }
  9208. shouldKeepAlternateBranch() {
  9209. let currentParent = this.parent;
  9210. do {
  9211. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9212. return true;
  9213. }
  9214. if (currentParent instanceof BlockStatement) {
  9215. return false;
  9216. }
  9217. currentParent = currentParent.parent;
  9218. } while (currentParent);
  9219. return false;
  9220. }
  9221. }
  9222. class ImportDeclaration extends NodeBase {
  9223. // Do not bind specifiers
  9224. bind() { }
  9225. hasEffects() {
  9226. return false;
  9227. }
  9228. initialise() {
  9229. this.context.addImport(this);
  9230. }
  9231. render(code, _options, nodeRenderOptions) {
  9232. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9233. }
  9234. applyDeoptimizations() { }
  9235. }
  9236. ImportDeclaration.prototype.needsBoundaries = true;
  9237. class ImportDefaultSpecifier extends NodeBase {
  9238. applyDeoptimizations() { }
  9239. }
  9240. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9241. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  9242. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9243. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9244. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9245. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9246. const defaultInteropHelpersByInteropType = {
  9247. auto: INTEROP_DEFAULT_VARIABLE,
  9248. default: null,
  9249. defaultOnly: null,
  9250. esModule: null,
  9251. false: null,
  9252. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  9253. };
  9254. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9255. (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
  9256. const namespaceInteropHelpersByInteropType = {
  9257. auto: INTEROP_NAMESPACE_VARIABLE,
  9258. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9259. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9260. esModule: null,
  9261. false: null,
  9262. true: INTEROP_NAMESPACE_VARIABLE
  9263. };
  9264. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
  9265. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
  9266. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9267. const usedHelpers = new Set(additionalHelpers);
  9268. for (const variable of HELPER_NAMES) {
  9269. if (accessedGlobals.has(variable)) {
  9270. usedHelpers.add(variable);
  9271. }
  9272. }
  9273. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9274. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  9275. : '').join('');
  9276. };
  9277. const HELPER_GENERATORS = {
  9278. [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
  9279. const { _, getDirectReturnFunction, n } = snippets;
  9280. const [left, right] = getDirectReturnFunction(['e'], {
  9281. functionReturn: true,
  9282. lineBreakIndent: null,
  9283. name: INTEROP_DEFAULT_LEGACY_VARIABLE
  9284. });
  9285. return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  9286. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9287. },
  9288. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9289. const { _, getDirectReturnFunction, n } = snippets;
  9290. const [left, right] = getDirectReturnFunction(['e'], {
  9291. functionReturn: true,
  9292. lineBreakIndent: null,
  9293. name: INTEROP_DEFAULT_VARIABLE
  9294. });
  9295. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9296. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9297. },
  9298. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  9299. const { getDirectReturnFunction, getObject, n } = snippets;
  9300. const [left, right] = getDirectReturnFunction(['e'], {
  9301. functionReturn: true,
  9302. lineBreakIndent: null,
  9303. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9304. });
  9305. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  9306. ['__proto__', 'null'],
  9307. ['default', 'e']
  9308. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9309. },
  9310. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9311. const { _, n } = snippets;
  9312. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9313. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9314. `}${n}${n}`);
  9315. },
  9316. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  9317. const { _, getDirectReturnFunction, n } = snippets;
  9318. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9319. const [left, right] = getDirectReturnFunction(['e'], {
  9320. functionReturn: true,
  9321. lineBreakIndent: null,
  9322. name: INTEROP_NAMESPACE_VARIABLE
  9323. });
  9324. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9325. }
  9326. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9327. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9328. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9329. `}${n}${n}`);
  9330. },
  9331. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9332. const { _, cnst, n } = snippets;
  9333. const useForEach = cnst === 'var' && liveBindings;
  9334. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9335. `${t}${loopOverNamespaces(`{${n}` +
  9336. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9337. (liveBindings
  9338. ? useForEach
  9339. ? copyOwnPropertyLiveBinding
  9340. : copyPropertyLiveBinding
  9341. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9342. `${t}${t}${t}}${n}` +
  9343. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9344. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  9345. `}${n}${n}`);
  9346. }
  9347. };
  9348. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9349. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9350. const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9351. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9352. const copyProperty = `{${n}` +
  9353. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
  9354. `${i}${t}}`;
  9355. return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  9356. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  9357. : ''});${n}` +
  9358. `${i}if${_}(e)${_}{${n}` +
  9359. `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9360. `${i}}${n}` +
  9361. `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9362. `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9363. };
  9364. const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
  9365. ? `for${_}(${cnst} k in e)${_}${body}`
  9366. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9367. isAsync: false,
  9368. name: null
  9369. })}${body})${s}`;
  9370. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9371. if (useForEach) {
  9372. const [left, right] = getDirectReturnFunction(['e'], {
  9373. functionReturn: false,
  9374. lineBreakIndent: { base: t, t },
  9375. name: null
  9376. });
  9377. return (`m.forEach(${left}` +
  9378. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9379. isAsync: false,
  9380. name: null
  9381. })}${body})${right});`);
  9382. }
  9383. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9384. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9385. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9386. };
  9387. const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
  9388. const { _, n } = snippets;
  9389. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9390. copyOwnPropertyLiveBinding(t, i + t, snippets) +
  9391. `${i}}${n}`);
  9392. };
  9393. const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9394. const [left, right] = getDirectReturnFunction([], {
  9395. functionReturn: true,
  9396. lineBreakIndent: null,
  9397. name: null
  9398. });
  9399. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9400. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9401. `${i}${t}enumerable:${_}true,${n}` +
  9402. `${i}${t}get:${_}${left}e[k]${right}${n}` +
  9403. `${i}});${n}`);
  9404. };
  9405. const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9406. const [left, right] = getDirectReturnFunction([], {
  9407. functionReturn: true,
  9408. lineBreakIndent: null,
  9409. name: null
  9410. });
  9411. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9412. `${i}if${_}(d)${_}{${n}` +
  9413. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9414. `${i}${t}${t}enumerable:${_}true,${n}` +
  9415. `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9416. `${i}${t}});${n}` +
  9417. `${i}}${n}`);
  9418. };
  9419. const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
  9420. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9421. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  9422. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9423. : fragment;
  9424. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9425. function getToStringTagValue(getObject) {
  9426. return getObject([['value', "'Module'"]], {
  9427. lineBreakIndent: null
  9428. });
  9429. }
  9430. class ImportExpression extends NodeBase {
  9431. constructor() {
  9432. super(...arguments);
  9433. this.inlineNamespace = null;
  9434. this.mechanism = null;
  9435. this.resolution = null;
  9436. }
  9437. hasEffects() {
  9438. return true;
  9439. }
  9440. include(context, includeChildrenRecursively) {
  9441. if (!this.included) {
  9442. this.included = true;
  9443. this.context.includeDynamicImport(this);
  9444. this.scope.addAccessedDynamicImport(this);
  9445. }
  9446. this.source.include(context, includeChildrenRecursively);
  9447. }
  9448. initialise() {
  9449. this.context.addDynamicImport(this);
  9450. }
  9451. render(code, options) {
  9452. if (this.inlineNamespace) {
  9453. const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
  9454. const [left, right] = getDirectReturnFunction([], {
  9455. functionReturn: true,
  9456. lineBreakIndent: null,
  9457. name: null
  9458. });
  9459. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
  9460. return;
  9461. }
  9462. if (this.mechanism) {
  9463. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  9464. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  9465. }
  9466. this.source.render(code, options);
  9467. }
  9468. renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
  9469. code.overwrite(this.source.start, this.source.end, resolution);
  9470. if (namespaceExportName) {
  9471. const [left, right] = getDirectReturnFunction(['n'], {
  9472. functionReturn: true,
  9473. lineBreakIndent: null,
  9474. name: null
  9475. });
  9476. code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
  9477. }
  9478. }
  9479. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
  9480. const { format } = options;
  9481. this.inlineNamespace = null;
  9482. this.resolution = resolution;
  9483. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9484. let helper;
  9485. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9486. if (helper) {
  9487. accessedGlobals.push(helper);
  9488. }
  9489. if (accessedGlobals.length > 0) {
  9490. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9491. }
  9492. }
  9493. setInternalResolution(inlineNamespace) {
  9494. this.inlineNamespace = inlineNamespace;
  9495. }
  9496. applyDeoptimizations() { }
  9497. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9498. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9499. {
  9500. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9501. format,
  9502. moduleId: this.context.module.id,
  9503. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9504. }
  9505. ]);
  9506. if (mechanism) {
  9507. return { helper: null, mechanism };
  9508. }
  9509. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9510. switch (format) {
  9511. case 'cjs': {
  9512. const helper = getInteropHelper(resolution, exportMode, interop);
  9513. let left = `require(`;
  9514. let right = `)`;
  9515. if (helper) {
  9516. left = `/*#__PURE__*/${helper}(${left}`;
  9517. right += ')';
  9518. }
  9519. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9520. functionReturn: true,
  9521. lineBreakIndent: null,
  9522. name: null
  9523. });
  9524. left = `Promise.resolve().then(${functionLeft}${left}`;
  9525. right += `${functionRight})`;
  9526. if (!arrowFunctions && hasDynamicTarget) {
  9527. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9528. needsArrowReturnParens: false,
  9529. needsWrappedFunction: true
  9530. });
  9531. right = ')';
  9532. }
  9533. return {
  9534. helper,
  9535. mechanism: { left, right }
  9536. };
  9537. }
  9538. case 'amd': {
  9539. const resolve = compact ? 'c' : 'resolve';
  9540. const reject = compact ? 'e' : 'reject';
  9541. const helper = getInteropHelper(resolution, exportMode, interop);
  9542. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9543. functionReturn: false,
  9544. lineBreakIndent: null,
  9545. name: null
  9546. });
  9547. const resolveNamespace = helper
  9548. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9549. : resolve;
  9550. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9551. functionReturn: false,
  9552. lineBreakIndent: null,
  9553. name: null
  9554. });
  9555. let left = `new Promise(${handlerLeft}require([`;
  9556. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9557. if (!arrowFunctions && hasDynamicTarget) {
  9558. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9559. needsArrowReturnParens: false,
  9560. needsWrappedFunction: true
  9561. });
  9562. right = ')';
  9563. }
  9564. return {
  9565. helper,
  9566. mechanism: { left, right }
  9567. };
  9568. }
  9569. case 'system':
  9570. return {
  9571. helper: null,
  9572. mechanism: {
  9573. left: 'module.import(',
  9574. right: ')'
  9575. }
  9576. };
  9577. case 'es':
  9578. if (dynamicImportFunction) {
  9579. return {
  9580. helper: null,
  9581. mechanism: {
  9582. left: `${dynamicImportFunction}(`,
  9583. right: ')'
  9584. }
  9585. };
  9586. }
  9587. }
  9588. return { helper: null, mechanism: null };
  9589. }
  9590. }
  9591. function getInteropHelper(resolution, exportMode, interop) {
  9592. return exportMode === 'external'
  9593. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  9594. : exportMode === 'default'
  9595. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9596. : null;
  9597. }
  9598. const accessedImportGlobals = {
  9599. amd: ['require'],
  9600. cjs: ['require'],
  9601. system: ['module']
  9602. };
  9603. class ImportNamespaceSpecifier extends NodeBase {
  9604. applyDeoptimizations() { }
  9605. }
  9606. class ImportSpecifier extends NodeBase {
  9607. applyDeoptimizations() { }
  9608. }
  9609. class LabeledStatement extends NodeBase {
  9610. hasEffects(context) {
  9611. const brokenFlow = context.brokenFlow;
  9612. context.ignore.labels.add(this.label.name);
  9613. if (this.body.hasEffects(context))
  9614. return true;
  9615. context.ignore.labels.delete(this.label.name);
  9616. if (context.includedLabels.has(this.label.name)) {
  9617. context.includedLabels.delete(this.label.name);
  9618. context.brokenFlow = brokenFlow;
  9619. }
  9620. return false;
  9621. }
  9622. include(context, includeChildrenRecursively) {
  9623. this.included = true;
  9624. const brokenFlow = context.brokenFlow;
  9625. this.body.include(context, includeChildrenRecursively);
  9626. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9627. this.label.include();
  9628. context.includedLabels.delete(this.label.name);
  9629. context.brokenFlow = brokenFlow;
  9630. }
  9631. }
  9632. render(code, options) {
  9633. if (this.label.included) {
  9634. this.label.render(code, options);
  9635. }
  9636. else {
  9637. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9638. }
  9639. this.body.render(code, options);
  9640. }
  9641. }
  9642. class LogicalExpression extends NodeBase {
  9643. constructor() {
  9644. super(...arguments);
  9645. // We collect deoptimization information if usedBranch !== null
  9646. this.expressionsToBeDeoptimized = [];
  9647. this.isBranchResolutionAnalysed = false;
  9648. this.usedBranch = null;
  9649. }
  9650. deoptimizeCache() {
  9651. if (this.usedBranch) {
  9652. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9653. this.usedBranch = null;
  9654. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9655. for (const expression of this.expressionsToBeDeoptimized) {
  9656. expression.deoptimizeCache();
  9657. }
  9658. // Request another pass because we need to ensure "include" runs again if
  9659. // it is rendered
  9660. this.context.requestTreeshakingPass();
  9661. }
  9662. }
  9663. deoptimizePath(path) {
  9664. const usedBranch = this.getUsedBranch();
  9665. if (!usedBranch) {
  9666. this.left.deoptimizePath(path);
  9667. this.right.deoptimizePath(path);
  9668. }
  9669. else {
  9670. usedBranch.deoptimizePath(path);
  9671. }
  9672. }
  9673. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9674. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9675. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9676. }
  9677. getLiteralValueAtPath(path, recursionTracker, origin) {
  9678. const usedBranch = this.getUsedBranch();
  9679. if (!usedBranch)
  9680. return UnknownValue;
  9681. this.expressionsToBeDeoptimized.push(origin);
  9682. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9683. }
  9684. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9685. const usedBranch = this.getUsedBranch();
  9686. if (!usedBranch)
  9687. return new MultiExpression([
  9688. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  9689. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  9690. ]);
  9691. this.expressionsToBeDeoptimized.push(origin);
  9692. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9693. }
  9694. hasEffects(context) {
  9695. if (this.left.hasEffects(context)) {
  9696. return true;
  9697. }
  9698. if (this.getUsedBranch() !== this.left) {
  9699. return this.right.hasEffects(context);
  9700. }
  9701. return false;
  9702. }
  9703. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9704. const usedBranch = this.getUsedBranch();
  9705. if (!usedBranch) {
  9706. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9707. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  9708. }
  9709. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9710. }
  9711. include(context, includeChildrenRecursively) {
  9712. this.included = true;
  9713. const usedBranch = this.getUsedBranch();
  9714. if (includeChildrenRecursively ||
  9715. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  9716. !usedBranch) {
  9717. this.left.include(context, includeChildrenRecursively);
  9718. this.right.include(context, includeChildrenRecursively);
  9719. }
  9720. else {
  9721. usedBranch.include(context, includeChildrenRecursively);
  9722. }
  9723. }
  9724. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9725. if (!this.left.included || !this.right.included) {
  9726. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  9727. if (this.right.included) {
  9728. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  9729. code.remove(this.start, removePos);
  9730. if (preventASI) {
  9731. removeLineBreaks(code, removePos, this.right.start);
  9732. }
  9733. }
  9734. else {
  9735. code.remove(operatorPos, this.end);
  9736. }
  9737. removeAnnotations(this, code);
  9738. this.getUsedBranch().render(code, options, {
  9739. isCalleeOfRenderedParent,
  9740. preventASI,
  9741. renderedParentType: renderedParentType || this.parent.type,
  9742. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9743. });
  9744. }
  9745. else {
  9746. this.left.render(code, options, {
  9747. preventASI,
  9748. renderedSurroundingElement
  9749. });
  9750. this.right.render(code, options);
  9751. }
  9752. }
  9753. getUsedBranch() {
  9754. if (!this.isBranchResolutionAnalysed) {
  9755. this.isBranchResolutionAnalysed = true;
  9756. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9757. if (typeof leftValue === 'symbol') {
  9758. return null;
  9759. }
  9760. else {
  9761. this.usedBranch =
  9762. (this.operator === '||' && leftValue) ||
  9763. (this.operator === '&&' && !leftValue) ||
  9764. (this.operator === '??' && leftValue != null)
  9765. ? this.left
  9766. : this.right;
  9767. }
  9768. }
  9769. return this.usedBranch;
  9770. }
  9771. }
  9772. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  9773. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  9774. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  9775. class MetaProperty extends NodeBase {
  9776. addAccessedGlobals(format, accessedGlobalsByScope) {
  9777. const metaProperty = this.metaProperty;
  9778. const accessedGlobals = (metaProperty &&
  9779. (metaProperty.startsWith(FILE_PREFIX) ||
  9780. metaProperty.startsWith(ASSET_PREFIX) ||
  9781. metaProperty.startsWith(CHUNK_PREFIX))
  9782. ? accessedFileUrlGlobals
  9783. : accessedMetaUrlGlobals)[format];
  9784. if (accessedGlobals.length > 0) {
  9785. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9786. }
  9787. }
  9788. getReferencedFileName(outputPluginDriver) {
  9789. const metaProperty = this.metaProperty;
  9790. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  9791. return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
  9792. }
  9793. return null;
  9794. }
  9795. hasEffects() {
  9796. return false;
  9797. }
  9798. hasEffectsOnInteractionAtPath(path, { type }) {
  9799. return path.length > 1 || type !== INTERACTION_ACCESSED;
  9800. }
  9801. include() {
  9802. if (!this.included) {
  9803. this.included = true;
  9804. if (this.meta.name === 'import') {
  9805. this.context.addImportMeta(this);
  9806. const parent = this.parent;
  9807. this.metaProperty =
  9808. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  9809. ? parent.propertyKey
  9810. : null;
  9811. }
  9812. }
  9813. }
  9814. renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
  9815. var _a;
  9816. const parent = this.parent;
  9817. const metaProperty = this.metaProperty;
  9818. if (metaProperty &&
  9819. (metaProperty.startsWith(FILE_PREFIX) ||
  9820. metaProperty.startsWith(ASSET_PREFIX) ||
  9821. metaProperty.startsWith(CHUNK_PREFIX))) {
  9822. let referenceId = null;
  9823. let assetReferenceId = null;
  9824. let chunkReferenceId = null;
  9825. let fileName;
  9826. if (metaProperty.startsWith(FILE_PREFIX)) {
  9827. referenceId = metaProperty.substring(FILE_PREFIX.length);
  9828. fileName = outputPluginDriver.getFileName(referenceId);
  9829. }
  9830. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  9831. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9832. assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
  9833. fileName = outputPluginDriver.getFileName(assetReferenceId);
  9834. }
  9835. else {
  9836. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9837. chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
  9838. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  9839. }
  9840. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  9841. let replacement;
  9842. if (assetReferenceId !== null) {
  9843. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  9844. {
  9845. assetFileName: fileName,
  9846. chunkId,
  9847. format,
  9848. moduleId: this.context.module.id,
  9849. relativeAssetPath: relativePath
  9850. }
  9851. ]);
  9852. }
  9853. if (!replacement) {
  9854. replacement =
  9855. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  9856. {
  9857. assetReferenceId,
  9858. chunkId,
  9859. chunkReferenceId,
  9860. fileName,
  9861. format,
  9862. moduleId: this.context.module.id,
  9863. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  9864. relativePath
  9865. }
  9866. ]) || relativeUrlMechanisms[format](relativePath);
  9867. }
  9868. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9869. return;
  9870. }
  9871. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  9872. metaProperty,
  9873. {
  9874. chunkId,
  9875. format,
  9876. moduleId: this.context.module.id
  9877. }
  9878. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
  9879. if (typeof replacement === 'string') {
  9880. if (parent instanceof MemberExpression) {
  9881. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9882. }
  9883. else {
  9884. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  9885. }
  9886. }
  9887. }
  9888. }
  9889. const accessedMetaUrlGlobals = {
  9890. amd: ['document', 'module', 'URL'],
  9891. cjs: ['document', 'require', 'URL'],
  9892. es: [],
  9893. iife: ['document', 'URL'],
  9894. system: ['module'],
  9895. umd: ['document', 'require', 'URL']
  9896. };
  9897. const accessedFileUrlGlobals = {
  9898. amd: ['document', 'require', 'URL'],
  9899. cjs: ['document', 'require', 'URL'],
  9900. es: [],
  9901. iife: ['document', 'URL'],
  9902. system: ['module', 'URL'],
  9903. umd: ['document', 'require', 'URL']
  9904. };
  9905. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  9906. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  9907. const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
  9908. const urlMechanism = getUrl(chunkId);
  9909. return prop === null
  9910. ? `({ url: ${urlMechanism} })`
  9911. : prop === 'url'
  9912. ? urlMechanism
  9913. : 'undefined';
  9914. };
  9915. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  9916. const relativeUrlMechanisms = {
  9917. amd: relativePath => {
  9918. if (relativePath[0] !== '.')
  9919. relativePath = './' + relativePath;
  9920. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  9921. },
  9922. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  9923. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  9924. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  9925. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  9926. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  9927. };
  9928. const importMetaMechanisms = {
  9929. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  9930. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  9931. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  9932. system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
  9933. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  9934. };
  9935. class NewExpression extends NodeBase {
  9936. hasEffects(context) {
  9937. try {
  9938. for (const argument of this.arguments) {
  9939. if (argument.hasEffects(context))
  9940. return true;
  9941. }
  9942. if (this.context.options.treeshake.annotations &&
  9943. this.annotations) {
  9944. return false;
  9945. }
  9946. return (this.callee.hasEffects(context) ||
  9947. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9948. }
  9949. finally {
  9950. if (!this.deoptimized)
  9951. this.applyDeoptimizations();
  9952. }
  9953. }
  9954. hasEffectsOnInteractionAtPath(path, { type }) {
  9955. return path.length > 0 || type !== INTERACTION_ACCESSED;
  9956. }
  9957. include(context, includeChildrenRecursively) {
  9958. if (!this.deoptimized)
  9959. this.applyDeoptimizations();
  9960. if (includeChildrenRecursively) {
  9961. super.include(context, includeChildrenRecursively);
  9962. }
  9963. else {
  9964. this.included = true;
  9965. this.callee.include(context, false);
  9966. }
  9967. this.callee.includeCallArguments(context, this.arguments);
  9968. }
  9969. initialise() {
  9970. this.interaction = {
  9971. args: this.arguments,
  9972. thisArg: null,
  9973. type: INTERACTION_CALLED,
  9974. withNew: true
  9975. };
  9976. }
  9977. render(code, options) {
  9978. this.callee.render(code, options);
  9979. renderCallArguments(code, options, this);
  9980. }
  9981. applyDeoptimizations() {
  9982. this.deoptimized = true;
  9983. for (const argument of this.arguments) {
  9984. // This will make sure all properties of parameters behave as "unknown"
  9985. argument.deoptimizePath(UNKNOWN_PATH);
  9986. }
  9987. this.context.requestTreeshakingPass();
  9988. }
  9989. }
  9990. class ObjectExpression extends NodeBase {
  9991. constructor() {
  9992. super(...arguments);
  9993. this.objectEntity = null;
  9994. }
  9995. deoptimizeCache() {
  9996. this.getObjectEntity().deoptimizeAllProperties();
  9997. }
  9998. deoptimizePath(path) {
  9999. this.getObjectEntity().deoptimizePath(path);
  10000. }
  10001. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10002. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10003. }
  10004. getLiteralValueAtPath(path, recursionTracker, origin) {
  10005. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10006. }
  10007. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10008. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10009. }
  10010. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10011. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10012. }
  10013. render(code, options, { renderedSurroundingElement } = BLANK) {
  10014. super.render(code, options);
  10015. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10016. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10017. code.appendRight(this.start, '(');
  10018. code.prependLeft(this.end, ')');
  10019. }
  10020. }
  10021. applyDeoptimizations() { }
  10022. getObjectEntity() {
  10023. if (this.objectEntity !== null) {
  10024. return this.objectEntity;
  10025. }
  10026. let prototype = OBJECT_PROTOTYPE;
  10027. const properties = [];
  10028. for (const property of this.properties) {
  10029. if (property instanceof SpreadElement) {
  10030. properties.push({ key: UnknownKey, kind: 'init', property });
  10031. continue;
  10032. }
  10033. let key;
  10034. if (property.computed) {
  10035. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10036. if (typeof keyValue === 'symbol') {
  10037. properties.push({ key: UnknownKey, kind: property.kind, property });
  10038. continue;
  10039. }
  10040. else {
  10041. key = String(keyValue);
  10042. }
  10043. }
  10044. else {
  10045. key =
  10046. property.key instanceof Identifier
  10047. ? property.key.name
  10048. : String(property.key.value);
  10049. if (key === '__proto__' && property.kind === 'init') {
  10050. prototype =
  10051. property.value instanceof Literal && property.value.value === null
  10052. ? null
  10053. : property.value;
  10054. continue;
  10055. }
  10056. }
  10057. properties.push({ key, kind: property.kind, property });
  10058. }
  10059. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10060. }
  10061. }
  10062. class PrivateIdentifier extends NodeBase {
  10063. }
  10064. class Program extends NodeBase {
  10065. constructor() {
  10066. super(...arguments);
  10067. this.hasCachedEffect = false;
  10068. }
  10069. hasEffects(context) {
  10070. // We are caching here to later more efficiently identify side-effect-free modules
  10071. if (this.hasCachedEffect)
  10072. return true;
  10073. for (const node of this.body) {
  10074. if (node.hasEffects(context)) {
  10075. return (this.hasCachedEffect = true);
  10076. }
  10077. }
  10078. return false;
  10079. }
  10080. include(context, includeChildrenRecursively) {
  10081. this.included = true;
  10082. for (const node of this.body) {
  10083. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10084. node.include(context, includeChildrenRecursively);
  10085. }
  10086. }
  10087. }
  10088. render(code, options) {
  10089. if (this.body.length) {
  10090. renderStatementList(this.body, code, this.start, this.end, options);
  10091. }
  10092. else {
  10093. super.render(code, options);
  10094. }
  10095. }
  10096. applyDeoptimizations() { }
  10097. }
  10098. class Property extends MethodBase {
  10099. constructor() {
  10100. super(...arguments);
  10101. this.declarationInit = null;
  10102. }
  10103. declare(kind, init) {
  10104. this.declarationInit = init;
  10105. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10106. }
  10107. hasEffects(context) {
  10108. if (!this.deoptimized)
  10109. this.applyDeoptimizations();
  10110. const propertyReadSideEffects = this.context.options.treeshake
  10111. .propertyReadSideEffects;
  10112. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10113. this.key.hasEffects(context) ||
  10114. this.value.hasEffects(context));
  10115. }
  10116. markDeclarationReached() {
  10117. this.value.markDeclarationReached();
  10118. }
  10119. render(code, options) {
  10120. if (!this.shorthand) {
  10121. this.key.render(code, options);
  10122. }
  10123. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10124. }
  10125. applyDeoptimizations() {
  10126. this.deoptimized = true;
  10127. if (this.declarationInit !== null) {
  10128. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10129. this.context.requestTreeshakingPass();
  10130. }
  10131. }
  10132. }
  10133. class PropertyDefinition extends NodeBase {
  10134. deoptimizePath(path) {
  10135. var _a;
  10136. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  10137. }
  10138. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10139. var _a;
  10140. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10141. }
  10142. getLiteralValueAtPath(path, recursionTracker, origin) {
  10143. return this.value
  10144. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10145. : UnknownValue;
  10146. }
  10147. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10148. return this.value
  10149. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10150. : UNKNOWN_EXPRESSION;
  10151. }
  10152. hasEffects(context) {
  10153. var _a;
  10154. return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10155. }
  10156. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10157. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10158. }
  10159. applyDeoptimizations() { }
  10160. }
  10161. class ReturnStatement extends NodeBase {
  10162. hasEffects(context) {
  10163. var _a;
  10164. if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
  10165. return true;
  10166. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10167. return false;
  10168. }
  10169. include(context, includeChildrenRecursively) {
  10170. var _a;
  10171. this.included = true;
  10172. (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10173. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10174. }
  10175. initialise() {
  10176. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10177. }
  10178. render(code, options) {
  10179. if (this.argument) {
  10180. this.argument.render(code, options, { preventASI: true });
  10181. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10182. code.prependLeft(this.start + 6, ' ');
  10183. }
  10184. }
  10185. }
  10186. }
  10187. class SequenceExpression extends NodeBase {
  10188. deoptimizePath(path) {
  10189. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10190. }
  10191. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10192. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10193. }
  10194. getLiteralValueAtPath(path, recursionTracker, origin) {
  10195. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10196. }
  10197. hasEffects(context) {
  10198. for (const expression of this.expressions) {
  10199. if (expression.hasEffects(context))
  10200. return true;
  10201. }
  10202. return false;
  10203. }
  10204. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10205. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10206. }
  10207. include(context, includeChildrenRecursively) {
  10208. this.included = true;
  10209. const lastExpression = this.expressions[this.expressions.length - 1];
  10210. for (const expression of this.expressions) {
  10211. if (includeChildrenRecursively ||
  10212. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10213. expression.shouldBeIncluded(context))
  10214. expression.include(context, includeChildrenRecursively);
  10215. }
  10216. }
  10217. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10218. let includedNodes = 0;
  10219. let lastSeparatorPos = null;
  10220. const lastNode = this.expressions[this.expressions.length - 1];
  10221. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10222. if (!node.included) {
  10223. treeshakeNode(node, code, start, end);
  10224. continue;
  10225. }
  10226. includedNodes++;
  10227. lastSeparatorPos = separator;
  10228. if (includedNodes === 1 && preventASI) {
  10229. removeLineBreaks(code, start, node.start);
  10230. }
  10231. if (includedNodes === 1) {
  10232. const parentType = renderedParentType || this.parent.type;
  10233. node.render(code, options, {
  10234. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10235. renderedParentType: parentType,
  10236. renderedSurroundingElement: parentType
  10237. });
  10238. }
  10239. else {
  10240. node.render(code, options);
  10241. }
  10242. }
  10243. if (lastSeparatorPos) {
  10244. code.remove(lastSeparatorPos, this.end);
  10245. }
  10246. }
  10247. }
  10248. class StaticBlock extends NodeBase {
  10249. createScope(parentScope) {
  10250. this.scope = new BlockScope(parentScope);
  10251. }
  10252. hasEffects(context) {
  10253. for (const node of this.body) {
  10254. if (node.hasEffects(context))
  10255. return true;
  10256. }
  10257. return false;
  10258. }
  10259. include(context, includeChildrenRecursively) {
  10260. this.included = true;
  10261. for (const node of this.body) {
  10262. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10263. node.include(context, includeChildrenRecursively);
  10264. }
  10265. }
  10266. render(code, options) {
  10267. if (this.body.length) {
  10268. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  10269. }
  10270. else {
  10271. super.render(code, options);
  10272. }
  10273. }
  10274. }
  10275. class Super extends NodeBase {
  10276. bind() {
  10277. this.variable = this.scope.findVariable('this');
  10278. }
  10279. deoptimizePath(path) {
  10280. this.variable.deoptimizePath(path);
  10281. }
  10282. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10283. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10284. }
  10285. include() {
  10286. if (!this.included) {
  10287. this.included = true;
  10288. this.context.includeVariableInModule(this.variable);
  10289. }
  10290. }
  10291. }
  10292. class SwitchCase extends NodeBase {
  10293. hasEffects(context) {
  10294. var _a;
  10295. if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
  10296. return true;
  10297. for (const node of this.consequent) {
  10298. if (context.brokenFlow)
  10299. break;
  10300. if (node.hasEffects(context))
  10301. return true;
  10302. }
  10303. return false;
  10304. }
  10305. include(context, includeChildrenRecursively) {
  10306. var _a;
  10307. this.included = true;
  10308. (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10309. for (const node of this.consequent) {
  10310. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10311. node.include(context, includeChildrenRecursively);
  10312. }
  10313. }
  10314. render(code, options, nodeRenderOptions) {
  10315. if (this.consequent.length) {
  10316. this.test && this.test.render(code, options);
  10317. const testEnd = this.test
  10318. ? this.test.end
  10319. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10320. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10321. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10322. }
  10323. else {
  10324. super.render(code, options);
  10325. }
  10326. }
  10327. }
  10328. SwitchCase.prototype.needsBoundaries = true;
  10329. class SwitchStatement extends NodeBase {
  10330. createScope(parentScope) {
  10331. this.scope = new BlockScope(parentScope);
  10332. }
  10333. hasEffects(context) {
  10334. if (this.discriminant.hasEffects(context))
  10335. return true;
  10336. const { brokenFlow, ignore: { breaks } } = context;
  10337. let minBrokenFlow = Infinity;
  10338. context.ignore.breaks = true;
  10339. for (const switchCase of this.cases) {
  10340. if (switchCase.hasEffects(context))
  10341. return true;
  10342. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  10343. context.brokenFlow = brokenFlow;
  10344. }
  10345. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10346. context.brokenFlow = minBrokenFlow;
  10347. }
  10348. context.ignore.breaks = breaks;
  10349. return false;
  10350. }
  10351. include(context, includeChildrenRecursively) {
  10352. this.included = true;
  10353. this.discriminant.include(context, includeChildrenRecursively);
  10354. const { brokenFlow } = context;
  10355. let minBrokenFlow = Infinity;
  10356. let isCaseIncluded = includeChildrenRecursively ||
  10357. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10358. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10359. const switchCase = this.cases[caseIndex];
  10360. if (switchCase.included) {
  10361. isCaseIncluded = true;
  10362. }
  10363. if (!isCaseIncluded) {
  10364. const hasEffectsContext = createHasEffectsContext();
  10365. hasEffectsContext.ignore.breaks = true;
  10366. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10367. }
  10368. if (isCaseIncluded) {
  10369. switchCase.include(context, includeChildrenRecursively);
  10370. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  10371. context.brokenFlow = brokenFlow;
  10372. }
  10373. else {
  10374. minBrokenFlow = brokenFlow;
  10375. }
  10376. }
  10377. if (isCaseIncluded &&
  10378. this.defaultCase !== null &&
  10379. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10380. context.brokenFlow = minBrokenFlow;
  10381. }
  10382. }
  10383. initialise() {
  10384. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10385. if (this.cases[caseIndex].test === null) {
  10386. this.defaultCase = caseIndex;
  10387. return;
  10388. }
  10389. }
  10390. this.defaultCase = null;
  10391. }
  10392. render(code, options) {
  10393. this.discriminant.render(code, options);
  10394. if (this.cases.length > 0) {
  10395. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10396. }
  10397. }
  10398. }
  10399. class TaggedTemplateExpression extends CallExpressionBase {
  10400. bind() {
  10401. super.bind();
  10402. if (this.tag.type === Identifier$1) {
  10403. const name = this.tag.name;
  10404. const variable = this.scope.findVariable(name);
  10405. if (variable.isNamespace) {
  10406. this.context.warn({
  10407. code: 'CANNOT_CALL_NAMESPACE',
  10408. message: `Cannot call a namespace ('${name}')`
  10409. }, this.start);
  10410. }
  10411. }
  10412. }
  10413. hasEffects(context) {
  10414. try {
  10415. for (const argument of this.quasi.expressions) {
  10416. if (argument.hasEffects(context))
  10417. return true;
  10418. }
  10419. return (this.tag.hasEffects(context) ||
  10420. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10421. }
  10422. finally {
  10423. if (!this.deoptimized)
  10424. this.applyDeoptimizations();
  10425. }
  10426. }
  10427. include(context, includeChildrenRecursively) {
  10428. if (!this.deoptimized)
  10429. this.applyDeoptimizations();
  10430. if (includeChildrenRecursively) {
  10431. super.include(context, includeChildrenRecursively);
  10432. }
  10433. else {
  10434. this.included = true;
  10435. this.tag.include(context, includeChildrenRecursively);
  10436. this.quasi.include(context, includeChildrenRecursively);
  10437. }
  10438. this.tag.includeCallArguments(context, this.interaction.args);
  10439. const returnExpression = this.getReturnExpression();
  10440. if (!returnExpression.included) {
  10441. returnExpression.include(context, false);
  10442. }
  10443. }
  10444. initialise() {
  10445. this.interaction = {
  10446. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  10447. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10448. type: INTERACTION_CALLED,
  10449. withNew: false
  10450. };
  10451. }
  10452. render(code, options) {
  10453. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10454. this.quasi.render(code, options);
  10455. }
  10456. applyDeoptimizations() {
  10457. this.deoptimized = true;
  10458. if (this.interaction.thisArg) {
  10459. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10460. }
  10461. for (const argument of this.quasi.expressions) {
  10462. // This will make sure all properties of parameters behave as "unknown"
  10463. argument.deoptimizePath(UNKNOWN_PATH);
  10464. }
  10465. this.context.requestTreeshakingPass();
  10466. }
  10467. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10468. if (this.returnExpression === null) {
  10469. this.returnExpression = UNKNOWN_EXPRESSION;
  10470. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10471. }
  10472. return this.returnExpression;
  10473. }
  10474. }
  10475. class TemplateElement extends NodeBase {
  10476. // Do not try to bind value
  10477. bind() { }
  10478. hasEffects() {
  10479. return false;
  10480. }
  10481. include() {
  10482. this.included = true;
  10483. }
  10484. parseNode(esTreeNode) {
  10485. this.value = esTreeNode.value;
  10486. super.parseNode(esTreeNode);
  10487. }
  10488. render() { }
  10489. }
  10490. class TemplateLiteral extends NodeBase {
  10491. deoptimizeThisOnInteractionAtPath() { }
  10492. getLiteralValueAtPath(path) {
  10493. if (path.length > 0 || this.quasis.length !== 1) {
  10494. return UnknownValue;
  10495. }
  10496. return this.quasis[0].value.cooked;
  10497. }
  10498. getReturnExpressionWhenCalledAtPath(path) {
  10499. if (path.length !== 1) {
  10500. return UNKNOWN_EXPRESSION;
  10501. }
  10502. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10503. }
  10504. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10505. if (interaction.type === INTERACTION_ACCESSED) {
  10506. return path.length > 1;
  10507. }
  10508. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10509. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10510. }
  10511. return true;
  10512. }
  10513. render(code, options) {
  10514. code.indentExclusionRanges.push([this.start, this.end]);
  10515. super.render(code, options);
  10516. }
  10517. }
  10518. class UndefinedVariable extends Variable {
  10519. constructor() {
  10520. super('undefined');
  10521. }
  10522. getLiteralValueAtPath() {
  10523. return undefined;
  10524. }
  10525. }
  10526. class ExportDefaultVariable extends LocalVariable {
  10527. constructor(name, exportDefaultDeclaration, context) {
  10528. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  10529. this.hasId = false;
  10530. this.originalId = null;
  10531. this.originalVariable = null;
  10532. const declaration = exportDefaultDeclaration.declaration;
  10533. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10534. declaration.id) {
  10535. this.hasId = true;
  10536. this.originalId = declaration.id;
  10537. }
  10538. else if (declaration instanceof Identifier) {
  10539. this.originalId = declaration;
  10540. }
  10541. }
  10542. addReference(identifier) {
  10543. if (!this.hasId) {
  10544. this.name = identifier.name;
  10545. }
  10546. }
  10547. getAssignedVariableName() {
  10548. return (this.originalId && this.originalId.name) || null;
  10549. }
  10550. getBaseVariableName() {
  10551. const original = this.getOriginalVariable();
  10552. if (original === this) {
  10553. return super.getBaseVariableName();
  10554. }
  10555. else {
  10556. return original.getBaseVariableName();
  10557. }
  10558. }
  10559. getDirectOriginalVariable() {
  10560. return this.originalId &&
  10561. (this.hasId ||
  10562. !(this.originalId.isPossibleTDZ() ||
  10563. this.originalId.variable.isReassigned ||
  10564. this.originalId.variable instanceof UndefinedVariable ||
  10565. // this avoids a circular dependency
  10566. 'syntheticNamespace' in this.originalId.variable))
  10567. ? this.originalId.variable
  10568. : null;
  10569. }
  10570. getName(getPropertyAccess) {
  10571. const original = this.getOriginalVariable();
  10572. if (original === this) {
  10573. return super.getName(getPropertyAccess);
  10574. }
  10575. else {
  10576. return original.getName(getPropertyAccess);
  10577. }
  10578. }
  10579. getOriginalVariable() {
  10580. if (this.originalVariable)
  10581. return this.originalVariable;
  10582. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10583. let original = this;
  10584. let currentVariable;
  10585. const checkedVariables = new Set();
  10586. do {
  10587. checkedVariables.add(original);
  10588. currentVariable = original;
  10589. original = currentVariable.getDirectOriginalVariable();
  10590. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10591. return (this.originalVariable = original || currentVariable);
  10592. }
  10593. }
  10594. class ModuleScope extends ChildScope {
  10595. constructor(parent, context) {
  10596. super(parent);
  10597. this.context = context;
  10598. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  10599. }
  10600. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10601. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10602. this.variables.set('default', variable);
  10603. return variable;
  10604. }
  10605. addNamespaceMemberAccess() { }
  10606. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10607. // all module level variables are already deconflicted when deconflicting the chunk
  10608. for (const scope of this.children)
  10609. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10610. }
  10611. findLexicalBoundary() {
  10612. return this;
  10613. }
  10614. findVariable(name) {
  10615. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  10616. if (knownVariable) {
  10617. return knownVariable;
  10618. }
  10619. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  10620. if (variable instanceof GlobalVariable) {
  10621. this.accessedOutsideVariables.set(name, variable);
  10622. }
  10623. return variable;
  10624. }
  10625. }
  10626. class ThisExpression extends NodeBase {
  10627. bind() {
  10628. this.variable = this.scope.findVariable('this');
  10629. }
  10630. deoptimizePath(path) {
  10631. this.variable.deoptimizePath(path);
  10632. }
  10633. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10634. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  10635. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  10636. }
  10637. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10638. if (path.length === 0) {
  10639. return interaction.type !== INTERACTION_ACCESSED;
  10640. }
  10641. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10642. }
  10643. include() {
  10644. if (!this.included) {
  10645. this.included = true;
  10646. this.context.includeVariableInModule(this.variable);
  10647. }
  10648. }
  10649. initialise() {
  10650. this.alias =
  10651. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  10652. if (this.alias === 'undefined') {
  10653. this.context.warn({
  10654. code: 'THIS_IS_UNDEFINED',
  10655. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  10656. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  10657. }, this.start);
  10658. }
  10659. }
  10660. render(code) {
  10661. if (this.alias !== null) {
  10662. code.overwrite(this.start, this.end, this.alias, {
  10663. contentOnly: false,
  10664. storeName: true
  10665. });
  10666. }
  10667. }
  10668. }
  10669. class ThrowStatement extends NodeBase {
  10670. hasEffects() {
  10671. return true;
  10672. }
  10673. include(context, includeChildrenRecursively) {
  10674. this.included = true;
  10675. this.argument.include(context, includeChildrenRecursively);
  10676. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10677. }
  10678. render(code, options) {
  10679. this.argument.render(code, options, { preventASI: true });
  10680. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  10681. code.prependLeft(this.start + 5, ' ');
  10682. }
  10683. }
  10684. }
  10685. class TryStatement extends NodeBase {
  10686. constructor() {
  10687. super(...arguments);
  10688. this.directlyIncluded = false;
  10689. this.includedLabelsAfterBlock = null;
  10690. }
  10691. hasEffects(context) {
  10692. var _a;
  10693. return ((this.context.options.treeshake.tryCatchDeoptimization
  10694. ? this.block.body.length > 0
  10695. : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10696. }
  10697. include(context, includeChildrenRecursively) {
  10698. var _a, _b;
  10699. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  10700. const { brokenFlow } = context;
  10701. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  10702. this.included = true;
  10703. this.directlyIncluded = true;
  10704. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  10705. if (context.includedLabels.size > 0) {
  10706. this.includedLabelsAfterBlock = [...context.includedLabels];
  10707. }
  10708. context.brokenFlow = brokenFlow;
  10709. }
  10710. else if (this.includedLabelsAfterBlock) {
  10711. for (const label of this.includedLabelsAfterBlock) {
  10712. context.includedLabels.add(label);
  10713. }
  10714. }
  10715. if (this.handler !== null) {
  10716. this.handler.include(context, includeChildrenRecursively);
  10717. context.brokenFlow = brokenFlow;
  10718. }
  10719. (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  10720. }
  10721. }
  10722. const unaryOperators = {
  10723. '!': value => !value,
  10724. '+': value => +value,
  10725. '-': value => -value,
  10726. delete: () => UnknownValue,
  10727. typeof: value => typeof value,
  10728. void: () => undefined,
  10729. '~': value => ~value
  10730. };
  10731. class UnaryExpression extends NodeBase {
  10732. getLiteralValueAtPath(path, recursionTracker, origin) {
  10733. if (path.length > 0)
  10734. return UnknownValue;
  10735. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10736. if (typeof argumentValue === 'symbol')
  10737. return UnknownValue;
  10738. return unaryOperators[this.operator](argumentValue);
  10739. }
  10740. hasEffects(context) {
  10741. if (!this.deoptimized)
  10742. this.applyDeoptimizations();
  10743. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  10744. return false;
  10745. return (this.argument.hasEffects(context) ||
  10746. (this.operator === 'delete' &&
  10747. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  10748. }
  10749. hasEffectsOnInteractionAtPath(path, { type }) {
  10750. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  10751. }
  10752. applyDeoptimizations() {
  10753. this.deoptimized = true;
  10754. if (this.operator === 'delete') {
  10755. this.argument.deoptimizePath(EMPTY_PATH);
  10756. this.context.requestTreeshakingPass();
  10757. }
  10758. }
  10759. }
  10760. class UnknownNode extends NodeBase {
  10761. hasEffects() {
  10762. return true;
  10763. }
  10764. include(context) {
  10765. super.include(context, true);
  10766. }
  10767. }
  10768. class UpdateExpression extends NodeBase {
  10769. hasEffects(context) {
  10770. if (!this.deoptimized)
  10771. this.applyDeoptimizations();
  10772. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  10773. }
  10774. hasEffectsOnInteractionAtPath(path, { type }) {
  10775. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10776. }
  10777. include(context, includeChildrenRecursively) {
  10778. if (!this.deoptimized)
  10779. this.applyDeoptimizations();
  10780. this.included = true;
  10781. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  10782. }
  10783. initialise() {
  10784. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  10785. }
  10786. render(code, options) {
  10787. const { exportNamesByVariable, format, snippets: { _ } } = options;
  10788. this.argument.render(code, options);
  10789. if (format === 'system') {
  10790. const variable = this.argument.variable;
  10791. const exportNames = exportNamesByVariable.get(variable);
  10792. if (exportNames) {
  10793. if (this.prefix) {
  10794. if (exportNames.length === 1) {
  10795. renderSystemExportExpression(variable, this.start, this.end, code, options);
  10796. }
  10797. else {
  10798. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  10799. }
  10800. }
  10801. else {
  10802. const operator = this.operator[0];
  10803. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  10804. }
  10805. }
  10806. }
  10807. }
  10808. applyDeoptimizations() {
  10809. this.deoptimized = true;
  10810. this.argument.deoptimizePath(EMPTY_PATH);
  10811. if (this.argument instanceof Identifier) {
  10812. const variable = this.scope.findVariable(this.argument.name);
  10813. variable.isReassigned = true;
  10814. }
  10815. this.context.requestTreeshakingPass();
  10816. }
  10817. }
  10818. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10819. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10820. }
  10821. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  10822. for (const declarator of declarations) {
  10823. if (!declarator.id.included)
  10824. return false;
  10825. if (declarator.id.type === Identifier$1) {
  10826. if (exportNamesByVariable.has(declarator.id.variable))
  10827. return false;
  10828. }
  10829. else {
  10830. const exportedVariables = [];
  10831. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  10832. if (exportedVariables.length > 0)
  10833. return false;
  10834. }
  10835. }
  10836. return true;
  10837. }
  10838. class VariableDeclaration extends NodeBase {
  10839. deoptimizePath() {
  10840. for (const declarator of this.declarations) {
  10841. declarator.deoptimizePath(EMPTY_PATH);
  10842. }
  10843. }
  10844. hasEffectsOnInteractionAtPath() {
  10845. return false;
  10846. }
  10847. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  10848. this.included = true;
  10849. for (const declarator of this.declarations) {
  10850. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  10851. declarator.include(context, includeChildrenRecursively);
  10852. if (asSingleStatement) {
  10853. declarator.id.include(context, includeChildrenRecursively);
  10854. }
  10855. }
  10856. }
  10857. initialise() {
  10858. for (const declarator of this.declarations) {
  10859. declarator.declareDeclarator(this.kind);
  10860. }
  10861. }
  10862. render(code, options, nodeRenderOptions = BLANK) {
  10863. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  10864. for (const declarator of this.declarations) {
  10865. declarator.render(code, options);
  10866. }
  10867. if (!nodeRenderOptions.isNoStatement &&
  10868. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  10869. code.appendLeft(this.end, ';');
  10870. }
  10871. }
  10872. else {
  10873. this.renderReplacedDeclarations(code, options);
  10874. }
  10875. }
  10876. applyDeoptimizations() { }
  10877. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  10878. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  10879. code.remove(this.end - 1, this.end);
  10880. }
  10881. separatorString += ';';
  10882. if (lastSeparatorPos !== null) {
  10883. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  10884. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  10885. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  10886. actualContentEnd--;
  10887. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  10888. actualContentEnd--;
  10889. }
  10890. }
  10891. if (actualContentEnd === lastSeparatorPos + 1) {
  10892. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  10893. }
  10894. else {
  10895. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10896. code.remove(actualContentEnd, renderedContentEnd);
  10897. }
  10898. }
  10899. else {
  10900. code.appendLeft(renderedContentEnd, separatorString);
  10901. }
  10902. if (systemPatternExports.length > 0) {
  10903. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  10904. }
  10905. }
  10906. renderReplacedDeclarations(code, options) {
  10907. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  10908. let actualContentEnd, renderedContentEnd;
  10909. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  10910. let lastSeparatorPos = renderedContentEnd - 1;
  10911. code.remove(this.start, lastSeparatorPos);
  10912. let isInDeclaration = false;
  10913. let hasRenderedContent = false;
  10914. let separatorString = '', leadingString, nextSeparatorString;
  10915. const aggregatedSystemExports = [];
  10916. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  10917. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  10918. if (!node.included) {
  10919. code.remove(start, end);
  10920. continue;
  10921. }
  10922. node.render(code, options);
  10923. leadingString = '';
  10924. nextSeparatorString = '';
  10925. if (!node.id.included ||
  10926. (node.id instanceof Identifier &&
  10927. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  10928. if (hasRenderedContent) {
  10929. separatorString += ';';
  10930. }
  10931. isInDeclaration = false;
  10932. }
  10933. else {
  10934. if (singleSystemExport && singleSystemExport === node.id.variable) {
  10935. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  10936. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  10937. }
  10938. if (isInDeclaration) {
  10939. separatorString += ',';
  10940. }
  10941. else {
  10942. if (hasRenderedContent) {
  10943. separatorString += ';';
  10944. }
  10945. leadingString += `${this.kind} `;
  10946. isInDeclaration = true;
  10947. }
  10948. }
  10949. if (renderedContentEnd === lastSeparatorPos + 1) {
  10950. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  10951. }
  10952. else {
  10953. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10954. code.appendLeft(renderedContentEnd, leadingString);
  10955. }
  10956. actualContentEnd = contentEnd;
  10957. renderedContentEnd = end;
  10958. hasRenderedContent = true;
  10959. lastSeparatorPos = separator;
  10960. separatorString = nextSeparatorString;
  10961. }
  10962. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  10963. }
  10964. }
  10965. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  10966. var _a;
  10967. let singleSystemExport = null;
  10968. if (options.format === 'system') {
  10969. for (const { node } of separatedNodes) {
  10970. if (node.id instanceof Identifier &&
  10971. node.init &&
  10972. aggregatedSystemExports.length === 0 &&
  10973. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  10974. singleSystemExport = node.id.variable;
  10975. aggregatedSystemExports.push(singleSystemExport);
  10976. }
  10977. else {
  10978. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  10979. }
  10980. }
  10981. if (aggregatedSystemExports.length > 1) {
  10982. singleSystemExport = null;
  10983. }
  10984. else if (singleSystemExport) {
  10985. aggregatedSystemExports.length = 0;
  10986. }
  10987. }
  10988. return singleSystemExport;
  10989. }
  10990. class VariableDeclarator extends NodeBase {
  10991. declareDeclarator(kind) {
  10992. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  10993. }
  10994. deoptimizePath(path) {
  10995. this.id.deoptimizePath(path);
  10996. }
  10997. hasEffects(context) {
  10998. var _a;
  10999. const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
  11000. this.id.markDeclarationReached();
  11001. return initEffect || this.id.hasEffects(context);
  11002. }
  11003. include(context, includeChildrenRecursively) {
  11004. var _a;
  11005. this.included = true;
  11006. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  11007. this.id.markDeclarationReached();
  11008. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  11009. this.id.include(context, includeChildrenRecursively);
  11010. }
  11011. }
  11012. render(code, options) {
  11013. const { exportNamesByVariable, snippets: { _ } } = options;
  11014. const renderId = this.id.included;
  11015. if (renderId) {
  11016. this.id.render(code, options);
  11017. }
  11018. else {
  11019. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  11020. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  11021. }
  11022. if (this.init) {
  11023. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11024. }
  11025. else if (this.id instanceof Identifier &&
  11026. isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
  11027. code.appendLeft(this.end, `${_}=${_}void 0`);
  11028. }
  11029. }
  11030. applyDeoptimizations() { }
  11031. }
  11032. class WhileStatement extends NodeBase {
  11033. hasEffects(context) {
  11034. if (this.test.hasEffects(context))
  11035. return true;
  11036. const { brokenFlow, ignore: { breaks, continues } } = context;
  11037. context.ignore.breaks = true;
  11038. context.ignore.continues = true;
  11039. if (this.body.hasEffects(context))
  11040. return true;
  11041. context.ignore.breaks = breaks;
  11042. context.ignore.continues = continues;
  11043. context.brokenFlow = brokenFlow;
  11044. return false;
  11045. }
  11046. include(context, includeChildrenRecursively) {
  11047. this.included = true;
  11048. this.test.include(context, includeChildrenRecursively);
  11049. const { brokenFlow } = context;
  11050. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11051. context.brokenFlow = brokenFlow;
  11052. }
  11053. }
  11054. class YieldExpression extends NodeBase {
  11055. hasEffects(context) {
  11056. var _a;
  11057. if (!this.deoptimized)
  11058. this.applyDeoptimizations();
  11059. return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  11060. }
  11061. render(code, options) {
  11062. if (this.argument) {
  11063. this.argument.render(code, options, { preventASI: true });
  11064. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11065. code.prependLeft(this.start + 5, ' ');
  11066. }
  11067. }
  11068. }
  11069. }
  11070. const nodeConstructors = {
  11071. ArrayExpression,
  11072. ArrayPattern,
  11073. ArrowFunctionExpression,
  11074. AssignmentExpression,
  11075. AssignmentPattern,
  11076. AwaitExpression,
  11077. BinaryExpression,
  11078. BlockStatement,
  11079. BreakStatement,
  11080. CallExpression,
  11081. CatchClause,
  11082. ChainExpression,
  11083. ClassBody,
  11084. ClassDeclaration,
  11085. ClassExpression,
  11086. ConditionalExpression,
  11087. ContinueStatement,
  11088. DoWhileStatement,
  11089. EmptyStatement,
  11090. ExportAllDeclaration,
  11091. ExportDefaultDeclaration,
  11092. ExportNamedDeclaration,
  11093. ExportSpecifier,
  11094. ExpressionStatement,
  11095. ForInStatement,
  11096. ForOfStatement,
  11097. ForStatement,
  11098. FunctionDeclaration,
  11099. FunctionExpression,
  11100. Identifier,
  11101. IfStatement,
  11102. ImportDeclaration,
  11103. ImportDefaultSpecifier,
  11104. ImportExpression,
  11105. ImportNamespaceSpecifier,
  11106. ImportSpecifier,
  11107. LabeledStatement,
  11108. Literal,
  11109. LogicalExpression,
  11110. MemberExpression,
  11111. MetaProperty,
  11112. MethodDefinition,
  11113. NewExpression,
  11114. ObjectExpression,
  11115. ObjectPattern,
  11116. PrivateIdentifier,
  11117. Program,
  11118. Property,
  11119. PropertyDefinition,
  11120. RestElement,
  11121. ReturnStatement,
  11122. SequenceExpression,
  11123. SpreadElement,
  11124. StaticBlock,
  11125. Super,
  11126. SwitchCase,
  11127. SwitchStatement,
  11128. TaggedTemplateExpression,
  11129. TemplateElement,
  11130. TemplateLiteral,
  11131. ThisExpression,
  11132. ThrowStatement,
  11133. TryStatement,
  11134. UnaryExpression,
  11135. UnknownNode,
  11136. UpdateExpression,
  11137. VariableDeclaration,
  11138. VariableDeclarator,
  11139. WhileStatement,
  11140. YieldExpression
  11141. };
  11142. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11143. class ExportShimVariable extends Variable {
  11144. constructor(module) {
  11145. super(MISSING_EXPORT_SHIM_VARIABLE);
  11146. this.module = module;
  11147. }
  11148. include() {
  11149. super.include();
  11150. this.module.needsExportShim = true;
  11151. }
  11152. }
  11153. class NamespaceVariable extends Variable {
  11154. constructor(context) {
  11155. super(context.getModuleName());
  11156. this.memberVariables = null;
  11157. this.mergedNamespaces = [];
  11158. this.referencedEarly = false;
  11159. this.references = [];
  11160. this.context = context;
  11161. this.module = context.module;
  11162. }
  11163. addReference(identifier) {
  11164. this.references.push(identifier);
  11165. this.name = identifier.name;
  11166. }
  11167. getMemberVariables() {
  11168. if (this.memberVariables) {
  11169. return this.memberVariables;
  11170. }
  11171. const memberVariables = Object.create(null);
  11172. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  11173. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  11174. const exportedVariable = this.context.traceExport(name);
  11175. if (exportedVariable) {
  11176. memberVariables[name] = exportedVariable;
  11177. }
  11178. }
  11179. }
  11180. return (this.memberVariables = memberVariables);
  11181. }
  11182. include() {
  11183. this.included = true;
  11184. this.context.includeAllExports();
  11185. }
  11186. prepare(accessedGlobalsByScope) {
  11187. if (this.mergedNamespaces.length > 0) {
  11188. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11189. }
  11190. }
  11191. renderBlock(options) {
  11192. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11193. const memberVariables = this.getMemberVariables();
  11194. const members = Object.entries(memberVariables).map(([name, original]) => {
  11195. if (this.referencedEarly || original.isReassigned) {
  11196. return [
  11197. null,
  11198. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  11199. ];
  11200. }
  11201. return [name, original.getName(getPropertyAccess)];
  11202. });
  11203. members.unshift([null, `__proto__:${_}null`]);
  11204. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11205. if (this.mergedNamespaces.length > 0) {
  11206. const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11207. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
  11208. }
  11209. else {
  11210. // The helper to merge namespaces will also take care of freezing and toStringTag
  11211. if (namespaceToStringTag) {
  11212. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11213. }
  11214. if (freeze) {
  11215. output = `/*#__PURE__*/Object.freeze(${output})`;
  11216. }
  11217. }
  11218. const name = this.getName(getPropertyAccess);
  11219. output = `${cnst} ${name}${_}=${_}${output};`;
  11220. if (format === 'system' && exportNamesByVariable.has(this)) {
  11221. output += `${n}${getSystemExportStatement([this], options)};`;
  11222. }
  11223. return output;
  11224. }
  11225. renderFirst() {
  11226. return this.referencedEarly;
  11227. }
  11228. setMergedNamespaces(mergedNamespaces) {
  11229. this.mergedNamespaces = mergedNamespaces;
  11230. const moduleExecIndex = this.context.getModuleExecIndex();
  11231. for (const identifier of this.references) {
  11232. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  11233. this.referencedEarly = true;
  11234. break;
  11235. }
  11236. }
  11237. }
  11238. }
  11239. NamespaceVariable.prototype.isNamespace = true;
  11240. class SyntheticNamedExportVariable extends Variable {
  11241. constructor(context, name, syntheticNamespace) {
  11242. super(name);
  11243. this.baseVariable = null;
  11244. this.context = context;
  11245. this.module = context.module;
  11246. this.syntheticNamespace = syntheticNamespace;
  11247. }
  11248. getBaseVariable() {
  11249. if (this.baseVariable)
  11250. return this.baseVariable;
  11251. let baseVariable = this.syntheticNamespace;
  11252. while (baseVariable instanceof ExportDefaultVariable ||
  11253. baseVariable instanceof SyntheticNamedExportVariable) {
  11254. if (baseVariable instanceof ExportDefaultVariable) {
  11255. const original = baseVariable.getOriginalVariable();
  11256. if (original === baseVariable)
  11257. break;
  11258. baseVariable = original;
  11259. }
  11260. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11261. baseVariable = baseVariable.syntheticNamespace;
  11262. }
  11263. }
  11264. return (this.baseVariable = baseVariable);
  11265. }
  11266. getBaseVariableName() {
  11267. return this.syntheticNamespace.getBaseVariableName();
  11268. }
  11269. getName(getPropertyAccess) {
  11270. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11271. }
  11272. include() {
  11273. this.included = true;
  11274. this.context.includeVariableInModule(this.syntheticNamespace);
  11275. }
  11276. setRenderNames(baseName, name) {
  11277. super.setRenderNames(baseName, name);
  11278. }
  11279. }
  11280. var BuildPhase;
  11281. (function (BuildPhase) {
  11282. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11283. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11284. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11285. })(BuildPhase || (BuildPhase = {}));
  11286. function getId(m) {
  11287. return m.id;
  11288. }
  11289. function getOriginalLocation(sourcemapChain, location) {
  11290. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11291. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11292. const sourcemap = filteredSourcemapChain.pop();
  11293. const line = sourcemap.mappings[location.line - 1];
  11294. if (line) {
  11295. const filteredLine = line.filter((segment) => segment.length > 1);
  11296. const lastSegment = filteredLine[filteredLine.length - 1];
  11297. for (const segment of filteredLine) {
  11298. if (segment[0] >= location.column || segment === lastSegment) {
  11299. location = {
  11300. column: segment[3],
  11301. line: segment[2] + 1
  11302. };
  11303. continue traceSourcemap;
  11304. }
  11305. }
  11306. }
  11307. throw new Error("Can't resolve original location of error.");
  11308. }
  11309. return location;
  11310. }
  11311. const NOOP = () => { };
  11312. let timers = new Map();
  11313. function getPersistedLabel(label, level) {
  11314. switch (level) {
  11315. case 1:
  11316. return `# ${label}`;
  11317. case 2:
  11318. return `## ${label}`;
  11319. case 3:
  11320. return label;
  11321. default:
  11322. return `${' '.repeat(level - 4)}- ${label}`;
  11323. }
  11324. }
  11325. function timeStartImpl(label, level = 3) {
  11326. label = getPersistedLabel(label, level);
  11327. const startMemory = process$1.memoryUsage().heapUsed;
  11328. const startTime = performance.now();
  11329. const timer = timers.get(label);
  11330. if (timer === undefined) {
  11331. timers.set(label, {
  11332. memory: 0,
  11333. startMemory,
  11334. startTime,
  11335. time: 0,
  11336. totalMemory: 0
  11337. });
  11338. }
  11339. else {
  11340. timer.startMemory = startMemory;
  11341. timer.startTime = startTime;
  11342. }
  11343. }
  11344. function timeEndImpl(label, level = 3) {
  11345. label = getPersistedLabel(label, level);
  11346. const timer = timers.get(label);
  11347. if (timer !== undefined) {
  11348. const currentMemory = process$1.memoryUsage().heapUsed;
  11349. timer.memory += currentMemory - timer.startMemory;
  11350. timer.time += performance.now() - timer.startTime;
  11351. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  11352. }
  11353. }
  11354. function getTimings() {
  11355. const newTimings = {};
  11356. for (const [label, { memory, time, totalMemory }] of timers) {
  11357. newTimings[label] = [time, memory, totalMemory];
  11358. }
  11359. return newTimings;
  11360. }
  11361. let timeStart = NOOP;
  11362. let timeEnd = NOOP;
  11363. const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
  11364. function getPluginWithTimers(plugin, index) {
  11365. for (const hook of TIMED_PLUGIN_HOOKS) {
  11366. if (hook in plugin) {
  11367. let timerLabel = `plugin ${index}`;
  11368. if (plugin.name) {
  11369. timerLabel += ` (${plugin.name})`;
  11370. }
  11371. timerLabel += ` - ${hook}`;
  11372. const func = plugin[hook];
  11373. plugin[hook] = function (...args) {
  11374. timeStart(timerLabel, 4);
  11375. const result = func.apply(this, args);
  11376. timeEnd(timerLabel, 4);
  11377. if (result && typeof result.then === 'function') {
  11378. timeStart(`${timerLabel} (async)`, 4);
  11379. return result.then((hookResult) => {
  11380. timeEnd(`${timerLabel} (async)`, 4);
  11381. return hookResult;
  11382. });
  11383. }
  11384. return result;
  11385. };
  11386. }
  11387. }
  11388. return plugin;
  11389. }
  11390. function initialiseTimers(inputOptions) {
  11391. if (inputOptions.perf) {
  11392. timers = new Map();
  11393. timeStart = timeStartImpl;
  11394. timeEnd = timeEndImpl;
  11395. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  11396. }
  11397. else {
  11398. timeStart = NOOP;
  11399. timeEnd = NOOP;
  11400. }
  11401. }
  11402. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  11403. baseModule.isExecuted = true;
  11404. const modules = [baseModule];
  11405. const visitedModules = new Set();
  11406. for (const module of modules) {
  11407. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  11408. if (!(dependency instanceof ExternalModule) &&
  11409. !dependency.isExecuted &&
  11410. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  11411. !visitedModules.has(dependency.id)) {
  11412. dependency.isExecuted = true;
  11413. visitedModules.add(dependency.id);
  11414. modules.push(dependency);
  11415. }
  11416. }
  11417. }
  11418. }
  11419. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  11420. identifier: null,
  11421. localName: MISSING_EXPORT_SHIM_VARIABLE
  11422. };
  11423. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  11424. const searchedModules = searchedNamesAndModules.get(name);
  11425. if (searchedModules) {
  11426. if (searchedModules.has(target)) {
  11427. return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
  11428. }
  11429. searchedModules.add(target);
  11430. }
  11431. else {
  11432. searchedNamesAndModules.set(name, new Set([target]));
  11433. }
  11434. return target.getVariableForExportName(name, {
  11435. importerForSideEffects,
  11436. isExportAllSearch,
  11437. searchedNamesAndModules
  11438. });
  11439. }
  11440. function getAndExtendSideEffectModules(variable, module) {
  11441. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  11442. let currentVariable = variable;
  11443. const referencedVariables = new Set([currentVariable]);
  11444. while (true) {
  11445. const importingModule = currentVariable.module;
  11446. currentVariable =
  11447. currentVariable instanceof ExportDefaultVariable
  11448. ? currentVariable.getDirectOriginalVariable()
  11449. : currentVariable instanceof SyntheticNamedExportVariable
  11450. ? currentVariable.syntheticNamespace
  11451. : null;
  11452. if (!currentVariable || referencedVariables.has(currentVariable)) {
  11453. break;
  11454. }
  11455. referencedVariables.add(currentVariable);
  11456. sideEffectModules.add(importingModule);
  11457. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  11458. if (originalSideEffects) {
  11459. for (const module of originalSideEffects) {
  11460. sideEffectModules.add(module);
  11461. }
  11462. }
  11463. }
  11464. return sideEffectModules;
  11465. }
  11466. class Module {
  11467. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
  11468. this.graph = graph;
  11469. this.id = id;
  11470. this.options = options;
  11471. this.alternativeReexportModules = new Map();
  11472. this.chunkFileNames = new Set();
  11473. this.chunkNames = [];
  11474. this.cycles = new Set();
  11475. this.dependencies = new Set();
  11476. this.dynamicDependencies = new Set();
  11477. this.dynamicImporters = [];
  11478. this.dynamicImports = [];
  11479. this.execIndex = Infinity;
  11480. this.implicitlyLoadedAfter = new Set();
  11481. this.implicitlyLoadedBefore = new Set();
  11482. this.importDescriptions = new Map();
  11483. this.importMetas = [];
  11484. this.importedFromNotTreeshaken = false;
  11485. this.importers = [];
  11486. this.includedDynamicImporters = [];
  11487. this.includedImports = new Set();
  11488. this.isExecuted = false;
  11489. this.isUserDefinedEntryPoint = false;
  11490. this.needsExportShim = false;
  11491. this.sideEffectDependenciesByVariable = new Map();
  11492. this.sources = new Set();
  11493. this.usesTopLevelAwait = false;
  11494. this.allExportNames = null;
  11495. this.ast = null;
  11496. this.exportAllModules = [];
  11497. this.exportAllSources = new Set();
  11498. this.exportNamesByVariable = null;
  11499. this.exportShimVariable = new ExportShimVariable(this);
  11500. this.exports = new Map();
  11501. this.namespaceReexportsByName = new Map();
  11502. this.reexportDescriptions = new Map();
  11503. this.relevantDependencies = null;
  11504. this.syntheticExports = new Map();
  11505. this.syntheticNamespace = null;
  11506. this.transformDependencies = [];
  11507. this.transitiveReexports = null;
  11508. this.excludeFromSourcemap = /\0/.test(id);
  11509. this.context = options.moduleContext(id);
  11510. this.preserveSignature = this.options.preserveEntrySignatures;
  11511. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11512. const module = this;
  11513. const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
  11514. this.info = {
  11515. ast: null,
  11516. code: null,
  11517. get dynamicallyImportedIdResolutions() {
  11518. return dynamicImports
  11519. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  11520. .filter(Boolean);
  11521. },
  11522. get dynamicallyImportedIds() {
  11523. // We cannot use this.dynamicDependencies because this is needed before
  11524. // dynamicDependencies are populated
  11525. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  11526. },
  11527. get dynamicImporters() {
  11528. return dynamicImporters.sort();
  11529. },
  11530. get hasDefaultExport() {
  11531. // This information is only valid after parsing
  11532. if (!module.ast) {
  11533. return null;
  11534. }
  11535. return module.exports.has('default') || reexportDescriptions.has('default');
  11536. },
  11537. get hasModuleSideEffects() {
  11538. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  11539. return this.moduleSideEffects;
  11540. },
  11541. id,
  11542. get implicitlyLoadedAfterOneOf() {
  11543. return Array.from(implicitlyLoadedAfter, getId).sort();
  11544. },
  11545. get implicitlyLoadedBefore() {
  11546. return Array.from(implicitlyLoadedBefore, getId).sort();
  11547. },
  11548. get importedIdResolutions() {
  11549. return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
  11550. },
  11551. get importedIds() {
  11552. // We cannot use this.dependencies because this is needed before
  11553. // dependencies are populated
  11554. return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
  11555. },
  11556. get importers() {
  11557. return importers.sort();
  11558. },
  11559. isEntry,
  11560. isExternal: false,
  11561. get isIncluded() {
  11562. if (graph.phase !== BuildPhase.GENERATE) {
  11563. return null;
  11564. }
  11565. return module.isIncluded();
  11566. },
  11567. meta: { ...meta },
  11568. moduleSideEffects,
  11569. syntheticNamedExports
  11570. };
  11571. // Hide the deprecated key so that it only warns when accessed explicitly
  11572. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  11573. enumerable: false
  11574. });
  11575. }
  11576. basename() {
  11577. const base = basename(this.id);
  11578. const ext = extname(this.id);
  11579. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  11580. }
  11581. bindReferences() {
  11582. this.ast.bind();
  11583. }
  11584. error(props, pos) {
  11585. this.addLocationToLogProps(props, pos);
  11586. return error(props);
  11587. }
  11588. getAllExportNames() {
  11589. if (this.allExportNames) {
  11590. return this.allExportNames;
  11591. }
  11592. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  11593. for (const module of this.exportAllModules) {
  11594. if (module instanceof ExternalModule) {
  11595. this.allExportNames.add(`*${module.id}`);
  11596. continue;
  11597. }
  11598. for (const name of module.getAllExportNames()) {
  11599. if (name !== 'default')
  11600. this.allExportNames.add(name);
  11601. }
  11602. }
  11603. // We do not count the synthetic namespace as a regular export to hide it
  11604. // from entry signatures and namespace objects
  11605. if (typeof this.info.syntheticNamedExports === 'string') {
  11606. this.allExportNames.delete(this.info.syntheticNamedExports);
  11607. }
  11608. return this.allExportNames;
  11609. }
  11610. getDependenciesToBeIncluded() {
  11611. if (this.relevantDependencies)
  11612. return this.relevantDependencies;
  11613. this.relevantDependencies = new Set();
  11614. const necessaryDependencies = new Set();
  11615. const alwaysCheckedDependencies = new Set();
  11616. const dependencyVariables = new Set(this.includedImports);
  11617. if (this.info.isEntry ||
  11618. this.includedDynamicImporters.length > 0 ||
  11619. this.namespace.included ||
  11620. this.implicitlyLoadedAfter.size > 0) {
  11621. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  11622. const [exportedVariable] = this.getVariableForExportName(exportName);
  11623. if (exportedVariable) {
  11624. dependencyVariables.add(exportedVariable);
  11625. }
  11626. }
  11627. }
  11628. for (let variable of dependencyVariables) {
  11629. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  11630. if (sideEffectDependencies) {
  11631. for (const module of sideEffectDependencies) {
  11632. alwaysCheckedDependencies.add(module);
  11633. }
  11634. }
  11635. if (variable instanceof SyntheticNamedExportVariable) {
  11636. variable = variable.getBaseVariable();
  11637. }
  11638. else if (variable instanceof ExportDefaultVariable) {
  11639. variable = variable.getOriginalVariable();
  11640. }
  11641. necessaryDependencies.add(variable.module);
  11642. }
  11643. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  11644. for (const dependency of this.dependencies) {
  11645. this.relevantDependencies.add(dependency);
  11646. }
  11647. }
  11648. else {
  11649. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  11650. }
  11651. for (const dependency of necessaryDependencies) {
  11652. this.relevantDependencies.add(dependency);
  11653. }
  11654. return this.relevantDependencies;
  11655. }
  11656. getExportNamesByVariable() {
  11657. if (this.exportNamesByVariable) {
  11658. return this.exportNamesByVariable;
  11659. }
  11660. const exportNamesByVariable = new Map();
  11661. for (const exportName of this.getAllExportNames()) {
  11662. let [tracedVariable] = this.getVariableForExportName(exportName);
  11663. if (tracedVariable instanceof ExportDefaultVariable) {
  11664. tracedVariable = tracedVariable.getOriginalVariable();
  11665. }
  11666. if (!tracedVariable ||
  11667. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  11668. continue;
  11669. }
  11670. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  11671. if (existingExportNames) {
  11672. existingExportNames.push(exportName);
  11673. }
  11674. else {
  11675. exportNamesByVariable.set(tracedVariable, [exportName]);
  11676. }
  11677. }
  11678. return (this.exportNamesByVariable = exportNamesByVariable);
  11679. }
  11680. getExports() {
  11681. return Array.from(this.exports.keys());
  11682. }
  11683. getReexports() {
  11684. if (this.transitiveReexports) {
  11685. return this.transitiveReexports;
  11686. }
  11687. // to avoid infinite recursion when using circular `export * from X`
  11688. this.transitiveReexports = [];
  11689. const reexports = new Set(this.reexportDescriptions.keys());
  11690. for (const module of this.exportAllModules) {
  11691. if (module instanceof ExternalModule) {
  11692. reexports.add(`*${module.id}`);
  11693. }
  11694. else {
  11695. for (const name of [...module.getReexports(), ...module.getExports()]) {
  11696. if (name !== 'default')
  11697. reexports.add(name);
  11698. }
  11699. }
  11700. }
  11701. return (this.transitiveReexports = [...reexports]);
  11702. }
  11703. getRenderedExports() {
  11704. // only direct exports are counted here, not reexports at all
  11705. const renderedExports = [];
  11706. const removedExports = [];
  11707. for (const exportName of this.exports.keys()) {
  11708. const [variable] = this.getVariableForExportName(exportName);
  11709. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  11710. }
  11711. return { removedExports, renderedExports };
  11712. }
  11713. getSyntheticNamespace() {
  11714. if (this.syntheticNamespace === null) {
  11715. this.syntheticNamespace = undefined;
  11716. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  11717. ? this.info.syntheticNamedExports
  11718. : 'default', { onlyExplicit: true });
  11719. }
  11720. if (!this.syntheticNamespace) {
  11721. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  11722. }
  11723. return this.syntheticNamespace;
  11724. }
  11725. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  11726. var _a;
  11727. if (name[0] === '*') {
  11728. if (name.length === 1) {
  11729. // export * from './other'
  11730. return [this.namespace];
  11731. }
  11732. // export * from 'external'
  11733. const module = this.graph.modulesById.get(name.slice(1));
  11734. return module.getVariableForExportName('*');
  11735. }
  11736. // export { foo } from './other'
  11737. const reexportDeclaration = this.reexportDescriptions.get(name);
  11738. if (reexportDeclaration) {
  11739. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  11740. if (!variable) {
  11741. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  11742. }
  11743. if (importerForSideEffects) {
  11744. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11745. }
  11746. return [variable];
  11747. }
  11748. const exportDeclaration = this.exports.get(name);
  11749. if (exportDeclaration) {
  11750. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  11751. return [this.exportShimVariable];
  11752. }
  11753. const name = exportDeclaration.localName;
  11754. const variable = this.traceVariable(name, {
  11755. importerForSideEffects,
  11756. searchedNamesAndModules
  11757. });
  11758. if (importerForSideEffects) {
  11759. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  11760. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11761. }
  11762. return [variable];
  11763. }
  11764. if (onlyExplicit) {
  11765. return [null];
  11766. }
  11767. if (name !== 'default') {
  11768. const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  11769. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  11770. if (foundNamespaceReexport[0]) {
  11771. return foundNamespaceReexport;
  11772. }
  11773. }
  11774. if (this.info.syntheticNamedExports) {
  11775. return [
  11776. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  11777. ];
  11778. }
  11779. // we don't want to create shims when we are just
  11780. // probing export * modules for exports
  11781. if (!isExportAllSearch) {
  11782. if (this.options.shimMissingExports) {
  11783. this.shimMissingExport(name);
  11784. return [this.exportShimVariable];
  11785. }
  11786. }
  11787. return [null];
  11788. }
  11789. hasEffects() {
  11790. return (this.info.moduleSideEffects === 'no-treeshake' ||
  11791. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  11792. }
  11793. include() {
  11794. const context = createInclusionContext();
  11795. if (this.ast.shouldBeIncluded(context))
  11796. this.ast.include(context, false);
  11797. }
  11798. includeAllExports(includeNamespaceMembers) {
  11799. if (!this.isExecuted) {
  11800. markModuleAndImpureDependenciesAsExecuted(this);
  11801. this.graph.needsTreeshakingPass = true;
  11802. }
  11803. for (const exportName of this.exports.keys()) {
  11804. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  11805. const variable = this.getVariableForExportName(exportName)[0];
  11806. variable.deoptimizePath(UNKNOWN_PATH);
  11807. if (!variable.included) {
  11808. this.includeVariable(variable);
  11809. }
  11810. }
  11811. }
  11812. for (const name of this.getReexports()) {
  11813. const [variable] = this.getVariableForExportName(name);
  11814. if (variable) {
  11815. variable.deoptimizePath(UNKNOWN_PATH);
  11816. if (!variable.included) {
  11817. this.includeVariable(variable);
  11818. }
  11819. if (variable instanceof ExternalVariable) {
  11820. variable.module.reexported = true;
  11821. }
  11822. }
  11823. }
  11824. if (includeNamespaceMembers) {
  11825. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  11826. }
  11827. }
  11828. includeAllInBundle() {
  11829. this.ast.include(createInclusionContext(), true);
  11830. this.includeAllExports(false);
  11831. }
  11832. isIncluded() {
  11833. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  11834. }
  11835. linkImports() {
  11836. this.addModulesToImportDescriptions(this.importDescriptions);
  11837. this.addModulesToImportDescriptions(this.reexportDescriptions);
  11838. const externalExportAllModules = [];
  11839. for (const source of this.exportAllSources) {
  11840. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  11841. if (module instanceof ExternalModule) {
  11842. externalExportAllModules.push(module);
  11843. continue;
  11844. }
  11845. this.exportAllModules.push(module);
  11846. }
  11847. this.exportAllModules.push(...externalExportAllModules);
  11848. }
  11849. render(options) {
  11850. const magicString = this.magicString.clone();
  11851. this.ast.render(magicString, options);
  11852. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  11853. return magicString;
  11854. }
  11855. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  11856. this.info.code = code;
  11857. this.originalCode = originalCode;
  11858. this.originalSourcemap = originalSourcemap;
  11859. this.sourcemapChain = sourcemapChain;
  11860. if (transformFiles) {
  11861. this.transformFiles = transformFiles;
  11862. }
  11863. this.transformDependencies = transformDependencies;
  11864. this.customTransformCache = customTransformCache;
  11865. this.updateOptions(moduleOptions);
  11866. timeStart('generate ast', 3);
  11867. if (!ast) {
  11868. ast = this.tryParse();
  11869. }
  11870. timeEnd('generate ast', 3);
  11871. this.resolvedIds = resolvedIds || Object.create(null);
  11872. // By default, `id` is the file name. Custom resolvers and loaders
  11873. // can change that, but it makes sense to use it for the source file name
  11874. const fileName = this.id;
  11875. this.magicString = new MagicString(code, {
  11876. filename: (this.excludeFromSourcemap ? null : fileName),
  11877. indentExclusionRanges: []
  11878. });
  11879. timeStart('analyse ast', 3);
  11880. this.astContext = {
  11881. addDynamicImport: this.addDynamicImport.bind(this),
  11882. addExport: this.addExport.bind(this),
  11883. addImport: this.addImport.bind(this),
  11884. addImportMeta: this.addImportMeta.bind(this),
  11885. code,
  11886. deoptimizationTracker: this.graph.deoptimizationTracker,
  11887. error: this.error.bind(this),
  11888. fileName,
  11889. getExports: this.getExports.bind(this),
  11890. getModuleExecIndex: () => this.execIndex,
  11891. getModuleName: this.basename.bind(this),
  11892. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  11893. getReexports: this.getReexports.bind(this),
  11894. importDescriptions: this.importDescriptions,
  11895. includeAllExports: () => this.includeAllExports(true),
  11896. includeDynamicImport: this.includeDynamicImport.bind(this),
  11897. includeVariableInModule: this.includeVariableInModule.bind(this),
  11898. magicString: this.magicString,
  11899. module: this,
  11900. moduleContext: this.context,
  11901. options: this.options,
  11902. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  11903. traceExport: (name) => this.getVariableForExportName(name)[0],
  11904. traceVariable: this.traceVariable.bind(this),
  11905. usesTopLevelAwait: false,
  11906. warn: this.warn.bind(this)
  11907. };
  11908. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  11909. this.namespace = new NamespaceVariable(this.astContext);
  11910. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  11911. this.info.ast = ast;
  11912. timeEnd('analyse ast', 3);
  11913. }
  11914. toJSON() {
  11915. return {
  11916. ast: this.ast.esTreeNode,
  11917. code: this.info.code,
  11918. customTransformCache: this.customTransformCache,
  11919. dependencies: Array.from(this.dependencies, getId),
  11920. id: this.id,
  11921. meta: this.info.meta,
  11922. moduleSideEffects: this.info.moduleSideEffects,
  11923. originalCode: this.originalCode,
  11924. originalSourcemap: this.originalSourcemap,
  11925. resolvedIds: this.resolvedIds,
  11926. sourcemapChain: this.sourcemapChain,
  11927. syntheticNamedExports: this.info.syntheticNamedExports,
  11928. transformDependencies: this.transformDependencies,
  11929. transformFiles: this.transformFiles
  11930. };
  11931. }
  11932. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  11933. const localVariable = this.scope.variables.get(name);
  11934. if (localVariable) {
  11935. return localVariable;
  11936. }
  11937. const importDeclaration = this.importDescriptions.get(name);
  11938. if (importDeclaration) {
  11939. const otherModule = importDeclaration.module;
  11940. if (otherModule instanceof Module && importDeclaration.name === '*') {
  11941. return otherModule.namespace;
  11942. }
  11943. const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  11944. if (!declaration) {
  11945. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  11946. }
  11947. return declaration;
  11948. }
  11949. return null;
  11950. }
  11951. tryParse() {
  11952. try {
  11953. return this.graph.contextParse(this.info.code);
  11954. }
  11955. catch (err) {
  11956. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  11957. if (this.id.endsWith('.json')) {
  11958. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  11959. }
  11960. else if (!this.id.endsWith('.js')) {
  11961. message += ' (Note that you need plugins to import files that are not JavaScript)';
  11962. }
  11963. return this.error({
  11964. code: 'PARSE_ERROR',
  11965. message,
  11966. parserError: err
  11967. }, err.pos);
  11968. }
  11969. }
  11970. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  11971. if (moduleSideEffects != null) {
  11972. this.info.moduleSideEffects = moduleSideEffects;
  11973. }
  11974. if (syntheticNamedExports != null) {
  11975. this.info.syntheticNamedExports = syntheticNamedExports;
  11976. }
  11977. if (meta != null) {
  11978. Object.assign(this.info.meta, meta);
  11979. }
  11980. }
  11981. warn(props, pos) {
  11982. this.addLocationToLogProps(props, pos);
  11983. this.options.onwarn(props);
  11984. }
  11985. addDynamicImport(node) {
  11986. let argument = node.source;
  11987. if (argument instanceof TemplateLiteral) {
  11988. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  11989. argument = argument.quasis[0].value.cooked;
  11990. }
  11991. }
  11992. else if (argument instanceof Literal && typeof argument.value === 'string') {
  11993. argument = argument.value;
  11994. }
  11995. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  11996. }
  11997. addExport(node) {
  11998. if (node instanceof ExportDefaultDeclaration) {
  11999. // export default foo;
  12000. this.exports.set('default', {
  12001. identifier: node.variable.getAssignedVariableName(),
  12002. localName: 'default'
  12003. });
  12004. }
  12005. else if (node instanceof ExportAllDeclaration) {
  12006. const source = node.source.value;
  12007. this.sources.add(source);
  12008. if (node.exported) {
  12009. // export * as name from './other'
  12010. const name = node.exported.name;
  12011. this.reexportDescriptions.set(name, {
  12012. localName: '*',
  12013. module: null,
  12014. source,
  12015. start: node.start
  12016. });
  12017. }
  12018. else {
  12019. // export * from './other'
  12020. this.exportAllSources.add(source);
  12021. }
  12022. }
  12023. else if (node.source instanceof Literal) {
  12024. // export { name } from './other'
  12025. const source = node.source.value;
  12026. this.sources.add(source);
  12027. for (const specifier of node.specifiers) {
  12028. const name = specifier.exported.name;
  12029. this.reexportDescriptions.set(name, {
  12030. localName: specifier.local.name,
  12031. module: null,
  12032. source,
  12033. start: specifier.start
  12034. });
  12035. }
  12036. }
  12037. else if (node.declaration) {
  12038. const declaration = node.declaration;
  12039. if (declaration instanceof VariableDeclaration) {
  12040. // export var { foo, bar } = ...
  12041. // export var foo = 1, bar = 2;
  12042. for (const declarator of declaration.declarations) {
  12043. for (const localName of extractAssignedNames(declarator.id)) {
  12044. this.exports.set(localName, { identifier: null, localName });
  12045. }
  12046. }
  12047. }
  12048. else {
  12049. // export function foo () {}
  12050. const localName = declaration.id.name;
  12051. this.exports.set(localName, { identifier: null, localName });
  12052. }
  12053. }
  12054. else {
  12055. // export { foo, bar, baz }
  12056. for (const specifier of node.specifiers) {
  12057. const localName = specifier.local.name;
  12058. const exportedName = specifier.exported.name;
  12059. this.exports.set(exportedName, { identifier: null, localName });
  12060. }
  12061. }
  12062. }
  12063. addImport(node) {
  12064. const source = node.source.value;
  12065. this.sources.add(source);
  12066. for (const specifier of node.specifiers) {
  12067. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  12068. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  12069. const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
  12070. this.importDescriptions.set(specifier.local.name, {
  12071. module: null,
  12072. name,
  12073. source,
  12074. start: specifier.start
  12075. });
  12076. }
  12077. }
  12078. addImportMeta(node) {
  12079. this.importMetas.push(node);
  12080. }
  12081. addLocationToLogProps(props, pos) {
  12082. props.id = this.id;
  12083. props.pos = pos;
  12084. let code = this.info.code;
  12085. const location = locate(code, pos, { offsetLine: 1 });
  12086. if (location) {
  12087. let { column, line } = location;
  12088. try {
  12089. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  12090. code = this.originalCode;
  12091. }
  12092. catch (err) {
  12093. this.options.onwarn({
  12094. code: 'SOURCEMAP_ERROR',
  12095. id: this.id,
  12096. loc: {
  12097. column,
  12098. file: this.id,
  12099. line
  12100. },
  12101. message: `Error when using sourcemap for reporting an error: ${err.message}`,
  12102. pos
  12103. });
  12104. }
  12105. augmentCodeLocation(props, { column, line }, code, this.id);
  12106. }
  12107. }
  12108. addModulesToImportDescriptions(importDescription) {
  12109. for (const specifier of importDescription.values()) {
  12110. const { id } = this.resolvedIds[specifier.source];
  12111. specifier.module = this.graph.modulesById.get(id);
  12112. }
  12113. }
  12114. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  12115. const handledDependencies = new Set();
  12116. const addSideEffectDependencies = (possibleDependencies) => {
  12117. for (const dependency of possibleDependencies) {
  12118. if (handledDependencies.has(dependency)) {
  12119. continue;
  12120. }
  12121. handledDependencies.add(dependency);
  12122. if (necessaryDependencies.has(dependency)) {
  12123. relevantDependencies.add(dependency);
  12124. continue;
  12125. }
  12126. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  12127. continue;
  12128. }
  12129. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  12130. relevantDependencies.add(dependency);
  12131. continue;
  12132. }
  12133. addSideEffectDependencies(dependency.dependencies);
  12134. }
  12135. };
  12136. addSideEffectDependencies(this.dependencies);
  12137. addSideEffectDependencies(alwaysCheckedDependencies);
  12138. }
  12139. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  12140. let foundSyntheticDeclaration = null;
  12141. const foundInternalDeclarations = new Map();
  12142. const foundExternalDeclarations = new Set();
  12143. for (const module of this.exportAllModules) {
  12144. // Synthetic namespaces should not hide "regular" exports of the same name
  12145. if (module.info.syntheticNamedExports === name) {
  12146. continue;
  12147. }
  12148. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  12149. // We are creating a copy to handle the case where the same binding is
  12150. // imported through different namespace reexports gracefully
  12151. copyNameToModulesMap(searchedNamesAndModules));
  12152. if (module instanceof ExternalModule || indirectExternal) {
  12153. foundExternalDeclarations.add(variable);
  12154. }
  12155. else if (variable instanceof SyntheticNamedExportVariable) {
  12156. if (!foundSyntheticDeclaration) {
  12157. foundSyntheticDeclaration = variable;
  12158. }
  12159. }
  12160. else if (variable) {
  12161. foundInternalDeclarations.set(variable, module);
  12162. }
  12163. }
  12164. if (foundInternalDeclarations.size > 0) {
  12165. const foundDeclarationList = [...foundInternalDeclarations];
  12166. const usedDeclaration = foundDeclarationList[0][0];
  12167. if (foundDeclarationList.length === 1) {
  12168. return [usedDeclaration];
  12169. }
  12170. this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  12171. // TODO we are pretending it was not found while it should behave like "undefined"
  12172. return [null];
  12173. }
  12174. if (foundExternalDeclarations.size > 0) {
  12175. const foundDeclarationList = [...foundExternalDeclarations];
  12176. const usedDeclaration = foundDeclarationList[0];
  12177. if (foundDeclarationList.length > 1) {
  12178. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  12179. }
  12180. return [usedDeclaration, true];
  12181. }
  12182. if (foundSyntheticDeclaration) {
  12183. return [foundSyntheticDeclaration];
  12184. }
  12185. return [null];
  12186. }
  12187. includeAndGetAdditionalMergedNamespaces() {
  12188. const externalNamespaces = new Set();
  12189. const syntheticNamespaces = new Set();
  12190. for (const module of [this, ...this.exportAllModules]) {
  12191. if (module instanceof ExternalModule) {
  12192. const [externalVariable] = module.getVariableForExportName('*');
  12193. externalVariable.include();
  12194. this.includedImports.add(externalVariable);
  12195. externalNamespaces.add(externalVariable);
  12196. }
  12197. else if (module.info.syntheticNamedExports) {
  12198. const syntheticNamespace = module.getSyntheticNamespace();
  12199. syntheticNamespace.include();
  12200. this.includedImports.add(syntheticNamespace);
  12201. syntheticNamespaces.add(syntheticNamespace);
  12202. }
  12203. }
  12204. return [...syntheticNamespaces, ...externalNamespaces];
  12205. }
  12206. includeDynamicImport(node) {
  12207. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  12208. if (resolution instanceof Module) {
  12209. resolution.includedDynamicImporters.push(this);
  12210. resolution.includeAllExports(true);
  12211. }
  12212. }
  12213. includeVariable(variable) {
  12214. if (!variable.included) {
  12215. variable.include();
  12216. this.graph.needsTreeshakingPass = true;
  12217. const variableModule = variable.module;
  12218. if (variableModule instanceof Module) {
  12219. if (!variableModule.isExecuted) {
  12220. markModuleAndImpureDependenciesAsExecuted(variableModule);
  12221. }
  12222. if (variableModule !== this) {
  12223. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  12224. for (const module of sideEffectModules) {
  12225. if (!module.isExecuted) {
  12226. markModuleAndImpureDependenciesAsExecuted(module);
  12227. }
  12228. }
  12229. }
  12230. }
  12231. }
  12232. }
  12233. includeVariableInModule(variable) {
  12234. this.includeVariable(variable);
  12235. const variableModule = variable.module;
  12236. if (variableModule && variableModule !== this) {
  12237. this.includedImports.add(variable);
  12238. }
  12239. }
  12240. shimMissingExport(name) {
  12241. this.options.onwarn({
  12242. code: 'SHIMMED_EXPORT',
  12243. exporter: relativeId(this.id),
  12244. exportName: name,
  12245. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  12246. });
  12247. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  12248. }
  12249. }
  12250. // if there is a cyclic import in the reexport chain, we should not
  12251. // import from the original module but from the cyclic module to not
  12252. // mess up execution order.
  12253. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  12254. if (variable.module instanceof Module && variable.module !== reexporter) {
  12255. const exporterCycles = variable.module.cycles;
  12256. if (exporterCycles.size > 0) {
  12257. const importerCycles = reexporter.cycles;
  12258. for (const cycleSymbol of importerCycles) {
  12259. if (exporterCycles.has(cycleSymbol)) {
  12260. importer.alternativeReexportModules.set(variable, reexporter);
  12261. break;
  12262. }
  12263. }
  12264. }
  12265. }
  12266. }
  12267. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  12268. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  12269. function removeJsExtension(name) {
  12270. return name.endsWith('.js') ? name.slice(0, -3) : name;
  12271. }
  12272. function getCompleteAmdId(options, chunkId) {
  12273. if (options.autoId) {
  12274. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  12275. }
  12276. return options.id || '';
  12277. }
  12278. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  12279. const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  12280. if (!namedExportsMode) {
  12281. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  12282. }
  12283. let exportBlock = '';
  12284. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12285. if (reexports && namedExportsMode) {
  12286. for (const specifier of reexports) {
  12287. if (specifier.reexported !== '*') {
  12288. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12289. if (exportBlock)
  12290. exportBlock += n;
  12291. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  12292. const [left, right] = getDirectReturnFunction([], {
  12293. functionReturn: true,
  12294. lineBreakIndent: null,
  12295. name: null
  12296. });
  12297. exportBlock +=
  12298. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  12299. `${t}enumerable:${_}true,${n}` +
  12300. `${t}get:${_}${left}${importName}${right}${n}});`;
  12301. }
  12302. else {
  12303. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  12304. }
  12305. }
  12306. }
  12307. }
  12308. }
  12309. for (const { exported, local } of exports) {
  12310. const lhs = `exports${getPropertyAccess(exported)}`;
  12311. const rhs = local;
  12312. if (lhs !== rhs) {
  12313. if (exportBlock)
  12314. exportBlock += n;
  12315. exportBlock += `${lhs}${_}=${_}${rhs};`;
  12316. }
  12317. }
  12318. for (const { name, reexports } of dependencies) {
  12319. if (reexports && namedExportsMode) {
  12320. for (const specifier of reexports) {
  12321. if (specifier.reexported === '*') {
  12322. if (exportBlock)
  12323. exportBlock += n;
  12324. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  12325. exportBlock +=
  12326. cnst === 'var' && specifier.needsLiveBinding
  12327. ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  12328. isAsync: false,
  12329. name: null
  12330. })}${copyPropertyIfNecessary});`
  12331. : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
  12332. }
  12333. }
  12334. }
  12335. }
  12336. if (exportBlock) {
  12337. return `${n}${n}${exportBlock}`;
  12338. }
  12339. return '';
  12340. }
  12341. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  12342. if (exports.length > 0) {
  12343. return exports[0].local;
  12344. }
  12345. else {
  12346. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12347. if (reexports) {
  12348. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12349. }
  12350. }
  12351. }
  12352. }
  12353. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  12354. if (imported === 'default') {
  12355. if (!isChunk) {
  12356. const moduleInterop = String(interop(moduleId));
  12357. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  12358. ? defaultVariableName
  12359. : moduleVariableName;
  12360. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  12361. ? `${variableName}${getPropertyAccess('default')}`
  12362. : variableName;
  12363. }
  12364. return depNamedExportsMode
  12365. ? `${moduleVariableName}${getPropertyAccess('default')}`
  12366. : moduleVariableName;
  12367. }
  12368. if (imported === '*') {
  12369. return (isChunk
  12370. ? !depNamedExportsMode
  12371. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  12372. ? namespaceVariableName
  12373. : moduleVariableName;
  12374. }
  12375. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  12376. }
  12377. function getEsModuleValue(getObject) {
  12378. return getObject([['value', 'true']], {
  12379. lineBreakIndent: null
  12380. });
  12381. }
  12382. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  12383. if (hasNamedExports) {
  12384. if (addEsModule) {
  12385. if (addNamespaceToStringTag) {
  12386. return `Object.defineProperties(exports,${_}${getObject([
  12387. ['__esModule', getEsModuleValue(getObject)],
  12388. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  12389. ], {
  12390. lineBreakIndent: null
  12391. })});`;
  12392. }
  12393. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  12394. }
  12395. if (addNamespaceToStringTag) {
  12396. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  12397. }
  12398. }
  12399. return '';
  12400. }
  12401. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  12402. if (needsLiveBinding) {
  12403. const [left, right] = getDirectReturnFunction([], {
  12404. functionReturn: true,
  12405. lineBreakIndent: null,
  12406. name: null
  12407. });
  12408. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  12409. `${t}${t}enumerable:${_}true,${n}` +
  12410. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  12411. }
  12412. return `exports[k]${_}=${_}${name}[k]`;
  12413. };
  12414. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  12415. const { _, cnst, n } = snippets;
  12416. const neededInteropHelpers = new Set();
  12417. const interopStatements = [];
  12418. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  12419. neededInteropHelpers.add(helper);
  12420. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  12421. };
  12422. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12423. if (isChunk) {
  12424. for (const { imported, reexported } of [
  12425. ...(imports || []),
  12426. ...(reexports || [])
  12427. ]) {
  12428. if (imported === '*' && reexported !== '*') {
  12429. if (!namedExportsMode) {
  12430. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  12431. }
  12432. break;
  12433. }
  12434. }
  12435. }
  12436. else {
  12437. const moduleInterop = String(interop(id));
  12438. let hasDefault = false;
  12439. let hasNamespace = false;
  12440. for (const { imported, reexported } of [
  12441. ...(imports || []),
  12442. ...(reexports || [])
  12443. ]) {
  12444. let helper;
  12445. let variableName;
  12446. if (imported === 'default') {
  12447. if (!hasDefault) {
  12448. hasDefault = true;
  12449. if (defaultVariableName !== namespaceVariableName) {
  12450. variableName = defaultVariableName;
  12451. helper = defaultInteropHelpersByInteropType[moduleInterop];
  12452. }
  12453. }
  12454. }
  12455. else if (imported === '*' && reexported !== '*') {
  12456. if (!hasNamespace) {
  12457. hasNamespace = true;
  12458. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  12459. variableName = namespaceVariableName;
  12460. }
  12461. }
  12462. if (helper) {
  12463. addInteropStatement(variableName, helper, name);
  12464. }
  12465. }
  12466. }
  12467. }
  12468. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  12469. }
  12470. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  12471. // The assumption is that this makes sense for all relative ids:
  12472. // https://requirejs.org/docs/api.html#jsfiles
  12473. function removeExtensionFromRelativeAmdId(id) {
  12474. return id[0] === '.' ? removeJsExtension(id) : id;
  12475. }
  12476. const builtins = {
  12477. assert: true,
  12478. buffer: true,
  12479. console: true,
  12480. constants: true,
  12481. domain: true,
  12482. events: true,
  12483. http: true,
  12484. https: true,
  12485. os: true,
  12486. path: true,
  12487. process: true,
  12488. punycode: true,
  12489. querystring: true,
  12490. stream: true,
  12491. string_decoder: true,
  12492. timers: true,
  12493. tty: true,
  12494. url: true,
  12495. util: true,
  12496. vm: true,
  12497. zlib: true
  12498. };
  12499. function warnOnBuiltins(warn, dependencies) {
  12500. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  12501. if (!externalBuiltins.length)
  12502. return;
  12503. warn({
  12504. code: 'MISSING_NODE_BUILTINS',
  12505. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`,
  12506. modules: externalBuiltins
  12507. });
  12508. }
  12509. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12510. warnOnBuiltins(warn, dependencies);
  12511. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  12512. const args = dependencies.map(m => m.name);
  12513. const { n, getNonArrowFunctionIntro, _ } = snippets;
  12514. if (namedExportsMode && hasExports) {
  12515. args.unshift(`exports`);
  12516. deps.unshift(`'exports'`);
  12517. }
  12518. if (accessedGlobals.has('require')) {
  12519. args.unshift('require');
  12520. deps.unshift(`'require'`);
  12521. }
  12522. if (accessedGlobals.has('module')) {
  12523. args.unshift('module');
  12524. deps.unshift(`'module'`);
  12525. }
  12526. const completeAmdId = getCompleteAmdId(amd, id);
  12527. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12528. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  12529. const useStrict = strict ? `${_}'use strict';` : '';
  12530. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  12531. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12532. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12533. if (namespaceMarkers) {
  12534. namespaceMarkers = n + n + namespaceMarkers;
  12535. }
  12536. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12537. return (magicString
  12538. .indent(t)
  12539. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12540. // cf. https://v8.dev/blog/preparser#pife
  12541. .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
  12542. isAsync: false,
  12543. name: null
  12544. })}{${useStrict}${n}${n}`)
  12545. .append(`${n}${n}}));`));
  12546. }
  12547. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12548. const { _, n } = snippets;
  12549. const useStrict = strict ? `'use strict';${n}${n}` : '';
  12550. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12551. if (namespaceMarkers) {
  12552. namespaceMarkers += n + n;
  12553. }
  12554. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  12555. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12556. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  12557. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  12558. return magicString.append(`${exportBlock}${outro}`);
  12559. }
  12560. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  12561. let importBlock = '';
  12562. let definingVariable = false;
  12563. for (const { id, name, reexports, imports } of dependencies) {
  12564. if (!reexports && !imports) {
  12565. if (importBlock) {
  12566. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  12567. }
  12568. definingVariable = false;
  12569. importBlock += `require('${id}')`;
  12570. }
  12571. else {
  12572. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  12573. definingVariable = true;
  12574. importBlock += `${name}${_}=${_}require('${id}')`;
  12575. }
  12576. }
  12577. if (importBlock) {
  12578. return `${importBlock};${n}${n}`;
  12579. }
  12580. return '';
  12581. }
  12582. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  12583. const { _, n } = snippets;
  12584. const importBlock = getImportBlock(dependencies, _);
  12585. if (importBlock.length > 0)
  12586. intro += importBlock.join(n) + n + n;
  12587. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  12588. if (intro)
  12589. magicString.prepend(intro);
  12590. const exportBlock = getExportBlock(exports, snippets);
  12591. if (exportBlock.length)
  12592. magicString.append(n + n + exportBlock.join(n).trim());
  12593. if (outro)
  12594. magicString.append(outro);
  12595. return magicString.trim();
  12596. }
  12597. function getImportBlock(dependencies, _) {
  12598. const importBlock = [];
  12599. for (const { id, reexports, imports, name } of dependencies) {
  12600. if (!reexports && !imports) {
  12601. importBlock.push(`import${_}'${id}';`);
  12602. continue;
  12603. }
  12604. if (imports) {
  12605. let defaultImport = null;
  12606. let starImport = null;
  12607. const importedNames = [];
  12608. for (const specifier of imports) {
  12609. if (specifier.imported === 'default') {
  12610. defaultImport = specifier;
  12611. }
  12612. else if (specifier.imported === '*') {
  12613. starImport = specifier;
  12614. }
  12615. else {
  12616. importedNames.push(specifier);
  12617. }
  12618. }
  12619. if (starImport) {
  12620. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  12621. }
  12622. if (defaultImport && importedNames.length === 0) {
  12623. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  12624. }
  12625. else if (importedNames.length > 0) {
  12626. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  12627. .map(specifier => {
  12628. if (specifier.imported === specifier.local) {
  12629. return specifier.imported;
  12630. }
  12631. else {
  12632. return `${specifier.imported} as ${specifier.local}`;
  12633. }
  12634. })
  12635. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12636. }
  12637. }
  12638. if (reexports) {
  12639. let starExport = null;
  12640. const namespaceReexports = [];
  12641. const namedReexports = [];
  12642. for (const specifier of reexports) {
  12643. if (specifier.reexported === '*') {
  12644. starExport = specifier;
  12645. }
  12646. else if (specifier.imported === '*') {
  12647. namespaceReexports.push(specifier);
  12648. }
  12649. else {
  12650. namedReexports.push(specifier);
  12651. }
  12652. }
  12653. if (starExport) {
  12654. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  12655. }
  12656. if (namespaceReexports.length > 0) {
  12657. if (!imports ||
  12658. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  12659. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  12660. }
  12661. for (const specifier of namespaceReexports) {
  12662. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  12663. }
  12664. }
  12665. if (namedReexports.length > 0) {
  12666. importBlock.push(`export${_}{${_}${namedReexports
  12667. .map(specifier => {
  12668. if (specifier.imported === specifier.reexported) {
  12669. return specifier.imported;
  12670. }
  12671. else {
  12672. return `${specifier.imported} as ${specifier.reexported}`;
  12673. }
  12674. })
  12675. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12676. }
  12677. }
  12678. }
  12679. return importBlock;
  12680. }
  12681. function getExportBlock(exports, { _, cnst }) {
  12682. const exportBlock = [];
  12683. const exportDeclaration = [];
  12684. for (const specifier of exports) {
  12685. if (specifier.expression) {
  12686. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  12687. }
  12688. exportDeclaration.push(specifier.exported === specifier.local
  12689. ? specifier.local
  12690. : `${specifier.local} as ${specifier.exported}`);
  12691. }
  12692. if (exportDeclaration.length) {
  12693. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  12694. }
  12695. return exportBlock;
  12696. }
  12697. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  12698. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  12699. const parts = name.split('.');
  12700. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12701. parts.pop();
  12702. let propertyPath = root;
  12703. return (parts
  12704. .map(part => {
  12705. propertyPath += getPropertyAccess(part);
  12706. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  12707. })
  12708. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  12709. }
  12710. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  12711. const parts = deepName.split('.');
  12712. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12713. const last = parts.pop();
  12714. let propertyPath = root;
  12715. let deepAssignment = parts
  12716. .map(part => {
  12717. propertyPath += getPropertyAccess(part);
  12718. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12719. })
  12720. .concat(`${propertyPath}${getPropertyAccess(last)}`)
  12721. .join(`,${_}`) + `${_}=${_}${assignment}`;
  12722. if (parts.length > 0) {
  12723. deepAssignment = `(${deepAssignment})`;
  12724. }
  12725. return deepAssignment;
  12726. }
  12727. function trimEmptyImports(dependencies) {
  12728. let i = dependencies.length;
  12729. while (i--) {
  12730. const { imports, reexports } = dependencies[i];
  12731. if (imports || reexports) {
  12732. return dependencies.slice(0, i + 1);
  12733. }
  12734. }
  12735. return [];
  12736. }
  12737. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  12738. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12739. const isNamespaced = name && name.includes('.');
  12740. const useVariableAssignment = !extend && !isNamespaced;
  12741. if (name && useVariableAssignment && !isLegal(name)) {
  12742. return error({
  12743. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  12744. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  12745. });
  12746. }
  12747. warnOnBuiltins(warn, dependencies);
  12748. const external = trimEmptyImports(dependencies);
  12749. const deps = external.map(dep => dep.globalName || 'null');
  12750. const args = external.map(m => m.name);
  12751. if (hasExports && !name) {
  12752. warn({
  12753. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12754. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  12755. });
  12756. }
  12757. if (namedExportsMode && hasExports) {
  12758. if (extend) {
  12759. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12760. args.unshift('exports');
  12761. }
  12762. else {
  12763. deps.unshift('{}');
  12764. args.unshift('exports');
  12765. }
  12766. }
  12767. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12768. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12769. magicString.prepend(`${intro}${interopBlock}`);
  12770. let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
  12771. isAsync: false,
  12772. name: null
  12773. })}{${n}${useStrict}${n}`;
  12774. if (hasExports) {
  12775. if (name && !(extend && namedExportsMode)) {
  12776. wrapperIntro =
  12777. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12778. `${_}=${_}${wrapperIntro}`;
  12779. }
  12780. if (isNamespaced) {
  12781. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  12782. }
  12783. }
  12784. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12785. if (hasExports && !extend && namedExportsMode) {
  12786. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12787. }
  12788. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12789. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  12790. if (namespaceMarkers) {
  12791. namespaceMarkers = n + n + namespaceMarkers;
  12792. }
  12793. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12794. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  12795. }
  12796. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  12797. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12798. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  12799. const registeredName = name ? `'${name}',${_}` : '';
  12800. const wrapperParams = accessedGlobals.has('module')
  12801. ? ['exports', 'module']
  12802. : hasExports
  12803. ? ['exports']
  12804. : [];
  12805. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12806. // cf. https://v8.dev/blog/preparser#pife
  12807. let wrapperStart = `System.register(${registeredName}[` +
  12808. dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
  12809. `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12810. getStarExcludesBlock(starExcludes, t, snippets) +
  12811. getImportBindingsBlock(importBindings, t, snippets) +
  12812. `${n}${t}return${_}{${setters.length
  12813. ? `${n}${t}${t}setters:${_}[${setters
  12814. .map(setter => setter
  12815. ? `${getFunctionIntro(['module'], {
  12816. isAsync: false,
  12817. name: null
  12818. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12819. : systemNullSetters
  12820. ? `null`
  12821. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12822. .join(`,${_}`)}],`
  12823. : ''}${n}`;
  12824. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12825. isAsync: usesTopLevelAwait,
  12826. name: null
  12827. })}{${n}${n}`;
  12828. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12829. magicString.prepend(intro +
  12830. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  12831. getHoistedExportsBlock(exports, t, snippets));
  12832. magicString.append(`${outro}${n}${n}` +
  12833. getSyntheticExportsBlock(exports, t, snippets) +
  12834. getMissingExportsBlock(exports, t, snippets));
  12835. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  12836. }
  12837. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12838. const importBindings = [];
  12839. const setters = [];
  12840. let starExcludes = null;
  12841. for (const { imports, reexports } of dependencies) {
  12842. const setter = [];
  12843. if (imports) {
  12844. for (const specifier of imports) {
  12845. importBindings.push(specifier.local);
  12846. if (specifier.imported === '*') {
  12847. setter.push(`${specifier.local}${_}=${_}module;`);
  12848. }
  12849. else {
  12850. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12851. }
  12852. }
  12853. }
  12854. if (reexports) {
  12855. const reexportedNames = [];
  12856. let hasStarReexport = false;
  12857. for (const { imported, reexported } of reexports) {
  12858. if (reexported === '*') {
  12859. hasStarReexport = true;
  12860. }
  12861. else {
  12862. reexportedNames.push([
  12863. reexported,
  12864. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  12865. ]);
  12866. }
  12867. }
  12868. if (reexportedNames.length > 1 || hasStarReexport) {
  12869. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12870. if (hasStarReexport) {
  12871. if (!starExcludes) {
  12872. starExcludes = getStarExcludes({ dependencies, exports });
  12873. }
  12874. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  12875. }
  12876. else {
  12877. setter.push(`exports(${exportMapping});`);
  12878. }
  12879. }
  12880. else {
  12881. const [key, value] = reexportedNames[0];
  12882. setter.push(`exports('${key}',${_}${value});`);
  12883. }
  12884. }
  12885. setters.push(setter.join(`${n}${t}${t}${t}`));
  12886. }
  12887. return { importBindings, setters, starExcludes };
  12888. }
  12889. const getStarExcludes = ({ dependencies, exports }) => {
  12890. const starExcludes = new Set(exports.map(expt => expt.exported));
  12891. starExcludes.add('default');
  12892. for (const { reexports } of dependencies) {
  12893. if (reexports) {
  12894. for (const reexport of reexports) {
  12895. if (reexport.reexported !== '*')
  12896. starExcludes.add(reexport.reexported);
  12897. }
  12898. }
  12899. }
  12900. return starExcludes;
  12901. };
  12902. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  12903. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
  12904. : '';
  12905. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  12906. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12907. function getExportsBlock(exports, t, { _, n }) {
  12908. if (exports.length === 0) {
  12909. return '';
  12910. }
  12911. if (exports.length === 1) {
  12912. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  12913. }
  12914. return (`exports({${n}` +
  12915. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  12916. `${n}});${n}${n}`);
  12917. }
  12918. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12919. .filter(expt => expt.expression)
  12920. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12921. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12922. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  12923. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  12924. function globalProp(name, globalVar, getPropertyAccess) {
  12925. if (!name)
  12926. return 'null';
  12927. return `${globalVar}${keypath(name, getPropertyAccess)}`;
  12928. }
  12929. function safeAccess(name, globalVar, { _, getPropertyAccess }) {
  12930. let propertyPath = globalVar;
  12931. return name
  12932. .split('.')
  12933. .map(part => (propertyPath += getPropertyAccess(part)))
  12934. .join(`${_}&&${_}`);
  12935. }
  12936. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, namedExportsMode, outro, snippets, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  12937. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  12938. const factoryVar = compact ? 'f' : 'factory';
  12939. const globalVar = compact ? 'g' : 'global';
  12940. if (hasExports && !name) {
  12941. return error({
  12942. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12943. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  12944. });
  12945. }
  12946. warnOnBuiltins(warn, dependencies);
  12947. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  12948. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  12949. const trimmedImports = trimEmptyImports(dependencies);
  12950. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
  12951. const factoryParams = trimmedImports.map(m => m.name);
  12952. if (namedExportsMode && (hasExports || noConflict)) {
  12953. amdDeps.unshift(`'exports'`);
  12954. cjsDeps.unshift(`exports`);
  12955. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  12956. factoryParams.unshift('exports');
  12957. }
  12958. const completeAmdId = getCompleteAmdId(amd, id);
  12959. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12960. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  12961. const define = amd.define;
  12962. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  12963. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  12964. let iifeExport;
  12965. if (noConflict) {
  12966. const noConflictExportsVar = compact ? 'e' : 'exports';
  12967. let factory;
  12968. if (!namedExportsMode && hasExports) {
  12969. factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  12970. }
  12971. else {
  12972. const module = globalDeps.shift();
  12973. factory =
  12974. `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
  12975. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  12976. }
  12977. iifeExport =
  12978. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  12979. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
  12980. `${t}${t}${factory}${n}` +
  12981. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
  12982. isAsync: false,
  12983. name: null
  12984. })}{${_}` +
  12985. `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
  12986. `${t}})()`;
  12987. }
  12988. else {
  12989. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  12990. if (!namedExportsMode && hasExports) {
  12991. iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
  12992. }
  12993. }
  12994. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  12995. const wrapperParams = [factoryVar];
  12996. if (iifeNeedsGlobal) {
  12997. wrapperParams.unshift(globalVar);
  12998. }
  12999. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  13000. const iifeStart = iifeNeedsGlobal
  13001. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  13002. : '';
  13003. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  13004. const cjsIntro = iifeNeedsGlobal
  13005. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  13006. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  13007. : '';
  13008. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
  13009. cjsIntro +
  13010. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  13011. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  13012. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13013. // cf. https://v8.dev/blog/preparser#pife
  13014. `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
  13015. isAsync: false,
  13016. name: null
  13017. })}{${useStrict}${n}`;
  13018. const wrapperOutro = n + n + '}));';
  13019. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13020. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13021. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  13022. if (namespaceMarkers) {
  13023. namespaceMarkers = n + n + namespaceMarkers;
  13024. }
  13025. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  13026. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  13027. }
  13028. const finalisers = { amd, cjs, es, iife, system, umd };
  13029. class Source {
  13030. constructor(filename, content) {
  13031. this.isOriginal = true;
  13032. this.filename = filename;
  13033. this.content = content;
  13034. }
  13035. traceSegment(line, column, name) {
  13036. return { column, line, name, source: this };
  13037. }
  13038. }
  13039. class Link {
  13040. constructor(map, sources) {
  13041. this.sources = sources;
  13042. this.names = map.names;
  13043. this.mappings = map.mappings;
  13044. }
  13045. traceMappings() {
  13046. const sources = [];
  13047. const sourceIndexMap = new Map();
  13048. const sourcesContent = [];
  13049. const names = [];
  13050. const nameIndexMap = new Map();
  13051. const mappings = [];
  13052. for (const line of this.mappings) {
  13053. const tracedLine = [];
  13054. for (const segment of line) {
  13055. if (segment.length === 1)
  13056. continue;
  13057. const source = this.sources[segment[1]];
  13058. if (!source)
  13059. continue;
  13060. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  13061. if (traced) {
  13062. const { column, line, name, source: { content, filename } } = traced;
  13063. let sourceIndex = sourceIndexMap.get(filename);
  13064. if (sourceIndex === undefined) {
  13065. sourceIndex = sources.length;
  13066. sources.push(filename);
  13067. sourceIndexMap.set(filename, sourceIndex);
  13068. sourcesContent[sourceIndex] = content;
  13069. }
  13070. else if (sourcesContent[sourceIndex] == null) {
  13071. sourcesContent[sourceIndex] = content;
  13072. }
  13073. else if (content != null && sourcesContent[sourceIndex] !== content) {
  13074. return error({
  13075. message: `Multiple conflicting contents for sourcemap source ${filename}`
  13076. });
  13077. }
  13078. const tracedSegment = [segment[0], sourceIndex, line, column];
  13079. if (name) {
  13080. let nameIndex = nameIndexMap.get(name);
  13081. if (nameIndex === undefined) {
  13082. nameIndex = names.length;
  13083. names.push(name);
  13084. nameIndexMap.set(name, nameIndex);
  13085. }
  13086. tracedSegment[4] = nameIndex;
  13087. }
  13088. tracedLine.push(tracedSegment);
  13089. }
  13090. }
  13091. mappings.push(tracedLine);
  13092. }
  13093. return { mappings, names, sources, sourcesContent };
  13094. }
  13095. traceSegment(line, column, name) {
  13096. const segments = this.mappings[line];
  13097. if (!segments)
  13098. return null;
  13099. // binary search through segments for the given column
  13100. let searchStart = 0;
  13101. let searchEnd = segments.length - 1;
  13102. while (searchStart <= searchEnd) {
  13103. const m = (searchStart + searchEnd) >> 1;
  13104. const segment = segments[m];
  13105. // If a sourcemap does not have sufficient resolution to contain a
  13106. // necessary mapping, e.g. because it only contains line information, we
  13107. // use the best approximation we could find
  13108. if (segment[0] === column || searchStart === searchEnd) {
  13109. if (segment.length == 1)
  13110. return null;
  13111. const source = this.sources[segment[1]];
  13112. if (!source)
  13113. return null;
  13114. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  13115. }
  13116. if (segment[0] > column) {
  13117. searchEnd = m - 1;
  13118. }
  13119. else {
  13120. searchStart = m + 1;
  13121. }
  13122. }
  13123. return null;
  13124. }
  13125. }
  13126. function getLinkMap(warn) {
  13127. return function linkMap(source, map) {
  13128. if (map.mappings) {
  13129. return new Link(map, [source]);
  13130. }
  13131. warn({
  13132. code: 'SOURCEMAP_BROKEN',
  13133. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  13134. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  13135. 'documentation for help',
  13136. plugin: map.plugin,
  13137. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  13138. });
  13139. return new Link({
  13140. mappings: [],
  13141. names: []
  13142. }, [source]);
  13143. };
  13144. }
  13145. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  13146. let source;
  13147. if (!originalSourcemap) {
  13148. source = new Source(id, originalCode);
  13149. }
  13150. else {
  13151. const sources = originalSourcemap.sources;
  13152. const sourcesContent = originalSourcemap.sourcesContent || [];
  13153. const directory = dirname(id) || '.';
  13154. const sourceRoot = originalSourcemap.sourceRoot || '.';
  13155. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  13156. source = new Link(originalSourcemap, baseSources);
  13157. }
  13158. return sourcemapChain.reduce(linkMap, source);
  13159. }
  13160. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  13161. const linkMap = getLinkMap(warn);
  13162. const moduleSources = modules
  13163. .filter(module => !module.excludeFromSourcemap)
  13164. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  13165. const link = new Link(map, moduleSources);
  13166. const source = bundleSourcemapChain.reduce(linkMap, link);
  13167. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  13168. if (file) {
  13169. const directory = dirname(file);
  13170. sources = sources.map((source) => relative$1(directory, source));
  13171. file = basename(file);
  13172. }
  13173. sourcesContent = (excludeContent ? null : sourcesContent);
  13174. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  13175. }
  13176. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  13177. if (!sourcemapChain.length) {
  13178. return originalSourcemap;
  13179. }
  13180. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  13181. const map = source.traceMappings();
  13182. return { version: 3, ...map };
  13183. }
  13184. const createHash = () => createHash$1('sha256');
  13185. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  13186. amd: deconflictImportsOther,
  13187. cjs: deconflictImportsOther,
  13188. es: deconflictImportsEsmOrSystem,
  13189. iife: deconflictImportsOther,
  13190. system: deconflictImportsEsmOrSystem,
  13191. umd: deconflictImportsOther
  13192. };
  13193. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  13194. const reversedModules = modules.slice().reverse();
  13195. for (const module of reversedModules) {
  13196. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  13197. }
  13198. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  13199. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  13200. for (const module of reversedModules) {
  13201. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13202. }
  13203. }
  13204. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  13205. // This is needed for namespace reexports
  13206. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  13207. if (preserveModules || dependency instanceof ExternalModule) {
  13208. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  13209. }
  13210. }
  13211. for (const variable of imports) {
  13212. const module = variable.module;
  13213. const name = variable.name;
  13214. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  13215. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  13216. }
  13217. else if (module instanceof ExternalModule && name === 'default') {
  13218. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  13219. ? module.suggestedVariableName + '__default'
  13220. : module.suggestedVariableName, usedNames));
  13221. }
  13222. else {
  13223. variable.setRenderNames(null, getSafeName(name, usedNames));
  13224. }
  13225. }
  13226. for (const variable of syntheticExports) {
  13227. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13228. }
  13229. }
  13230. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  13231. for (const chunkOrExternalModule of dependencies) {
  13232. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  13233. }
  13234. for (const externalModuleOrChunk of deconflictedNamespace) {
  13235. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  13236. }
  13237. for (const externalModule of deconflictedDefault) {
  13238. if (deconflictedNamespace.has(externalModule) &&
  13239. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  13240. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  13241. }
  13242. else {
  13243. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  13244. }
  13245. }
  13246. for (const variable of imports) {
  13247. const module = variable.module;
  13248. if (module instanceof ExternalModule) {
  13249. const name = variable.name;
  13250. if (name === 'default') {
  13251. const moduleInterop = String(interop(module.id));
  13252. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13253. ? module.defaultVariableName
  13254. : module.variableName;
  13255. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  13256. variable.setRenderNames(variableName, 'default');
  13257. }
  13258. else {
  13259. variable.setRenderNames(null, variableName);
  13260. }
  13261. }
  13262. else if (name === '*') {
  13263. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  13264. ? module.namespaceVariableName
  13265. : module.variableName);
  13266. }
  13267. else {
  13268. // if the second parameter is `null`, it uses its "name" for the property name
  13269. variable.setRenderNames(module.variableName, null);
  13270. }
  13271. }
  13272. else {
  13273. const chunk = chunkByModule.get(module);
  13274. if (preserveModules && variable.isNamespace) {
  13275. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  13276. }
  13277. else if (chunk.exportMode === 'default') {
  13278. variable.setRenderNames(null, chunk.variableName);
  13279. }
  13280. else {
  13281. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  13282. }
  13283. }
  13284. }
  13285. }
  13286. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  13287. for (const module of modules) {
  13288. for (const variable of module.scope.variables.values()) {
  13289. if (variable.included &&
  13290. // this will only happen for exports in some formats
  13291. !(variable.renderBaseName ||
  13292. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  13293. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13294. }
  13295. }
  13296. if (includedNamespaces.has(module)) {
  13297. const namespace = module.namespace;
  13298. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  13299. }
  13300. }
  13301. }
  13302. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  13303. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  13304. const backSlashRegEx = /\\/g;
  13305. function escapeId(id) {
  13306. if (!id.match(needsEscapeRegEx))
  13307. return id;
  13308. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  13309. }
  13310. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  13311. let nameIndex = 0;
  13312. for (const variable of exports) {
  13313. let [exportName] = variable.name;
  13314. if (exportsByName.has(exportName)) {
  13315. do {
  13316. exportName = toBase64(++nameIndex);
  13317. // skip past leading number identifiers
  13318. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  13319. nameIndex += 9 * 64 ** (exportName.length - 1);
  13320. exportName = toBase64(nameIndex);
  13321. }
  13322. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  13323. }
  13324. exportsByName.set(exportName, variable);
  13325. exportNamesByVariable.set(variable, [exportName]);
  13326. }
  13327. }
  13328. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  13329. for (const variable of exports) {
  13330. let nameIndex = 0;
  13331. let exportName = variable.name;
  13332. while (exportsByName.has(exportName)) {
  13333. exportName = variable.name + '$' + ++nameIndex;
  13334. }
  13335. exportsByName.set(exportName, variable);
  13336. exportNamesByVariable.set(variable, [exportName]);
  13337. }
  13338. }
  13339. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  13340. const exportKeys = chunk.getExportNames();
  13341. if (exportMode === 'default') {
  13342. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13343. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13344. }
  13345. }
  13346. else if (exportMode === 'none' && exportKeys.length) {
  13347. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13348. }
  13349. if (exportMode === 'auto') {
  13350. if (exportKeys.length === 0) {
  13351. exportMode = 'none';
  13352. }
  13353. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13354. if (format === 'cjs' && unsetOptions.has('exports')) {
  13355. warn(errPreferNamedExports(facadeModuleId));
  13356. }
  13357. exportMode = 'default';
  13358. }
  13359. else {
  13360. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  13361. warn(errMixedExport(facadeModuleId, name));
  13362. }
  13363. exportMode = 'named';
  13364. }
  13365. }
  13366. return exportMode;
  13367. }
  13368. function guessIndentString(code) {
  13369. const lines = code.split('\n');
  13370. const tabbed = lines.filter(line => /^\t+/.test(line));
  13371. const spaced = lines.filter(line => /^ {2,}/.test(line));
  13372. if (tabbed.length === 0 && spaced.length === 0) {
  13373. return null;
  13374. }
  13375. // More lines tabbed than spaced? Assume tabs, and
  13376. // default to tabs in the case of a tie (or nothing
  13377. // to go on)
  13378. if (tabbed.length >= spaced.length) {
  13379. return '\t';
  13380. }
  13381. // Otherwise, we need to guess the multiple
  13382. const min = spaced.reduce((previous, current) => {
  13383. const numSpaces = /^ +/.exec(current)[0].length;
  13384. return Math.min(numSpaces, previous);
  13385. }, Infinity);
  13386. return new Array(min + 1).join(' ');
  13387. }
  13388. function getIndentString(modules, options) {
  13389. if (options.indent !== true)
  13390. return options.indent;
  13391. for (const module of modules) {
  13392. const indent = guessIndentString(module.originalCode);
  13393. if (indent !== null)
  13394. return indent;
  13395. }
  13396. return '\t';
  13397. }
  13398. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  13399. const staticDependencyBlocks = [];
  13400. const handledDependencies = new Set();
  13401. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  13402. const module = orderedModules[modulePos];
  13403. if (!handledDependencies.has(module)) {
  13404. const staticDependencies = [];
  13405. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  13406. staticDependencyBlocks.unshift(staticDependencies);
  13407. }
  13408. }
  13409. const dependencies = new Set();
  13410. for (const block of staticDependencyBlocks) {
  13411. for (const dependency of block) {
  13412. dependencies.add(dependency);
  13413. }
  13414. }
  13415. return dependencies;
  13416. }
  13417. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  13418. const dependencies = module.getDependenciesToBeIncluded();
  13419. for (const dependency of dependencies) {
  13420. if (dependency instanceof ExternalModule) {
  13421. staticDependencies.push(dependency);
  13422. continue;
  13423. }
  13424. const dependencyChunk = chunkByModule.get(dependency);
  13425. if (dependencyChunk !== chunk) {
  13426. staticDependencies.push(dependencyChunk);
  13427. continue;
  13428. }
  13429. if (!handledModules.has(dependency)) {
  13430. handledModules.add(dependency);
  13431. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  13432. }
  13433. }
  13434. }
  13435. function decodedSourcemap(map) {
  13436. if (!map)
  13437. return null;
  13438. if (typeof map === 'string') {
  13439. map = JSON.parse(map);
  13440. }
  13441. if (map.mappings === '') {
  13442. return {
  13443. mappings: [],
  13444. names: [],
  13445. sources: [],
  13446. version: 3
  13447. };
  13448. }
  13449. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  13450. return { ...map, mappings };
  13451. }
  13452. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  13453. const renderChunkReducer = (code, result, plugin) => {
  13454. if (result == null)
  13455. return code;
  13456. if (typeof result === 'string')
  13457. result = {
  13458. code: result,
  13459. map: undefined
  13460. };
  13461. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  13462. if (result.map !== null) {
  13463. const map = decodedSourcemap(result.map);
  13464. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  13465. }
  13466. return result.code;
  13467. };
  13468. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  13469. }
  13470. function renderNamePattern(pattern, patternName, replacements) {
  13471. if (isPathFragment(pattern))
  13472. return error(errFailedValidation(`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.`));
  13473. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  13474. if (!replacements.hasOwnProperty(type)) {
  13475. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  13476. }
  13477. const replacement = replacements[type]();
  13478. if (isPathFragment(replacement))
  13479. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  13480. return replacement;
  13481. });
  13482. }
  13483. function makeUnique(name, existingNames) {
  13484. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  13485. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  13486. return name;
  13487. const ext = extname(name);
  13488. name = name.substring(0, name.length - ext.length);
  13489. let uniqueName, uniqueIndex = 1;
  13490. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  13491. ;
  13492. return uniqueName;
  13493. }
  13494. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  13495. function getGlobalName(module, globals, hasExports, warn) {
  13496. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  13497. if (globalName) {
  13498. return globalName;
  13499. }
  13500. if (hasExports) {
  13501. warn({
  13502. code: 'MISSING_GLOBAL_NAME',
  13503. guess: module.variableName,
  13504. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  13505. source: module.id
  13506. });
  13507. return module.variableName;
  13508. }
  13509. }
  13510. class Chunk {
  13511. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  13512. this.orderedModules = orderedModules;
  13513. this.inputOptions = inputOptions;
  13514. this.outputOptions = outputOptions;
  13515. this.unsetOptions = unsetOptions;
  13516. this.pluginDriver = pluginDriver;
  13517. this.modulesById = modulesById;
  13518. this.chunkByModule = chunkByModule;
  13519. this.facadeChunkByModule = facadeChunkByModule;
  13520. this.includedNamespaces = includedNamespaces;
  13521. this.manualChunkAlias = manualChunkAlias;
  13522. this.entryModules = [];
  13523. this.exportMode = 'named';
  13524. this.facadeModule = null;
  13525. this.id = null;
  13526. this.namespaceVariableName = '';
  13527. this.needsExportsShim = false;
  13528. this.variableName = '';
  13529. this.accessedGlobalsByScope = new Map();
  13530. this.dependencies = new Set();
  13531. this.dynamicDependencies = new Set();
  13532. this.dynamicEntryModules = [];
  13533. this.dynamicName = null;
  13534. this.exportNamesByVariable = new Map();
  13535. this.exports = new Set();
  13536. this.exportsByName = new Map();
  13537. this.fileName = null;
  13538. this.implicitEntryModules = [];
  13539. this.implicitlyLoadedBefore = new Set();
  13540. this.imports = new Set();
  13541. this.includedReexportsByModule = new Map();
  13542. this.indentString = undefined;
  13543. // This may only be updated in the constructor
  13544. this.isEmpty = true;
  13545. this.name = null;
  13546. this.renderedDependencies = null;
  13547. this.renderedExports = null;
  13548. this.renderedHash = undefined;
  13549. this.renderedModuleSources = new Map();
  13550. this.renderedModules = Object.create(null);
  13551. this.renderedSource = null;
  13552. this.sortedExportNames = null;
  13553. this.strictFacade = false;
  13554. this.usedModules = undefined;
  13555. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  13556. const chunkModules = new Set(orderedModules);
  13557. for (const module of orderedModules) {
  13558. if (module.namespace.included) {
  13559. includedNamespaces.add(module);
  13560. }
  13561. if (this.isEmpty && module.isIncluded()) {
  13562. this.isEmpty = false;
  13563. }
  13564. if (module.info.isEntry || outputOptions.preserveModules) {
  13565. this.entryModules.push(module);
  13566. }
  13567. for (const importer of module.includedDynamicImporters) {
  13568. if (!chunkModules.has(importer)) {
  13569. this.dynamicEntryModules.push(module);
  13570. // Modules with synthetic exports need an artificial namespace for dynamic imports
  13571. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  13572. includedNamespaces.add(module);
  13573. this.exports.add(module.namespace);
  13574. }
  13575. }
  13576. }
  13577. if (module.implicitlyLoadedAfter.size > 0) {
  13578. this.implicitEntryModules.push(module);
  13579. }
  13580. }
  13581. this.suggestedVariableName = makeLegal(this.generateVariableName());
  13582. }
  13583. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  13584. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  13585. chunk.assignFacadeName(facadeName, facadedModule);
  13586. if (!facadeChunkByModule.has(facadedModule)) {
  13587. facadeChunkByModule.set(facadedModule, chunk);
  13588. }
  13589. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  13590. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  13591. }
  13592. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  13593. facadedModule.info.moduleSideEffects &&
  13594. facadedModule.hasEffects()) {
  13595. chunk.dependencies.add(chunkByModule.get(facadedModule));
  13596. }
  13597. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  13598. chunk.facadeModule = facadedModule;
  13599. chunk.strictFacade = true;
  13600. return chunk;
  13601. }
  13602. canModuleBeFacade(module, exposedVariables) {
  13603. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  13604. for (const exposedVariable of this.exports) {
  13605. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  13606. if (moduleExportNamesByVariable.size === 0 &&
  13607. module.isUserDefinedEntryPoint &&
  13608. module.preserveSignature === 'strict' &&
  13609. this.unsetOptions.has('preserveEntrySignatures')) {
  13610. this.inputOptions.onwarn({
  13611. code: 'EMPTY_FACADE',
  13612. id: module.id,
  13613. message: `To preserve the export signature of the entry module "${relativeId(module.id)}", an empty facade chunk was created. This often happens when creating a bundle for a web app where chunks are placed in script tags and exports are ignored. In this case it is recommended to set "preserveEntrySignatures: false" to avoid this and reduce the number of chunks. Otherwise if this is intentional, set "preserveEntrySignatures: 'strict'" explicitly to silence this warning.`,
  13614. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  13615. });
  13616. }
  13617. return false;
  13618. }
  13619. }
  13620. for (const exposedVariable of exposedVariables) {
  13621. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  13622. return false;
  13623. }
  13624. }
  13625. return true;
  13626. }
  13627. generateExports() {
  13628. this.sortedExportNames = null;
  13629. const remainingExports = new Set(this.exports);
  13630. if (this.facadeModule !== null &&
  13631. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  13632. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  13633. for (const [variable, exportNames] of exportNamesByVariable) {
  13634. this.exportNamesByVariable.set(variable, [...exportNames]);
  13635. for (const exportName of exportNames) {
  13636. this.exportsByName.set(exportName, variable);
  13637. }
  13638. remainingExports.delete(variable);
  13639. }
  13640. }
  13641. if (this.outputOptions.minifyInternalExports) {
  13642. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13643. }
  13644. else {
  13645. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13646. }
  13647. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  13648. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  13649. }
  13650. generateFacades() {
  13651. var _a;
  13652. const facades = [];
  13653. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  13654. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  13655. for (const module of entryModules) {
  13656. if (module.preserveSignature) {
  13657. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  13658. exposedVariables.add(exportedVariable);
  13659. }
  13660. }
  13661. }
  13662. for (const module of entryModules) {
  13663. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  13664. // mapping must run after Set 'name' dedupe
  13665. name => ({
  13666. name
  13667. }));
  13668. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  13669. requiredFacades.push({});
  13670. }
  13671. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  13672. if (requiredFacades.length === 0) {
  13673. requiredFacades.push({});
  13674. }
  13675. if (!this.facadeModule) {
  13676. const needsStrictFacade = module.preserveSignature === 'strict' ||
  13677. (module.preserveSignature === 'exports-only' &&
  13678. module.getExportNamesByVariable().size !== 0);
  13679. if (!needsStrictFacade ||
  13680. this.outputOptions.preserveModules ||
  13681. this.canModuleBeFacade(module, exposedVariables)) {
  13682. this.facadeModule = module;
  13683. this.facadeChunkByModule.set(module, this);
  13684. if (module.preserveSignature) {
  13685. this.strictFacade = needsStrictFacade;
  13686. }
  13687. this.assignFacadeName(requiredFacades.shift(), module);
  13688. }
  13689. }
  13690. for (const facadeName of requiredFacades) {
  13691. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  13692. }
  13693. }
  13694. for (const module of this.dynamicEntryModules) {
  13695. if (module.info.syntheticNamedExports)
  13696. continue;
  13697. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  13698. this.facadeModule = module;
  13699. this.facadeChunkByModule.set(module, this);
  13700. this.strictFacade = true;
  13701. this.dynamicName = getChunkNameFromModule(module);
  13702. }
  13703. else if (this.facadeModule === module &&
  13704. !this.strictFacade &&
  13705. this.canModuleBeFacade(module, exposedVariables)) {
  13706. this.strictFacade = true;
  13707. }
  13708. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  13709. this.includedNamespaces.add(module);
  13710. this.exports.add(module.namespace);
  13711. }
  13712. }
  13713. if (!this.outputOptions.preserveModules) {
  13714. this.addNecessaryImportsForFacades();
  13715. }
  13716. return facades;
  13717. }
  13718. generateId(addons, options, existingNames, includeHash) {
  13719. if (this.fileName !== null) {
  13720. return this.fileName;
  13721. }
  13722. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  13723. ? [options.entryFileNames, 'output.entryFileNames']
  13724. : [options.chunkFileNames, 'output.chunkFileNames'];
  13725. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  13726. format: () => options.format,
  13727. hash: () => includeHash
  13728. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  13729. : '[hash]',
  13730. name: () => this.getChunkName()
  13731. }), existingNames);
  13732. }
  13733. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  13734. const [{ id }] = this.orderedModules;
  13735. const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
  13736. let path;
  13737. const patternOpt = unsetOptions.has('entryFileNames')
  13738. ? '[name][assetExtname].js'
  13739. : options.entryFileNames;
  13740. const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
  13741. if (isAbsolute(sanitizedId)) {
  13742. const currentDir = dirname(sanitizedId);
  13743. const extension = extname(sanitizedId);
  13744. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13745. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13746. ext: () => extension.substring(1),
  13747. extname: () => extension,
  13748. format: () => options.format,
  13749. name: () => this.getChunkName()
  13750. });
  13751. const currentPath = `${currentDir}/${fileName}`;
  13752. const { preserveModulesRoot } = options;
  13753. if (preserveModulesRoot && resolve(currentPath).startsWith(preserveModulesRoot)) {
  13754. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  13755. }
  13756. else {
  13757. path = relative(preserveModulesRelativeDir, currentPath);
  13758. }
  13759. }
  13760. else {
  13761. const extension = extname(sanitizedId);
  13762. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13763. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13764. ext: () => extension.substring(1),
  13765. extname: () => extension,
  13766. format: () => options.format,
  13767. name: () => getAliasName(sanitizedId)
  13768. });
  13769. path = `_virtual/${fileName}`;
  13770. }
  13771. return makeUnique(normalize(path), existingNames);
  13772. }
  13773. getChunkInfo() {
  13774. const facadeModule = this.facadeModule;
  13775. const getChunkName = this.getChunkName.bind(this);
  13776. return {
  13777. exports: this.getExportNames(),
  13778. facadeModuleId: facadeModule && facadeModule.id,
  13779. isDynamicEntry: this.dynamicEntryModules.length > 0,
  13780. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  13781. isImplicitEntry: this.implicitEntryModules.length > 0,
  13782. modules: this.renderedModules,
  13783. get name() {
  13784. return getChunkName();
  13785. },
  13786. type: 'chunk'
  13787. };
  13788. }
  13789. getChunkInfoWithFileNames() {
  13790. return Object.assign(this.getChunkInfo(), {
  13791. code: undefined,
  13792. dynamicImports: Array.from(this.dynamicDependencies, getId),
  13793. fileName: this.id,
  13794. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  13795. importedBindings: this.getImportedBindingsPerDependency(),
  13796. imports: Array.from(this.dependencies, getId),
  13797. map: undefined,
  13798. referencedFiles: this.getReferencedFiles()
  13799. });
  13800. }
  13801. getChunkName() {
  13802. var _a;
  13803. return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  13804. }
  13805. getExportNames() {
  13806. var _a;
  13807. return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
  13808. }
  13809. getRenderedHash() {
  13810. if (this.renderedHash)
  13811. return this.renderedHash;
  13812. const hash = createHash();
  13813. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  13814. if (pluginHash) {
  13815. augmentation += pluginHash;
  13816. }
  13817. return augmentation;
  13818. });
  13819. hash.update(hashAugmentation);
  13820. hash.update(this.renderedSource.toString());
  13821. hash.update(this.getExportNames()
  13822. .map(exportName => {
  13823. const variable = this.exportsByName.get(exportName);
  13824. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  13825. })
  13826. .join(','));
  13827. return (this.renderedHash = hash.digest('hex'));
  13828. }
  13829. getVariableExportName(variable) {
  13830. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  13831. return '*';
  13832. }
  13833. return this.exportNamesByVariable.get(variable)[0];
  13834. }
  13835. link() {
  13836. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  13837. for (const module of this.orderedModules) {
  13838. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  13839. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  13840. this.setUpChunkImportsAndExportsForModule(module);
  13841. }
  13842. }
  13843. // prerender allows chunk hashes and names to be generated before finalizing
  13844. preRender(options, inputBase, snippets) {
  13845. const { _, getPropertyAccess, n } = snippets;
  13846. const magicString = new Bundle$1({ separator: `${n}${n}` });
  13847. this.usedModules = [];
  13848. this.indentString = getIndentString(this.orderedModules, options);
  13849. const renderOptions = {
  13850. dynamicImportFunction: options.dynamicImportFunction,
  13851. exportNamesByVariable: this.exportNamesByVariable,
  13852. format: options.format,
  13853. freeze: options.freeze,
  13854. indent: this.indentString,
  13855. namespaceToStringTag: options.namespaceToStringTag,
  13856. outputPluginDriver: this.pluginDriver,
  13857. snippets
  13858. };
  13859. // for static and dynamic entry points, inline the execution list to avoid loading latency
  13860. if (options.hoistTransitiveImports &&
  13861. !this.outputOptions.preserveModules &&
  13862. this.facadeModule !== null) {
  13863. for (const dep of this.dependencies) {
  13864. if (dep instanceof Chunk)
  13865. this.inlineChunkDependencies(dep);
  13866. }
  13867. }
  13868. this.prepareModulesForRendering(snippets);
  13869. this.setIdentifierRenderResolutions(options);
  13870. let hoistedSource = '';
  13871. const renderedModules = this.renderedModules;
  13872. for (const module of this.orderedModules) {
  13873. let renderedLength = 0;
  13874. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  13875. const source = module.render(renderOptions).trim();
  13876. renderedLength = source.length();
  13877. if (renderedLength) {
  13878. if (options.compact && source.lastLine().includes('//'))
  13879. source.append('\n');
  13880. this.renderedModuleSources.set(module, source);
  13881. magicString.addSource(source);
  13882. this.usedModules.push(module);
  13883. }
  13884. const namespace = module.namespace;
  13885. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  13886. const rendered = namespace.renderBlock(renderOptions);
  13887. if (namespace.renderFirst())
  13888. hoistedSource += n + rendered;
  13889. else
  13890. magicString.addSource(new MagicString(rendered));
  13891. }
  13892. }
  13893. const { renderedExports, removedExports } = module.getRenderedExports();
  13894. const { renderedModuleSources } = this;
  13895. renderedModules[module.id] = {
  13896. get code() {
  13897. var _a, _b;
  13898. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  13899. },
  13900. originalLength: module.originalCode.length,
  13901. removedExports,
  13902. renderedExports,
  13903. renderedLength
  13904. };
  13905. }
  13906. if (hoistedSource)
  13907. magicString.prepend(hoistedSource + n + n);
  13908. if (this.needsExportsShim) {
  13909. magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  13910. }
  13911. if (options.compact) {
  13912. this.renderedSource = magicString;
  13913. }
  13914. else {
  13915. this.renderedSource = magicString.trim();
  13916. }
  13917. this.renderedHash = undefined;
  13918. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  13919. const chunkName = this.getChunkName();
  13920. this.inputOptions.onwarn({
  13921. chunkName,
  13922. code: 'EMPTY_BUNDLE',
  13923. message: `Generated an empty chunk: "${chunkName}"`
  13924. });
  13925. }
  13926. this.setExternalRenderPaths(options, inputBase);
  13927. this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
  13928. this.renderedExports =
  13929. this.exportMode === 'none'
  13930. ? []
  13931. : this.getChunkExportDeclarations(options.format, getPropertyAccess);
  13932. }
  13933. async render(options, addons, outputChunk, snippets) {
  13934. timeStart('render format', 2);
  13935. const format = options.format;
  13936. const finalise = finalisers[format];
  13937. if (options.dynamicImportFunction && format !== 'es') {
  13938. this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
  13939. }
  13940. // populate ids in the rendered declarations only here
  13941. // as chunk ids known only after prerender
  13942. for (const dependency of this.dependencies) {
  13943. const renderedDependency = this.renderedDependencies.get(dependency);
  13944. if (dependency instanceof ExternalModule) {
  13945. const originalId = dependency.renderPath;
  13946. renderedDependency.id = escapeId(dependency.renormalizeRenderPath
  13947. ? getImportPath(this.id, originalId, false, false)
  13948. : originalId);
  13949. }
  13950. else {
  13951. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  13952. renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
  13953. }
  13954. }
  13955. this.finaliseDynamicImports(options, snippets);
  13956. this.finaliseImportMetas(format, snippets);
  13957. const hasExports = this.renderedExports.length !== 0 ||
  13958. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  13959. let topLevelAwaitModule = null;
  13960. const accessedGlobals = new Set();
  13961. for (const module of this.orderedModules) {
  13962. if (module.usesTopLevelAwait) {
  13963. topLevelAwaitModule = module.id;
  13964. }
  13965. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  13966. if (accessedGlobalVariables) {
  13967. for (const name of accessedGlobalVariables) {
  13968. accessedGlobals.add(name);
  13969. }
  13970. }
  13971. }
  13972. if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
  13973. return error({
  13974. code: 'INVALID_TLA_FORMAT',
  13975. id: topLevelAwaitModule,
  13976. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  13977. });
  13978. }
  13979. /* istanbul ignore next */
  13980. if (!this.id) {
  13981. throw new Error('Internal Error: expecting chunk id');
  13982. }
  13983. const magicString = finalise(this.renderedSource, {
  13984. accessedGlobals,
  13985. dependencies: [...this.renderedDependencies.values()],
  13986. exports: this.renderedExports,
  13987. hasExports,
  13988. id: this.id,
  13989. indent: this.indentString,
  13990. intro: addons.intro,
  13991. isEntryFacade: this.outputOptions.preserveModules ||
  13992. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  13993. isModuleFacade: this.facadeModule !== null,
  13994. namedExportsMode: this.exportMode !== 'default',
  13995. outro: addons.outro,
  13996. snippets,
  13997. usesTopLevelAwait: topLevelAwaitModule !== null,
  13998. warn: this.inputOptions.onwarn
  13999. }, options);
  14000. if (addons.banner)
  14001. magicString.prepend(addons.banner);
  14002. if (addons.footer)
  14003. magicString.append(addons.footer);
  14004. const prevCode = magicString.toString();
  14005. timeEnd('render format', 2);
  14006. let map = null;
  14007. const chunkSourcemapChain = [];
  14008. let code = await renderChunk({
  14009. code: prevCode,
  14010. options,
  14011. outputPluginDriver: this.pluginDriver,
  14012. renderChunk: outputChunk,
  14013. sourcemapChain: chunkSourcemapChain
  14014. });
  14015. if (options.sourcemap) {
  14016. timeStart('sourcemap', 2);
  14017. let file;
  14018. if (options.file)
  14019. file = resolve(options.sourcemapFile || options.file);
  14020. else if (options.dir)
  14021. file = resolve(options.dir, this.id);
  14022. else
  14023. file = resolve(this.id);
  14024. const decodedMap = magicString.generateDecodedMap({});
  14025. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  14026. map.sources = map.sources
  14027. .map(sourcePath => {
  14028. const { sourcemapPathTransform } = options;
  14029. if (sourcemapPathTransform) {
  14030. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  14031. if (typeof newSourcePath !== 'string') {
  14032. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  14033. }
  14034. return newSourcePath;
  14035. }
  14036. return sourcePath;
  14037. })
  14038. .map(normalize);
  14039. timeEnd('sourcemap', 2);
  14040. }
  14041. if (!options.compact && code[code.length - 1] !== '\n')
  14042. code += '\n';
  14043. return { code, map };
  14044. }
  14045. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  14046. for (const module of moduleDependencies) {
  14047. if (module instanceof Module) {
  14048. const chunk = this.chunkByModule.get(module);
  14049. if (chunk && chunk !== this) {
  14050. chunkDependencies.add(chunk);
  14051. }
  14052. }
  14053. else {
  14054. chunkDependencies.add(module);
  14055. }
  14056. }
  14057. }
  14058. addNecessaryImportsForFacades() {
  14059. for (const [module, variables] of this.includedReexportsByModule) {
  14060. if (this.includedNamespaces.has(module)) {
  14061. for (const variable of variables) {
  14062. this.imports.add(variable);
  14063. }
  14064. }
  14065. }
  14066. }
  14067. assignFacadeName({ fileName, name }, facadedModule) {
  14068. if (fileName) {
  14069. this.fileName = fileName;
  14070. }
  14071. else {
  14072. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  14073. }
  14074. }
  14075. checkCircularDependencyImport(variable, importingModule) {
  14076. const variableModule = variable.module;
  14077. if (variableModule instanceof Module) {
  14078. const exportChunk = this.chunkByModule.get(variableModule);
  14079. let alternativeReexportModule;
  14080. do {
  14081. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  14082. if (alternativeReexportModule) {
  14083. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  14084. if (exportingChunk && exportingChunk !== exportChunk) {
  14085. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  14086. }
  14087. importingModule = alternativeReexportModule;
  14088. }
  14089. } while (alternativeReexportModule);
  14090. }
  14091. }
  14092. computeContentHashWithDependencies(addons, options, existingNames) {
  14093. const hash = createHash();
  14094. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
  14095. hash.update(options.format);
  14096. const dependenciesForHashing = new Set([this]);
  14097. for (const current of dependenciesForHashing) {
  14098. if (current instanceof ExternalModule) {
  14099. hash.update(`:${current.renderPath}`);
  14100. }
  14101. else {
  14102. hash.update(current.getRenderedHash());
  14103. hash.update(current.generateId(addons, options, existingNames, false));
  14104. }
  14105. if (current instanceof ExternalModule)
  14106. continue;
  14107. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  14108. dependenciesForHashing.add(dependency);
  14109. }
  14110. }
  14111. return hash.digest('hex').substr(0, 8);
  14112. }
  14113. ensureReexportsAreAvailableForModule(module) {
  14114. const includedReexports = [];
  14115. const map = module.getExportNamesByVariable();
  14116. for (const exportedVariable of map.keys()) {
  14117. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  14118. const importedVariable = isSynthetic
  14119. ? exportedVariable.getBaseVariable()
  14120. : exportedVariable;
  14121. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  14122. this.checkCircularDependencyImport(importedVariable, module);
  14123. const exportingModule = importedVariable.module;
  14124. if (exportingModule instanceof Module) {
  14125. const chunk = this.chunkByModule.get(exportingModule);
  14126. if (chunk && chunk !== this) {
  14127. chunk.exports.add(importedVariable);
  14128. includedReexports.push(importedVariable);
  14129. if (isSynthetic) {
  14130. this.imports.add(importedVariable);
  14131. }
  14132. }
  14133. }
  14134. }
  14135. }
  14136. if (includedReexports.length) {
  14137. this.includedReexportsByModule.set(module, includedReexports);
  14138. }
  14139. }
  14140. finaliseDynamicImports(options, snippets) {
  14141. const stripKnownJsExtensions = options.format === 'amd';
  14142. for (const [module, code] of this.renderedModuleSources) {
  14143. for (const { node, resolution } of module.dynamicImports) {
  14144. const chunk = this.chunkByModule.get(resolution);
  14145. const facadeChunk = this.facadeChunkByModule.get(resolution);
  14146. if (!resolution || !node.included || chunk === this) {
  14147. continue;
  14148. }
  14149. const renderedResolution = resolution instanceof Module
  14150. ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
  14151. : resolution instanceof ExternalModule
  14152. ? `'${escapeId(resolution.renormalizeRenderPath
  14153. ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
  14154. : resolution.renderPath)}'`
  14155. : resolution;
  14156. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  14157. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  14158. chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
  14159. }
  14160. }
  14161. }
  14162. finaliseImportMetas(format, snippets) {
  14163. for (const [module, code] of this.renderedModuleSources) {
  14164. for (const importMeta of module.importMetas) {
  14165. importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
  14166. }
  14167. }
  14168. }
  14169. generateVariableName() {
  14170. if (this.manualChunkAlias) {
  14171. return this.manualChunkAlias;
  14172. }
  14173. const moduleForNaming = this.entryModules[0] ||
  14174. this.implicitEntryModules[0] ||
  14175. this.dynamicEntryModules[0] ||
  14176. this.orderedModules[this.orderedModules.length - 1];
  14177. if (moduleForNaming) {
  14178. return getChunkNameFromModule(moduleForNaming);
  14179. }
  14180. return 'chunk';
  14181. }
  14182. getChunkDependencyDeclarations(options, getPropertyAccess) {
  14183. const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
  14184. const reexportSpecifiers = this.getReexportSpecifiers();
  14185. const dependencyDeclaration = new Map();
  14186. for (const dep of this.dependencies) {
  14187. const imports = importSpecifiers.get(dep) || null;
  14188. const reexports = reexportSpecifiers.get(dep) || null;
  14189. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  14190. dependencyDeclaration.set(dep, {
  14191. defaultVariableName: dep.defaultVariableName,
  14192. globalName: (dep instanceof ExternalModule &&
  14193. (options.format === 'umd' || options.format === 'iife') &&
  14194. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  14195. id: undefined,
  14196. imports,
  14197. isChunk: dep instanceof Chunk,
  14198. name: dep.variableName,
  14199. namedExportsMode,
  14200. namespaceVariableName: dep.namespaceVariableName,
  14201. reexports
  14202. });
  14203. }
  14204. return dependencyDeclaration;
  14205. }
  14206. getChunkExportDeclarations(format, getPropertyAccess) {
  14207. const exports = [];
  14208. for (const exportName of this.getExportNames()) {
  14209. if (exportName[0] === '*')
  14210. continue;
  14211. const variable = this.exportsByName.get(exportName);
  14212. if (!(variable instanceof SyntheticNamedExportVariable)) {
  14213. const module = variable.module;
  14214. if (module && this.chunkByModule.get(module) !== this)
  14215. continue;
  14216. }
  14217. let expression = null;
  14218. let hoisted = false;
  14219. let local = variable.getName(getPropertyAccess);
  14220. if (variable instanceof LocalVariable) {
  14221. for (const declaration of variable.declarations) {
  14222. if (declaration.parent instanceof FunctionDeclaration ||
  14223. (declaration instanceof ExportDefaultDeclaration &&
  14224. declaration.declaration instanceof FunctionDeclaration)) {
  14225. hoisted = true;
  14226. break;
  14227. }
  14228. }
  14229. }
  14230. else if (variable instanceof SyntheticNamedExportVariable) {
  14231. expression = local;
  14232. if (format === 'es') {
  14233. local = variable.renderName;
  14234. }
  14235. }
  14236. exports.push({
  14237. exported: exportName,
  14238. expression,
  14239. hoisted,
  14240. local
  14241. });
  14242. }
  14243. return exports;
  14244. }
  14245. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  14246. const dependencies = new Set();
  14247. const deconflictedDefault = new Set();
  14248. const deconflictedNamespace = new Set();
  14249. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  14250. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  14251. const module = variable.module;
  14252. if (module instanceof ExternalModule) {
  14253. dependencies.add(module);
  14254. if (addNonNamespacesAndInteropHelpers) {
  14255. if (variable.name === 'default') {
  14256. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  14257. deconflictedDefault.add(module);
  14258. }
  14259. }
  14260. else if (variable.name === '*') {
  14261. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  14262. deconflictedNamespace.add(module);
  14263. }
  14264. }
  14265. }
  14266. }
  14267. else {
  14268. const chunk = this.chunkByModule.get(module);
  14269. if (chunk !== this) {
  14270. dependencies.add(chunk);
  14271. if (addNonNamespacesAndInteropHelpers &&
  14272. chunk.exportMode === 'default' &&
  14273. variable.isNamespace) {
  14274. deconflictedNamespace.add(chunk);
  14275. }
  14276. }
  14277. }
  14278. }
  14279. }
  14280. if (addDependenciesWithoutBindings) {
  14281. for (const dependency of this.dependencies) {
  14282. dependencies.add(dependency);
  14283. }
  14284. }
  14285. return { deconflictedDefault, deconflictedNamespace, dependencies };
  14286. }
  14287. getFallbackChunkName() {
  14288. if (this.manualChunkAlias) {
  14289. return this.manualChunkAlias;
  14290. }
  14291. if (this.dynamicName) {
  14292. return this.dynamicName;
  14293. }
  14294. if (this.fileName) {
  14295. return getAliasName(this.fileName);
  14296. }
  14297. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  14298. }
  14299. getImportSpecifiers(getPropertyAccess) {
  14300. const { interop } = this.outputOptions;
  14301. const importsByDependency = new Map();
  14302. for (const variable of this.imports) {
  14303. const module = variable.module;
  14304. let dependency;
  14305. let imported;
  14306. if (module instanceof ExternalModule) {
  14307. dependency = module;
  14308. imported = variable.name;
  14309. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14310. return error(errUnexpectedNamedImport(module.id, imported, false));
  14311. }
  14312. }
  14313. else {
  14314. dependency = this.chunkByModule.get(module);
  14315. imported = dependency.getVariableExportName(variable);
  14316. }
  14317. getOrCreate(importsByDependency, dependency, () => []).push({
  14318. imported,
  14319. local: variable.getName(getPropertyAccess)
  14320. });
  14321. }
  14322. return importsByDependency;
  14323. }
  14324. getImportedBindingsPerDependency() {
  14325. const importSpecifiers = {};
  14326. for (const [dependency, declaration] of this.renderedDependencies) {
  14327. const specifiers = new Set();
  14328. if (declaration.imports) {
  14329. for (const { imported } of declaration.imports) {
  14330. specifiers.add(imported);
  14331. }
  14332. }
  14333. if (declaration.reexports) {
  14334. for (const { imported } of declaration.reexports) {
  14335. specifiers.add(imported);
  14336. }
  14337. }
  14338. importSpecifiers[dependency.id] = [...specifiers];
  14339. }
  14340. return importSpecifiers;
  14341. }
  14342. getReexportSpecifiers() {
  14343. const { externalLiveBindings, interop } = this.outputOptions;
  14344. const reexportSpecifiers = new Map();
  14345. for (let exportName of this.getExportNames()) {
  14346. let dependency;
  14347. let imported;
  14348. let needsLiveBinding = false;
  14349. if (exportName[0] === '*') {
  14350. const id = exportName.substring(1);
  14351. if (interop(id) === 'defaultOnly') {
  14352. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  14353. }
  14354. needsLiveBinding = externalLiveBindings;
  14355. dependency = this.modulesById.get(id);
  14356. imported = exportName = '*';
  14357. }
  14358. else {
  14359. const variable = this.exportsByName.get(exportName);
  14360. if (variable instanceof SyntheticNamedExportVariable)
  14361. continue;
  14362. const module = variable.module;
  14363. if (module instanceof Module) {
  14364. dependency = this.chunkByModule.get(module);
  14365. if (dependency === this)
  14366. continue;
  14367. imported = dependency.getVariableExportName(variable);
  14368. needsLiveBinding = variable.isReassigned;
  14369. }
  14370. else {
  14371. dependency = module;
  14372. imported = variable.name;
  14373. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14374. return error(errUnexpectedNamedImport(module.id, imported, true));
  14375. }
  14376. needsLiveBinding =
  14377. externalLiveBindings &&
  14378. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  14379. }
  14380. }
  14381. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  14382. imported,
  14383. needsLiveBinding,
  14384. reexported: exportName
  14385. });
  14386. }
  14387. return reexportSpecifiers;
  14388. }
  14389. getReferencedFiles() {
  14390. const referencedFiles = [];
  14391. for (const module of this.orderedModules) {
  14392. for (const meta of module.importMetas) {
  14393. const fileName = meta.getReferencedFileName(this.pluginDriver);
  14394. if (fileName) {
  14395. referencedFiles.push(fileName);
  14396. }
  14397. }
  14398. }
  14399. return referencedFiles;
  14400. }
  14401. inlineChunkDependencies(chunk) {
  14402. for (const dep of chunk.dependencies) {
  14403. if (this.dependencies.has(dep))
  14404. continue;
  14405. this.dependencies.add(dep);
  14406. if (dep instanceof Chunk) {
  14407. this.inlineChunkDependencies(dep);
  14408. }
  14409. }
  14410. }
  14411. prepareModulesForRendering(snippets) {
  14412. var _a;
  14413. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  14414. for (const module of this.orderedModules) {
  14415. for (const { node, resolution } of module.dynamicImports) {
  14416. if (node.included) {
  14417. if (resolution instanceof Module) {
  14418. const chunk = this.chunkByModule.get(resolution);
  14419. if (chunk === this) {
  14420. node.setInternalResolution(resolution.namespace);
  14421. }
  14422. else {
  14423. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14424. }
  14425. }
  14426. else {
  14427. node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14428. }
  14429. }
  14430. }
  14431. for (const importMeta of module.importMetas) {
  14432. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  14433. }
  14434. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14435. module.namespace.prepare(accessedGlobalsByScope);
  14436. }
  14437. }
  14438. }
  14439. setExternalRenderPaths(options, inputBase) {
  14440. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  14441. if (dependency instanceof ExternalModule) {
  14442. dependency.setRenderPath(options, inputBase);
  14443. }
  14444. }
  14445. }
  14446. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  14447. const syntheticExports = new Set();
  14448. for (const exportName of this.getExportNames()) {
  14449. const exportVariable = this.exportsByName.get(exportName);
  14450. if (format !== 'es' &&
  14451. format !== 'system' &&
  14452. exportVariable.isReassigned &&
  14453. !exportVariable.isId) {
  14454. exportVariable.setRenderNames('exports', exportName);
  14455. }
  14456. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  14457. syntheticExports.add(exportVariable);
  14458. }
  14459. else {
  14460. exportVariable.setRenderNames(null, null);
  14461. }
  14462. }
  14463. for (const module of this.orderedModules) {
  14464. if (module.needsExportShim) {
  14465. this.needsExportsShim = true;
  14466. break;
  14467. }
  14468. }
  14469. const usedNames = new Set(['Object', 'Promise']);
  14470. if (this.needsExportsShim) {
  14471. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  14472. }
  14473. if (namespaceToStringTag) {
  14474. usedNames.add('Symbol');
  14475. }
  14476. switch (format) {
  14477. case 'system':
  14478. usedNames.add('module').add('exports');
  14479. break;
  14480. case 'es':
  14481. break;
  14482. case 'cjs':
  14483. usedNames.add('module').add('require').add('__filename').add('__dirname');
  14484. // fallthrough
  14485. default:
  14486. usedNames.add('exports');
  14487. for (const helper of HELPER_NAMES) {
  14488. usedNames.add(helper);
  14489. }
  14490. }
  14491. deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
  14492. }
  14493. setUpChunkImportsAndExportsForModule(module) {
  14494. const moduleImports = new Set(module.includedImports);
  14495. // when we are not preserving modules, we need to make all namespace variables available for
  14496. // rendering the namespace object
  14497. if (!this.outputOptions.preserveModules) {
  14498. if (this.includedNamespaces.has(module)) {
  14499. const memberVariables = module.namespace.getMemberVariables();
  14500. for (const variable of Object.values(memberVariables)) {
  14501. moduleImports.add(variable);
  14502. }
  14503. }
  14504. }
  14505. for (let variable of moduleImports) {
  14506. if (variable instanceof ExportDefaultVariable) {
  14507. variable = variable.getOriginalVariable();
  14508. }
  14509. if (variable instanceof SyntheticNamedExportVariable) {
  14510. variable = variable.getBaseVariable();
  14511. }
  14512. const chunk = this.chunkByModule.get(variable.module);
  14513. if (chunk !== this) {
  14514. this.imports.add(variable);
  14515. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  14516. variable.module instanceof Module) {
  14517. chunk.exports.add(variable);
  14518. this.checkCircularDependencyImport(variable, module);
  14519. }
  14520. }
  14521. }
  14522. if (this.includedNamespaces.has(module) ||
  14523. (module.info.isEntry && module.preserveSignature !== false) ||
  14524. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  14525. this.ensureReexportsAreAvailableForModule(module);
  14526. }
  14527. for (const { node, resolution } of module.dynamicImports) {
  14528. if (node.included &&
  14529. resolution instanceof Module &&
  14530. this.chunkByModule.get(resolution) === this &&
  14531. !this.includedNamespaces.has(resolution)) {
  14532. this.includedNamespaces.add(resolution);
  14533. this.ensureReexportsAreAvailableForModule(resolution);
  14534. }
  14535. }
  14536. }
  14537. }
  14538. function getChunkNameFromModule(module) {
  14539. var _a, _b, _c, _d;
  14540. return ((_d = (_b = (_a = module.chunkNames.find(({ isUserDefined }) => isUserDefined)) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : (_c = module.chunkNames[0]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : getAliasName(module.id));
  14541. }
  14542. const QUERY_HASH_REGEX = /[?#]/;
  14543. function generateAssetFileName(name, source, outputOptions, bundle) {
  14544. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  14545. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  14546. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  14547. : outputOptions.assetFileNames, 'output.assetFileNames', {
  14548. ext: () => extname(emittedName).substring(1),
  14549. extname: () => extname(emittedName),
  14550. hash() {
  14551. return createHash()
  14552. .update(emittedName)
  14553. .update(':')
  14554. .update(source)
  14555. .digest('hex')
  14556. .substring(0, 8);
  14557. },
  14558. name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
  14559. }), bundle);
  14560. }
  14561. function reserveFileNameInBundle(fileName, bundle, warn) {
  14562. if (fileName in bundle) {
  14563. warn(errFileNameConflict(fileName));
  14564. }
  14565. bundle[fileName] = FILE_PLACEHOLDER;
  14566. }
  14567. const FILE_PLACEHOLDER = {
  14568. type: 'placeholder'
  14569. };
  14570. function hasValidType(emittedFile) {
  14571. return Boolean(emittedFile &&
  14572. (emittedFile.type === 'asset' ||
  14573. emittedFile.type === 'chunk'));
  14574. }
  14575. function hasValidName(emittedFile) {
  14576. const validatedName = emittedFile.fileName || emittedFile.name;
  14577. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  14578. }
  14579. function getValidSource(source, emittedFile, fileReferenceId) {
  14580. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  14581. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  14582. return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  14583. }
  14584. return source;
  14585. }
  14586. function getAssetFileName(file, referenceId) {
  14587. if (typeof file.fileName !== 'string') {
  14588. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  14589. }
  14590. return file.fileName;
  14591. }
  14592. function getChunkFileName(file, facadeChunkByModule) {
  14593. var _a;
  14594. const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
  14595. if (!fileName)
  14596. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  14597. return fileName;
  14598. }
  14599. class FileEmitter {
  14600. constructor(graph, options, baseFileEmitter) {
  14601. this.graph = graph;
  14602. this.options = options;
  14603. this.bundle = null;
  14604. this.facadeChunkByModule = null;
  14605. this.outputOptions = null;
  14606. this.assertAssetsFinalized = () => {
  14607. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  14608. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  14609. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  14610. }
  14611. };
  14612. this.emitFile = (emittedFile) => {
  14613. if (!hasValidType(emittedFile)) {
  14614. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  14615. }
  14616. if (!hasValidName(emittedFile)) {
  14617. return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  14618. }
  14619. if (emittedFile.type === 'chunk') {
  14620. return this.emitChunk(emittedFile);
  14621. }
  14622. return this.emitAsset(emittedFile);
  14623. };
  14624. this.getFileName = (fileReferenceId) => {
  14625. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  14626. if (!emittedFile)
  14627. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  14628. if (emittedFile.type === 'chunk') {
  14629. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  14630. }
  14631. return getAssetFileName(emittedFile, fileReferenceId);
  14632. };
  14633. this.setAssetSource = (referenceId, requestedSource) => {
  14634. const consumedFile = this.filesByReferenceId.get(referenceId);
  14635. if (!consumedFile)
  14636. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  14637. if (consumedFile.type !== 'asset') {
  14638. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  14639. }
  14640. if (consumedFile.source !== undefined) {
  14641. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  14642. }
  14643. const source = getValidSource(requestedSource, consumedFile, referenceId);
  14644. if (this.bundle) {
  14645. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  14646. }
  14647. else {
  14648. consumedFile.source = source;
  14649. }
  14650. };
  14651. this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
  14652. this.outputOptions = outputOptions;
  14653. this.bundle = outputBundle;
  14654. this.facadeChunkByModule = facadeChunkByModule;
  14655. for (const emittedFile of this.filesByReferenceId.values()) {
  14656. if (emittedFile.fileName) {
  14657. reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
  14658. }
  14659. }
  14660. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  14661. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  14662. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
  14663. }
  14664. }
  14665. };
  14666. this.filesByReferenceId = baseFileEmitter
  14667. ? new Map(baseFileEmitter.filesByReferenceId)
  14668. : new Map();
  14669. }
  14670. assignReferenceId(file, idBase) {
  14671. let referenceId;
  14672. do {
  14673. referenceId = createHash()
  14674. .update(referenceId || idBase)
  14675. .digest('hex')
  14676. .substring(0, 8);
  14677. } while (this.filesByReferenceId.has(referenceId));
  14678. this.filesByReferenceId.set(referenceId, file);
  14679. return referenceId;
  14680. }
  14681. emitAsset(emittedAsset) {
  14682. const source = typeof emittedAsset.source !== 'undefined'
  14683. ? getValidSource(emittedAsset.source, emittedAsset, null)
  14684. : undefined;
  14685. const consumedAsset = {
  14686. fileName: emittedAsset.fileName,
  14687. name: emittedAsset.name,
  14688. source,
  14689. type: 'asset'
  14690. };
  14691. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  14692. if (this.bundle) {
  14693. if (emittedAsset.fileName) {
  14694. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  14695. }
  14696. if (source !== undefined) {
  14697. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  14698. }
  14699. }
  14700. return referenceId;
  14701. }
  14702. emitChunk(emittedChunk) {
  14703. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  14704. return error(errInvalidRollupPhaseForChunkEmission());
  14705. }
  14706. if (typeof emittedChunk.id !== 'string') {
  14707. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  14708. }
  14709. const consumedChunk = {
  14710. fileName: emittedChunk.fileName,
  14711. module: null,
  14712. name: emittedChunk.name || emittedChunk.id,
  14713. type: 'chunk'
  14714. };
  14715. this.graph.moduleLoader
  14716. .emitChunk(emittedChunk)
  14717. .then(module => (consumedChunk.module = module))
  14718. .catch(() => {
  14719. // Avoid unhandled Promise rejection as the error will be thrown later
  14720. // once module loading has finished
  14721. });
  14722. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  14723. }
  14724. finalizeAsset(consumedFile, source, referenceId, bundle) {
  14725. const fileName = consumedFile.fileName ||
  14726. findExistingAssetFileNameWithSource(bundle, source) ||
  14727. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  14728. // We must not modify the original assets to avoid interaction between outputs
  14729. const assetWithFileName = { ...consumedFile, fileName, source };
  14730. this.filesByReferenceId.set(referenceId, assetWithFileName);
  14731. const { options } = this;
  14732. bundle[fileName] = {
  14733. fileName,
  14734. get isAsset() {
  14735. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  14736. return true;
  14737. },
  14738. name: consumedFile.name,
  14739. source,
  14740. type: 'asset'
  14741. };
  14742. }
  14743. }
  14744. function findExistingAssetFileNameWithSource(bundle, source) {
  14745. for (const [fileName, outputFile] of Object.entries(bundle)) {
  14746. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  14747. return fileName;
  14748. }
  14749. return null;
  14750. }
  14751. function areSourcesEqual(sourceA, sourceB) {
  14752. if (typeof sourceA === 'string') {
  14753. return sourceA === sourceB;
  14754. }
  14755. if (typeof sourceB === 'string') {
  14756. return false;
  14757. }
  14758. if ('equals' in sourceA) {
  14759. return sourceA.equals(sourceB);
  14760. }
  14761. if (sourceA.length !== sourceB.length) {
  14762. return false;
  14763. }
  14764. for (let index = 0; index < sourceA.length; index++) {
  14765. if (sourceA[index] !== sourceB[index]) {
  14766. return false;
  14767. }
  14768. }
  14769. return true;
  14770. }
  14771. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  14772. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  14773. async function createAddons(options, outputPluginDriver) {
  14774. try {
  14775. let [banner, footer, intro, outro] = await Promise.all([
  14776. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  14777. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  14778. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  14779. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  14780. ]);
  14781. if (intro)
  14782. intro += '\n\n';
  14783. if (outro)
  14784. outro = `\n\n${outro}`;
  14785. if (banner.length)
  14786. banner += '\n';
  14787. if (footer.length)
  14788. footer = '\n' + footer;
  14789. return { banner, footer, intro, outro };
  14790. }
  14791. catch (err) {
  14792. return error({
  14793. code: 'ADDON_ERROR',
  14794. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  14795. \tError Message: ${err.message}`
  14796. });
  14797. }
  14798. }
  14799. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  14800. const chunkDefinitions = [];
  14801. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  14802. const manualChunkModulesByAlias = Object.create(null);
  14803. for (const [entry, alias] of manualChunkAliasByEntry) {
  14804. const chunkModules = (manualChunkModulesByAlias[alias] =
  14805. manualChunkModulesByAlias[alias] || []);
  14806. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  14807. }
  14808. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  14809. chunkDefinitions.push({ alias, modules });
  14810. }
  14811. const assignedEntryPointsByModule = new Map();
  14812. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  14813. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  14814. const staticEntries = new Set(entryModules);
  14815. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  14816. const modulesToHandle = new Set([entry]);
  14817. for (const module of modulesToHandle) {
  14818. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  14819. if (dynamicDependentEntryPoints &&
  14820. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  14821. continue;
  14822. }
  14823. else {
  14824. assignedEntryPoints.add(entry);
  14825. }
  14826. for (const dependency of module.getDependenciesToBeIncluded()) {
  14827. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14828. modulesToHandle.add(dependency);
  14829. }
  14830. }
  14831. }
  14832. }
  14833. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  14834. const entriesToCheck = new Set(entryPoints);
  14835. for (const entry of entriesToCheck) {
  14836. if (!containedIn.has(entry)) {
  14837. if (staticEntries.has(entry))
  14838. return false;
  14839. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  14840. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  14841. entriesToCheck.add(dependentEntry);
  14842. }
  14843. }
  14844. }
  14845. return true;
  14846. }
  14847. for (const entry of entryModules) {
  14848. if (!modulesInManualChunks.has(entry)) {
  14849. assignEntryToStaticDependencies(entry, null);
  14850. }
  14851. }
  14852. for (const entry of dynamicEntryModules) {
  14853. if (!modulesInManualChunks.has(entry)) {
  14854. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  14855. }
  14856. }
  14857. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  14858. return chunkDefinitions;
  14859. }
  14860. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  14861. const modulesToHandle = new Set([entry]);
  14862. for (const module of modulesToHandle) {
  14863. modulesInManualChunks.add(module);
  14864. manualChunkModules.push(module);
  14865. for (const dependency of module.dependencies) {
  14866. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14867. modulesToHandle.add(dependency);
  14868. }
  14869. }
  14870. }
  14871. }
  14872. function analyzeModuleGraph(entryModules) {
  14873. const dynamicEntryModules = new Set();
  14874. const dependentEntryPointsByModule = new Map();
  14875. const entriesToHandle = new Set(entryModules);
  14876. for (const currentEntry of entriesToHandle) {
  14877. const modulesToHandle = new Set([currentEntry]);
  14878. for (const module of modulesToHandle) {
  14879. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  14880. for (const dependency of module.getDependenciesToBeIncluded()) {
  14881. if (!(dependency instanceof ExternalModule)) {
  14882. modulesToHandle.add(dependency);
  14883. }
  14884. }
  14885. for (const { resolution } of module.dynamicImports) {
  14886. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  14887. dynamicEntryModules.add(resolution);
  14888. entriesToHandle.add(resolution);
  14889. }
  14890. }
  14891. for (const dependency of module.implicitlyLoadedBefore) {
  14892. dynamicEntryModules.add(dependency);
  14893. entriesToHandle.add(dependency);
  14894. }
  14895. }
  14896. }
  14897. return { dependentEntryPointsByModule, dynamicEntryModules };
  14898. }
  14899. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  14900. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  14901. for (const dynamicEntry of dynamicEntryModules) {
  14902. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  14903. for (const importer of [
  14904. ...dynamicEntry.includedDynamicImporters,
  14905. ...dynamicEntry.implicitlyLoadedAfter
  14906. ]) {
  14907. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  14908. dynamicDependentEntryPoints.add(entryPoint);
  14909. }
  14910. }
  14911. }
  14912. return dynamicallyDependentEntryPointsByDynamicEntry;
  14913. }
  14914. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  14915. const chunkModules = Object.create(null);
  14916. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  14917. let chunkSignature = '';
  14918. for (const entry of allEntryPoints) {
  14919. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  14920. }
  14921. const chunk = chunkModules[chunkSignature];
  14922. if (chunk) {
  14923. chunk.push(module);
  14924. }
  14925. else {
  14926. chunkModules[chunkSignature] = [module];
  14927. }
  14928. }
  14929. return Object.values(chunkModules).map(modules => ({
  14930. alias: null,
  14931. modules
  14932. }));
  14933. }
  14934. // ported from https://github.com/substack/node-commondir
  14935. function commondir(files) {
  14936. if (files.length === 0)
  14937. return '/';
  14938. if (files.length === 1)
  14939. return dirname(files[0]);
  14940. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  14941. const pathSegements = file.split(/\/+|\\+/);
  14942. let i;
  14943. for (i = 0; commonSegments[i] === pathSegements[i] &&
  14944. i < Math.min(commonSegments.length, pathSegements.length); i++)
  14945. ;
  14946. return commonSegments.slice(0, i);
  14947. }, files[0].split(/\/+|\\+/));
  14948. // Windows correctly handles paths with forward-slashes
  14949. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  14950. }
  14951. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  14952. function sortByExecutionOrder(units) {
  14953. units.sort(compareExecIndex);
  14954. }
  14955. function analyseModuleExecution(entryModules) {
  14956. let nextExecIndex = 0;
  14957. const cyclePaths = [];
  14958. const analysedModules = new Set();
  14959. const dynamicImports = new Set();
  14960. const parents = new Map();
  14961. const orderedModules = [];
  14962. const analyseModule = (module) => {
  14963. if (module instanceof Module) {
  14964. for (const dependency of module.dependencies) {
  14965. if (parents.has(dependency)) {
  14966. if (!analysedModules.has(dependency)) {
  14967. cyclePaths.push(getCyclePath(dependency, module, parents));
  14968. }
  14969. continue;
  14970. }
  14971. parents.set(dependency, module);
  14972. analyseModule(dependency);
  14973. }
  14974. for (const dependency of module.implicitlyLoadedBefore) {
  14975. dynamicImports.add(dependency);
  14976. }
  14977. for (const { resolution } of module.dynamicImports) {
  14978. if (resolution instanceof Module) {
  14979. dynamicImports.add(resolution);
  14980. }
  14981. }
  14982. orderedModules.push(module);
  14983. }
  14984. module.execIndex = nextExecIndex++;
  14985. analysedModules.add(module);
  14986. };
  14987. for (const curEntry of entryModules) {
  14988. if (!parents.has(curEntry)) {
  14989. parents.set(curEntry, null);
  14990. analyseModule(curEntry);
  14991. }
  14992. }
  14993. for (const curEntry of dynamicImports) {
  14994. if (!parents.has(curEntry)) {
  14995. parents.set(curEntry, null);
  14996. analyseModule(curEntry);
  14997. }
  14998. }
  14999. return { cyclePaths, orderedModules };
  15000. }
  15001. function getCyclePath(module, parent, parents) {
  15002. const cycleSymbol = Symbol(module.id);
  15003. const path = [relativeId(module.id)];
  15004. let nextModule = parent;
  15005. module.cycles.add(cycleSymbol);
  15006. while (nextModule !== module) {
  15007. nextModule.cycles.add(cycleSymbol);
  15008. path.push(relativeId(nextModule.id));
  15009. nextModule = parents.get(nextModule);
  15010. }
  15011. path.push(path[0]);
  15012. path.reverse();
  15013. return path;
  15014. }
  15015. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  15016. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  15017. const cnst = constBindings ? 'const' : 'var';
  15018. const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
  15019. const getFunctionIntro = arrowFunctions
  15020. ? (params, { isAsync, name }) => {
  15021. const singleParam = params.length === 1;
  15022. const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
  15023. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
  15024. }
  15025. : getNonArrowFunctionIntro;
  15026. const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
  15027. `${getFunctionIntro(params, {
  15028. isAsync: false,
  15029. name
  15030. })}${arrowFunctions
  15031. ? lineBreakIndent
  15032. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  15033. : ''
  15034. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  15035. arrowFunctions
  15036. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  15037. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  15038. ];
  15039. const isValidPropName = reservedNamesAsProps
  15040. ? (name) => validPropName.test(name)
  15041. : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
  15042. return {
  15043. _,
  15044. cnst,
  15045. getDirectReturnFunction,
  15046. getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  15047. const [left, right] = getDirectReturnFunction(params, {
  15048. functionReturn: true,
  15049. lineBreakIndent: null,
  15050. name: null
  15051. });
  15052. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  15053. },
  15054. getFunctionIntro,
  15055. getNonArrowFunctionIntro,
  15056. getObject(fields, { lineBreakIndent }) {
  15057. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  15058. return `{${fields
  15059. .map(([key, value]) => {
  15060. if (key === null)
  15061. return `${prefix}${value}`;
  15062. const needsQuotes = !isValidPropName(key);
  15063. return key === value && objectShorthand && !needsQuotes
  15064. ? prefix + key
  15065. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  15066. })
  15067. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  15068. },
  15069. getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  15070. n,
  15071. s
  15072. };
  15073. }
  15074. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  15075. const validPropName = /^(?!\d)[\w$]+$/;
  15076. class Bundle {
  15077. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  15078. this.outputOptions = outputOptions;
  15079. this.unsetOptions = unsetOptions;
  15080. this.inputOptions = inputOptions;
  15081. this.pluginDriver = pluginDriver;
  15082. this.graph = graph;
  15083. this.facadeChunkByModule = new Map();
  15084. this.includedNamespaces = new Set();
  15085. }
  15086. async generate(isWrite) {
  15087. timeStart('GENERATE', 1);
  15088. const outputBundle = Object.create(null);
  15089. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  15090. try {
  15091. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  15092. timeStart('generate chunks', 2);
  15093. const chunks = await this.generateChunks();
  15094. if (chunks.length > 1) {
  15095. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  15096. }
  15097. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  15098. timeEnd('generate chunks', 2);
  15099. timeStart('render modules', 2);
  15100. // We need to create addons before prerender because at the moment, there
  15101. // can be no async code between prerender and render due to internal state
  15102. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  15103. const snippets = getGenerateCodeSnippets(this.outputOptions);
  15104. this.prerenderChunks(chunks, inputBase, snippets);
  15105. timeEnd('render modules', 2);
  15106. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
  15107. }
  15108. catch (err) {
  15109. await this.pluginDriver.hookParallel('renderError', [err]);
  15110. throw err;
  15111. }
  15112. await this.pluginDriver.hookSeq('generateBundle', [
  15113. this.outputOptions,
  15114. outputBundle,
  15115. isWrite
  15116. ]);
  15117. this.finaliseAssets(outputBundle);
  15118. timeEnd('GENERATE', 1);
  15119. return outputBundle;
  15120. }
  15121. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
  15122. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  15123. for (const chunk of chunks) {
  15124. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  15125. }
  15126. await Promise.all(chunks.map(async (chunk) => {
  15127. const outputChunk = outputBundle[chunk.id];
  15128. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
  15129. }));
  15130. }
  15131. async addManualChunks(manualChunks) {
  15132. const manualChunkAliasByEntry = new Map();
  15133. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  15134. alias,
  15135. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  15136. })));
  15137. for (const { alias, entries } of chunkEntries) {
  15138. for (const entry of entries) {
  15139. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  15140. }
  15141. }
  15142. return manualChunkAliasByEntry;
  15143. }
  15144. assignChunkIds(chunks, inputBase, addons, bundle) {
  15145. const entryChunks = [];
  15146. const otherChunks = [];
  15147. for (const chunk of chunks) {
  15148. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  15149. ? entryChunks
  15150. : otherChunks).push(chunk);
  15151. }
  15152. // make sure entry chunk names take precedence with regard to deconflicting
  15153. const chunksForNaming = entryChunks.concat(otherChunks);
  15154. for (const chunk of chunksForNaming) {
  15155. if (this.outputOptions.file) {
  15156. chunk.id = basename(this.outputOptions.file);
  15157. }
  15158. else if (this.outputOptions.preserveModules) {
  15159. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  15160. }
  15161. else {
  15162. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  15163. }
  15164. bundle[chunk.id] = FILE_PLACEHOLDER;
  15165. }
  15166. }
  15167. assignManualChunks(getManualChunk) {
  15168. const manualChunkAliasesWithEntry = [];
  15169. const manualChunksApi = {
  15170. getModuleIds: () => this.graph.modulesById.keys(),
  15171. getModuleInfo: this.graph.getModuleInfo
  15172. };
  15173. for (const module of this.graph.modulesById.values()) {
  15174. if (module instanceof Module) {
  15175. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  15176. if (typeof manualChunkAlias === 'string') {
  15177. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  15178. }
  15179. }
  15180. }
  15181. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  15182. const manualChunkAliasByEntry = new Map();
  15183. for (const [alias, module] of manualChunkAliasesWithEntry) {
  15184. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  15185. }
  15186. return manualChunkAliasByEntry;
  15187. }
  15188. finaliseAssets(outputBundle) {
  15189. for (const file of Object.values(outputBundle)) {
  15190. if (!file.type) {
  15191. warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
  15192. file.type = 'asset';
  15193. }
  15194. if (this.outputOptions.validate && 'code' in file) {
  15195. try {
  15196. this.graph.contextParse(file.code, {
  15197. allowHashBang: true,
  15198. ecmaVersion: 'latest'
  15199. });
  15200. }
  15201. catch (err) {
  15202. this.inputOptions.onwarn(errChunkInvalid(file, err));
  15203. }
  15204. }
  15205. }
  15206. this.pluginDriver.finaliseAssets();
  15207. }
  15208. async generateChunks() {
  15209. const { manualChunks } = this.outputOptions;
  15210. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  15211. ? await this.addManualChunks(manualChunks)
  15212. : this.assignManualChunks(manualChunks);
  15213. const chunks = [];
  15214. const chunkByModule = new Map();
  15215. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  15216. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  15217. : this.outputOptions.preserveModules
  15218. ? getIncludedModules(this.graph.modulesById).map(module => ({
  15219. alias: null,
  15220. modules: [module]
  15221. }))
  15222. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  15223. sortByExecutionOrder(modules);
  15224. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  15225. chunks.push(chunk);
  15226. for (const module of modules) {
  15227. chunkByModule.set(module, chunk);
  15228. }
  15229. }
  15230. for (const chunk of chunks) {
  15231. chunk.link();
  15232. }
  15233. const facades = [];
  15234. for (const chunk of chunks) {
  15235. facades.push(...chunk.generateFacades());
  15236. }
  15237. return [...chunks, ...facades];
  15238. }
  15239. prerenderChunks(chunks, inputBase, snippets) {
  15240. for (const chunk of chunks) {
  15241. chunk.generateExports();
  15242. }
  15243. for (const chunk of chunks) {
  15244. chunk.preRender(this.outputOptions, inputBase, snippets);
  15245. }
  15246. }
  15247. }
  15248. function getAbsoluteEntryModulePaths(chunks) {
  15249. const absoluteEntryModulePaths = [];
  15250. for (const chunk of chunks) {
  15251. for (const entryModule of chunk.entryModules) {
  15252. if (isAbsolute(entryModule.id)) {
  15253. absoluteEntryModulePaths.push(entryModule.id);
  15254. }
  15255. }
  15256. }
  15257. return absoluteEntryModulePaths;
  15258. }
  15259. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  15260. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  15261. return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  15262. if (typeof outputOptions.file === 'string')
  15263. return error(errInvalidOption('output.file', 'outputdir', 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
  15264. if (outputOptions.sourcemapFile)
  15265. return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
  15266. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  15267. onWarn(errInvalidOption('output.amd.id', 'outputamd', 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  15268. }
  15269. function getIncludedModules(modulesById) {
  15270. return [...modulesById.values()].filter((module) => module instanceof Module &&
  15271. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  15272. }
  15273. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  15274. const existingAlias = manualChunkAliasByEntry.get(module);
  15275. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  15276. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  15277. }
  15278. manualChunkAliasByEntry.set(module, alias);
  15279. }
  15280. // This file was generated. Do not modify manually!
  15281. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  15282. // This file was generated. Do not modify manually!
  15283. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  15284. // This file was generated. Do not modify manually!
  15285. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  15286. // This file was generated. Do not modify manually!
  15287. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  15288. // These are a run-length and offset encoded representation of the
  15289. // Reserved word lists for various dialects of the language
  15290. var reservedWords = {
  15291. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  15292. 5: "class enum extends super const export import",
  15293. 6: "enum",
  15294. strict: "implements interface let package private protected public static yield",
  15295. strictBind: "eval arguments"
  15296. };
  15297. // And the keywords
  15298. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  15299. var keywords$1 = {
  15300. 5: ecma5AndLessKeywords,
  15301. "5module": ecma5AndLessKeywords + " export import",
  15302. 6: ecma5AndLessKeywords + " const class extends export import super"
  15303. };
  15304. var keywordRelationalOperator = /^in(stanceof)?$/;
  15305. // ## Character categories
  15306. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  15307. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  15308. // This has a complexity linear to the value of the code. The
  15309. // assumption is that looking up astral identifier characters is
  15310. // rare.
  15311. function isInAstralSet(code, set) {
  15312. var pos = 0x10000;
  15313. for (var i = 0; i < set.length; i += 2) {
  15314. pos += set[i];
  15315. if (pos > code) { return false }
  15316. pos += set[i + 1];
  15317. if (pos >= code) { return true }
  15318. }
  15319. }
  15320. // Test whether a given character code starts an identifier.
  15321. function isIdentifierStart(code, astral) {
  15322. if (code < 65) { return code === 36 }
  15323. if (code < 91) { return true }
  15324. if (code < 97) { return code === 95 }
  15325. if (code < 123) { return true }
  15326. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  15327. if (astral === false) { return false }
  15328. return isInAstralSet(code, astralIdentifierStartCodes)
  15329. }
  15330. // Test whether a given character is part of an identifier.
  15331. function isIdentifierChar(code, astral) {
  15332. if (code < 48) { return code === 36 }
  15333. if (code < 58) { return true }
  15334. if (code < 65) { return false }
  15335. if (code < 91) { return true }
  15336. if (code < 97) { return code === 95 }
  15337. if (code < 123) { return true }
  15338. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  15339. if (astral === false) { return false }
  15340. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  15341. }
  15342. // ## Token types
  15343. // The assignment of fine-grained, information-carrying type objects
  15344. // allows the tokenizer to store the information it has about a
  15345. // token in a way that is very cheap for the parser to look up.
  15346. // All token type variables start with an underscore, to make them
  15347. // easy to recognize.
  15348. // The `beforeExpr` property is used to disambiguate between regular
  15349. // expressions and divisions. It is set on all token types that can
  15350. // be followed by an expression (thus, a slash after them would be a
  15351. // regular expression).
  15352. //
  15353. // The `startsExpr` property is used to check if the token ends a
  15354. // `yield` expression. It is set on all token types that either can
  15355. // directly start an expression (like a quotation mark) or can
  15356. // continue an expression (like the body of a string).
  15357. //
  15358. // `isLoop` marks a keyword as starting a loop, which is important
  15359. // to know when parsing a label, in order to allow or disallow
  15360. // continue jumps to that label.
  15361. var TokenType = function TokenType(label, conf) {
  15362. if ( conf === void 0 ) conf = {};
  15363. this.label = label;
  15364. this.keyword = conf.keyword;
  15365. this.beforeExpr = !!conf.beforeExpr;
  15366. this.startsExpr = !!conf.startsExpr;
  15367. this.isLoop = !!conf.isLoop;
  15368. this.isAssign = !!conf.isAssign;
  15369. this.prefix = !!conf.prefix;
  15370. this.postfix = !!conf.postfix;
  15371. this.binop = conf.binop || null;
  15372. this.updateContext = null;
  15373. };
  15374. function binop(name, prec) {
  15375. return new TokenType(name, {beforeExpr: true, binop: prec})
  15376. }
  15377. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  15378. // Map keyword names to token types.
  15379. var keywords = {};
  15380. // Succinct definitions of keyword token types
  15381. function kw(name, options) {
  15382. if ( options === void 0 ) options = {};
  15383. options.keyword = name;
  15384. return keywords[name] = new TokenType(name, options)
  15385. }
  15386. var types$1 = {
  15387. num: new TokenType("num", startsExpr),
  15388. regexp: new TokenType("regexp", startsExpr),
  15389. string: new TokenType("string", startsExpr),
  15390. name: new TokenType("name", startsExpr),
  15391. privateId: new TokenType("privateId", startsExpr),
  15392. eof: new TokenType("eof"),
  15393. // Punctuation token types.
  15394. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  15395. bracketR: new TokenType("]"),
  15396. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  15397. braceR: new TokenType("}"),
  15398. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  15399. parenR: new TokenType(")"),
  15400. comma: new TokenType(",", beforeExpr),
  15401. semi: new TokenType(";", beforeExpr),
  15402. colon: new TokenType(":", beforeExpr),
  15403. dot: new TokenType("."),
  15404. question: new TokenType("?", beforeExpr),
  15405. questionDot: new TokenType("?."),
  15406. arrow: new TokenType("=>", beforeExpr),
  15407. template: new TokenType("template"),
  15408. invalidTemplate: new TokenType("invalidTemplate"),
  15409. ellipsis: new TokenType("...", beforeExpr),
  15410. backQuote: new TokenType("`", startsExpr),
  15411. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  15412. // Operators. These carry several kinds of properties to help the
  15413. // parser use them properly (the presence of these properties is
  15414. // what categorizes them as operators).
  15415. //
  15416. // `binop`, when present, specifies that this operator is a binary
  15417. // operator, and will refer to its precedence.
  15418. //
  15419. // `prefix` and `postfix` mark the operator as a prefix or postfix
  15420. // unary operator.
  15421. //
  15422. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  15423. // binary operators with a very low precedence, that should result
  15424. // in AssignmentExpression nodes.
  15425. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  15426. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  15427. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  15428. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  15429. logicalOR: binop("||", 1),
  15430. logicalAND: binop("&&", 2),
  15431. bitwiseOR: binop("|", 3),
  15432. bitwiseXOR: binop("^", 4),
  15433. bitwiseAND: binop("&", 5),
  15434. equality: binop("==/!=/===/!==", 6),
  15435. relational: binop("</>/<=/>=", 7),
  15436. bitShift: binop("<</>>/>>>", 8),
  15437. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  15438. modulo: binop("%", 10),
  15439. star: binop("*", 10),
  15440. slash: binop("/", 10),
  15441. starstar: new TokenType("**", {beforeExpr: true}),
  15442. coalesce: binop("??", 1),
  15443. // Keyword token types.
  15444. _break: kw("break"),
  15445. _case: kw("case", beforeExpr),
  15446. _catch: kw("catch"),
  15447. _continue: kw("continue"),
  15448. _debugger: kw("debugger"),
  15449. _default: kw("default", beforeExpr),
  15450. _do: kw("do", {isLoop: true, beforeExpr: true}),
  15451. _else: kw("else", beforeExpr),
  15452. _finally: kw("finally"),
  15453. _for: kw("for", {isLoop: true}),
  15454. _function: kw("function", startsExpr),
  15455. _if: kw("if"),
  15456. _return: kw("return", beforeExpr),
  15457. _switch: kw("switch"),
  15458. _throw: kw("throw", beforeExpr),
  15459. _try: kw("try"),
  15460. _var: kw("var"),
  15461. _const: kw("const"),
  15462. _while: kw("while", {isLoop: true}),
  15463. _with: kw("with"),
  15464. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  15465. _this: kw("this", startsExpr),
  15466. _super: kw("super", startsExpr),
  15467. _class: kw("class", startsExpr),
  15468. _extends: kw("extends", beforeExpr),
  15469. _export: kw("export"),
  15470. _import: kw("import", startsExpr),
  15471. _null: kw("null", startsExpr),
  15472. _true: kw("true", startsExpr),
  15473. _false: kw("false", startsExpr),
  15474. _in: kw("in", {beforeExpr: true, binop: 7}),
  15475. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  15476. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  15477. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  15478. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  15479. };
  15480. // Matches a whole line break (where CRLF is considered a single
  15481. // line break). Used to count lines.
  15482. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  15483. var lineBreakG = new RegExp(lineBreak.source, "g");
  15484. function isNewLine(code) {
  15485. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15486. }
  15487. function nextLineBreak(code, from, end) {
  15488. if ( end === void 0 ) end = code.length;
  15489. for (var i = from; i < end; i++) {
  15490. var next = code.charCodeAt(i);
  15491. if (isNewLine(next))
  15492. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15493. }
  15494. return -1
  15495. }
  15496. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15497. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15498. var ref = Object.prototype;
  15499. var hasOwnProperty = ref.hasOwnProperty;
  15500. var toString = ref.toString;
  15501. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15502. hasOwnProperty.call(obj, propName)
  15503. ); });
  15504. var isArray = Array.isArray || (function (obj) { return (
  15505. toString.call(obj) === "[object Array]"
  15506. ); });
  15507. function wordsRegexp(words) {
  15508. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15509. }
  15510. function codePointToString(code) {
  15511. // UTF-16 Decoding
  15512. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15513. code -= 0x10000;
  15514. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15515. }
  15516. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15517. // These are used when `options.locations` is on, for the
  15518. // `startLoc` and `endLoc` properties.
  15519. var Position = function Position(line, col) {
  15520. this.line = line;
  15521. this.column = col;
  15522. };
  15523. Position.prototype.offset = function offset (n) {
  15524. return new Position(this.line, this.column + n)
  15525. };
  15526. var SourceLocation = function SourceLocation(p, start, end) {
  15527. this.start = start;
  15528. this.end = end;
  15529. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15530. };
  15531. // The `getLineInfo` function is mostly useful when the
  15532. // `locations` option is off (for performance reasons) and you
  15533. // want to find the line/column position for a given character
  15534. // offset. `input` should be the code string that the offset refers
  15535. // into.
  15536. function getLineInfo(input, offset) {
  15537. for (var line = 1, cur = 0;;) {
  15538. var nextBreak = nextLineBreak(input, cur, offset);
  15539. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15540. ++line;
  15541. cur = nextBreak;
  15542. }
  15543. }
  15544. // A second argument must be given to configure the parser process.
  15545. // These options are recognized (only `ecmaVersion` is required):
  15546. var defaultOptions = {
  15547. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15548. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15549. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  15550. // latest version the library supports). This influences support
  15551. // for strict mode, the set of reserved words, and support for
  15552. // new syntax features.
  15553. ecmaVersion: null,
  15554. // `sourceType` indicates the mode the code should be parsed in.
  15555. // Can be either `"script"` or `"module"`. This influences global
  15556. // strict mode and parsing of `import` and `export` declarations.
  15557. sourceType: "script",
  15558. // `onInsertedSemicolon` can be a callback that will be called
  15559. // when a semicolon is automatically inserted. It will be passed
  15560. // the position of the comma as an offset, and if `locations` is
  15561. // enabled, it is given the location as a `{line, column}` object
  15562. // as second argument.
  15563. onInsertedSemicolon: null,
  15564. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15565. // trailing commas.
  15566. onTrailingComma: null,
  15567. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15568. // Set `allowReserved` to a boolean value to explicitly turn this on
  15569. // an off. When this option has the value "never", reserved words
  15570. // and keywords can also not be used as property names.
  15571. allowReserved: null,
  15572. // When enabled, a return at the top level is not considered an
  15573. // error.
  15574. allowReturnOutsideFunction: false,
  15575. // When enabled, import/export statements are not constrained to
  15576. // appearing at the top of the program, and an import.meta expression
  15577. // in a script isn't considered an error.
  15578. allowImportExportEverywhere: false,
  15579. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15580. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15581. // but they are still not allowed in non-async functions.
  15582. allowAwaitOutsideFunction: null,
  15583. // When enabled, super identifiers are not constrained to
  15584. // appearing in methods and do not raise an error when they appear elsewhere.
  15585. allowSuperOutsideMethod: null,
  15586. // When enabled, hashbang directive in the beginning of file
  15587. // is allowed and treated as a line comment.
  15588. allowHashBang: false,
  15589. // When `locations` is on, `loc` properties holding objects with
  15590. // `start` and `end` properties in `{line, column}` form (with
  15591. // line being 1-based and column 0-based) will be attached to the
  15592. // nodes.
  15593. locations: false,
  15594. // A function can be passed as `onToken` option, which will
  15595. // cause Acorn to call that function with object in the same
  15596. // format as tokens returned from `tokenizer().getToken()`. Note
  15597. // that you are not allowed to call the parser from the
  15598. // callback—that will corrupt its internal state.
  15599. onToken: null,
  15600. // A function can be passed as `onComment` option, which will
  15601. // cause Acorn to call that function with `(block, text, start,
  15602. // end)` parameters whenever a comment is skipped. `block` is a
  15603. // boolean indicating whether this is a block (`/* */`) comment,
  15604. // `text` is the content of the comment, and `start` and `end` are
  15605. // character offsets that denote the start and end of the comment.
  15606. // When the `locations` option is on, two more parameters are
  15607. // passed, the full `{line, column}` locations of the start and
  15608. // end of the comments. Note that you are not allowed to call the
  15609. // parser from the callback—that will corrupt its internal state.
  15610. onComment: null,
  15611. // Nodes have their start and end characters offsets recorded in
  15612. // `start` and `end` properties (directly on the node, rather than
  15613. // the `loc` object, which holds line/column data. To also add a
  15614. // [semi-standardized][range] `range` property holding a `[start,
  15615. // end]` array with the same numbers, set the `ranges` option to
  15616. // `true`.
  15617. //
  15618. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15619. ranges: false,
  15620. // It is possible to parse multiple files into a single AST by
  15621. // passing the tree produced by parsing the first file as
  15622. // `program` option in subsequent parses. This will add the
  15623. // toplevel forms of the parsed file to the `Program` (top) node
  15624. // of an existing parse tree.
  15625. program: null,
  15626. // When `locations` is on, you can pass this to record the source
  15627. // file in every node's `loc` object.
  15628. sourceFile: null,
  15629. // This value, if given, is stored in every node, whether
  15630. // `locations` is on or off.
  15631. directSourceFile: null,
  15632. // When enabled, parenthesized expressions are represented by
  15633. // (non-standard) ParenthesizedExpression nodes
  15634. preserveParens: false
  15635. };
  15636. // Interpret and default an options object
  15637. var warnedAboutEcmaVersion = false;
  15638. function getOptions(opts) {
  15639. var options = {};
  15640. for (var opt in defaultOptions)
  15641. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15642. if (options.ecmaVersion === "latest") {
  15643. options.ecmaVersion = 1e8;
  15644. } else if (options.ecmaVersion == null) {
  15645. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15646. warnedAboutEcmaVersion = true;
  15647. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15648. }
  15649. options.ecmaVersion = 11;
  15650. } else if (options.ecmaVersion >= 2015) {
  15651. options.ecmaVersion -= 2009;
  15652. }
  15653. if (options.allowReserved == null)
  15654. { options.allowReserved = options.ecmaVersion < 5; }
  15655. if (isArray(options.onToken)) {
  15656. var tokens = options.onToken;
  15657. options.onToken = function (token) { return tokens.push(token); };
  15658. }
  15659. if (isArray(options.onComment))
  15660. { options.onComment = pushComment(options, options.onComment); }
  15661. return options
  15662. }
  15663. function pushComment(options, array) {
  15664. return function(block, text, start, end, startLoc, endLoc) {
  15665. var comment = {
  15666. type: block ? "Block" : "Line",
  15667. value: text,
  15668. start: start,
  15669. end: end
  15670. };
  15671. if (options.locations)
  15672. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15673. if (options.ranges)
  15674. { comment.range = [start, end]; }
  15675. array.push(comment);
  15676. }
  15677. }
  15678. // Each scope gets a bitset that may contain these flags
  15679. var
  15680. SCOPE_TOP = 1,
  15681. SCOPE_FUNCTION = 2,
  15682. SCOPE_ASYNC = 4,
  15683. SCOPE_GENERATOR = 8,
  15684. SCOPE_ARROW = 16,
  15685. SCOPE_SIMPLE_CATCH = 32,
  15686. SCOPE_SUPER = 64,
  15687. SCOPE_DIRECT_SUPER = 128,
  15688. SCOPE_CLASS_STATIC_BLOCK = 256,
  15689. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15690. function functionFlags(async, generator) {
  15691. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15692. }
  15693. // Used in checkLVal* and declareName to determine the type of a binding
  15694. var
  15695. BIND_NONE = 0, // Not a binding
  15696. BIND_VAR = 1, // Var-style binding
  15697. BIND_LEXICAL = 2, // Let- or const-style binding
  15698. BIND_FUNCTION = 3, // Function declaration
  15699. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15700. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15701. var Parser = function Parser(options, input, startPos) {
  15702. this.options = options = getOptions(options);
  15703. this.sourceFile = options.sourceFile;
  15704. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15705. var reserved = "";
  15706. if (options.allowReserved !== true) {
  15707. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15708. if (options.sourceType === "module") { reserved += " await"; }
  15709. }
  15710. this.reservedWords = wordsRegexp(reserved);
  15711. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15712. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15713. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15714. this.input = String(input);
  15715. // Used to signal to callers of `readWord1` whether the word
  15716. // contained any escape sequences. This is needed because words with
  15717. // escape sequences must not be interpreted as keywords.
  15718. this.containsEsc = false;
  15719. // Set up token state
  15720. // The current position of the tokenizer in the input.
  15721. if (startPos) {
  15722. this.pos = startPos;
  15723. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15724. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15725. } else {
  15726. this.pos = this.lineStart = 0;
  15727. this.curLine = 1;
  15728. }
  15729. // Properties of the current token:
  15730. // Its type
  15731. this.type = types$1.eof;
  15732. // For tokens that include more information than their type, the value
  15733. this.value = null;
  15734. // Its start and end offset
  15735. this.start = this.end = this.pos;
  15736. // And, if locations are used, the {line, column} object
  15737. // corresponding to those offsets
  15738. this.startLoc = this.endLoc = this.curPosition();
  15739. // Position information for the previous token
  15740. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15741. this.lastTokStart = this.lastTokEnd = this.pos;
  15742. // The context stack is used to superficially track syntactic
  15743. // context to predict whether a regular expression is allowed in a
  15744. // given position.
  15745. this.context = this.initialContext();
  15746. this.exprAllowed = true;
  15747. // Figure out if it's a module code.
  15748. this.inModule = options.sourceType === "module";
  15749. this.strict = this.inModule || this.strictDirective(this.pos);
  15750. // Used to signify the start of a potential arrow function
  15751. this.potentialArrowAt = -1;
  15752. this.potentialArrowInForAwait = false;
  15753. // Positions to delayed-check that yield/await does not exist in default parameters.
  15754. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15755. // Labels in scope.
  15756. this.labels = [];
  15757. // Thus-far undefined exports.
  15758. this.undefinedExports = Object.create(null);
  15759. // If enabled, skip leading hashbang line.
  15760. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15761. { this.skipLineComment(2); }
  15762. // Scope tracking for duplicate variable names (see scope.js)
  15763. this.scopeStack = [];
  15764. this.enterScope(SCOPE_TOP);
  15765. // For RegExp validation
  15766. this.regexpState = null;
  15767. // The stack of private names.
  15768. // Each element has two properties: 'declared' and 'used'.
  15769. // When it exited from the outermost class definition, all used private names must be declared.
  15770. this.privateNameStack = [];
  15771. };
  15772. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  15773. Parser.prototype.parse = function parse () {
  15774. var node = this.options.program || this.startNode();
  15775. this.nextToken();
  15776. return this.parseTopLevel(node)
  15777. };
  15778. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15779. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15780. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15781. prototypeAccessors.canAwait.get = function () {
  15782. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15783. var scope = this.scopeStack[i];
  15784. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15785. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15786. }
  15787. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15788. };
  15789. prototypeAccessors.allowSuper.get = function () {
  15790. var ref = this.currentThisScope();
  15791. var flags = ref.flags;
  15792. var inClassFieldInit = ref.inClassFieldInit;
  15793. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15794. };
  15795. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15796. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15797. prototypeAccessors.allowNewDotTarget.get = function () {
  15798. var ref = this.currentThisScope();
  15799. var flags = ref.flags;
  15800. var inClassFieldInit = ref.inClassFieldInit;
  15801. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15802. };
  15803. prototypeAccessors.inClassStaticBlock.get = function () {
  15804. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15805. };
  15806. Parser.extend = function extend () {
  15807. var plugins = [], len = arguments.length;
  15808. while ( len-- ) plugins[ len ] = arguments[ len ];
  15809. var cls = this;
  15810. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15811. return cls
  15812. };
  15813. Parser.parse = function parse (input, options) {
  15814. return new this(options, input).parse()
  15815. };
  15816. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15817. var parser = new this(options, input, pos);
  15818. parser.nextToken();
  15819. return parser.parseExpression()
  15820. };
  15821. Parser.tokenizer = function tokenizer (input, options) {
  15822. return new this(options, input)
  15823. };
  15824. Object.defineProperties( Parser.prototype, prototypeAccessors );
  15825. var pp$9 = Parser.prototype;
  15826. // ## Parser utilities
  15827. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15828. pp$9.strictDirective = function(start) {
  15829. if (this.options.ecmaVersion < 5) { return false }
  15830. for (;;) {
  15831. // Try to find string literal.
  15832. skipWhiteSpace.lastIndex = start;
  15833. start += skipWhiteSpace.exec(this.input)[0].length;
  15834. var match = literal.exec(this.input.slice(start));
  15835. if (!match) { return false }
  15836. if ((match[1] || match[2]) === "use strict") {
  15837. skipWhiteSpace.lastIndex = start + match[0].length;
  15838. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15839. var next = this.input.charAt(end);
  15840. return next === ";" || next === "}" ||
  15841. (lineBreak.test(spaceAfter[0]) &&
  15842. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15843. }
  15844. start += match[0].length;
  15845. // Skip semicolon, if any.
  15846. skipWhiteSpace.lastIndex = start;
  15847. start += skipWhiteSpace.exec(this.input)[0].length;
  15848. if (this.input[start] === ";")
  15849. { start++; }
  15850. }
  15851. };
  15852. // Predicate that tests whether the next token is of the given
  15853. // type, and if yes, consumes it as a side effect.
  15854. pp$9.eat = function(type) {
  15855. if (this.type === type) {
  15856. this.next();
  15857. return true
  15858. } else {
  15859. return false
  15860. }
  15861. };
  15862. // Tests whether parsed token is a contextual keyword.
  15863. pp$9.isContextual = function(name) {
  15864. return this.type === types$1.name && this.value === name && !this.containsEsc
  15865. };
  15866. // Consumes contextual keyword if possible.
  15867. pp$9.eatContextual = function(name) {
  15868. if (!this.isContextual(name)) { return false }
  15869. this.next();
  15870. return true
  15871. };
  15872. // Asserts that following token is given contextual keyword.
  15873. pp$9.expectContextual = function(name) {
  15874. if (!this.eatContextual(name)) { this.unexpected(); }
  15875. };
  15876. // Test whether a semicolon can be inserted at the current position.
  15877. pp$9.canInsertSemicolon = function() {
  15878. return this.type === types$1.eof ||
  15879. this.type === types$1.braceR ||
  15880. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15881. };
  15882. pp$9.insertSemicolon = function() {
  15883. if (this.canInsertSemicolon()) {
  15884. if (this.options.onInsertedSemicolon)
  15885. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  15886. return true
  15887. }
  15888. };
  15889. // Consume a semicolon, or, failing that, see if we are allowed to
  15890. // pretend that there is a semicolon at this position.
  15891. pp$9.semicolon = function() {
  15892. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  15893. };
  15894. pp$9.afterTrailingComma = function(tokType, notNext) {
  15895. if (this.type === tokType) {
  15896. if (this.options.onTrailingComma)
  15897. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  15898. if (!notNext)
  15899. { this.next(); }
  15900. return true
  15901. }
  15902. };
  15903. // Expect a token of a given type. If found, consume it, otherwise,
  15904. // raise an unexpected token error.
  15905. pp$9.expect = function(type) {
  15906. this.eat(type) || this.unexpected();
  15907. };
  15908. // Raise an unexpected token error.
  15909. pp$9.unexpected = function(pos) {
  15910. this.raise(pos != null ? pos : this.start, "Unexpected token");
  15911. };
  15912. var DestructuringErrors = function DestructuringErrors() {
  15913. this.shorthandAssign =
  15914. this.trailingComma =
  15915. this.parenthesizedAssign =
  15916. this.parenthesizedBind =
  15917. this.doubleProto =
  15918. -1;
  15919. };
  15920. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  15921. if (!refDestructuringErrors) { return }
  15922. if (refDestructuringErrors.trailingComma > -1)
  15923. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  15924. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  15925. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  15926. };
  15927. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  15928. if (!refDestructuringErrors) { return false }
  15929. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  15930. var doubleProto = refDestructuringErrors.doubleProto;
  15931. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  15932. if (shorthandAssign >= 0)
  15933. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  15934. if (doubleProto >= 0)
  15935. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  15936. };
  15937. pp$9.checkYieldAwaitInDefaultParams = function() {
  15938. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  15939. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  15940. if (this.awaitPos)
  15941. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  15942. };
  15943. pp$9.isSimpleAssignTarget = function(expr) {
  15944. if (expr.type === "ParenthesizedExpression")
  15945. { return this.isSimpleAssignTarget(expr.expression) }
  15946. return expr.type === "Identifier" || expr.type === "MemberExpression"
  15947. };
  15948. var pp$8 = Parser.prototype;
  15949. // ### Statement parsing
  15950. // Parse a program. Initializes the parser, reads any number of
  15951. // statements, and wraps them in a Program node. Optionally takes a
  15952. // `program` argument. If present, the statements will be appended
  15953. // to its body instead of creating a new node.
  15954. pp$8.parseTopLevel = function(node) {
  15955. var exports = Object.create(null);
  15956. if (!node.body) { node.body = []; }
  15957. while (this.type !== types$1.eof) {
  15958. var stmt = this.parseStatement(null, true, exports);
  15959. node.body.push(stmt);
  15960. }
  15961. if (this.inModule)
  15962. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  15963. {
  15964. var name = list[i];
  15965. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  15966. } }
  15967. this.adaptDirectivePrologue(node.body);
  15968. this.next();
  15969. node.sourceType = this.options.sourceType;
  15970. return this.finishNode(node, "Program")
  15971. };
  15972. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  15973. pp$8.isLet = function(context) {
  15974. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  15975. skipWhiteSpace.lastIndex = this.pos;
  15976. var skip = skipWhiteSpace.exec(this.input);
  15977. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15978. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  15979. // Statement) is allowed here. If context is not empty then only a Statement
  15980. // is allowed. However, `let [` is an explicit negative lookahead for
  15981. // ExpressionStatement, so special-case it first.
  15982. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  15983. if (context) { return false }
  15984. if (nextCh === 123) { return true } // '{'
  15985. if (isIdentifierStart(nextCh, true)) {
  15986. var pos = next + 1;
  15987. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  15988. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  15989. var ident = this.input.slice(next, pos);
  15990. if (!keywordRelationalOperator.test(ident)) { return true }
  15991. }
  15992. return false
  15993. };
  15994. // check 'async [no LineTerminator here] function'
  15995. // - 'async /*foo*/ function' is OK.
  15996. // - 'async /*\n*/ function' is invalid.
  15997. pp$8.isAsyncFunction = function() {
  15998. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  15999. { return false }
  16000. skipWhiteSpace.lastIndex = this.pos;
  16001. var skip = skipWhiteSpace.exec(this.input);
  16002. var next = this.pos + skip[0].length, after;
  16003. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  16004. this.input.slice(next, next + 8) === "function" &&
  16005. (next + 8 === this.input.length ||
  16006. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  16007. };
  16008. // Parse a single statement.
  16009. //
  16010. // If expecting a statement and finding a slash operator, parse a
  16011. // regular expression literal. This is to handle cases like
  16012. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  16013. // does not help.
  16014. pp$8.parseStatement = function(context, topLevel, exports) {
  16015. var starttype = this.type, node = this.startNode(), kind;
  16016. if (this.isLet(context)) {
  16017. starttype = types$1._var;
  16018. kind = "let";
  16019. }
  16020. // Most types of statements are recognized by the keyword they
  16021. // start with. Many are trivial to parse, some require a bit of
  16022. // complexity.
  16023. switch (starttype) {
  16024. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  16025. case types$1._debugger: return this.parseDebuggerStatement(node)
  16026. case types$1._do: return this.parseDoStatement(node)
  16027. case types$1._for: return this.parseForStatement(node)
  16028. case types$1._function:
  16029. // Function as sole body of either an if statement or a labeled statement
  16030. // works, but not when it is part of a labeled statement that is the sole
  16031. // body of an if statement.
  16032. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  16033. return this.parseFunctionStatement(node, false, !context)
  16034. case types$1._class:
  16035. if (context) { this.unexpected(); }
  16036. return this.parseClass(node, true)
  16037. case types$1._if: return this.parseIfStatement(node)
  16038. case types$1._return: return this.parseReturnStatement(node)
  16039. case types$1._switch: return this.parseSwitchStatement(node)
  16040. case types$1._throw: return this.parseThrowStatement(node)
  16041. case types$1._try: return this.parseTryStatement(node)
  16042. case types$1._const: case types$1._var:
  16043. kind = kind || this.value;
  16044. if (context && kind !== "var") { this.unexpected(); }
  16045. return this.parseVarStatement(node, kind)
  16046. case types$1._while: return this.parseWhileStatement(node)
  16047. case types$1._with: return this.parseWithStatement(node)
  16048. case types$1.braceL: return this.parseBlock(true, node)
  16049. case types$1.semi: return this.parseEmptyStatement(node)
  16050. case types$1._export:
  16051. case types$1._import:
  16052. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  16053. skipWhiteSpace.lastIndex = this.pos;
  16054. var skip = skipWhiteSpace.exec(this.input);
  16055. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  16056. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  16057. { return this.parseExpressionStatement(node, this.parseExpression()) }
  16058. }
  16059. if (!this.options.allowImportExportEverywhere) {
  16060. if (!topLevel)
  16061. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  16062. if (!this.inModule)
  16063. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  16064. }
  16065. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  16066. // If the statement does not start with a statement keyword or a
  16067. // brace, it's an ExpressionStatement or LabeledStatement. We
  16068. // simply start parsing an expression, and afterwards, if the
  16069. // next token is a colon and the expression was a simple
  16070. // Identifier node, we switch to interpreting it as a label.
  16071. default:
  16072. if (this.isAsyncFunction()) {
  16073. if (context) { this.unexpected(); }
  16074. this.next();
  16075. return this.parseFunctionStatement(node, true, !context)
  16076. }
  16077. var maybeName = this.value, expr = this.parseExpression();
  16078. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  16079. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  16080. else { return this.parseExpressionStatement(node, expr) }
  16081. }
  16082. };
  16083. pp$8.parseBreakContinueStatement = function(node, keyword) {
  16084. var isBreak = keyword === "break";
  16085. this.next();
  16086. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  16087. else if (this.type !== types$1.name) { this.unexpected(); }
  16088. else {
  16089. node.label = this.parseIdent();
  16090. this.semicolon();
  16091. }
  16092. // Verify that there is an actual destination to break or
  16093. // continue to.
  16094. var i = 0;
  16095. for (; i < this.labels.length; ++i) {
  16096. var lab = this.labels[i];
  16097. if (node.label == null || lab.name === node.label.name) {
  16098. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  16099. if (node.label && isBreak) { break }
  16100. }
  16101. }
  16102. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  16103. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  16104. };
  16105. pp$8.parseDebuggerStatement = function(node) {
  16106. this.next();
  16107. this.semicolon();
  16108. return this.finishNode(node, "DebuggerStatement")
  16109. };
  16110. pp$8.parseDoStatement = function(node) {
  16111. this.next();
  16112. this.labels.push(loopLabel);
  16113. node.body = this.parseStatement("do");
  16114. this.labels.pop();
  16115. this.expect(types$1._while);
  16116. node.test = this.parseParenExpression();
  16117. if (this.options.ecmaVersion >= 6)
  16118. { this.eat(types$1.semi); }
  16119. else
  16120. { this.semicolon(); }
  16121. return this.finishNode(node, "DoWhileStatement")
  16122. };
  16123. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  16124. // loop is non-trivial. Basically, we have to parse the init `var`
  16125. // statement or expression, disallowing the `in` operator (see
  16126. // the second parameter to `parseExpression`), and then check
  16127. // whether the next token is `in` or `of`. When there is no init
  16128. // part (semicolon immediately after the opening parenthesis), it
  16129. // is a regular `for` loop.
  16130. pp$8.parseForStatement = function(node) {
  16131. this.next();
  16132. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  16133. this.labels.push(loopLabel);
  16134. this.enterScope(0);
  16135. this.expect(types$1.parenL);
  16136. if (this.type === types$1.semi) {
  16137. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16138. return this.parseFor(node, null)
  16139. }
  16140. var isLet = this.isLet();
  16141. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  16142. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  16143. this.next();
  16144. this.parseVar(init$1, true, kind);
  16145. this.finishNode(init$1, "VariableDeclaration");
  16146. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  16147. if (this.options.ecmaVersion >= 9) {
  16148. if (this.type === types$1._in) {
  16149. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16150. } else { node.await = awaitAt > -1; }
  16151. }
  16152. return this.parseForIn(node, init$1)
  16153. }
  16154. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16155. return this.parseFor(node, init$1)
  16156. }
  16157. var startsWithLet = this.isContextual("let"), isForOf = false;
  16158. var refDestructuringErrors = new DestructuringErrors;
  16159. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  16160. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  16161. if (this.options.ecmaVersion >= 9) {
  16162. if (this.type === types$1._in) {
  16163. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16164. } else { node.await = awaitAt > -1; }
  16165. }
  16166. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  16167. this.toAssignable(init, false, refDestructuringErrors);
  16168. this.checkLValPattern(init);
  16169. return this.parseForIn(node, init)
  16170. } else {
  16171. this.checkExpressionErrors(refDestructuringErrors, true);
  16172. }
  16173. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16174. return this.parseFor(node, init)
  16175. };
  16176. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  16177. this.next();
  16178. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  16179. };
  16180. pp$8.parseIfStatement = function(node) {
  16181. this.next();
  16182. node.test = this.parseParenExpression();
  16183. // allow function declarations in branches, but only in non-strict mode
  16184. node.consequent = this.parseStatement("if");
  16185. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  16186. return this.finishNode(node, "IfStatement")
  16187. };
  16188. pp$8.parseReturnStatement = function(node) {
  16189. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  16190. { this.raise(this.start, "'return' outside of function"); }
  16191. this.next();
  16192. // In `return` (and `break`/`continue`), the keywords with
  16193. // optional arguments, we eagerly look for a semicolon or the
  16194. // possibility to insert one.
  16195. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  16196. else { node.argument = this.parseExpression(); this.semicolon(); }
  16197. return this.finishNode(node, "ReturnStatement")
  16198. };
  16199. pp$8.parseSwitchStatement = function(node) {
  16200. this.next();
  16201. node.discriminant = this.parseParenExpression();
  16202. node.cases = [];
  16203. this.expect(types$1.braceL);
  16204. this.labels.push(switchLabel);
  16205. this.enterScope(0);
  16206. // Statements under must be grouped (by label) in SwitchCase
  16207. // nodes. `cur` is used to keep the node that we are currently
  16208. // adding statements to.
  16209. var cur;
  16210. for (var sawDefault = false; this.type !== types$1.braceR;) {
  16211. if (this.type === types$1._case || this.type === types$1._default) {
  16212. var isCase = this.type === types$1._case;
  16213. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16214. node.cases.push(cur = this.startNode());
  16215. cur.consequent = [];
  16216. this.next();
  16217. if (isCase) {
  16218. cur.test = this.parseExpression();
  16219. } else {
  16220. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  16221. sawDefault = true;
  16222. cur.test = null;
  16223. }
  16224. this.expect(types$1.colon);
  16225. } else {
  16226. if (!cur) { this.unexpected(); }
  16227. cur.consequent.push(this.parseStatement(null));
  16228. }
  16229. }
  16230. this.exitScope();
  16231. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16232. this.next(); // Closing brace
  16233. this.labels.pop();
  16234. return this.finishNode(node, "SwitchStatement")
  16235. };
  16236. pp$8.parseThrowStatement = function(node) {
  16237. this.next();
  16238. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  16239. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  16240. node.argument = this.parseExpression();
  16241. this.semicolon();
  16242. return this.finishNode(node, "ThrowStatement")
  16243. };
  16244. // Reused empty array added for node fields that are always empty.
  16245. var empty$1 = [];
  16246. pp$8.parseTryStatement = function(node) {
  16247. this.next();
  16248. node.block = this.parseBlock();
  16249. node.handler = null;
  16250. if (this.type === types$1._catch) {
  16251. var clause = this.startNode();
  16252. this.next();
  16253. if (this.eat(types$1.parenL)) {
  16254. clause.param = this.parseBindingAtom();
  16255. var simple = clause.param.type === "Identifier";
  16256. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  16257. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  16258. this.expect(types$1.parenR);
  16259. } else {
  16260. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  16261. clause.param = null;
  16262. this.enterScope(0);
  16263. }
  16264. clause.body = this.parseBlock(false);
  16265. this.exitScope();
  16266. node.handler = this.finishNode(clause, "CatchClause");
  16267. }
  16268. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  16269. if (!node.handler && !node.finalizer)
  16270. { this.raise(node.start, "Missing catch or finally clause"); }
  16271. return this.finishNode(node, "TryStatement")
  16272. };
  16273. pp$8.parseVarStatement = function(node, kind) {
  16274. this.next();
  16275. this.parseVar(node, false, kind);
  16276. this.semicolon();
  16277. return this.finishNode(node, "VariableDeclaration")
  16278. };
  16279. pp$8.parseWhileStatement = function(node) {
  16280. this.next();
  16281. node.test = this.parseParenExpression();
  16282. this.labels.push(loopLabel);
  16283. node.body = this.parseStatement("while");
  16284. this.labels.pop();
  16285. return this.finishNode(node, "WhileStatement")
  16286. };
  16287. pp$8.parseWithStatement = function(node) {
  16288. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  16289. this.next();
  16290. node.object = this.parseParenExpression();
  16291. node.body = this.parseStatement("with");
  16292. return this.finishNode(node, "WithStatement")
  16293. };
  16294. pp$8.parseEmptyStatement = function(node) {
  16295. this.next();
  16296. return this.finishNode(node, "EmptyStatement")
  16297. };
  16298. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  16299. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  16300. {
  16301. var label = list[i$1];
  16302. if (label.name === maybeName)
  16303. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  16304. } }
  16305. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  16306. for (var i = this.labels.length - 1; i >= 0; i--) {
  16307. var label$1 = this.labels[i];
  16308. if (label$1.statementStart === node.start) {
  16309. // Update information about previous labels on this node
  16310. label$1.statementStart = this.start;
  16311. label$1.kind = kind;
  16312. } else { break }
  16313. }
  16314. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  16315. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  16316. this.labels.pop();
  16317. node.label = expr;
  16318. return this.finishNode(node, "LabeledStatement")
  16319. };
  16320. pp$8.parseExpressionStatement = function(node, expr) {
  16321. node.expression = expr;
  16322. this.semicolon();
  16323. return this.finishNode(node, "ExpressionStatement")
  16324. };
  16325. // Parse a semicolon-enclosed block of statements, handling `"use
  16326. // strict"` declarations when `allowStrict` is true (used for
  16327. // function bodies).
  16328. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  16329. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  16330. if ( node === void 0 ) node = this.startNode();
  16331. node.body = [];
  16332. this.expect(types$1.braceL);
  16333. if (createNewLexicalScope) { this.enterScope(0); }
  16334. while (this.type !== types$1.braceR) {
  16335. var stmt = this.parseStatement(null);
  16336. node.body.push(stmt);
  16337. }
  16338. if (exitStrict) { this.strict = false; }
  16339. this.next();
  16340. if (createNewLexicalScope) { this.exitScope(); }
  16341. return this.finishNode(node, "BlockStatement")
  16342. };
  16343. // Parse a regular `for` loop. The disambiguation code in
  16344. // `parseStatement` will already have parsed the init statement or
  16345. // expression.
  16346. pp$8.parseFor = function(node, init) {
  16347. node.init = init;
  16348. this.expect(types$1.semi);
  16349. node.test = this.type === types$1.semi ? null : this.parseExpression();
  16350. this.expect(types$1.semi);
  16351. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  16352. this.expect(types$1.parenR);
  16353. node.body = this.parseStatement("for");
  16354. this.exitScope();
  16355. this.labels.pop();
  16356. return this.finishNode(node, "ForStatement")
  16357. };
  16358. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  16359. // same from parser's perspective.
  16360. pp$8.parseForIn = function(node, init) {
  16361. var isForIn = this.type === types$1._in;
  16362. this.next();
  16363. if (
  16364. init.type === "VariableDeclaration" &&
  16365. init.declarations[0].init != null &&
  16366. (
  16367. !isForIn ||
  16368. this.options.ecmaVersion < 8 ||
  16369. this.strict ||
  16370. init.kind !== "var" ||
  16371. init.declarations[0].id.type !== "Identifier"
  16372. )
  16373. ) {
  16374. this.raise(
  16375. init.start,
  16376. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  16377. );
  16378. }
  16379. node.left = init;
  16380. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  16381. this.expect(types$1.parenR);
  16382. node.body = this.parseStatement("for");
  16383. this.exitScope();
  16384. this.labels.pop();
  16385. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  16386. };
  16387. // Parse a list of variable declarations.
  16388. pp$8.parseVar = function(node, isFor, kind) {
  16389. node.declarations = [];
  16390. node.kind = kind;
  16391. for (;;) {
  16392. var decl = this.startNode();
  16393. this.parseVarId(decl, kind);
  16394. if (this.eat(types$1.eq)) {
  16395. decl.init = this.parseMaybeAssign(isFor);
  16396. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  16397. this.unexpected();
  16398. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  16399. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  16400. } else {
  16401. decl.init = null;
  16402. }
  16403. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  16404. if (!this.eat(types$1.comma)) { break }
  16405. }
  16406. return node
  16407. };
  16408. pp$8.parseVarId = function(decl, kind) {
  16409. decl.id = this.parseBindingAtom();
  16410. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  16411. };
  16412. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  16413. // Parse a function declaration or literal (depending on the
  16414. // `statement & FUNC_STATEMENT`).
  16415. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  16416. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  16417. this.initFunction(node);
  16418. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  16419. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  16420. { this.unexpected(); }
  16421. node.generator = this.eat(types$1.star);
  16422. }
  16423. if (this.options.ecmaVersion >= 8)
  16424. { node.async = !!isAsync; }
  16425. if (statement & FUNC_STATEMENT) {
  16426. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  16427. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  16428. // If it is a regular function declaration in sloppy mode, then it is
  16429. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  16430. // mode depends on properties of the current scope (see
  16431. // treatFunctionsAsVar).
  16432. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  16433. }
  16434. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  16435. this.yieldPos = 0;
  16436. this.awaitPos = 0;
  16437. this.awaitIdentPos = 0;
  16438. this.enterScope(functionFlags(node.async, node.generator));
  16439. if (!(statement & FUNC_STATEMENT))
  16440. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  16441. this.parseFunctionParams(node);
  16442. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  16443. this.yieldPos = oldYieldPos;
  16444. this.awaitPos = oldAwaitPos;
  16445. this.awaitIdentPos = oldAwaitIdentPos;
  16446. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  16447. };
  16448. pp$8.parseFunctionParams = function(node) {
  16449. this.expect(types$1.parenL);
  16450. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  16451. this.checkYieldAwaitInDefaultParams();
  16452. };
  16453. // Parse a class declaration or literal (depending on the
  16454. // `isStatement` parameter).
  16455. pp$8.parseClass = function(node, isStatement) {
  16456. this.next();
  16457. // ecma-262 14.6 Class Definitions
  16458. // A class definition is always strict mode code.
  16459. var oldStrict = this.strict;
  16460. this.strict = true;
  16461. this.parseClassId(node, isStatement);
  16462. this.parseClassSuper(node);
  16463. var privateNameMap = this.enterClassBody();
  16464. var classBody = this.startNode();
  16465. var hadConstructor = false;
  16466. classBody.body = [];
  16467. this.expect(types$1.braceL);
  16468. while (this.type !== types$1.braceR) {
  16469. var element = this.parseClassElement(node.superClass !== null);
  16470. if (element) {
  16471. classBody.body.push(element);
  16472. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  16473. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  16474. hadConstructor = true;
  16475. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  16476. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  16477. }
  16478. }
  16479. }
  16480. this.strict = oldStrict;
  16481. this.next();
  16482. node.body = this.finishNode(classBody, "ClassBody");
  16483. this.exitClassBody();
  16484. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16485. };
  16486. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16487. if (this.eat(types$1.semi)) { return null }
  16488. var ecmaVersion = this.options.ecmaVersion;
  16489. var node = this.startNode();
  16490. var keyName = "";
  16491. var isGenerator = false;
  16492. var isAsync = false;
  16493. var kind = "method";
  16494. var isStatic = false;
  16495. if (this.eatContextual("static")) {
  16496. // Parse static init block
  16497. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16498. this.parseClassStaticBlock(node);
  16499. return node
  16500. }
  16501. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16502. isStatic = true;
  16503. } else {
  16504. keyName = "static";
  16505. }
  16506. }
  16507. node.static = isStatic;
  16508. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16509. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16510. isAsync = true;
  16511. } else {
  16512. keyName = "async";
  16513. }
  16514. }
  16515. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16516. isGenerator = true;
  16517. }
  16518. if (!keyName && !isAsync && !isGenerator) {
  16519. var lastValue = this.value;
  16520. if (this.eatContextual("get") || this.eatContextual("set")) {
  16521. if (this.isClassElementNameStart()) {
  16522. kind = lastValue;
  16523. } else {
  16524. keyName = lastValue;
  16525. }
  16526. }
  16527. }
  16528. // Parse element name
  16529. if (keyName) {
  16530. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16531. // The last token is any of those. Make it the element name.
  16532. node.computed = false;
  16533. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16534. node.key.name = keyName;
  16535. this.finishNode(node.key, "Identifier");
  16536. } else {
  16537. this.parseClassElementName(node);
  16538. }
  16539. // Parse element value
  16540. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16541. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16542. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16543. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16544. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16545. node.kind = isConstructor ? "constructor" : kind;
  16546. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16547. } else {
  16548. this.parseClassField(node);
  16549. }
  16550. return node
  16551. };
  16552. pp$8.isClassElementNameStart = function() {
  16553. return (
  16554. this.type === types$1.name ||
  16555. this.type === types$1.privateId ||
  16556. this.type === types$1.num ||
  16557. this.type === types$1.string ||
  16558. this.type === types$1.bracketL ||
  16559. this.type.keyword
  16560. )
  16561. };
  16562. pp$8.parseClassElementName = function(element) {
  16563. if (this.type === types$1.privateId) {
  16564. if (this.value === "constructor") {
  16565. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16566. }
  16567. element.computed = false;
  16568. element.key = this.parsePrivateIdent();
  16569. } else {
  16570. this.parsePropertyName(element);
  16571. }
  16572. };
  16573. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16574. // Check key and flags
  16575. var key = method.key;
  16576. if (method.kind === "constructor") {
  16577. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16578. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16579. } else if (method.static && checkKeyName(method, "prototype")) {
  16580. this.raise(key.start, "Classes may not have a static property named prototype");
  16581. }
  16582. // Parse value
  16583. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16584. // Check value
  16585. if (method.kind === "get" && value.params.length !== 0)
  16586. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16587. if (method.kind === "set" && value.params.length !== 1)
  16588. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16589. if (method.kind === "set" && value.params[0].type === "RestElement")
  16590. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16591. return this.finishNode(method, "MethodDefinition")
  16592. };
  16593. pp$8.parseClassField = function(field) {
  16594. if (checkKeyName(field, "constructor")) {
  16595. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16596. } else if (field.static && checkKeyName(field, "prototype")) {
  16597. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16598. }
  16599. if (this.eat(types$1.eq)) {
  16600. // To raise SyntaxError if 'arguments' exists in the initializer.
  16601. var scope = this.currentThisScope();
  16602. var inClassFieldInit = scope.inClassFieldInit;
  16603. scope.inClassFieldInit = true;
  16604. field.value = this.parseMaybeAssign();
  16605. scope.inClassFieldInit = inClassFieldInit;
  16606. } else {
  16607. field.value = null;
  16608. }
  16609. this.semicolon();
  16610. return this.finishNode(field, "PropertyDefinition")
  16611. };
  16612. pp$8.parseClassStaticBlock = function(node) {
  16613. node.body = [];
  16614. var oldLabels = this.labels;
  16615. this.labels = [];
  16616. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16617. while (this.type !== types$1.braceR) {
  16618. var stmt = this.parseStatement(null);
  16619. node.body.push(stmt);
  16620. }
  16621. this.next();
  16622. this.exitScope();
  16623. this.labels = oldLabels;
  16624. return this.finishNode(node, "StaticBlock")
  16625. };
  16626. pp$8.parseClassId = function(node, isStatement) {
  16627. if (this.type === types$1.name) {
  16628. node.id = this.parseIdent();
  16629. if (isStatement)
  16630. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16631. } else {
  16632. if (isStatement === true)
  16633. { this.unexpected(); }
  16634. node.id = null;
  16635. }
  16636. };
  16637. pp$8.parseClassSuper = function(node) {
  16638. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  16639. };
  16640. pp$8.enterClassBody = function() {
  16641. var element = {declared: Object.create(null), used: []};
  16642. this.privateNameStack.push(element);
  16643. return element.declared
  16644. };
  16645. pp$8.exitClassBody = function() {
  16646. var ref = this.privateNameStack.pop();
  16647. var declared = ref.declared;
  16648. var used = ref.used;
  16649. var len = this.privateNameStack.length;
  16650. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16651. for (var i = 0; i < used.length; ++i) {
  16652. var id = used[i];
  16653. if (!hasOwn(declared, id.name)) {
  16654. if (parent) {
  16655. parent.used.push(id);
  16656. } else {
  16657. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16658. }
  16659. }
  16660. }
  16661. };
  16662. function isPrivateNameConflicted(privateNameMap, element) {
  16663. var name = element.key.name;
  16664. var curr = privateNameMap[name];
  16665. var next = "true";
  16666. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16667. next = (element.static ? "s" : "i") + element.kind;
  16668. }
  16669. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16670. if (
  16671. curr === "iget" && next === "iset" ||
  16672. curr === "iset" && next === "iget" ||
  16673. curr === "sget" && next === "sset" ||
  16674. curr === "sset" && next === "sget"
  16675. ) {
  16676. privateNameMap[name] = "true";
  16677. return false
  16678. } else if (!curr) {
  16679. privateNameMap[name] = next;
  16680. return false
  16681. } else {
  16682. return true
  16683. }
  16684. }
  16685. function checkKeyName(node, name) {
  16686. var computed = node.computed;
  16687. var key = node.key;
  16688. return !computed && (
  16689. key.type === "Identifier" && key.name === name ||
  16690. key.type === "Literal" && key.value === name
  16691. )
  16692. }
  16693. // Parses module export declaration.
  16694. pp$8.parseExport = function(node, exports) {
  16695. this.next();
  16696. // export * from '...'
  16697. if (this.eat(types$1.star)) {
  16698. if (this.options.ecmaVersion >= 11) {
  16699. if (this.eatContextual("as")) {
  16700. node.exported = this.parseModuleExportName();
  16701. this.checkExport(exports, node.exported, this.lastTokStart);
  16702. } else {
  16703. node.exported = null;
  16704. }
  16705. }
  16706. this.expectContextual("from");
  16707. if (this.type !== types$1.string) { this.unexpected(); }
  16708. node.source = this.parseExprAtom();
  16709. this.semicolon();
  16710. return this.finishNode(node, "ExportAllDeclaration")
  16711. }
  16712. if (this.eat(types$1._default)) { // export default ...
  16713. this.checkExport(exports, "default", this.lastTokStart);
  16714. var isAsync;
  16715. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16716. var fNode = this.startNode();
  16717. this.next();
  16718. if (isAsync) { this.next(); }
  16719. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16720. } else if (this.type === types$1._class) {
  16721. var cNode = this.startNode();
  16722. node.declaration = this.parseClass(cNode, "nullableID");
  16723. } else {
  16724. node.declaration = this.parseMaybeAssign();
  16725. this.semicolon();
  16726. }
  16727. return this.finishNode(node, "ExportDefaultDeclaration")
  16728. }
  16729. // export var|const|let|function|class ...
  16730. if (this.shouldParseExportStatement()) {
  16731. node.declaration = this.parseStatement(null);
  16732. if (node.declaration.type === "VariableDeclaration")
  16733. { this.checkVariableExport(exports, node.declaration.declarations); }
  16734. else
  16735. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16736. node.specifiers = [];
  16737. node.source = null;
  16738. } else { // export { x, y as z } [from '...']
  16739. node.declaration = null;
  16740. node.specifiers = this.parseExportSpecifiers(exports);
  16741. if (this.eatContextual("from")) {
  16742. if (this.type !== types$1.string) { this.unexpected(); }
  16743. node.source = this.parseExprAtom();
  16744. } else {
  16745. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16746. // check for keywords used as local names
  16747. var spec = list[i];
  16748. this.checkUnreserved(spec.local);
  16749. // check if export is defined
  16750. this.checkLocalExport(spec.local);
  16751. if (spec.local.type === "Literal") {
  16752. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16753. }
  16754. }
  16755. node.source = null;
  16756. }
  16757. this.semicolon();
  16758. }
  16759. return this.finishNode(node, "ExportNamedDeclaration")
  16760. };
  16761. pp$8.checkExport = function(exports, name, pos) {
  16762. if (!exports) { return }
  16763. if (typeof name !== "string")
  16764. { name = name.type === "Identifier" ? name.name : name.value; }
  16765. if (hasOwn(exports, name))
  16766. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16767. exports[name] = true;
  16768. };
  16769. pp$8.checkPatternExport = function(exports, pat) {
  16770. var type = pat.type;
  16771. if (type === "Identifier")
  16772. { this.checkExport(exports, pat, pat.start); }
  16773. else if (type === "ObjectPattern")
  16774. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16775. {
  16776. var prop = list[i];
  16777. this.checkPatternExport(exports, prop);
  16778. } }
  16779. else if (type === "ArrayPattern")
  16780. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16781. var elt = list$1[i$1];
  16782. if (elt) { this.checkPatternExport(exports, elt); }
  16783. } }
  16784. else if (type === "Property")
  16785. { this.checkPatternExport(exports, pat.value); }
  16786. else if (type === "AssignmentPattern")
  16787. { this.checkPatternExport(exports, pat.left); }
  16788. else if (type === "RestElement")
  16789. { this.checkPatternExport(exports, pat.argument); }
  16790. else if (type === "ParenthesizedExpression")
  16791. { this.checkPatternExport(exports, pat.expression); }
  16792. };
  16793. pp$8.checkVariableExport = function(exports, decls) {
  16794. if (!exports) { return }
  16795. for (var i = 0, list = decls; i < list.length; i += 1)
  16796. {
  16797. var decl = list[i];
  16798. this.checkPatternExport(exports, decl.id);
  16799. }
  16800. };
  16801. pp$8.shouldParseExportStatement = function() {
  16802. return this.type.keyword === "var" ||
  16803. this.type.keyword === "const" ||
  16804. this.type.keyword === "class" ||
  16805. this.type.keyword === "function" ||
  16806. this.isLet() ||
  16807. this.isAsyncFunction()
  16808. };
  16809. // Parses a comma-separated list of module exports.
  16810. pp$8.parseExportSpecifiers = function(exports) {
  16811. var nodes = [], first = true;
  16812. // export { x, y as z } [from '...']
  16813. this.expect(types$1.braceL);
  16814. while (!this.eat(types$1.braceR)) {
  16815. if (!first) {
  16816. this.expect(types$1.comma);
  16817. if (this.afterTrailingComma(types$1.braceR)) { break }
  16818. } else { first = false; }
  16819. var node = this.startNode();
  16820. node.local = this.parseModuleExportName();
  16821. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16822. this.checkExport(
  16823. exports,
  16824. node.exported,
  16825. node.exported.start
  16826. );
  16827. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16828. }
  16829. return nodes
  16830. };
  16831. // Parses import declaration.
  16832. pp$8.parseImport = function(node) {
  16833. this.next();
  16834. // import '...'
  16835. if (this.type === types$1.string) {
  16836. node.specifiers = empty$1;
  16837. node.source = this.parseExprAtom();
  16838. } else {
  16839. node.specifiers = this.parseImportSpecifiers();
  16840. this.expectContextual("from");
  16841. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16842. }
  16843. this.semicolon();
  16844. return this.finishNode(node, "ImportDeclaration")
  16845. };
  16846. // Parses a comma-separated list of module imports.
  16847. pp$8.parseImportSpecifiers = function() {
  16848. var nodes = [], first = true;
  16849. if (this.type === types$1.name) {
  16850. // import defaultObj, { x, y as z } from '...'
  16851. var node = this.startNode();
  16852. node.local = this.parseIdent();
  16853. this.checkLValSimple(node.local, BIND_LEXICAL);
  16854. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16855. if (!this.eat(types$1.comma)) { return nodes }
  16856. }
  16857. if (this.type === types$1.star) {
  16858. var node$1 = this.startNode();
  16859. this.next();
  16860. this.expectContextual("as");
  16861. node$1.local = this.parseIdent();
  16862. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16863. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16864. return nodes
  16865. }
  16866. this.expect(types$1.braceL);
  16867. while (!this.eat(types$1.braceR)) {
  16868. if (!first) {
  16869. this.expect(types$1.comma);
  16870. if (this.afterTrailingComma(types$1.braceR)) { break }
  16871. } else { first = false; }
  16872. var node$2 = this.startNode();
  16873. node$2.imported = this.parseModuleExportName();
  16874. if (this.eatContextual("as")) {
  16875. node$2.local = this.parseIdent();
  16876. } else {
  16877. this.checkUnreserved(node$2.imported);
  16878. node$2.local = node$2.imported;
  16879. }
  16880. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  16881. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  16882. }
  16883. return nodes
  16884. };
  16885. pp$8.parseModuleExportName = function() {
  16886. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  16887. var stringLiteral = this.parseLiteral(this.value);
  16888. if (loneSurrogate.test(stringLiteral.value)) {
  16889. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  16890. }
  16891. return stringLiteral
  16892. }
  16893. return this.parseIdent(true)
  16894. };
  16895. // Set `ExpressionStatement#directive` property for directive prologues.
  16896. pp$8.adaptDirectivePrologue = function(statements) {
  16897. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  16898. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  16899. }
  16900. };
  16901. pp$8.isDirectiveCandidate = function(statement) {
  16902. return (
  16903. statement.type === "ExpressionStatement" &&
  16904. statement.expression.type === "Literal" &&
  16905. typeof statement.expression.value === "string" &&
  16906. // Reject parenthesized strings.
  16907. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  16908. )
  16909. };
  16910. var pp$7 = Parser.prototype;
  16911. // Convert existing expression atom to assignable pattern
  16912. // if possible.
  16913. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  16914. if (this.options.ecmaVersion >= 6 && node) {
  16915. switch (node.type) {
  16916. case "Identifier":
  16917. if (this.inAsync && node.name === "await")
  16918. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  16919. break
  16920. case "ObjectPattern":
  16921. case "ArrayPattern":
  16922. case "AssignmentPattern":
  16923. case "RestElement":
  16924. break
  16925. case "ObjectExpression":
  16926. node.type = "ObjectPattern";
  16927. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16928. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  16929. var prop = list[i];
  16930. this.toAssignable(prop, isBinding);
  16931. // Early error:
  16932. // AssignmentRestProperty[Yield, Await] :
  16933. // `...` DestructuringAssignmentTarget[Yield, Await]
  16934. //
  16935. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  16936. if (
  16937. prop.type === "RestElement" &&
  16938. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  16939. ) {
  16940. this.raise(prop.argument.start, "Unexpected token");
  16941. }
  16942. }
  16943. break
  16944. case "Property":
  16945. // AssignmentProperty has type === "Property"
  16946. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  16947. this.toAssignable(node.value, isBinding);
  16948. break
  16949. case "ArrayExpression":
  16950. node.type = "ArrayPattern";
  16951. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16952. this.toAssignableList(node.elements, isBinding);
  16953. break
  16954. case "SpreadElement":
  16955. node.type = "RestElement";
  16956. this.toAssignable(node.argument, isBinding);
  16957. if (node.argument.type === "AssignmentPattern")
  16958. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  16959. break
  16960. case "AssignmentExpression":
  16961. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  16962. node.type = "AssignmentPattern";
  16963. delete node.operator;
  16964. this.toAssignable(node.left, isBinding);
  16965. break
  16966. case "ParenthesizedExpression":
  16967. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  16968. break
  16969. case "ChainExpression":
  16970. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  16971. break
  16972. case "MemberExpression":
  16973. if (!isBinding) { break }
  16974. default:
  16975. this.raise(node.start, "Assigning to rvalue");
  16976. }
  16977. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16978. return node
  16979. };
  16980. // Convert list of expression atoms to binding list.
  16981. pp$7.toAssignableList = function(exprList, isBinding) {
  16982. var end = exprList.length;
  16983. for (var i = 0; i < end; i++) {
  16984. var elt = exprList[i];
  16985. if (elt) { this.toAssignable(elt, isBinding); }
  16986. }
  16987. if (end) {
  16988. var last = exprList[end - 1];
  16989. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  16990. { this.unexpected(last.argument.start); }
  16991. }
  16992. return exprList
  16993. };
  16994. // Parses spread element.
  16995. pp$7.parseSpread = function(refDestructuringErrors) {
  16996. var node = this.startNode();
  16997. this.next();
  16998. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  16999. return this.finishNode(node, "SpreadElement")
  17000. };
  17001. pp$7.parseRestBinding = function() {
  17002. var node = this.startNode();
  17003. this.next();
  17004. // RestElement inside of a function parameter must be an identifier
  17005. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  17006. { this.unexpected(); }
  17007. node.argument = this.parseBindingAtom();
  17008. return this.finishNode(node, "RestElement")
  17009. };
  17010. // Parses lvalue (assignable) atom.
  17011. pp$7.parseBindingAtom = function() {
  17012. if (this.options.ecmaVersion >= 6) {
  17013. switch (this.type) {
  17014. case types$1.bracketL:
  17015. var node = this.startNode();
  17016. this.next();
  17017. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  17018. return this.finishNode(node, "ArrayPattern")
  17019. case types$1.braceL:
  17020. return this.parseObj(true)
  17021. }
  17022. }
  17023. return this.parseIdent()
  17024. };
  17025. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  17026. var elts = [], first = true;
  17027. while (!this.eat(close)) {
  17028. if (first) { first = false; }
  17029. else { this.expect(types$1.comma); }
  17030. if (allowEmpty && this.type === types$1.comma) {
  17031. elts.push(null);
  17032. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  17033. break
  17034. } else if (this.type === types$1.ellipsis) {
  17035. var rest = this.parseRestBinding();
  17036. this.parseBindingListItem(rest);
  17037. elts.push(rest);
  17038. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17039. this.expect(close);
  17040. break
  17041. } else {
  17042. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  17043. this.parseBindingListItem(elem);
  17044. elts.push(elem);
  17045. }
  17046. }
  17047. return elts
  17048. };
  17049. pp$7.parseBindingListItem = function(param) {
  17050. return param
  17051. };
  17052. // Parses assignment pattern around given atom if possible.
  17053. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  17054. left = left || this.parseBindingAtom();
  17055. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  17056. var node = this.startNodeAt(startPos, startLoc);
  17057. node.left = left;
  17058. node.right = this.parseMaybeAssign();
  17059. return this.finishNode(node, "AssignmentPattern")
  17060. };
  17061. // The following three functions all verify that a node is an lvalue —
  17062. // something that can be bound, or assigned to. In order to do so, they perform
  17063. // a variety of checks:
  17064. //
  17065. // - Check that none of the bound/assigned-to identifiers are reserved words.
  17066. // - Record name declarations for bindings in the appropriate scope.
  17067. // - Check duplicate argument names, if checkClashes is set.
  17068. //
  17069. // If a complex binding pattern is encountered (e.g., object and array
  17070. // destructuring), the entire pattern is recursively checked.
  17071. //
  17072. // There are three versions of checkLVal*() appropriate for different
  17073. // circumstances:
  17074. //
  17075. // - checkLValSimple() shall be used if the syntactic construct supports
  17076. // nothing other than identifiers and member expressions. Parenthesized
  17077. // expressions are also correctly handled. This is generally appropriate for
  17078. // constructs for which the spec says
  17079. //
  17080. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  17081. // > simple.
  17082. //
  17083. // It is also appropriate for checking if an identifier is valid and not
  17084. // defined elsewhere, like import declarations or function/class identifiers.
  17085. //
  17086. // Examples where this is used include:
  17087. // a += …;
  17088. // import a from '…';
  17089. // where a is the node to be checked.
  17090. //
  17091. // - checkLValPattern() shall be used if the syntactic construct supports
  17092. // anything checkLValSimple() supports, as well as object and array
  17093. // destructuring patterns. This is generally appropriate for constructs for
  17094. // which the spec says
  17095. //
  17096. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  17097. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  17098. // > simple.
  17099. //
  17100. // Examples where this is used include:
  17101. // (a = …);
  17102. // const a = …;
  17103. // try { … } catch (a) { … }
  17104. // where a is the node to be checked.
  17105. //
  17106. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  17107. // anything checkLValPattern() supports, as well as default assignment
  17108. // patterns, rest elements, and other constructs that may appear within an
  17109. // object or array destructuring pattern.
  17110. //
  17111. // As a special case, function parameters also use checkLValInnerPattern(),
  17112. // as they also support defaults and rest constructs.
  17113. //
  17114. // These functions deliberately support both assignment and binding constructs,
  17115. // as the logic for both is exceedingly similar. If the node is the target of
  17116. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  17117. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  17118. // BIND_LEXICAL.
  17119. //
  17120. // If the function is called with a non-BIND_NONE bindingType, then
  17121. // additionally a checkClashes object may be specified to allow checking for
  17122. // duplicate argument names. checkClashes is ignored if the provided construct
  17123. // is an assignment (i.e., bindingType is BIND_NONE).
  17124. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  17125. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17126. var isBind = bindingType !== BIND_NONE;
  17127. switch (expr.type) {
  17128. case "Identifier":
  17129. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  17130. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  17131. if (isBind) {
  17132. if (bindingType === BIND_LEXICAL && expr.name === "let")
  17133. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  17134. if (checkClashes) {
  17135. if (hasOwn(checkClashes, expr.name))
  17136. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  17137. checkClashes[expr.name] = true;
  17138. }
  17139. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  17140. }
  17141. break
  17142. case "ChainExpression":
  17143. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  17144. break
  17145. case "MemberExpression":
  17146. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  17147. break
  17148. case "ParenthesizedExpression":
  17149. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  17150. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  17151. default:
  17152. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  17153. }
  17154. };
  17155. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  17156. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17157. switch (expr.type) {
  17158. case "ObjectPattern":
  17159. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  17160. var prop = list[i];
  17161. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  17162. }
  17163. break
  17164. case "ArrayPattern":
  17165. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  17166. var elem = list$1[i$1];
  17167. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  17168. }
  17169. break
  17170. default:
  17171. this.checkLValSimple(expr, bindingType, checkClashes);
  17172. }
  17173. };
  17174. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  17175. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17176. switch (expr.type) {
  17177. case "Property":
  17178. // AssignmentProperty has type === "Property"
  17179. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  17180. break
  17181. case "AssignmentPattern":
  17182. this.checkLValPattern(expr.left, bindingType, checkClashes);
  17183. break
  17184. case "RestElement":
  17185. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  17186. break
  17187. default:
  17188. this.checkLValPattern(expr, bindingType, checkClashes);
  17189. }
  17190. };
  17191. // The algorithm used to determine whether a regexp can appear at a
  17192. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  17193. this.token = token;
  17194. this.isExpr = !!isExpr;
  17195. this.preserveSpace = !!preserveSpace;
  17196. this.override = override;
  17197. this.generator = !!generator;
  17198. };
  17199. var types = {
  17200. b_stat: new TokContext("{", false),
  17201. b_expr: new TokContext("{", true),
  17202. b_tmpl: new TokContext("${", false),
  17203. p_stat: new TokContext("(", false),
  17204. p_expr: new TokContext("(", true),
  17205. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  17206. f_stat: new TokContext("function", false),
  17207. f_expr: new TokContext("function", true),
  17208. f_expr_gen: new TokContext("function", true, false, null, true),
  17209. f_gen: new TokContext("function", false, false, null, true)
  17210. };
  17211. var pp$6 = Parser.prototype;
  17212. pp$6.initialContext = function() {
  17213. return [types.b_stat]
  17214. };
  17215. pp$6.curContext = function() {
  17216. return this.context[this.context.length - 1]
  17217. };
  17218. pp$6.braceIsBlock = function(prevType) {
  17219. var parent = this.curContext();
  17220. if (parent === types.f_expr || parent === types.f_stat)
  17221. { return true }
  17222. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  17223. { return !parent.isExpr }
  17224. // The check for `tt.name && exprAllowed` detects whether we are
  17225. // after a `yield` or `of` construct. See the `updateContext` for
  17226. // `tt.name`.
  17227. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  17228. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  17229. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  17230. { return true }
  17231. if (prevType === types$1.braceL)
  17232. { return parent === types.b_stat }
  17233. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  17234. { return false }
  17235. return !this.exprAllowed
  17236. };
  17237. pp$6.inGeneratorContext = function() {
  17238. for (var i = this.context.length - 1; i >= 1; i--) {
  17239. var context = this.context[i];
  17240. if (context.token === "function")
  17241. { return context.generator }
  17242. }
  17243. return false
  17244. };
  17245. pp$6.updateContext = function(prevType) {
  17246. var update, type = this.type;
  17247. if (type.keyword && prevType === types$1.dot)
  17248. { this.exprAllowed = false; }
  17249. else if (update = type.updateContext)
  17250. { update.call(this, prevType); }
  17251. else
  17252. { this.exprAllowed = type.beforeExpr; }
  17253. };
  17254. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  17255. pp$6.overrideContext = function(tokenCtx) {
  17256. if (this.curContext() !== tokenCtx) {
  17257. this.context[this.context.length - 1] = tokenCtx;
  17258. }
  17259. };
  17260. // Token-specific context update code
  17261. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  17262. if (this.context.length === 1) {
  17263. this.exprAllowed = true;
  17264. return
  17265. }
  17266. var out = this.context.pop();
  17267. if (out === types.b_stat && this.curContext().token === "function") {
  17268. out = this.context.pop();
  17269. }
  17270. this.exprAllowed = !out.isExpr;
  17271. };
  17272. types$1.braceL.updateContext = function(prevType) {
  17273. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  17274. this.exprAllowed = true;
  17275. };
  17276. types$1.dollarBraceL.updateContext = function() {
  17277. this.context.push(types.b_tmpl);
  17278. this.exprAllowed = true;
  17279. };
  17280. types$1.parenL.updateContext = function(prevType) {
  17281. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  17282. this.context.push(statementParens ? types.p_stat : types.p_expr);
  17283. this.exprAllowed = true;
  17284. };
  17285. types$1.incDec.updateContext = function() {
  17286. // tokExprAllowed stays unchanged
  17287. };
  17288. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  17289. if (prevType.beforeExpr && prevType !== types$1._else &&
  17290. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  17291. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  17292. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  17293. { this.context.push(types.f_expr); }
  17294. else
  17295. { this.context.push(types.f_stat); }
  17296. this.exprAllowed = false;
  17297. };
  17298. types$1.backQuote.updateContext = function() {
  17299. if (this.curContext() === types.q_tmpl)
  17300. { this.context.pop(); }
  17301. else
  17302. { this.context.push(types.q_tmpl); }
  17303. this.exprAllowed = false;
  17304. };
  17305. types$1.star.updateContext = function(prevType) {
  17306. if (prevType === types$1._function) {
  17307. var index = this.context.length - 1;
  17308. if (this.context[index] === types.f_expr)
  17309. { this.context[index] = types.f_expr_gen; }
  17310. else
  17311. { this.context[index] = types.f_gen; }
  17312. }
  17313. this.exprAllowed = true;
  17314. };
  17315. types$1.name.updateContext = function(prevType) {
  17316. var allowed = false;
  17317. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  17318. if (this.value === "of" && !this.exprAllowed ||
  17319. this.value === "yield" && this.inGeneratorContext())
  17320. { allowed = true; }
  17321. }
  17322. this.exprAllowed = allowed;
  17323. };
  17324. // A recursive descent parser operates by defining functions for all
  17325. var pp$5 = Parser.prototype;
  17326. // Check if property name clashes with already added.
  17327. // Object/class getters and setters are not allowed to clash —
  17328. // either with each other or with an init property — and in
  17329. // strict mode, init properties are also not allowed to be repeated.
  17330. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  17331. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  17332. { return }
  17333. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  17334. { return }
  17335. var key = prop.key;
  17336. var name;
  17337. switch (key.type) {
  17338. case "Identifier": name = key.name; break
  17339. case "Literal": name = String(key.value); break
  17340. default: return
  17341. }
  17342. var kind = prop.kind;
  17343. if (this.options.ecmaVersion >= 6) {
  17344. if (name === "__proto__" && kind === "init") {
  17345. if (propHash.proto) {
  17346. if (refDestructuringErrors) {
  17347. if (refDestructuringErrors.doubleProto < 0) {
  17348. refDestructuringErrors.doubleProto = key.start;
  17349. }
  17350. } else {
  17351. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  17352. }
  17353. }
  17354. propHash.proto = true;
  17355. }
  17356. return
  17357. }
  17358. name = "$" + name;
  17359. var other = propHash[name];
  17360. if (other) {
  17361. var redefinition;
  17362. if (kind === "init") {
  17363. redefinition = this.strict && other.init || other.get || other.set;
  17364. } else {
  17365. redefinition = other.init || other[kind];
  17366. }
  17367. if (redefinition)
  17368. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  17369. } else {
  17370. other = propHash[name] = {
  17371. init: false,
  17372. get: false,
  17373. set: false
  17374. };
  17375. }
  17376. other[kind] = true;
  17377. };
  17378. // ### Expression parsing
  17379. // These nest, from the most general expression type at the top to
  17380. // 'atomic', nondivisible expression types at the bottom. Most of
  17381. // the functions will simply let the function(s) below them parse,
  17382. // and, *if* the syntactic construct they handle is present, wrap
  17383. // the AST node that the inner parser gave them in another node.
  17384. // Parse a full expression. The optional arguments are used to
  17385. // forbid the `in` operator (in for loops initalization expressions)
  17386. // and provide reference for storing '=' operator inside shorthand
  17387. // property assignment in contexts where both object expression
  17388. // and object pattern might appear (so it's possible to raise
  17389. // delayed syntax error at correct position).
  17390. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  17391. var startPos = this.start, startLoc = this.startLoc;
  17392. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  17393. if (this.type === types$1.comma) {
  17394. var node = this.startNodeAt(startPos, startLoc);
  17395. node.expressions = [expr];
  17396. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  17397. return this.finishNode(node, "SequenceExpression")
  17398. }
  17399. return expr
  17400. };
  17401. // Parse an assignment expression. This includes applications of
  17402. // operators like `+=`.
  17403. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  17404. if (this.isContextual("yield")) {
  17405. if (this.inGenerator) { return this.parseYield(forInit) }
  17406. // The tokenizer will assume an expression is allowed after
  17407. // `yield`, but this isn't that kind of yield
  17408. else { this.exprAllowed = false; }
  17409. }
  17410. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  17411. if (refDestructuringErrors) {
  17412. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  17413. oldTrailingComma = refDestructuringErrors.trailingComma;
  17414. oldDoubleProto = refDestructuringErrors.doubleProto;
  17415. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  17416. } else {
  17417. refDestructuringErrors = new DestructuringErrors;
  17418. ownDestructuringErrors = true;
  17419. }
  17420. var startPos = this.start, startLoc = this.startLoc;
  17421. if (this.type === types$1.parenL || this.type === types$1.name) {
  17422. this.potentialArrowAt = this.start;
  17423. this.potentialArrowInForAwait = forInit === "await";
  17424. }
  17425. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  17426. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  17427. if (this.type.isAssign) {
  17428. var node = this.startNodeAt(startPos, startLoc);
  17429. node.operator = this.value;
  17430. if (this.type === types$1.eq)
  17431. { left = this.toAssignable(left, false, refDestructuringErrors); }
  17432. if (!ownDestructuringErrors) {
  17433. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  17434. }
  17435. if (refDestructuringErrors.shorthandAssign >= left.start)
  17436. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  17437. if (this.type === types$1.eq)
  17438. { this.checkLValPattern(left); }
  17439. else
  17440. { this.checkLValSimple(left); }
  17441. node.left = left;
  17442. this.next();
  17443. node.right = this.parseMaybeAssign(forInit);
  17444. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  17445. return this.finishNode(node, "AssignmentExpression")
  17446. } else {
  17447. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  17448. }
  17449. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  17450. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  17451. return left
  17452. };
  17453. // Parse a ternary conditional (`?:`) operator.
  17454. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  17455. var startPos = this.start, startLoc = this.startLoc;
  17456. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  17457. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17458. if (this.eat(types$1.question)) {
  17459. var node = this.startNodeAt(startPos, startLoc);
  17460. node.test = expr;
  17461. node.consequent = this.parseMaybeAssign();
  17462. this.expect(types$1.colon);
  17463. node.alternate = this.parseMaybeAssign(forInit);
  17464. return this.finishNode(node, "ConditionalExpression")
  17465. }
  17466. return expr
  17467. };
  17468. // Start the precedence parser.
  17469. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  17470. var startPos = this.start, startLoc = this.startLoc;
  17471. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  17472. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17473. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  17474. };
  17475. // Parse binary operators with the operator precedence parsing
  17476. // algorithm. `left` is the left-hand side of the operator.
  17477. // `minPrec` provides context that allows the function to stop and
  17478. // defer further parser to one of its callers when it encounters an
  17479. // operator that has a lower precedence than the set it is parsing.
  17480. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  17481. var prec = this.type.binop;
  17482. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17483. if (prec > minPrec) {
  17484. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17485. var coalesce = this.type === types$1.coalesce;
  17486. if (coalesce) {
  17487. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17488. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17489. prec = types$1.logicalAND.binop;
  17490. }
  17491. var op = this.value;
  17492. this.next();
  17493. var startPos = this.start, startLoc = this.startLoc;
  17494. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17495. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17496. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17497. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17498. }
  17499. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17500. }
  17501. }
  17502. return left
  17503. };
  17504. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17505. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17506. var node = this.startNodeAt(startPos, startLoc);
  17507. node.left = left;
  17508. node.operator = op;
  17509. node.right = right;
  17510. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17511. };
  17512. // Parse unary operators, both prefix and postfix.
  17513. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17514. var startPos = this.start, startLoc = this.startLoc, expr;
  17515. if (this.isContextual("await") && this.canAwait) {
  17516. expr = this.parseAwait(forInit);
  17517. sawUnary = true;
  17518. } else if (this.type.prefix) {
  17519. var node = this.startNode(), update = this.type === types$1.incDec;
  17520. node.operator = this.value;
  17521. node.prefix = true;
  17522. this.next();
  17523. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17524. this.checkExpressionErrors(refDestructuringErrors, true);
  17525. if (update) { this.checkLValSimple(node.argument); }
  17526. else if (this.strict && node.operator === "delete" &&
  17527. node.argument.type === "Identifier")
  17528. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17529. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17530. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17531. else { sawUnary = true; }
  17532. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17533. } else if (!sawUnary && this.type === types$1.privateId) {
  17534. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17535. expr = this.parsePrivateIdent();
  17536. // only could be private fields in 'in', such as #x in obj
  17537. if (this.type !== types$1._in) { this.unexpected(); }
  17538. } else {
  17539. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17540. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17541. while (this.type.postfix && !this.canInsertSemicolon()) {
  17542. var node$1 = this.startNodeAt(startPos, startLoc);
  17543. node$1.operator = this.value;
  17544. node$1.prefix = false;
  17545. node$1.argument = expr;
  17546. this.checkLValSimple(expr);
  17547. this.next();
  17548. expr = this.finishNode(node$1, "UpdateExpression");
  17549. }
  17550. }
  17551. if (!incDec && this.eat(types$1.starstar)) {
  17552. if (sawUnary)
  17553. { this.unexpected(this.lastTokStart); }
  17554. else
  17555. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17556. } else {
  17557. return expr
  17558. }
  17559. };
  17560. function isPrivateFieldAccess(node) {
  17561. return (
  17562. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17563. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17564. )
  17565. }
  17566. // Parse call, dot, and `[]`-subscript expressions.
  17567. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17568. var startPos = this.start, startLoc = this.startLoc;
  17569. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17570. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17571. { return expr }
  17572. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17573. if (refDestructuringErrors && result.type === "MemberExpression") {
  17574. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17575. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17576. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17577. }
  17578. return result
  17579. };
  17580. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17581. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17582. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17583. this.potentialArrowAt === base.start;
  17584. var optionalChained = false;
  17585. while (true) {
  17586. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17587. if (element.optional) { optionalChained = true; }
  17588. if (element === base || element.type === "ArrowFunctionExpression") {
  17589. if (optionalChained) {
  17590. var chainNode = this.startNodeAt(startPos, startLoc);
  17591. chainNode.expression = element;
  17592. element = this.finishNode(chainNode, "ChainExpression");
  17593. }
  17594. return element
  17595. }
  17596. base = element;
  17597. }
  17598. };
  17599. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17600. var optionalSupported = this.options.ecmaVersion >= 11;
  17601. var optional = optionalSupported && this.eat(types$1.questionDot);
  17602. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17603. var computed = this.eat(types$1.bracketL);
  17604. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17605. var node = this.startNodeAt(startPos, startLoc);
  17606. node.object = base;
  17607. if (computed) {
  17608. node.property = this.parseExpression();
  17609. this.expect(types$1.bracketR);
  17610. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17611. node.property = this.parsePrivateIdent();
  17612. } else {
  17613. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17614. }
  17615. node.computed = !!computed;
  17616. if (optionalSupported) {
  17617. node.optional = optional;
  17618. }
  17619. base = this.finishNode(node, "MemberExpression");
  17620. } else if (!noCalls && this.eat(types$1.parenL)) {
  17621. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17622. this.yieldPos = 0;
  17623. this.awaitPos = 0;
  17624. this.awaitIdentPos = 0;
  17625. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17626. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17627. this.checkPatternErrors(refDestructuringErrors, false);
  17628. this.checkYieldAwaitInDefaultParams();
  17629. if (this.awaitIdentPos > 0)
  17630. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17631. this.yieldPos = oldYieldPos;
  17632. this.awaitPos = oldAwaitPos;
  17633. this.awaitIdentPos = oldAwaitIdentPos;
  17634. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17635. }
  17636. this.checkExpressionErrors(refDestructuringErrors, true);
  17637. this.yieldPos = oldYieldPos || this.yieldPos;
  17638. this.awaitPos = oldAwaitPos || this.awaitPos;
  17639. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17640. var node$1 = this.startNodeAt(startPos, startLoc);
  17641. node$1.callee = base;
  17642. node$1.arguments = exprList;
  17643. if (optionalSupported) {
  17644. node$1.optional = optional;
  17645. }
  17646. base = this.finishNode(node$1, "CallExpression");
  17647. } else if (this.type === types$1.backQuote) {
  17648. if (optional || optionalChained) {
  17649. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17650. }
  17651. var node$2 = this.startNodeAt(startPos, startLoc);
  17652. node$2.tag = base;
  17653. node$2.quasi = this.parseTemplate({isTagged: true});
  17654. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17655. }
  17656. return base
  17657. };
  17658. // Parse an atomic expression — either a single token that is an
  17659. // expression, an expression started by a keyword like `function` or
  17660. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17661. // or `{}`.
  17662. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17663. // If a division operator appears in an expression position, the
  17664. // tokenizer got confused, and we force it to read a regexp instead.
  17665. if (this.type === types$1.slash) { this.readRegexp(); }
  17666. var node, canBeArrow = this.potentialArrowAt === this.start;
  17667. switch (this.type) {
  17668. case types$1._super:
  17669. if (!this.allowSuper)
  17670. { this.raise(this.start, "'super' keyword outside a method"); }
  17671. node = this.startNode();
  17672. this.next();
  17673. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17674. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17675. // The `super` keyword can appear at below:
  17676. // SuperProperty:
  17677. // super [ Expression ]
  17678. // super . IdentifierName
  17679. // SuperCall:
  17680. // super ( Arguments )
  17681. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17682. { this.unexpected(); }
  17683. return this.finishNode(node, "Super")
  17684. case types$1._this:
  17685. node = this.startNode();
  17686. this.next();
  17687. return this.finishNode(node, "ThisExpression")
  17688. case types$1.name:
  17689. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17690. var id = this.parseIdent(false);
  17691. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17692. this.overrideContext(types.f_expr);
  17693. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17694. }
  17695. if (canBeArrow && !this.canInsertSemicolon()) {
  17696. if (this.eat(types$1.arrow))
  17697. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17698. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17699. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17700. id = this.parseIdent(false);
  17701. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17702. { this.unexpected(); }
  17703. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17704. }
  17705. }
  17706. return id
  17707. case types$1.regexp:
  17708. var value = this.value;
  17709. node = this.parseLiteral(value.value);
  17710. node.regex = {pattern: value.pattern, flags: value.flags};
  17711. return node
  17712. case types$1.num: case types$1.string:
  17713. return this.parseLiteral(this.value)
  17714. case types$1._null: case types$1._true: case types$1._false:
  17715. node = this.startNode();
  17716. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17717. node.raw = this.type.keyword;
  17718. this.next();
  17719. return this.finishNode(node, "Literal")
  17720. case types$1.parenL:
  17721. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17722. if (refDestructuringErrors) {
  17723. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17724. { refDestructuringErrors.parenthesizedAssign = start; }
  17725. if (refDestructuringErrors.parenthesizedBind < 0)
  17726. { refDestructuringErrors.parenthesizedBind = start; }
  17727. }
  17728. return expr
  17729. case types$1.bracketL:
  17730. node = this.startNode();
  17731. this.next();
  17732. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17733. return this.finishNode(node, "ArrayExpression")
  17734. case types$1.braceL:
  17735. this.overrideContext(types.b_expr);
  17736. return this.parseObj(false, refDestructuringErrors)
  17737. case types$1._function:
  17738. node = this.startNode();
  17739. this.next();
  17740. return this.parseFunction(node, 0)
  17741. case types$1._class:
  17742. return this.parseClass(this.startNode(), false)
  17743. case types$1._new:
  17744. return this.parseNew()
  17745. case types$1.backQuote:
  17746. return this.parseTemplate()
  17747. case types$1._import:
  17748. if (this.options.ecmaVersion >= 11) {
  17749. return this.parseExprImport()
  17750. } else {
  17751. return this.unexpected()
  17752. }
  17753. default:
  17754. this.unexpected();
  17755. }
  17756. };
  17757. pp$5.parseExprImport = function() {
  17758. var node = this.startNode();
  17759. // Consume `import` as an identifier for `import.meta`.
  17760. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17761. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17762. var meta = this.parseIdent(true);
  17763. switch (this.type) {
  17764. case types$1.parenL:
  17765. return this.parseDynamicImport(node)
  17766. case types$1.dot:
  17767. node.meta = meta;
  17768. return this.parseImportMeta(node)
  17769. default:
  17770. this.unexpected();
  17771. }
  17772. };
  17773. pp$5.parseDynamicImport = function(node) {
  17774. this.next(); // skip `(`
  17775. // Parse node.source.
  17776. node.source = this.parseMaybeAssign();
  17777. // Verify ending.
  17778. if (!this.eat(types$1.parenR)) {
  17779. var errorPos = this.start;
  17780. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17781. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17782. } else {
  17783. this.unexpected(errorPos);
  17784. }
  17785. }
  17786. return this.finishNode(node, "ImportExpression")
  17787. };
  17788. pp$5.parseImportMeta = function(node) {
  17789. this.next(); // skip `.`
  17790. var containsEsc = this.containsEsc;
  17791. node.property = this.parseIdent(true);
  17792. if (node.property.name !== "meta")
  17793. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17794. if (containsEsc)
  17795. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17796. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17797. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17798. return this.finishNode(node, "MetaProperty")
  17799. };
  17800. pp$5.parseLiteral = function(value) {
  17801. var node = this.startNode();
  17802. node.value = value;
  17803. node.raw = this.input.slice(this.start, this.end);
  17804. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17805. this.next();
  17806. return this.finishNode(node, "Literal")
  17807. };
  17808. pp$5.parseParenExpression = function() {
  17809. this.expect(types$1.parenL);
  17810. var val = this.parseExpression();
  17811. this.expect(types$1.parenR);
  17812. return val
  17813. };
  17814. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17815. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17816. if (this.options.ecmaVersion >= 6) {
  17817. this.next();
  17818. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17819. var exprList = [], first = true, lastIsComma = false;
  17820. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17821. this.yieldPos = 0;
  17822. this.awaitPos = 0;
  17823. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17824. while (this.type !== types$1.parenR) {
  17825. first ? first = false : this.expect(types$1.comma);
  17826. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17827. lastIsComma = true;
  17828. break
  17829. } else if (this.type === types$1.ellipsis) {
  17830. spreadStart = this.start;
  17831. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17832. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17833. break
  17834. } else {
  17835. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17836. }
  17837. }
  17838. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17839. this.expect(types$1.parenR);
  17840. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17841. this.checkPatternErrors(refDestructuringErrors, false);
  17842. this.checkYieldAwaitInDefaultParams();
  17843. this.yieldPos = oldYieldPos;
  17844. this.awaitPos = oldAwaitPos;
  17845. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17846. }
  17847. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17848. if (spreadStart) { this.unexpected(spreadStart); }
  17849. this.checkExpressionErrors(refDestructuringErrors, true);
  17850. this.yieldPos = oldYieldPos || this.yieldPos;
  17851. this.awaitPos = oldAwaitPos || this.awaitPos;
  17852. if (exprList.length > 1) {
  17853. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17854. val.expressions = exprList;
  17855. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17856. } else {
  17857. val = exprList[0];
  17858. }
  17859. } else {
  17860. val = this.parseParenExpression();
  17861. }
  17862. if (this.options.preserveParens) {
  17863. var par = this.startNodeAt(startPos, startLoc);
  17864. par.expression = val;
  17865. return this.finishNode(par, "ParenthesizedExpression")
  17866. } else {
  17867. return val
  17868. }
  17869. };
  17870. pp$5.parseParenItem = function(item) {
  17871. return item
  17872. };
  17873. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17874. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17875. };
  17876. // New's precedence is slightly tricky. It must allow its argument to
  17877. // be a `[]` or dot subscript expression, but not a call — at least,
  17878. // not without wrapping it in parentheses. Thus, it uses the noCalls
  17879. // argument to parseSubscripts to prevent it from consuming the
  17880. // argument list.
  17881. var empty = [];
  17882. pp$5.parseNew = function() {
  17883. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  17884. var node = this.startNode();
  17885. var meta = this.parseIdent(true);
  17886. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  17887. node.meta = meta;
  17888. var containsEsc = this.containsEsc;
  17889. node.property = this.parseIdent(true);
  17890. if (node.property.name !== "target")
  17891. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  17892. if (containsEsc)
  17893. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  17894. if (!this.allowNewDotTarget)
  17895. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  17896. return this.finishNode(node, "MetaProperty")
  17897. }
  17898. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  17899. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  17900. if (isImport && node.callee.type === "ImportExpression") {
  17901. this.raise(startPos, "Cannot use new with import()");
  17902. }
  17903. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  17904. else { node.arguments = empty; }
  17905. return this.finishNode(node, "NewExpression")
  17906. };
  17907. // Parse template expression.
  17908. pp$5.parseTemplateElement = function(ref) {
  17909. var isTagged = ref.isTagged;
  17910. var elem = this.startNode();
  17911. if (this.type === types$1.invalidTemplate) {
  17912. if (!isTagged) {
  17913. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  17914. }
  17915. elem.value = {
  17916. raw: this.value,
  17917. cooked: null
  17918. };
  17919. } else {
  17920. elem.value = {
  17921. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  17922. cooked: this.value
  17923. };
  17924. }
  17925. this.next();
  17926. elem.tail = this.type === types$1.backQuote;
  17927. return this.finishNode(elem, "TemplateElement")
  17928. };
  17929. pp$5.parseTemplate = function(ref) {
  17930. if ( ref === void 0 ) ref = {};
  17931. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  17932. var node = this.startNode();
  17933. this.next();
  17934. node.expressions = [];
  17935. var curElt = this.parseTemplateElement({isTagged: isTagged});
  17936. node.quasis = [curElt];
  17937. while (!curElt.tail) {
  17938. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  17939. this.expect(types$1.dollarBraceL);
  17940. node.expressions.push(this.parseExpression());
  17941. this.expect(types$1.braceR);
  17942. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  17943. }
  17944. this.next();
  17945. return this.finishNode(node, "TemplateLiteral")
  17946. };
  17947. pp$5.isAsyncProp = function(prop) {
  17948. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  17949. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  17950. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17951. };
  17952. // Parse an object literal or binding pattern.
  17953. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  17954. var node = this.startNode(), first = true, propHash = {};
  17955. node.properties = [];
  17956. this.next();
  17957. while (!this.eat(types$1.braceR)) {
  17958. if (!first) {
  17959. this.expect(types$1.comma);
  17960. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  17961. } else { first = false; }
  17962. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  17963. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  17964. node.properties.push(prop);
  17965. }
  17966. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  17967. };
  17968. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  17969. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  17970. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  17971. if (isPattern) {
  17972. prop.argument = this.parseIdent(false);
  17973. if (this.type === types$1.comma) {
  17974. this.raise(this.start, "Comma is not permitted after the rest element");
  17975. }
  17976. return this.finishNode(prop, "RestElement")
  17977. }
  17978. // To disallow parenthesized identifier via `this.toAssignable()`.
  17979. if (this.type === types$1.parenL && refDestructuringErrors) {
  17980. if (refDestructuringErrors.parenthesizedAssign < 0) {
  17981. refDestructuringErrors.parenthesizedAssign = this.start;
  17982. }
  17983. if (refDestructuringErrors.parenthesizedBind < 0) {
  17984. refDestructuringErrors.parenthesizedBind = this.start;
  17985. }
  17986. }
  17987. // Parse argument.
  17988. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17989. // To disallow trailing comma via `this.toAssignable()`.
  17990. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  17991. refDestructuringErrors.trailingComma = this.start;
  17992. }
  17993. // Finish
  17994. return this.finishNode(prop, "SpreadElement")
  17995. }
  17996. if (this.options.ecmaVersion >= 6) {
  17997. prop.method = false;
  17998. prop.shorthand = false;
  17999. if (isPattern || refDestructuringErrors) {
  18000. startPos = this.start;
  18001. startLoc = this.startLoc;
  18002. }
  18003. if (!isPattern)
  18004. { isGenerator = this.eat(types$1.star); }
  18005. }
  18006. var containsEsc = this.containsEsc;
  18007. this.parsePropertyName(prop);
  18008. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  18009. isAsync = true;
  18010. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  18011. this.parsePropertyName(prop, refDestructuringErrors);
  18012. } else {
  18013. isAsync = false;
  18014. }
  18015. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  18016. return this.finishNode(prop, "Property")
  18017. };
  18018. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  18019. if ((isGenerator || isAsync) && this.type === types$1.colon)
  18020. { this.unexpected(); }
  18021. if (this.eat(types$1.colon)) {
  18022. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  18023. prop.kind = "init";
  18024. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  18025. if (isPattern) { this.unexpected(); }
  18026. prop.kind = "init";
  18027. prop.method = true;
  18028. prop.value = this.parseMethod(isGenerator, isAsync);
  18029. } else if (!isPattern && !containsEsc &&
  18030. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  18031. (prop.key.name === "get" || prop.key.name === "set") &&
  18032. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  18033. if (isGenerator || isAsync) { this.unexpected(); }
  18034. prop.kind = prop.key.name;
  18035. this.parsePropertyName(prop);
  18036. prop.value = this.parseMethod(false);
  18037. var paramCount = prop.kind === "get" ? 0 : 1;
  18038. if (prop.value.params.length !== paramCount) {
  18039. var start = prop.value.start;
  18040. if (prop.kind === "get")
  18041. { this.raiseRecoverable(start, "getter should have no params"); }
  18042. else
  18043. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  18044. } else {
  18045. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  18046. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  18047. }
  18048. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  18049. if (isGenerator || isAsync) { this.unexpected(); }
  18050. this.checkUnreserved(prop.key);
  18051. if (prop.key.name === "await" && !this.awaitIdentPos)
  18052. { this.awaitIdentPos = startPos; }
  18053. prop.kind = "init";
  18054. if (isPattern) {
  18055. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18056. } else if (this.type === types$1.eq && refDestructuringErrors) {
  18057. if (refDestructuringErrors.shorthandAssign < 0)
  18058. { refDestructuringErrors.shorthandAssign = this.start; }
  18059. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18060. } else {
  18061. prop.value = this.copyNode(prop.key);
  18062. }
  18063. prop.shorthand = true;
  18064. } else { this.unexpected(); }
  18065. };
  18066. pp$5.parsePropertyName = function(prop) {
  18067. if (this.options.ecmaVersion >= 6) {
  18068. if (this.eat(types$1.bracketL)) {
  18069. prop.computed = true;
  18070. prop.key = this.parseMaybeAssign();
  18071. this.expect(types$1.bracketR);
  18072. return prop.key
  18073. } else {
  18074. prop.computed = false;
  18075. }
  18076. }
  18077. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  18078. };
  18079. // Initialize empty function node.
  18080. pp$5.initFunction = function(node) {
  18081. node.id = null;
  18082. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  18083. if (this.options.ecmaVersion >= 8) { node.async = false; }
  18084. };
  18085. // Parse object or class method.
  18086. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  18087. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18088. this.initFunction(node);
  18089. if (this.options.ecmaVersion >= 6)
  18090. { node.generator = isGenerator; }
  18091. if (this.options.ecmaVersion >= 8)
  18092. { node.async = !!isAsync; }
  18093. this.yieldPos = 0;
  18094. this.awaitPos = 0;
  18095. this.awaitIdentPos = 0;
  18096. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  18097. this.expect(types$1.parenL);
  18098. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18099. this.checkYieldAwaitInDefaultParams();
  18100. this.parseFunctionBody(node, false, true, false);
  18101. this.yieldPos = oldYieldPos;
  18102. this.awaitPos = oldAwaitPos;
  18103. this.awaitIdentPos = oldAwaitIdentPos;
  18104. return this.finishNode(node, "FunctionExpression")
  18105. };
  18106. // Parse arrow function expression with given parameters.
  18107. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  18108. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18109. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  18110. this.initFunction(node);
  18111. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  18112. this.yieldPos = 0;
  18113. this.awaitPos = 0;
  18114. this.awaitIdentPos = 0;
  18115. node.params = this.toAssignableList(params, true);
  18116. this.parseFunctionBody(node, true, false, forInit);
  18117. this.yieldPos = oldYieldPos;
  18118. this.awaitPos = oldAwaitPos;
  18119. this.awaitIdentPos = oldAwaitIdentPos;
  18120. return this.finishNode(node, "ArrowFunctionExpression")
  18121. };
  18122. // Parse function body and check parameters.
  18123. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  18124. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  18125. var oldStrict = this.strict, useStrict = false;
  18126. if (isExpression) {
  18127. node.body = this.parseMaybeAssign(forInit);
  18128. node.expression = true;
  18129. this.checkParams(node, false);
  18130. } else {
  18131. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  18132. if (!oldStrict || nonSimple) {
  18133. useStrict = this.strictDirective(this.end);
  18134. // If this is a strict mode function, verify that argument names
  18135. // are not repeated, and it does not try to bind the words `eval`
  18136. // or `arguments`.
  18137. if (useStrict && nonSimple)
  18138. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  18139. }
  18140. // Start a new scope with regard to labels and the `inFunction`
  18141. // flag (restore them to their old value afterwards).
  18142. var oldLabels = this.labels;
  18143. this.labels = [];
  18144. if (useStrict) { this.strict = true; }
  18145. // Add the params to varDeclaredNames to ensure that an error is thrown
  18146. // if a let/const declaration in the function clashes with one of the params.
  18147. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  18148. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  18149. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  18150. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  18151. node.expression = false;
  18152. this.adaptDirectivePrologue(node.body.body);
  18153. this.labels = oldLabels;
  18154. }
  18155. this.exitScope();
  18156. };
  18157. pp$5.isSimpleParamList = function(params) {
  18158. for (var i = 0, list = params; i < list.length; i += 1)
  18159. {
  18160. var param = list[i];
  18161. if (param.type !== "Identifier") { return false
  18162. } }
  18163. return true
  18164. };
  18165. // Checks function params for various disallowed patterns such as using "eval"
  18166. // or "arguments" and duplicate parameters.
  18167. pp$5.checkParams = function(node, allowDuplicates) {
  18168. var nameHash = Object.create(null);
  18169. for (var i = 0, list = node.params; i < list.length; i += 1)
  18170. {
  18171. var param = list[i];
  18172. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  18173. }
  18174. };
  18175. // Parses a comma-separated list of expressions, and returns them as
  18176. // an array. `close` is the token type that ends the list, and
  18177. // `allowEmpty` can be turned on to allow subsequent commas with
  18178. // nothing in between them to be parsed as `null` (which is needed
  18179. // for array literals).
  18180. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  18181. var elts = [], first = true;
  18182. while (!this.eat(close)) {
  18183. if (!first) {
  18184. this.expect(types$1.comma);
  18185. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  18186. } else { first = false; }
  18187. var elt = (void 0);
  18188. if (allowEmpty && this.type === types$1.comma)
  18189. { elt = null; }
  18190. else if (this.type === types$1.ellipsis) {
  18191. elt = this.parseSpread(refDestructuringErrors);
  18192. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  18193. { refDestructuringErrors.trailingComma = this.start; }
  18194. } else {
  18195. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  18196. }
  18197. elts.push(elt);
  18198. }
  18199. return elts
  18200. };
  18201. pp$5.checkUnreserved = function(ref) {
  18202. var start = ref.start;
  18203. var end = ref.end;
  18204. var name = ref.name;
  18205. if (this.inGenerator && name === "yield")
  18206. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  18207. if (this.inAsync && name === "await")
  18208. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  18209. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  18210. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  18211. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  18212. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  18213. if (this.keywords.test(name))
  18214. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  18215. if (this.options.ecmaVersion < 6 &&
  18216. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  18217. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  18218. if (re.test(name)) {
  18219. if (!this.inAsync && name === "await")
  18220. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  18221. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  18222. }
  18223. };
  18224. // Parse the next token as an identifier. If `liberal` is true (used
  18225. // when parsing properties), it will also convert keywords into
  18226. // identifiers.
  18227. pp$5.parseIdent = function(liberal, isBinding) {
  18228. var node = this.startNode();
  18229. if (this.type === types$1.name) {
  18230. node.name = this.value;
  18231. } else if (this.type.keyword) {
  18232. node.name = this.type.keyword;
  18233. // To fix https://github.com/acornjs/acorn/issues/575
  18234. // `class` and `function` keywords push new context into this.context.
  18235. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  18236. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  18237. if ((node.name === "class" || node.name === "function") &&
  18238. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  18239. this.context.pop();
  18240. }
  18241. } else {
  18242. this.unexpected();
  18243. }
  18244. this.next(!!liberal);
  18245. this.finishNode(node, "Identifier");
  18246. if (!liberal) {
  18247. this.checkUnreserved(node);
  18248. if (node.name === "await" && !this.awaitIdentPos)
  18249. { this.awaitIdentPos = node.start; }
  18250. }
  18251. return node
  18252. };
  18253. pp$5.parsePrivateIdent = function() {
  18254. var node = this.startNode();
  18255. if (this.type === types$1.privateId) {
  18256. node.name = this.value;
  18257. } else {
  18258. this.unexpected();
  18259. }
  18260. this.next();
  18261. this.finishNode(node, "PrivateIdentifier");
  18262. // For validating existence
  18263. if (this.privateNameStack.length === 0) {
  18264. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  18265. } else {
  18266. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  18267. }
  18268. return node
  18269. };
  18270. // Parses yield expression inside generator.
  18271. pp$5.parseYield = function(forInit) {
  18272. if (!this.yieldPos) { this.yieldPos = this.start; }
  18273. var node = this.startNode();
  18274. this.next();
  18275. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  18276. node.delegate = false;
  18277. node.argument = null;
  18278. } else {
  18279. node.delegate = this.eat(types$1.star);
  18280. node.argument = this.parseMaybeAssign(forInit);
  18281. }
  18282. return this.finishNode(node, "YieldExpression")
  18283. };
  18284. pp$5.parseAwait = function(forInit) {
  18285. if (!this.awaitPos) { this.awaitPos = this.start; }
  18286. var node = this.startNode();
  18287. this.next();
  18288. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  18289. return this.finishNode(node, "AwaitExpression")
  18290. };
  18291. var pp$4 = Parser.prototype;
  18292. // This function is used to raise exceptions on parse errors. It
  18293. // takes an offset integer (into the current `input`) to indicate
  18294. // the location of the error, attaches the position to the end
  18295. // of the error message, and then raises a `SyntaxError` with that
  18296. // message.
  18297. pp$4.raise = function(pos, message) {
  18298. var loc = getLineInfo(this.input, pos);
  18299. message += " (" + loc.line + ":" + loc.column + ")";
  18300. var err = new SyntaxError(message);
  18301. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  18302. throw err
  18303. };
  18304. pp$4.raiseRecoverable = pp$4.raise;
  18305. pp$4.curPosition = function() {
  18306. if (this.options.locations) {
  18307. return new Position(this.curLine, this.pos - this.lineStart)
  18308. }
  18309. };
  18310. var pp$3 = Parser.prototype;
  18311. var Scope = function Scope(flags) {
  18312. this.flags = flags;
  18313. // A list of var-declared names in the current lexical scope
  18314. this.var = [];
  18315. // A list of lexically-declared names in the current lexical scope
  18316. this.lexical = [];
  18317. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  18318. this.functions = [];
  18319. // A switch to disallow the identifier reference 'arguments'
  18320. this.inClassFieldInit = false;
  18321. };
  18322. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  18323. pp$3.enterScope = function(flags) {
  18324. this.scopeStack.push(new Scope(flags));
  18325. };
  18326. pp$3.exitScope = function() {
  18327. this.scopeStack.pop();
  18328. };
  18329. // The spec says:
  18330. // > At the top level of a function, or script, function declarations are
  18331. // > treated like var declarations rather than like lexical declarations.
  18332. pp$3.treatFunctionsAsVarInScope = function(scope) {
  18333. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  18334. };
  18335. pp$3.declareName = function(name, bindingType, pos) {
  18336. var redeclared = false;
  18337. if (bindingType === BIND_LEXICAL) {
  18338. var scope = this.currentScope();
  18339. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  18340. scope.lexical.push(name);
  18341. if (this.inModule && (scope.flags & SCOPE_TOP))
  18342. { delete this.undefinedExports[name]; }
  18343. } else if (bindingType === BIND_SIMPLE_CATCH) {
  18344. var scope$1 = this.currentScope();
  18345. scope$1.lexical.push(name);
  18346. } else if (bindingType === BIND_FUNCTION) {
  18347. var scope$2 = this.currentScope();
  18348. if (this.treatFunctionsAsVar)
  18349. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  18350. else
  18351. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  18352. scope$2.functions.push(name);
  18353. } else {
  18354. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  18355. var scope$3 = this.scopeStack[i];
  18356. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  18357. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  18358. redeclared = true;
  18359. break
  18360. }
  18361. scope$3.var.push(name);
  18362. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  18363. { delete this.undefinedExports[name]; }
  18364. if (scope$3.flags & SCOPE_VAR) { break }
  18365. }
  18366. }
  18367. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  18368. };
  18369. pp$3.checkLocalExport = function(id) {
  18370. // scope.functions must be empty as Module code is always strict.
  18371. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  18372. this.scopeStack[0].var.indexOf(id.name) === -1) {
  18373. this.undefinedExports[id.name] = id;
  18374. }
  18375. };
  18376. pp$3.currentScope = function() {
  18377. return this.scopeStack[this.scopeStack.length - 1]
  18378. };
  18379. pp$3.currentVarScope = function() {
  18380. for (var i = this.scopeStack.length - 1;; i--) {
  18381. var scope = this.scopeStack[i];
  18382. if (scope.flags & SCOPE_VAR) { return scope }
  18383. }
  18384. };
  18385. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  18386. pp$3.currentThisScope = function() {
  18387. for (var i = this.scopeStack.length - 1;; i--) {
  18388. var scope = this.scopeStack[i];
  18389. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  18390. }
  18391. };
  18392. var Node = function Node(parser, pos, loc) {
  18393. this.type = "";
  18394. this.start = pos;
  18395. this.end = 0;
  18396. if (parser.options.locations)
  18397. { this.loc = new SourceLocation(parser, loc); }
  18398. if (parser.options.directSourceFile)
  18399. { this.sourceFile = parser.options.directSourceFile; }
  18400. if (parser.options.ranges)
  18401. { this.range = [pos, 0]; }
  18402. };
  18403. // Start an AST node, attaching a start offset.
  18404. var pp$2 = Parser.prototype;
  18405. pp$2.startNode = function() {
  18406. return new Node(this, this.start, this.startLoc)
  18407. };
  18408. pp$2.startNodeAt = function(pos, loc) {
  18409. return new Node(this, pos, loc)
  18410. };
  18411. // Finish an AST node, adding `type` and `end` properties.
  18412. function finishNodeAt(node, type, pos, loc) {
  18413. node.type = type;
  18414. node.end = pos;
  18415. if (this.options.locations)
  18416. { node.loc.end = loc; }
  18417. if (this.options.ranges)
  18418. { node.range[1] = pos; }
  18419. return node
  18420. }
  18421. pp$2.finishNode = function(node, type) {
  18422. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  18423. };
  18424. // Finish node at given position
  18425. pp$2.finishNodeAt = function(node, type, pos, loc) {
  18426. return finishNodeAt.call(this, node, type, pos, loc)
  18427. };
  18428. pp$2.copyNode = function(node) {
  18429. var newNode = new Node(this, node.start, this.startLoc);
  18430. for (var prop in node) { newNode[prop] = node[prop]; }
  18431. return newNode
  18432. };
  18433. // This file contains Unicode properties extracted from the ECMAScript
  18434. // specification. The lists are extracted like so:
  18435. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  18436. // #table-binary-unicode-properties
  18437. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  18438. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  18439. var ecma11BinaryProperties = ecma10BinaryProperties;
  18440. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  18441. var ecma13BinaryProperties = ecma12BinaryProperties;
  18442. var unicodeBinaryProperties = {
  18443. 9: ecma9BinaryProperties,
  18444. 10: ecma10BinaryProperties,
  18445. 11: ecma11BinaryProperties,
  18446. 12: ecma12BinaryProperties,
  18447. 13: ecma13BinaryProperties
  18448. };
  18449. // #table-unicode-general-category-values
  18450. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  18451. // #table-unicode-script-values
  18452. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  18453. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  18454. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  18455. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  18456. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  18457. var unicodeScriptValues = {
  18458. 9: ecma9ScriptValues,
  18459. 10: ecma10ScriptValues,
  18460. 11: ecma11ScriptValues,
  18461. 12: ecma12ScriptValues,
  18462. 13: ecma13ScriptValues
  18463. };
  18464. var data = {};
  18465. function buildUnicodeData(ecmaVersion) {
  18466. var d = data[ecmaVersion] = {
  18467. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  18468. nonBinary: {
  18469. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  18470. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  18471. }
  18472. };
  18473. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  18474. d.nonBinary.gc = d.nonBinary.General_Category;
  18475. d.nonBinary.sc = d.nonBinary.Script;
  18476. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  18477. }
  18478. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  18479. var ecmaVersion = list[i];
  18480. buildUnicodeData(ecmaVersion);
  18481. }
  18482. var pp$1 = Parser.prototype;
  18483. var RegExpValidationState = function RegExpValidationState(parser) {
  18484. this.parser = parser;
  18485. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  18486. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  18487. this.source = "";
  18488. this.flags = "";
  18489. this.start = 0;
  18490. this.switchU = false;
  18491. this.switchN = false;
  18492. this.pos = 0;
  18493. this.lastIntValue = 0;
  18494. this.lastStringValue = "";
  18495. this.lastAssertionIsQuantifiable = false;
  18496. this.numCapturingParens = 0;
  18497. this.maxBackReference = 0;
  18498. this.groupNames = [];
  18499. this.backReferenceNames = [];
  18500. };
  18501. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18502. var unicode = flags.indexOf("u") !== -1;
  18503. this.start = start | 0;
  18504. this.source = pattern + "";
  18505. this.flags = flags;
  18506. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18507. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18508. };
  18509. RegExpValidationState.prototype.raise = function raise (message) {
  18510. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18511. };
  18512. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18513. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18514. RegExpValidationState.prototype.at = function at (i, forceU) {
  18515. if ( forceU === void 0 ) forceU = false;
  18516. var s = this.source;
  18517. var l = s.length;
  18518. if (i >= l) {
  18519. return -1
  18520. }
  18521. var c = s.charCodeAt(i);
  18522. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18523. return c
  18524. }
  18525. var next = s.charCodeAt(i + 1);
  18526. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18527. };
  18528. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18529. if ( forceU === void 0 ) forceU = false;
  18530. var s = this.source;
  18531. var l = s.length;
  18532. if (i >= l) {
  18533. return l
  18534. }
  18535. var c = s.charCodeAt(i), next;
  18536. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18537. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18538. return i + 1
  18539. }
  18540. return i + 2
  18541. };
  18542. RegExpValidationState.prototype.current = function current (forceU) {
  18543. if ( forceU === void 0 ) forceU = false;
  18544. return this.at(this.pos, forceU)
  18545. };
  18546. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18547. if ( forceU === void 0 ) forceU = false;
  18548. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18549. };
  18550. RegExpValidationState.prototype.advance = function advance (forceU) {
  18551. if ( forceU === void 0 ) forceU = false;
  18552. this.pos = this.nextIndex(this.pos, forceU);
  18553. };
  18554. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18555. if ( forceU === void 0 ) forceU = false;
  18556. if (this.current(forceU) === ch) {
  18557. this.advance(forceU);
  18558. return true
  18559. }
  18560. return false
  18561. };
  18562. /**
  18563. * Validate the flags part of a given RegExpLiteral.
  18564. *
  18565. * @param {RegExpValidationState} state The state to validate RegExp.
  18566. * @returns {void}
  18567. */
  18568. pp$1.validateRegExpFlags = function(state) {
  18569. var validFlags = state.validFlags;
  18570. var flags = state.flags;
  18571. for (var i = 0; i < flags.length; i++) {
  18572. var flag = flags.charAt(i);
  18573. if (validFlags.indexOf(flag) === -1) {
  18574. this.raise(state.start, "Invalid regular expression flag");
  18575. }
  18576. if (flags.indexOf(flag, i + 1) > -1) {
  18577. this.raise(state.start, "Duplicate regular expression flag");
  18578. }
  18579. }
  18580. };
  18581. /**
  18582. * Validate the pattern part of a given RegExpLiteral.
  18583. *
  18584. * @param {RegExpValidationState} state The state to validate RegExp.
  18585. * @returns {void}
  18586. */
  18587. pp$1.validateRegExpPattern = function(state) {
  18588. this.regexp_pattern(state);
  18589. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18590. // parsing contains a |GroupName|, reparse with the goal symbol
  18591. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18592. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18593. // were not matched by the parse, or if any Early Error conditions exist.
  18594. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18595. state.switchN = true;
  18596. this.regexp_pattern(state);
  18597. }
  18598. };
  18599. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18600. pp$1.regexp_pattern = function(state) {
  18601. state.pos = 0;
  18602. state.lastIntValue = 0;
  18603. state.lastStringValue = "";
  18604. state.lastAssertionIsQuantifiable = false;
  18605. state.numCapturingParens = 0;
  18606. state.maxBackReference = 0;
  18607. state.groupNames.length = 0;
  18608. state.backReferenceNames.length = 0;
  18609. this.regexp_disjunction(state);
  18610. if (state.pos !== state.source.length) {
  18611. // Make the same messages as V8.
  18612. if (state.eat(0x29 /* ) */)) {
  18613. state.raise("Unmatched ')'");
  18614. }
  18615. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18616. state.raise("Lone quantifier brackets");
  18617. }
  18618. }
  18619. if (state.maxBackReference > state.numCapturingParens) {
  18620. state.raise("Invalid escape");
  18621. }
  18622. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18623. var name = list[i];
  18624. if (state.groupNames.indexOf(name) === -1) {
  18625. state.raise("Invalid named capture referenced");
  18626. }
  18627. }
  18628. };
  18629. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18630. pp$1.regexp_disjunction = function(state) {
  18631. this.regexp_alternative(state);
  18632. while (state.eat(0x7C /* | */)) {
  18633. this.regexp_alternative(state);
  18634. }
  18635. // Make the same message as V8.
  18636. if (this.regexp_eatQuantifier(state, true)) {
  18637. state.raise("Nothing to repeat");
  18638. }
  18639. if (state.eat(0x7B /* { */)) {
  18640. state.raise("Lone quantifier brackets");
  18641. }
  18642. };
  18643. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18644. pp$1.regexp_alternative = function(state) {
  18645. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18646. { }
  18647. };
  18648. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18649. pp$1.regexp_eatTerm = function(state) {
  18650. if (this.regexp_eatAssertion(state)) {
  18651. // Handle `QuantifiableAssertion Quantifier` alternative.
  18652. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18653. // is a QuantifiableAssertion.
  18654. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18655. // Make the same message as V8.
  18656. if (state.switchU) {
  18657. state.raise("Invalid quantifier");
  18658. }
  18659. }
  18660. return true
  18661. }
  18662. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18663. this.regexp_eatQuantifier(state);
  18664. return true
  18665. }
  18666. return false
  18667. };
  18668. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18669. pp$1.regexp_eatAssertion = function(state) {
  18670. var start = state.pos;
  18671. state.lastAssertionIsQuantifiable = false;
  18672. // ^, $
  18673. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18674. return true
  18675. }
  18676. // \b \B
  18677. if (state.eat(0x5C /* \ */)) {
  18678. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18679. return true
  18680. }
  18681. state.pos = start;
  18682. }
  18683. // Lookahead / Lookbehind
  18684. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18685. var lookbehind = false;
  18686. if (this.options.ecmaVersion >= 9) {
  18687. lookbehind = state.eat(0x3C /* < */);
  18688. }
  18689. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18690. this.regexp_disjunction(state);
  18691. if (!state.eat(0x29 /* ) */)) {
  18692. state.raise("Unterminated group");
  18693. }
  18694. state.lastAssertionIsQuantifiable = !lookbehind;
  18695. return true
  18696. }
  18697. }
  18698. state.pos = start;
  18699. return false
  18700. };
  18701. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18702. pp$1.regexp_eatQuantifier = function(state, noError) {
  18703. if ( noError === void 0 ) noError = false;
  18704. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18705. state.eat(0x3F /* ? */);
  18706. return true
  18707. }
  18708. return false
  18709. };
  18710. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18711. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18712. return (
  18713. state.eat(0x2A /* * */) ||
  18714. state.eat(0x2B /* + */) ||
  18715. state.eat(0x3F /* ? */) ||
  18716. this.regexp_eatBracedQuantifier(state, noError)
  18717. )
  18718. };
  18719. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18720. var start = state.pos;
  18721. if (state.eat(0x7B /* { */)) {
  18722. var min = 0, max = -1;
  18723. if (this.regexp_eatDecimalDigits(state)) {
  18724. min = state.lastIntValue;
  18725. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18726. max = state.lastIntValue;
  18727. }
  18728. if (state.eat(0x7D /* } */)) {
  18729. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18730. if (max !== -1 && max < min && !noError) {
  18731. state.raise("numbers out of order in {} quantifier");
  18732. }
  18733. return true
  18734. }
  18735. }
  18736. if (state.switchU && !noError) {
  18737. state.raise("Incomplete quantifier");
  18738. }
  18739. state.pos = start;
  18740. }
  18741. return false
  18742. };
  18743. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18744. pp$1.regexp_eatAtom = function(state) {
  18745. return (
  18746. this.regexp_eatPatternCharacters(state) ||
  18747. state.eat(0x2E /* . */) ||
  18748. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18749. this.regexp_eatCharacterClass(state) ||
  18750. this.regexp_eatUncapturingGroup(state) ||
  18751. this.regexp_eatCapturingGroup(state)
  18752. )
  18753. };
  18754. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18755. var start = state.pos;
  18756. if (state.eat(0x5C /* \ */)) {
  18757. if (this.regexp_eatAtomEscape(state)) {
  18758. return true
  18759. }
  18760. state.pos = start;
  18761. }
  18762. return false
  18763. };
  18764. pp$1.regexp_eatUncapturingGroup = function(state) {
  18765. var start = state.pos;
  18766. if (state.eat(0x28 /* ( */)) {
  18767. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18768. this.regexp_disjunction(state);
  18769. if (state.eat(0x29 /* ) */)) {
  18770. return true
  18771. }
  18772. state.raise("Unterminated group");
  18773. }
  18774. state.pos = start;
  18775. }
  18776. return false
  18777. };
  18778. pp$1.regexp_eatCapturingGroup = function(state) {
  18779. if (state.eat(0x28 /* ( */)) {
  18780. if (this.options.ecmaVersion >= 9) {
  18781. this.regexp_groupSpecifier(state);
  18782. } else if (state.current() === 0x3F /* ? */) {
  18783. state.raise("Invalid group");
  18784. }
  18785. this.regexp_disjunction(state);
  18786. if (state.eat(0x29 /* ) */)) {
  18787. state.numCapturingParens += 1;
  18788. return true
  18789. }
  18790. state.raise("Unterminated group");
  18791. }
  18792. return false
  18793. };
  18794. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18795. pp$1.regexp_eatExtendedAtom = function(state) {
  18796. return (
  18797. state.eat(0x2E /* . */) ||
  18798. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18799. this.regexp_eatCharacterClass(state) ||
  18800. this.regexp_eatUncapturingGroup(state) ||
  18801. this.regexp_eatCapturingGroup(state) ||
  18802. this.regexp_eatInvalidBracedQuantifier(state) ||
  18803. this.regexp_eatExtendedPatternCharacter(state)
  18804. )
  18805. };
  18806. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18807. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18808. if (this.regexp_eatBracedQuantifier(state, true)) {
  18809. state.raise("Nothing to repeat");
  18810. }
  18811. return false
  18812. };
  18813. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18814. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18815. var ch = state.current();
  18816. if (isSyntaxCharacter(ch)) {
  18817. state.lastIntValue = ch;
  18818. state.advance();
  18819. return true
  18820. }
  18821. return false
  18822. };
  18823. function isSyntaxCharacter(ch) {
  18824. return (
  18825. ch === 0x24 /* $ */ ||
  18826. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18827. ch === 0x2E /* . */ ||
  18828. ch === 0x3F /* ? */ ||
  18829. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18830. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18831. )
  18832. }
  18833. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18834. // But eat eager.
  18835. pp$1.regexp_eatPatternCharacters = function(state) {
  18836. var start = state.pos;
  18837. var ch = 0;
  18838. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18839. state.advance();
  18840. }
  18841. return state.pos !== start
  18842. };
  18843. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18844. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18845. var ch = state.current();
  18846. if (
  18847. ch !== -1 &&
  18848. ch !== 0x24 /* $ */ &&
  18849. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18850. ch !== 0x2E /* . */ &&
  18851. ch !== 0x3F /* ? */ &&
  18852. ch !== 0x5B /* [ */ &&
  18853. ch !== 0x5E /* ^ */ &&
  18854. ch !== 0x7C /* | */
  18855. ) {
  18856. state.advance();
  18857. return true
  18858. }
  18859. return false
  18860. };
  18861. // GroupSpecifier ::
  18862. // [empty]
  18863. // `?` GroupName
  18864. pp$1.regexp_groupSpecifier = function(state) {
  18865. if (state.eat(0x3F /* ? */)) {
  18866. if (this.regexp_eatGroupName(state)) {
  18867. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18868. state.raise("Duplicate capture group name");
  18869. }
  18870. state.groupNames.push(state.lastStringValue);
  18871. return
  18872. }
  18873. state.raise("Invalid group");
  18874. }
  18875. };
  18876. // GroupName ::
  18877. // `<` RegExpIdentifierName `>`
  18878. // Note: this updates `state.lastStringValue` property with the eaten name.
  18879. pp$1.regexp_eatGroupName = function(state) {
  18880. state.lastStringValue = "";
  18881. if (state.eat(0x3C /* < */)) {
  18882. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  18883. return true
  18884. }
  18885. state.raise("Invalid capture group name");
  18886. }
  18887. return false
  18888. };
  18889. // RegExpIdentifierName ::
  18890. // RegExpIdentifierStart
  18891. // RegExpIdentifierName RegExpIdentifierPart
  18892. // Note: this updates `state.lastStringValue` property with the eaten name.
  18893. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  18894. state.lastStringValue = "";
  18895. if (this.regexp_eatRegExpIdentifierStart(state)) {
  18896. state.lastStringValue += codePointToString(state.lastIntValue);
  18897. while (this.regexp_eatRegExpIdentifierPart(state)) {
  18898. state.lastStringValue += codePointToString(state.lastIntValue);
  18899. }
  18900. return true
  18901. }
  18902. return false
  18903. };
  18904. // RegExpIdentifierStart ::
  18905. // UnicodeIDStart
  18906. // `$`
  18907. // `_`
  18908. // `\` RegExpUnicodeEscapeSequence[+U]
  18909. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  18910. var start = state.pos;
  18911. var forceU = this.options.ecmaVersion >= 11;
  18912. var ch = state.current(forceU);
  18913. state.advance(forceU);
  18914. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18915. ch = state.lastIntValue;
  18916. }
  18917. if (isRegExpIdentifierStart(ch)) {
  18918. state.lastIntValue = ch;
  18919. return true
  18920. }
  18921. state.pos = start;
  18922. return false
  18923. };
  18924. function isRegExpIdentifierStart(ch) {
  18925. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  18926. }
  18927. // RegExpIdentifierPart ::
  18928. // UnicodeIDContinue
  18929. // `$`
  18930. // `_`
  18931. // `\` RegExpUnicodeEscapeSequence[+U]
  18932. // <ZWNJ>
  18933. // <ZWJ>
  18934. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  18935. var start = state.pos;
  18936. var forceU = this.options.ecmaVersion >= 11;
  18937. var ch = state.current(forceU);
  18938. state.advance(forceU);
  18939. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18940. ch = state.lastIntValue;
  18941. }
  18942. if (isRegExpIdentifierPart(ch)) {
  18943. state.lastIntValue = ch;
  18944. return true
  18945. }
  18946. state.pos = start;
  18947. return false
  18948. };
  18949. function isRegExpIdentifierPart(ch) {
  18950. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  18951. }
  18952. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  18953. pp$1.regexp_eatAtomEscape = function(state) {
  18954. if (
  18955. this.regexp_eatBackReference(state) ||
  18956. this.regexp_eatCharacterClassEscape(state) ||
  18957. this.regexp_eatCharacterEscape(state) ||
  18958. (state.switchN && this.regexp_eatKGroupName(state))
  18959. ) {
  18960. return true
  18961. }
  18962. if (state.switchU) {
  18963. // Make the same message as V8.
  18964. if (state.current() === 0x63 /* c */) {
  18965. state.raise("Invalid unicode escape");
  18966. }
  18967. state.raise("Invalid escape");
  18968. }
  18969. return false
  18970. };
  18971. pp$1.regexp_eatBackReference = function(state) {
  18972. var start = state.pos;
  18973. if (this.regexp_eatDecimalEscape(state)) {
  18974. var n = state.lastIntValue;
  18975. if (state.switchU) {
  18976. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  18977. if (n > state.maxBackReference) {
  18978. state.maxBackReference = n;
  18979. }
  18980. return true
  18981. }
  18982. if (n <= state.numCapturingParens) {
  18983. return true
  18984. }
  18985. state.pos = start;
  18986. }
  18987. return false
  18988. };
  18989. pp$1.regexp_eatKGroupName = function(state) {
  18990. if (state.eat(0x6B /* k */)) {
  18991. if (this.regexp_eatGroupName(state)) {
  18992. state.backReferenceNames.push(state.lastStringValue);
  18993. return true
  18994. }
  18995. state.raise("Invalid named reference");
  18996. }
  18997. return false
  18998. };
  18999. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  19000. pp$1.regexp_eatCharacterEscape = function(state) {
  19001. return (
  19002. this.regexp_eatControlEscape(state) ||
  19003. this.regexp_eatCControlLetter(state) ||
  19004. this.regexp_eatZero(state) ||
  19005. this.regexp_eatHexEscapeSequence(state) ||
  19006. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  19007. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  19008. this.regexp_eatIdentityEscape(state)
  19009. )
  19010. };
  19011. pp$1.regexp_eatCControlLetter = function(state) {
  19012. var start = state.pos;
  19013. if (state.eat(0x63 /* c */)) {
  19014. if (this.regexp_eatControlLetter(state)) {
  19015. return true
  19016. }
  19017. state.pos = start;
  19018. }
  19019. return false
  19020. };
  19021. pp$1.regexp_eatZero = function(state) {
  19022. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  19023. state.lastIntValue = 0;
  19024. state.advance();
  19025. return true
  19026. }
  19027. return false
  19028. };
  19029. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  19030. pp$1.regexp_eatControlEscape = function(state) {
  19031. var ch = state.current();
  19032. if (ch === 0x74 /* t */) {
  19033. state.lastIntValue = 0x09; /* \t */
  19034. state.advance();
  19035. return true
  19036. }
  19037. if (ch === 0x6E /* n */) {
  19038. state.lastIntValue = 0x0A; /* \n */
  19039. state.advance();
  19040. return true
  19041. }
  19042. if (ch === 0x76 /* v */) {
  19043. state.lastIntValue = 0x0B; /* \v */
  19044. state.advance();
  19045. return true
  19046. }
  19047. if (ch === 0x66 /* f */) {
  19048. state.lastIntValue = 0x0C; /* \f */
  19049. state.advance();
  19050. return true
  19051. }
  19052. if (ch === 0x72 /* r */) {
  19053. state.lastIntValue = 0x0D; /* \r */
  19054. state.advance();
  19055. return true
  19056. }
  19057. return false
  19058. };
  19059. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  19060. pp$1.regexp_eatControlLetter = function(state) {
  19061. var ch = state.current();
  19062. if (isControlLetter(ch)) {
  19063. state.lastIntValue = ch % 0x20;
  19064. state.advance();
  19065. return true
  19066. }
  19067. return false
  19068. };
  19069. function isControlLetter(ch) {
  19070. return (
  19071. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  19072. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  19073. )
  19074. }
  19075. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  19076. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  19077. if ( forceU === void 0 ) forceU = false;
  19078. var start = state.pos;
  19079. var switchU = forceU || state.switchU;
  19080. if (state.eat(0x75 /* u */)) {
  19081. if (this.regexp_eatFixedHexDigits(state, 4)) {
  19082. var lead = state.lastIntValue;
  19083. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  19084. var leadSurrogateEnd = state.pos;
  19085. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  19086. var trail = state.lastIntValue;
  19087. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  19088. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  19089. return true
  19090. }
  19091. }
  19092. state.pos = leadSurrogateEnd;
  19093. state.lastIntValue = lead;
  19094. }
  19095. return true
  19096. }
  19097. if (
  19098. switchU &&
  19099. state.eat(0x7B /* { */) &&
  19100. this.regexp_eatHexDigits(state) &&
  19101. state.eat(0x7D /* } */) &&
  19102. isValidUnicode(state.lastIntValue)
  19103. ) {
  19104. return true
  19105. }
  19106. if (switchU) {
  19107. state.raise("Invalid unicode escape");
  19108. }
  19109. state.pos = start;
  19110. }
  19111. return false
  19112. };
  19113. function isValidUnicode(ch) {
  19114. return ch >= 0 && ch <= 0x10FFFF
  19115. }
  19116. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  19117. pp$1.regexp_eatIdentityEscape = function(state) {
  19118. if (state.switchU) {
  19119. if (this.regexp_eatSyntaxCharacter(state)) {
  19120. return true
  19121. }
  19122. if (state.eat(0x2F /* / */)) {
  19123. state.lastIntValue = 0x2F; /* / */
  19124. return true
  19125. }
  19126. return false
  19127. }
  19128. var ch = state.current();
  19129. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  19130. state.lastIntValue = ch;
  19131. state.advance();
  19132. return true
  19133. }
  19134. return false
  19135. };
  19136. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  19137. pp$1.regexp_eatDecimalEscape = function(state) {
  19138. state.lastIntValue = 0;
  19139. var ch = state.current();
  19140. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  19141. do {
  19142. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19143. state.advance();
  19144. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  19145. return true
  19146. }
  19147. return false
  19148. };
  19149. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  19150. pp$1.regexp_eatCharacterClassEscape = function(state) {
  19151. var ch = state.current();
  19152. if (isCharacterClassEscape(ch)) {
  19153. state.lastIntValue = -1;
  19154. state.advance();
  19155. return true
  19156. }
  19157. if (
  19158. state.switchU &&
  19159. this.options.ecmaVersion >= 9 &&
  19160. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  19161. ) {
  19162. state.lastIntValue = -1;
  19163. state.advance();
  19164. if (
  19165. state.eat(0x7B /* { */) &&
  19166. this.regexp_eatUnicodePropertyValueExpression(state) &&
  19167. state.eat(0x7D /* } */)
  19168. ) {
  19169. return true
  19170. }
  19171. state.raise("Invalid property name");
  19172. }
  19173. return false
  19174. };
  19175. function isCharacterClassEscape(ch) {
  19176. return (
  19177. ch === 0x64 /* d */ ||
  19178. ch === 0x44 /* D */ ||
  19179. ch === 0x73 /* s */ ||
  19180. ch === 0x53 /* S */ ||
  19181. ch === 0x77 /* w */ ||
  19182. ch === 0x57 /* W */
  19183. )
  19184. }
  19185. // UnicodePropertyValueExpression ::
  19186. // UnicodePropertyName `=` UnicodePropertyValue
  19187. // LoneUnicodePropertyNameOrValue
  19188. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  19189. var start = state.pos;
  19190. // UnicodePropertyName `=` UnicodePropertyValue
  19191. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  19192. var name = state.lastStringValue;
  19193. if (this.regexp_eatUnicodePropertyValue(state)) {
  19194. var value = state.lastStringValue;
  19195. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  19196. return true
  19197. }
  19198. }
  19199. state.pos = start;
  19200. // LoneUnicodePropertyNameOrValue
  19201. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  19202. var nameOrValue = state.lastStringValue;
  19203. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  19204. return true
  19205. }
  19206. return false
  19207. };
  19208. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  19209. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  19210. { state.raise("Invalid property name"); }
  19211. if (!state.unicodeProperties.nonBinary[name].test(value))
  19212. { state.raise("Invalid property value"); }
  19213. };
  19214. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  19215. if (!state.unicodeProperties.binary.test(nameOrValue))
  19216. { state.raise("Invalid property name"); }
  19217. };
  19218. // UnicodePropertyName ::
  19219. // UnicodePropertyNameCharacters
  19220. pp$1.regexp_eatUnicodePropertyName = function(state) {
  19221. var ch = 0;
  19222. state.lastStringValue = "";
  19223. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  19224. state.lastStringValue += codePointToString(ch);
  19225. state.advance();
  19226. }
  19227. return state.lastStringValue !== ""
  19228. };
  19229. function isUnicodePropertyNameCharacter(ch) {
  19230. return isControlLetter(ch) || ch === 0x5F /* _ */
  19231. }
  19232. // UnicodePropertyValue ::
  19233. // UnicodePropertyValueCharacters
  19234. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  19235. var ch = 0;
  19236. state.lastStringValue = "";
  19237. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  19238. state.lastStringValue += codePointToString(ch);
  19239. state.advance();
  19240. }
  19241. return state.lastStringValue !== ""
  19242. };
  19243. function isUnicodePropertyValueCharacter(ch) {
  19244. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  19245. }
  19246. // LoneUnicodePropertyNameOrValue ::
  19247. // UnicodePropertyValueCharacters
  19248. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  19249. return this.regexp_eatUnicodePropertyValue(state)
  19250. };
  19251. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  19252. pp$1.regexp_eatCharacterClass = function(state) {
  19253. if (state.eat(0x5B /* [ */)) {
  19254. state.eat(0x5E /* ^ */);
  19255. this.regexp_classRanges(state);
  19256. if (state.eat(0x5D /* ] */)) {
  19257. return true
  19258. }
  19259. // Unreachable since it threw "unterminated regular expression" error before.
  19260. state.raise("Unterminated character class");
  19261. }
  19262. return false
  19263. };
  19264. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  19265. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  19266. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  19267. pp$1.regexp_classRanges = function(state) {
  19268. while (this.regexp_eatClassAtom(state)) {
  19269. var left = state.lastIntValue;
  19270. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  19271. var right = state.lastIntValue;
  19272. if (state.switchU && (left === -1 || right === -1)) {
  19273. state.raise("Invalid character class");
  19274. }
  19275. if (left !== -1 && right !== -1 && left > right) {
  19276. state.raise("Range out of order in character class");
  19277. }
  19278. }
  19279. }
  19280. };
  19281. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  19282. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  19283. pp$1.regexp_eatClassAtom = function(state) {
  19284. var start = state.pos;
  19285. if (state.eat(0x5C /* \ */)) {
  19286. if (this.regexp_eatClassEscape(state)) {
  19287. return true
  19288. }
  19289. if (state.switchU) {
  19290. // Make the same message as V8.
  19291. var ch$1 = state.current();
  19292. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  19293. state.raise("Invalid class escape");
  19294. }
  19295. state.raise("Invalid escape");
  19296. }
  19297. state.pos = start;
  19298. }
  19299. var ch = state.current();
  19300. if (ch !== 0x5D /* ] */) {
  19301. state.lastIntValue = ch;
  19302. state.advance();
  19303. return true
  19304. }
  19305. return false
  19306. };
  19307. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  19308. pp$1.regexp_eatClassEscape = function(state) {
  19309. var start = state.pos;
  19310. if (state.eat(0x62 /* b */)) {
  19311. state.lastIntValue = 0x08; /* <BS> */
  19312. return true
  19313. }
  19314. if (state.switchU && state.eat(0x2D /* - */)) {
  19315. state.lastIntValue = 0x2D; /* - */
  19316. return true
  19317. }
  19318. if (!state.switchU && state.eat(0x63 /* c */)) {
  19319. if (this.regexp_eatClassControlLetter(state)) {
  19320. return true
  19321. }
  19322. state.pos = start;
  19323. }
  19324. return (
  19325. this.regexp_eatCharacterClassEscape(state) ||
  19326. this.regexp_eatCharacterEscape(state)
  19327. )
  19328. };
  19329. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  19330. pp$1.regexp_eatClassControlLetter = function(state) {
  19331. var ch = state.current();
  19332. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  19333. state.lastIntValue = ch % 0x20;
  19334. state.advance();
  19335. return true
  19336. }
  19337. return false
  19338. };
  19339. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19340. pp$1.regexp_eatHexEscapeSequence = function(state) {
  19341. var start = state.pos;
  19342. if (state.eat(0x78 /* x */)) {
  19343. if (this.regexp_eatFixedHexDigits(state, 2)) {
  19344. return true
  19345. }
  19346. if (state.switchU) {
  19347. state.raise("Invalid escape");
  19348. }
  19349. state.pos = start;
  19350. }
  19351. return false
  19352. };
  19353. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  19354. pp$1.regexp_eatDecimalDigits = function(state) {
  19355. var start = state.pos;
  19356. var ch = 0;
  19357. state.lastIntValue = 0;
  19358. while (isDecimalDigit(ch = state.current())) {
  19359. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19360. state.advance();
  19361. }
  19362. return state.pos !== start
  19363. };
  19364. function isDecimalDigit(ch) {
  19365. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  19366. }
  19367. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  19368. pp$1.regexp_eatHexDigits = function(state) {
  19369. var start = state.pos;
  19370. var ch = 0;
  19371. state.lastIntValue = 0;
  19372. while (isHexDigit(ch = state.current())) {
  19373. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19374. state.advance();
  19375. }
  19376. return state.pos !== start
  19377. };
  19378. function isHexDigit(ch) {
  19379. return (
  19380. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  19381. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  19382. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  19383. )
  19384. }
  19385. function hexToInt(ch) {
  19386. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  19387. return 10 + (ch - 0x41 /* A */)
  19388. }
  19389. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  19390. return 10 + (ch - 0x61 /* a */)
  19391. }
  19392. return ch - 0x30 /* 0 */
  19393. }
  19394. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  19395. // Allows only 0-377(octal) i.e. 0-255(decimal).
  19396. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  19397. if (this.regexp_eatOctalDigit(state)) {
  19398. var n1 = state.lastIntValue;
  19399. if (this.regexp_eatOctalDigit(state)) {
  19400. var n2 = state.lastIntValue;
  19401. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  19402. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  19403. } else {
  19404. state.lastIntValue = n1 * 8 + n2;
  19405. }
  19406. } else {
  19407. state.lastIntValue = n1;
  19408. }
  19409. return true
  19410. }
  19411. return false
  19412. };
  19413. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  19414. pp$1.regexp_eatOctalDigit = function(state) {
  19415. var ch = state.current();
  19416. if (isOctalDigit(ch)) {
  19417. state.lastIntValue = ch - 0x30; /* 0 */
  19418. state.advance();
  19419. return true
  19420. }
  19421. state.lastIntValue = 0;
  19422. return false
  19423. };
  19424. function isOctalDigit(ch) {
  19425. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  19426. }
  19427. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  19428. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  19429. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19430. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  19431. var start = state.pos;
  19432. state.lastIntValue = 0;
  19433. for (var i = 0; i < length; ++i) {
  19434. var ch = state.current();
  19435. if (!isHexDigit(ch)) {
  19436. state.pos = start;
  19437. return false
  19438. }
  19439. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19440. state.advance();
  19441. }
  19442. return true
  19443. };
  19444. // Object type used to represent tokens. Note that normally, tokens
  19445. // simply exist as properties on the parser object. This is only
  19446. // used for the onToken callback and the external tokenizer.
  19447. var Token = function Token(p) {
  19448. this.type = p.type;
  19449. this.value = p.value;
  19450. this.start = p.start;
  19451. this.end = p.end;
  19452. if (p.options.locations)
  19453. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  19454. if (p.options.ranges)
  19455. { this.range = [p.start, p.end]; }
  19456. };
  19457. // ## Tokenizer
  19458. var pp = Parser.prototype;
  19459. // Move to the next token
  19460. pp.next = function(ignoreEscapeSequenceInKeyword) {
  19461. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  19462. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  19463. if (this.options.onToken)
  19464. { this.options.onToken(new Token(this)); }
  19465. this.lastTokEnd = this.end;
  19466. this.lastTokStart = this.start;
  19467. this.lastTokEndLoc = this.endLoc;
  19468. this.lastTokStartLoc = this.startLoc;
  19469. this.nextToken();
  19470. };
  19471. pp.getToken = function() {
  19472. this.next();
  19473. return new Token(this)
  19474. };
  19475. // If we're in an ES6 environment, make parsers iterable
  19476. if (typeof Symbol !== "undefined")
  19477. { pp[Symbol.iterator] = function() {
  19478. var this$1$1 = this;
  19479. return {
  19480. next: function () {
  19481. var token = this$1$1.getToken();
  19482. return {
  19483. done: token.type === types$1.eof,
  19484. value: token
  19485. }
  19486. }
  19487. }
  19488. }; }
  19489. // Toggle strict mode. Re-reads the next number or string to please
  19490. // pedantic tests (`"use strict"; 010;` should fail).
  19491. // Read a single token, updating the parser object's token-related
  19492. // properties.
  19493. pp.nextToken = function() {
  19494. var curContext = this.curContext();
  19495. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19496. this.start = this.pos;
  19497. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19498. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19499. if (curContext.override) { return curContext.override(this) }
  19500. else { this.readToken(this.fullCharCodeAtPos()); }
  19501. };
  19502. pp.readToken = function(code) {
  19503. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19504. // identifiers, so '\' also dispatches to that.
  19505. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19506. { return this.readWord() }
  19507. return this.getTokenFromCode(code)
  19508. };
  19509. pp.fullCharCodeAtPos = function() {
  19510. var code = this.input.charCodeAt(this.pos);
  19511. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19512. var next = this.input.charCodeAt(this.pos + 1);
  19513. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19514. };
  19515. pp.skipBlockComment = function() {
  19516. var startLoc = this.options.onComment && this.curPosition();
  19517. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19518. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19519. this.pos = end + 2;
  19520. if (this.options.locations) {
  19521. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19522. ++this.curLine;
  19523. pos = this.lineStart = nextBreak;
  19524. }
  19525. }
  19526. if (this.options.onComment)
  19527. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19528. startLoc, this.curPosition()); }
  19529. };
  19530. pp.skipLineComment = function(startSkip) {
  19531. var start = this.pos;
  19532. var startLoc = this.options.onComment && this.curPosition();
  19533. var ch = this.input.charCodeAt(this.pos += startSkip);
  19534. while (this.pos < this.input.length && !isNewLine(ch)) {
  19535. ch = this.input.charCodeAt(++this.pos);
  19536. }
  19537. if (this.options.onComment)
  19538. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19539. startLoc, this.curPosition()); }
  19540. };
  19541. // Called at the start of the parse and after every token. Skips
  19542. // whitespace and comments, and.
  19543. pp.skipSpace = function() {
  19544. loop: while (this.pos < this.input.length) {
  19545. var ch = this.input.charCodeAt(this.pos);
  19546. switch (ch) {
  19547. case 32: case 160: // ' '
  19548. ++this.pos;
  19549. break
  19550. case 13:
  19551. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19552. ++this.pos;
  19553. }
  19554. case 10: case 8232: case 8233:
  19555. ++this.pos;
  19556. if (this.options.locations) {
  19557. ++this.curLine;
  19558. this.lineStart = this.pos;
  19559. }
  19560. break
  19561. case 47: // '/'
  19562. switch (this.input.charCodeAt(this.pos + 1)) {
  19563. case 42: // '*'
  19564. this.skipBlockComment();
  19565. break
  19566. case 47:
  19567. this.skipLineComment(2);
  19568. break
  19569. default:
  19570. break loop
  19571. }
  19572. break
  19573. default:
  19574. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19575. ++this.pos;
  19576. } else {
  19577. break loop
  19578. }
  19579. }
  19580. }
  19581. };
  19582. // Called at the end of every token. Sets `end`, `val`, and
  19583. // maintains `context` and `exprAllowed`, and skips the space after
  19584. // the token, so that the next one's `start` will point at the
  19585. // right position.
  19586. pp.finishToken = function(type, val) {
  19587. this.end = this.pos;
  19588. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19589. var prevType = this.type;
  19590. this.type = type;
  19591. this.value = val;
  19592. this.updateContext(prevType);
  19593. };
  19594. // ### Token reading
  19595. // This is the function that is called to fetch the next token. It
  19596. // is somewhat obscure, because it works in character codes rather
  19597. // than characters, and because operator parsing has been inlined
  19598. // into it.
  19599. //
  19600. // All in the name of speed.
  19601. //
  19602. pp.readToken_dot = function() {
  19603. var next = this.input.charCodeAt(this.pos + 1);
  19604. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19605. var next2 = this.input.charCodeAt(this.pos + 2);
  19606. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19607. this.pos += 3;
  19608. return this.finishToken(types$1.ellipsis)
  19609. } else {
  19610. ++this.pos;
  19611. return this.finishToken(types$1.dot)
  19612. }
  19613. };
  19614. pp.readToken_slash = function() { // '/'
  19615. var next = this.input.charCodeAt(this.pos + 1);
  19616. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19617. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19618. return this.finishOp(types$1.slash, 1)
  19619. };
  19620. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19621. var next = this.input.charCodeAt(this.pos + 1);
  19622. var size = 1;
  19623. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19624. // exponentiation operator ** and **=
  19625. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19626. ++size;
  19627. tokentype = types$1.starstar;
  19628. next = this.input.charCodeAt(this.pos + 2);
  19629. }
  19630. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19631. return this.finishOp(tokentype, size)
  19632. };
  19633. pp.readToken_pipe_amp = function(code) { // '|&'
  19634. var next = this.input.charCodeAt(this.pos + 1);
  19635. if (next === code) {
  19636. if (this.options.ecmaVersion >= 12) {
  19637. var next2 = this.input.charCodeAt(this.pos + 2);
  19638. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19639. }
  19640. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19641. }
  19642. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19643. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19644. };
  19645. pp.readToken_caret = function() { // '^'
  19646. var next = this.input.charCodeAt(this.pos + 1);
  19647. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19648. return this.finishOp(types$1.bitwiseXOR, 1)
  19649. };
  19650. pp.readToken_plus_min = function(code) { // '+-'
  19651. var next = this.input.charCodeAt(this.pos + 1);
  19652. if (next === code) {
  19653. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19654. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19655. // A `-->` line comment
  19656. this.skipLineComment(3);
  19657. this.skipSpace();
  19658. return this.nextToken()
  19659. }
  19660. return this.finishOp(types$1.incDec, 2)
  19661. }
  19662. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19663. return this.finishOp(types$1.plusMin, 1)
  19664. };
  19665. pp.readToken_lt_gt = function(code) { // '<>'
  19666. var next = this.input.charCodeAt(this.pos + 1);
  19667. var size = 1;
  19668. if (next === code) {
  19669. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19670. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19671. return this.finishOp(types$1.bitShift, size)
  19672. }
  19673. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19674. this.input.charCodeAt(this.pos + 3) === 45) {
  19675. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19676. this.skipLineComment(4);
  19677. this.skipSpace();
  19678. return this.nextToken()
  19679. }
  19680. if (next === 61) { size = 2; }
  19681. return this.finishOp(types$1.relational, size)
  19682. };
  19683. pp.readToken_eq_excl = function(code) { // '=!'
  19684. var next = this.input.charCodeAt(this.pos + 1);
  19685. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19686. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19687. this.pos += 2;
  19688. return this.finishToken(types$1.arrow)
  19689. }
  19690. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19691. };
  19692. pp.readToken_question = function() { // '?'
  19693. var ecmaVersion = this.options.ecmaVersion;
  19694. if (ecmaVersion >= 11) {
  19695. var next = this.input.charCodeAt(this.pos + 1);
  19696. if (next === 46) {
  19697. var next2 = this.input.charCodeAt(this.pos + 2);
  19698. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19699. }
  19700. if (next === 63) {
  19701. if (ecmaVersion >= 12) {
  19702. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19703. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19704. }
  19705. return this.finishOp(types$1.coalesce, 2)
  19706. }
  19707. }
  19708. return this.finishOp(types$1.question, 1)
  19709. };
  19710. pp.readToken_numberSign = function() { // '#'
  19711. var ecmaVersion = this.options.ecmaVersion;
  19712. var code = 35; // '#'
  19713. if (ecmaVersion >= 13) {
  19714. ++this.pos;
  19715. code = this.fullCharCodeAtPos();
  19716. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19717. return this.finishToken(types$1.privateId, this.readWord1())
  19718. }
  19719. }
  19720. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19721. };
  19722. pp.getTokenFromCode = function(code) {
  19723. switch (code) {
  19724. // The interpretation of a dot depends on whether it is followed
  19725. // by a digit or another two dots.
  19726. case 46: // '.'
  19727. return this.readToken_dot()
  19728. // Punctuation tokens.
  19729. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19730. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19731. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19732. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19733. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19734. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19735. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19736. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19737. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19738. case 96: // '`'
  19739. if (this.options.ecmaVersion < 6) { break }
  19740. ++this.pos;
  19741. return this.finishToken(types$1.backQuote)
  19742. case 48: // '0'
  19743. var next = this.input.charCodeAt(this.pos + 1);
  19744. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19745. if (this.options.ecmaVersion >= 6) {
  19746. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19747. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19748. }
  19749. // Anything else beginning with a digit is an integer, octal
  19750. // number, or float.
  19751. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19752. return this.readNumber(false)
  19753. // Quotes produce strings.
  19754. case 34: case 39: // '"', "'"
  19755. return this.readString(code)
  19756. // Operators are parsed inline in tiny state machines. '=' (61) is
  19757. // often referred to. `finishOp` simply skips the amount of
  19758. // characters it is given as second argument, and returns a token
  19759. // of the type given by its first argument.
  19760. case 47: // '/'
  19761. return this.readToken_slash()
  19762. case 37: case 42: // '%*'
  19763. return this.readToken_mult_modulo_exp(code)
  19764. case 124: case 38: // '|&'
  19765. return this.readToken_pipe_amp(code)
  19766. case 94: // '^'
  19767. return this.readToken_caret()
  19768. case 43: case 45: // '+-'
  19769. return this.readToken_plus_min(code)
  19770. case 60: case 62: // '<>'
  19771. return this.readToken_lt_gt(code)
  19772. case 61: case 33: // '=!'
  19773. return this.readToken_eq_excl(code)
  19774. case 63: // '?'
  19775. return this.readToken_question()
  19776. case 126: // '~'
  19777. return this.finishOp(types$1.prefix, 1)
  19778. case 35: // '#'
  19779. return this.readToken_numberSign()
  19780. }
  19781. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19782. };
  19783. pp.finishOp = function(type, size) {
  19784. var str = this.input.slice(this.pos, this.pos + size);
  19785. this.pos += size;
  19786. return this.finishToken(type, str)
  19787. };
  19788. pp.readRegexp = function() {
  19789. var escaped, inClass, start = this.pos;
  19790. for (;;) {
  19791. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19792. var ch = this.input.charAt(this.pos);
  19793. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19794. if (!escaped) {
  19795. if (ch === "[") { inClass = true; }
  19796. else if (ch === "]" && inClass) { inClass = false; }
  19797. else if (ch === "/" && !inClass) { break }
  19798. escaped = ch === "\\";
  19799. } else { escaped = false; }
  19800. ++this.pos;
  19801. }
  19802. var pattern = this.input.slice(start, this.pos);
  19803. ++this.pos;
  19804. var flagsStart = this.pos;
  19805. var flags = this.readWord1();
  19806. if (this.containsEsc) { this.unexpected(flagsStart); }
  19807. // Validate pattern
  19808. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19809. state.reset(start, pattern, flags);
  19810. this.validateRegExpFlags(state);
  19811. this.validateRegExpPattern(state);
  19812. // Create Literal#value property value.
  19813. var value = null;
  19814. try {
  19815. value = new RegExp(pattern, flags);
  19816. } catch (e) {
  19817. // ESTree requires null if it failed to instantiate RegExp object.
  19818. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19819. }
  19820. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19821. };
  19822. // Read an integer in the given radix. Return null if zero digits
  19823. // were read, the integer value otherwise. When `len` is given, this
  19824. // will return `null` unless the integer has exactly `len` digits.
  19825. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19826. // `len` is used for character escape sequences. In that case, disallow separators.
  19827. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19828. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19829. // and isn't fraction part nor exponent part. In that case, if the first digit
  19830. // is zero then disallow separators.
  19831. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19832. var start = this.pos, total = 0, lastCode = 0;
  19833. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19834. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19835. if (allowSeparators && code === 95) {
  19836. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19837. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19838. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19839. lastCode = code;
  19840. continue
  19841. }
  19842. if (code >= 97) { val = code - 97 + 10; } // a
  19843. else if (code >= 65) { val = code - 65 + 10; } // A
  19844. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19845. else { val = Infinity; }
  19846. if (val >= radix) { break }
  19847. lastCode = code;
  19848. total = total * radix + val;
  19849. }
  19850. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19851. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19852. return total
  19853. };
  19854. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19855. if (isLegacyOctalNumericLiteral) {
  19856. return parseInt(str, 8)
  19857. }
  19858. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19859. return parseFloat(str.replace(/_/g, ""))
  19860. }
  19861. function stringToBigInt(str) {
  19862. if (typeof BigInt !== "function") {
  19863. return null
  19864. }
  19865. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19866. return BigInt(str.replace(/_/g, ""))
  19867. }
  19868. pp.readRadixNumber = function(radix) {
  19869. var start = this.pos;
  19870. this.pos += 2; // 0x
  19871. var val = this.readInt(radix);
  19872. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19873. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19874. val = stringToBigInt(this.input.slice(start, this.pos));
  19875. ++this.pos;
  19876. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19877. return this.finishToken(types$1.num, val)
  19878. };
  19879. // Read an integer, octal integer, or floating-point number.
  19880. pp.readNumber = function(startsWithDot) {
  19881. var start = this.pos;
  19882. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  19883. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  19884. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  19885. var next = this.input.charCodeAt(this.pos);
  19886. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  19887. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  19888. ++this.pos;
  19889. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19890. return this.finishToken(types$1.num, val$1)
  19891. }
  19892. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  19893. if (next === 46 && !octal) { // '.'
  19894. ++this.pos;
  19895. this.readInt(10);
  19896. next = this.input.charCodeAt(this.pos);
  19897. }
  19898. if ((next === 69 || next === 101) && !octal) { // 'eE'
  19899. next = this.input.charCodeAt(++this.pos);
  19900. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  19901. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  19902. }
  19903. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19904. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  19905. return this.finishToken(types$1.num, val)
  19906. };
  19907. // Read a string value, interpreting backslash-escapes.
  19908. pp.readCodePoint = function() {
  19909. var ch = this.input.charCodeAt(this.pos), code;
  19910. if (ch === 123) { // '{'
  19911. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  19912. var codePos = ++this.pos;
  19913. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  19914. ++this.pos;
  19915. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  19916. } else {
  19917. code = this.readHexChar(4);
  19918. }
  19919. return code
  19920. };
  19921. pp.readString = function(quote) {
  19922. var out = "", chunkStart = ++this.pos;
  19923. for (;;) {
  19924. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  19925. var ch = this.input.charCodeAt(this.pos);
  19926. if (ch === quote) { break }
  19927. if (ch === 92) { // '\'
  19928. out += this.input.slice(chunkStart, this.pos);
  19929. out += this.readEscapedChar(false);
  19930. chunkStart = this.pos;
  19931. } else if (ch === 0x2028 || ch === 0x2029) {
  19932. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  19933. ++this.pos;
  19934. if (this.options.locations) {
  19935. this.curLine++;
  19936. this.lineStart = this.pos;
  19937. }
  19938. } else {
  19939. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  19940. ++this.pos;
  19941. }
  19942. }
  19943. out += this.input.slice(chunkStart, this.pos++);
  19944. return this.finishToken(types$1.string, out)
  19945. };
  19946. // Reads template string tokens.
  19947. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  19948. pp.tryReadTemplateToken = function() {
  19949. this.inTemplateElement = true;
  19950. try {
  19951. this.readTmplToken();
  19952. } catch (err) {
  19953. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  19954. this.readInvalidTemplateToken();
  19955. } else {
  19956. throw err
  19957. }
  19958. }
  19959. this.inTemplateElement = false;
  19960. };
  19961. pp.invalidStringToken = function(position, message) {
  19962. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  19963. throw INVALID_TEMPLATE_ESCAPE_ERROR
  19964. } else {
  19965. this.raise(position, message);
  19966. }
  19967. };
  19968. pp.readTmplToken = function() {
  19969. var out = "", chunkStart = this.pos;
  19970. for (;;) {
  19971. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  19972. var ch = this.input.charCodeAt(this.pos);
  19973. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  19974. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  19975. if (ch === 36) {
  19976. this.pos += 2;
  19977. return this.finishToken(types$1.dollarBraceL)
  19978. } else {
  19979. ++this.pos;
  19980. return this.finishToken(types$1.backQuote)
  19981. }
  19982. }
  19983. out += this.input.slice(chunkStart, this.pos);
  19984. return this.finishToken(types$1.template, out)
  19985. }
  19986. if (ch === 92) { // '\'
  19987. out += this.input.slice(chunkStart, this.pos);
  19988. out += this.readEscapedChar(true);
  19989. chunkStart = this.pos;
  19990. } else if (isNewLine(ch)) {
  19991. out += this.input.slice(chunkStart, this.pos);
  19992. ++this.pos;
  19993. switch (ch) {
  19994. case 13:
  19995. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  19996. case 10:
  19997. out += "\n";
  19998. break
  19999. default:
  20000. out += String.fromCharCode(ch);
  20001. break
  20002. }
  20003. if (this.options.locations) {
  20004. ++this.curLine;
  20005. this.lineStart = this.pos;
  20006. }
  20007. chunkStart = this.pos;
  20008. } else {
  20009. ++this.pos;
  20010. }
  20011. }
  20012. };
  20013. // Reads a template token to search for the end, without validating any escape sequences
  20014. pp.readInvalidTemplateToken = function() {
  20015. for (; this.pos < this.input.length; this.pos++) {
  20016. switch (this.input[this.pos]) {
  20017. case "\\":
  20018. ++this.pos;
  20019. break
  20020. case "$":
  20021. if (this.input[this.pos + 1] !== "{") {
  20022. break
  20023. }
  20024. // falls through
  20025. case "`":
  20026. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  20027. // no default
  20028. }
  20029. }
  20030. this.raise(this.start, "Unterminated template");
  20031. };
  20032. // Used to read escaped characters
  20033. pp.readEscapedChar = function(inTemplate) {
  20034. var ch = this.input.charCodeAt(++this.pos);
  20035. ++this.pos;
  20036. switch (ch) {
  20037. case 110: return "\n" // 'n' -> '\n'
  20038. case 114: return "\r" // 'r' -> '\r'
  20039. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  20040. case 117: return codePointToString(this.readCodePoint()) // 'u'
  20041. case 116: return "\t" // 't' -> '\t'
  20042. case 98: return "\b" // 'b' -> '\b'
  20043. case 118: return "\u000b" // 'v' -> '\u000b'
  20044. case 102: return "\f" // 'f' -> '\f'
  20045. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  20046. case 10: // ' \n'
  20047. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  20048. return ""
  20049. case 56:
  20050. case 57:
  20051. if (this.strict) {
  20052. this.invalidStringToken(
  20053. this.pos - 1,
  20054. "Invalid escape sequence"
  20055. );
  20056. }
  20057. if (inTemplate) {
  20058. var codePos = this.pos - 1;
  20059. this.invalidStringToken(
  20060. codePos,
  20061. "Invalid escape sequence in template string"
  20062. );
  20063. return null
  20064. }
  20065. default:
  20066. if (ch >= 48 && ch <= 55) {
  20067. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  20068. var octal = parseInt(octalStr, 8);
  20069. if (octal > 255) {
  20070. octalStr = octalStr.slice(0, -1);
  20071. octal = parseInt(octalStr, 8);
  20072. }
  20073. this.pos += octalStr.length - 1;
  20074. ch = this.input.charCodeAt(this.pos);
  20075. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  20076. this.invalidStringToken(
  20077. this.pos - 1 - octalStr.length,
  20078. inTemplate
  20079. ? "Octal literal in template string"
  20080. : "Octal literal in strict mode"
  20081. );
  20082. }
  20083. return String.fromCharCode(octal)
  20084. }
  20085. if (isNewLine(ch)) {
  20086. // Unicode new line characters after \ get removed from output in both
  20087. // template literals and strings
  20088. return ""
  20089. }
  20090. return String.fromCharCode(ch)
  20091. }
  20092. };
  20093. // Used to read character escape sequences ('\x', '\u', '\U').
  20094. pp.readHexChar = function(len) {
  20095. var codePos = this.pos;
  20096. var n = this.readInt(16, len);
  20097. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  20098. return n
  20099. };
  20100. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  20101. // to whether the word contained a '\u' escape.
  20102. //
  20103. // Incrementally adds only escaped chars, adding other chunks as-is
  20104. // as a micro-optimization.
  20105. pp.readWord1 = function() {
  20106. this.containsEsc = false;
  20107. var word = "", first = true, chunkStart = this.pos;
  20108. var astral = this.options.ecmaVersion >= 6;
  20109. while (this.pos < this.input.length) {
  20110. var ch = this.fullCharCodeAtPos();
  20111. if (isIdentifierChar(ch, astral)) {
  20112. this.pos += ch <= 0xffff ? 1 : 2;
  20113. } else if (ch === 92) { // "\"
  20114. this.containsEsc = true;
  20115. word += this.input.slice(chunkStart, this.pos);
  20116. var escStart = this.pos;
  20117. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  20118. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  20119. ++this.pos;
  20120. var esc = this.readCodePoint();
  20121. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  20122. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  20123. word += codePointToString(esc);
  20124. chunkStart = this.pos;
  20125. } else {
  20126. break
  20127. }
  20128. first = false;
  20129. }
  20130. return word + this.input.slice(chunkStart, this.pos)
  20131. };
  20132. // Read an identifier or keyword token. Will check for reserved
  20133. // words when necessary.
  20134. pp.readWord = function() {
  20135. var word = this.readWord1();
  20136. var type = types$1.name;
  20137. if (this.keywords.test(word)) {
  20138. type = keywords[word];
  20139. }
  20140. return this.finishToken(type, word)
  20141. };
  20142. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  20143. var version = "8.7.1";
  20144. Parser.acorn = {
  20145. Parser: Parser,
  20146. version: version,
  20147. defaultOptions: defaultOptions,
  20148. Position: Position,
  20149. SourceLocation: SourceLocation,
  20150. getLineInfo: getLineInfo,
  20151. Node: Node,
  20152. TokenType: TokenType,
  20153. tokTypes: types$1,
  20154. keywordTypes: keywords,
  20155. TokContext: TokContext,
  20156. tokContexts: types,
  20157. isIdentifierChar: isIdentifierChar,
  20158. isIdentifierStart: isIdentifierStart,
  20159. Token: Token,
  20160. isNewLine: isNewLine,
  20161. lineBreak: lineBreak,
  20162. lineBreakG: lineBreakG,
  20163. nonASCIIwhitespace: nonASCIIwhitespace
  20164. };
  20165. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20166. let skipped = null;
  20167. let replaceContext = null;
  20168. if (skip) {
  20169. skipped = new Set();
  20170. for (const skippedCall of skip) {
  20171. if (source === skippedCall.source && importer === skippedCall.importer) {
  20172. skipped.add(skippedCall.plugin);
  20173. }
  20174. }
  20175. replaceContext = (pluginContext, plugin) => ({
  20176. ...pluginContext,
  20177. resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
  20178. return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20179. }
  20180. });
  20181. }
  20182. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
  20183. }
  20184. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20185. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
  20186. if (pluginResult != null)
  20187. return pluginResult;
  20188. // external modules (non-entry modules that start with neither '.' or '/')
  20189. // are skipped at this stage.
  20190. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  20191. return null;
  20192. // `resolve` processes paths from right to left, prepending them until an
  20193. // absolute path is created. Absolute importees therefore shortcircuit the
  20194. // resolve call and require no special handing on our part.
  20195. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20196. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  20197. }
  20198. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20199. var _a, _b;
  20200. return ((_b = (_a = (await findFile(file, preserveSymlinks))) !== null && _a !== void 0 ? _a : (await findFile(file + '.mjs', preserveSymlinks))) !== null && _b !== void 0 ? _b : (await findFile(file + '.js', preserveSymlinks)));
  20201. }
  20202. async function findFile(file, preserveSymlinks) {
  20203. try {
  20204. const stats = await promises.lstat(file);
  20205. if (!preserveSymlinks && stats.isSymbolicLink())
  20206. return await findFile(await promises.realpath(file), preserveSymlinks);
  20207. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20208. // check case
  20209. const name = basename(file);
  20210. const files = await promises.readdir(dirname(file));
  20211. if (files.includes(name))
  20212. return file;
  20213. }
  20214. }
  20215. catch (_a) {
  20216. // suppress
  20217. }
  20218. }
  20219. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20220. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20221. function throwPluginError(err, plugin, { hook, id } = {}) {
  20222. if (typeof err === 'string')
  20223. err = { message: err };
  20224. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  20225. err.pluginCode = err.code;
  20226. }
  20227. err.code = Errors.PLUGIN_ERROR;
  20228. err.plugin = plugin;
  20229. if (hook) {
  20230. err.hook = hook;
  20231. }
  20232. if (id) {
  20233. err.id = id;
  20234. }
  20235. return error(err);
  20236. }
  20237. const deprecatedHooks = [
  20238. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  20239. ];
  20240. function warnDeprecatedHooks(plugins, options) {
  20241. for (const { active, deprecated, replacement } of deprecatedHooks) {
  20242. for (const plugin of plugins) {
  20243. if (deprecated in plugin) {
  20244. warnDeprecation({
  20245. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  20246. plugin: plugin.name
  20247. }, active, options);
  20248. }
  20249. }
  20250. }
  20251. }
  20252. function createPluginCache(cache) {
  20253. return {
  20254. delete(id) {
  20255. return delete cache[id];
  20256. },
  20257. get(id) {
  20258. const item = cache[id];
  20259. if (!item)
  20260. return undefined;
  20261. item[0] = 0;
  20262. return item[1];
  20263. },
  20264. has(id) {
  20265. const item = cache[id];
  20266. if (!item)
  20267. return false;
  20268. item[0] = 0;
  20269. return true;
  20270. },
  20271. set(id, value) {
  20272. cache[id] = [0, value];
  20273. }
  20274. };
  20275. }
  20276. function getTrackedPluginCache(pluginCache, onUse) {
  20277. return {
  20278. delete(id) {
  20279. onUse();
  20280. return pluginCache.delete(id);
  20281. },
  20282. get(id) {
  20283. onUse();
  20284. return pluginCache.get(id);
  20285. },
  20286. has(id) {
  20287. onUse();
  20288. return pluginCache.has(id);
  20289. },
  20290. set(id, value) {
  20291. onUse();
  20292. return pluginCache.set(id, value);
  20293. }
  20294. };
  20295. }
  20296. const NO_CACHE = {
  20297. delete() {
  20298. return false;
  20299. },
  20300. get() {
  20301. return undefined;
  20302. },
  20303. has() {
  20304. return false;
  20305. },
  20306. set() { }
  20307. };
  20308. function uncacheablePluginError(pluginName) {
  20309. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20310. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20311. return error({
  20312. code: 'ANONYMOUS_PLUGIN_CACHE',
  20313. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  20314. });
  20315. }
  20316. return error({
  20317. code: 'DUPLICATE_PLUGIN_NAME',
  20318. message: `The plugin name ${pluginName} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
  20319. });
  20320. }
  20321. function getCacheForUncacheablePlugin(pluginName) {
  20322. return {
  20323. delete() {
  20324. return uncacheablePluginError(pluginName);
  20325. },
  20326. get() {
  20327. return uncacheablePluginError(pluginName);
  20328. },
  20329. has() {
  20330. return uncacheablePluginError(pluginName);
  20331. },
  20332. set() {
  20333. return uncacheablePluginError(pluginName);
  20334. }
  20335. };
  20336. }
  20337. async function transform(source, module, pluginDriver, warn) {
  20338. const id = module.id;
  20339. const sourcemapChain = [];
  20340. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20341. const originalCode = source.code;
  20342. let ast = source.ast;
  20343. const transformDependencies = [];
  20344. const emittedFiles = [];
  20345. let customTransformCache = false;
  20346. const useCustomTransformCache = () => (customTransformCache = true);
  20347. let pluginName = '';
  20348. const curSource = source.code;
  20349. function transformReducer(previousCode, result, plugin) {
  20350. let code;
  20351. let map;
  20352. if (typeof result === 'string') {
  20353. code = result;
  20354. }
  20355. else if (result && typeof result === 'object') {
  20356. module.updateOptions(result);
  20357. if (result.code == null) {
  20358. if (result.map || result.ast) {
  20359. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  20360. }
  20361. return previousCode;
  20362. }
  20363. ({ code, map, ast } = result);
  20364. }
  20365. else {
  20366. return previousCode;
  20367. }
  20368. // strict null check allows 'null' maps to not be pushed to the chain,
  20369. // while 'undefined' gets the missing map warning
  20370. if (map !== null) {
  20371. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20372. missing: true,
  20373. plugin: plugin.name
  20374. });
  20375. }
  20376. return code;
  20377. }
  20378. let code;
  20379. try {
  20380. code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  20381. pluginName = plugin.name;
  20382. return {
  20383. ...pluginContext,
  20384. addWatchFile(id) {
  20385. transformDependencies.push(id);
  20386. pluginContext.addWatchFile(id);
  20387. },
  20388. cache: customTransformCache
  20389. ? pluginContext.cache
  20390. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20391. emitAsset(name, source) {
  20392. emittedFiles.push({ name, source, type: 'asset' });
  20393. return pluginContext.emitAsset(name, source);
  20394. },
  20395. emitChunk(id, options) {
  20396. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  20397. return pluginContext.emitChunk(id, options);
  20398. },
  20399. emitFile(emittedFile) {
  20400. emittedFiles.push(emittedFile);
  20401. return pluginDriver.emitFile(emittedFile);
  20402. },
  20403. error(err, pos) {
  20404. if (typeof err === 'string')
  20405. err = { message: err };
  20406. if (pos)
  20407. augmentCodeLocation(err, pos, curSource, id);
  20408. err.id = id;
  20409. err.hook = 'transform';
  20410. return pluginContext.error(err);
  20411. },
  20412. getCombinedSourcemap() {
  20413. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  20414. if (!combinedMap) {
  20415. const magicString = new MagicString(originalCode);
  20416. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20417. }
  20418. if (originalSourcemap !== combinedMap) {
  20419. originalSourcemap = combinedMap;
  20420. sourcemapChain.length = 0;
  20421. }
  20422. return new SourceMap({
  20423. ...combinedMap,
  20424. file: null,
  20425. sourcesContent: combinedMap.sourcesContent
  20426. });
  20427. },
  20428. setAssetSource() {
  20429. return this.error({
  20430. code: 'INVALID_SETASSETSOURCE',
  20431. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  20432. });
  20433. },
  20434. warn(warning, pos) {
  20435. if (typeof warning === 'string')
  20436. warning = { message: warning };
  20437. if (pos)
  20438. augmentCodeLocation(warning, pos, curSource, id);
  20439. warning.id = id;
  20440. warning.hook = 'transform';
  20441. pluginContext.warn(warning);
  20442. }
  20443. };
  20444. });
  20445. }
  20446. catch (err) {
  20447. throwPluginError(err, pluginName, { hook: 'transform', id });
  20448. }
  20449. if (!customTransformCache) {
  20450. // files emitted by a transform hook need to be emitted again if the hook is skipped
  20451. if (emittedFiles.length)
  20452. module.transformFiles = emittedFiles;
  20453. }
  20454. return {
  20455. ast,
  20456. code,
  20457. customTransformCache,
  20458. originalCode,
  20459. originalSourcemap,
  20460. sourcemapChain,
  20461. transformDependencies
  20462. };
  20463. }
  20464. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20465. class ModuleLoader {
  20466. constructor(graph, modulesById, options, pluginDriver) {
  20467. this.graph = graph;
  20468. this.modulesById = modulesById;
  20469. this.options = options;
  20470. this.pluginDriver = pluginDriver;
  20471. this.implicitEntryModules = new Set();
  20472. this.indexedEntryModules = [];
  20473. this.latestLoadModulesPromise = Promise.resolve();
  20474. this.moduleLoadPromises = new Map();
  20475. this.modulesWithLoadedDependencies = new Set();
  20476. this.nextChunkNamePriority = 0;
  20477. this.nextEntryModuleIndex = 0;
  20478. this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
  20479. return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20480. ? false
  20481. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
  20482. };
  20483. this.hasModuleSideEffects = options.treeshake
  20484. ? options.treeshake.moduleSideEffects
  20485. : () => true;
  20486. }
  20487. async addAdditionalModules(unresolvedModules) {
  20488. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  20489. await this.awaitLoadModulesPromise();
  20490. return result;
  20491. }
  20492. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20493. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20494. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20495. const firstChunkNamePriority = this.nextChunkNamePriority;
  20496. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20497. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20498. for (let index = 0; index < entryModules.length; index++) {
  20499. const entryModule = entryModules[index];
  20500. entryModule.isUserDefinedEntryPoint =
  20501. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20502. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20503. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20504. if (!existingIndexedModule) {
  20505. this.indexedEntryModules.push({
  20506. index: firstEntryModuleIndex + index,
  20507. module: entryModule
  20508. });
  20509. }
  20510. else {
  20511. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20512. }
  20513. }
  20514. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20515. return entryModules;
  20516. }));
  20517. await this.awaitLoadModulesPromise();
  20518. return {
  20519. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20520. implicitEntryModules: [...this.implicitEntryModules],
  20521. newEntryModules
  20522. };
  20523. }
  20524. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20525. const unresolvedModule = {
  20526. fileName: fileName || null,
  20527. id,
  20528. importer,
  20529. name: name || null
  20530. };
  20531. const module = implicitlyLoadedAfterOneOf
  20532. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20533. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20534. if (preserveSignature != null) {
  20535. module.preserveSignature = preserveSignature;
  20536. }
  20537. return module;
  20538. }
  20539. async preloadModule(resolvedId) {
  20540. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20541. return module.info;
  20542. }
  20543. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20544. const chunkNamePriority = this.nextChunkNamePriority++;
  20545. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20546. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20547. if (!entryModule.info.isEntry) {
  20548. this.implicitEntryModules.add(entryModule);
  20549. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20550. for (const module of implicitlyLoadedAfterModules) {
  20551. entryModule.implicitlyLoadedAfter.add(module);
  20552. }
  20553. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20554. dependant.implicitlyLoadedBefore.add(entryModule);
  20555. }
  20556. }
  20557. return entryModule;
  20558. }));
  20559. }
  20560. async addModuleSource(id, importer, module) {
  20561. timeStart('load modules', 3);
  20562. let source;
  20563. try {
  20564. source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await promises.readFile(id, 'utf8')); });
  20565. }
  20566. catch (err) {
  20567. timeEnd('load modules', 3);
  20568. let msg = `Could not load ${id}`;
  20569. if (importer)
  20570. msg += ` (imported by ${relativeId(importer)})`;
  20571. msg += `: ${err.message}`;
  20572. err.message = msg;
  20573. throw err;
  20574. }
  20575. timeEnd('load modules', 3);
  20576. const sourceDescription = typeof source === 'string'
  20577. ? { code: source }
  20578. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20579. ? source
  20580. : error(errBadLoader(id));
  20581. const cachedModule = this.graph.cachedModules.get(id);
  20582. if (cachedModule &&
  20583. !cachedModule.customTransformCache &&
  20584. cachedModule.originalCode === sourceDescription.code &&
  20585. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20586. {
  20587. ast: cachedModule.ast,
  20588. code: cachedModule.code,
  20589. id: cachedModule.id,
  20590. meta: cachedModule.meta,
  20591. moduleSideEffects: cachedModule.moduleSideEffects,
  20592. resolvedSources: cachedModule.resolvedIds,
  20593. syntheticNamedExports: cachedModule.syntheticNamedExports
  20594. }
  20595. ]))) {
  20596. if (cachedModule.transformFiles) {
  20597. for (const emittedFile of cachedModule.transformFiles)
  20598. this.pluginDriver.emitFile(emittedFile);
  20599. }
  20600. module.setSource(cachedModule);
  20601. }
  20602. else {
  20603. module.updateOptions(sourceDescription);
  20604. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  20605. }
  20606. }
  20607. async awaitLoadModulesPromise() {
  20608. let startingPromise;
  20609. do {
  20610. startingPromise = this.latestLoadModulesPromise;
  20611. await startingPromise;
  20612. } while (startingPromise !== this.latestLoadModulesPromise);
  20613. }
  20614. extendLoadModulesPromise(loadNewModulesPromise) {
  20615. this.latestLoadModulesPromise = Promise.all([
  20616. loadNewModulesPromise,
  20617. this.latestLoadModulesPromise
  20618. ]);
  20619. this.latestLoadModulesPromise.catch(() => {
  20620. /* Avoid unhandled Promise rejections */
  20621. });
  20622. return loadNewModulesPromise;
  20623. }
  20624. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20625. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20626. if (resolvedId === null)
  20627. return null;
  20628. if (typeof resolvedId === 'string') {
  20629. dynamicImport.resolution = resolvedId;
  20630. return null;
  20631. }
  20632. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20633. })));
  20634. for (const dependency of dependencies) {
  20635. if (dependency) {
  20636. module.dynamicDependencies.add(dependency);
  20637. dependency.dynamicImporters.push(module.id);
  20638. }
  20639. }
  20640. }
  20641. // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
  20642. // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
  20643. // Otherwise it returns immediately.
  20644. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20645. const existingModule = this.modulesById.get(id);
  20646. if (existingModule instanceof Module) {
  20647. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20648. return existingModule;
  20649. }
  20650. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  20651. this.modulesById.set(id, module);
  20652. this.graph.watchFiles[id] = true;
  20653. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20654. this.getResolveStaticDependencyPromises(module),
  20655. this.getResolveDynamicImportPromises(module),
  20656. loadAndResolveDependenciesPromise
  20657. ]);
  20658. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20659. loadAndResolveDependenciesPromise.catch(() => {
  20660. /* avoid unhandled promise rejections */
  20661. });
  20662. this.moduleLoadPromises.set(module, loadPromise);
  20663. const resolveDependencyPromises = await loadPromise;
  20664. if (!isPreload) {
  20665. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20666. }
  20667. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20668. await loadAndResolveDependenciesPromise;
  20669. }
  20670. return module;
  20671. }
  20672. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20673. if (this.modulesWithLoadedDependencies.has(module)) {
  20674. return;
  20675. }
  20676. this.modulesWithLoadedDependencies.add(module);
  20677. await Promise.all([
  20678. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20679. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20680. ]);
  20681. module.linkImports();
  20682. // To handle errors when resolving dependencies or in moduleParsed
  20683. await loadAndResolveDependenciesPromise;
  20684. }
  20685. fetchResolvedDependency(source, importer, resolvedId) {
  20686. if (resolvedId.external) {
  20687. const { external, id, moduleSideEffects, meta } = resolvedId;
  20688. if (!this.modulesById.has(id)) {
  20689. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  20690. }
  20691. const externalModule = this.modulesById.get(id);
  20692. if (!(externalModule instanceof ExternalModule)) {
  20693. return error(errInternalIdCannotBeExternal(source, importer));
  20694. }
  20695. return Promise.resolve(externalModule);
  20696. }
  20697. return this.fetchModule(resolvedId, importer, false, false);
  20698. }
  20699. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20700. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20701. module.dependencies.add(dependency);
  20702. dependency.importers.push(module.id);
  20703. }
  20704. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20705. for (const dependency of module.dependencies) {
  20706. if (dependency instanceof Module) {
  20707. dependency.importedFromNotTreeshaken = true;
  20708. }
  20709. }
  20710. }
  20711. }
  20712. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20713. const { makeAbsoluteExternalsRelative } = this.options;
  20714. if (resolveIdResult) {
  20715. if (typeof resolveIdResult === 'object') {
  20716. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20717. return {
  20718. ...resolveIdResult,
  20719. external: external &&
  20720. (external === 'relative' ||
  20721. !isAbsolute(resolveIdResult.id) ||
  20722. (external === true &&
  20723. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20724. 'absolute')
  20725. };
  20726. }
  20727. const external = this.options.external(resolveIdResult, importer, true);
  20728. return {
  20729. external: external &&
  20730. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20731. 'absolute'),
  20732. id: external && makeAbsoluteExternalsRelative
  20733. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20734. : resolveIdResult
  20735. };
  20736. }
  20737. const id = makeAbsoluteExternalsRelative
  20738. ? normalizeRelativeExternalId(source, importer)
  20739. : source;
  20740. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20741. return null;
  20742. }
  20743. return {
  20744. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20745. id
  20746. };
  20747. }
  20748. getResolveDynamicImportPromises(module) {
  20749. return module.dynamicImports.map(async (dynamicImport) => {
  20750. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  20751. ? dynamicImport.argument
  20752. : dynamicImport.argument.esTreeNode, module.id);
  20753. if (resolvedId && typeof resolvedId === 'object') {
  20754. dynamicImport.id = resolvedId.id;
  20755. }
  20756. return [dynamicImport, resolvedId];
  20757. });
  20758. }
  20759. getResolveStaticDependencyPromises(module) {
  20760. return Array.from(module.sources, async (source) => [
  20761. source,
  20762. (module.resolvedIds[source] =
  20763. module.resolvedIds[source] ||
  20764. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
  20765. ]);
  20766. }
  20767. getResolvedIdWithDefaults(resolvedId) {
  20768. var _a, _b;
  20769. if (!resolvedId) {
  20770. return null;
  20771. }
  20772. const external = resolvedId.external || false;
  20773. return {
  20774. external,
  20775. id: resolvedId.id,
  20776. meta: resolvedId.meta || {},
  20777. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  20778. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  20779. };
  20780. }
  20781. async handleExistingModule(module, isEntry, isPreload) {
  20782. const loadPromise = this.moduleLoadPromises.get(module);
  20783. if (isPreload) {
  20784. return isPreload === RESOLVE_DEPENDENCIES
  20785. ? waitForDependencyResolution(loadPromise)
  20786. : loadPromise;
  20787. }
  20788. if (isEntry) {
  20789. module.info.isEntry = true;
  20790. this.implicitEntryModules.delete(module);
  20791. for (const dependant of module.implicitlyLoadedAfter) {
  20792. dependant.implicitlyLoadedBefore.delete(module);
  20793. }
  20794. module.implicitlyLoadedAfter.clear();
  20795. }
  20796. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20797. }
  20798. handleResolveId(resolvedId, source, importer) {
  20799. if (resolvedId === null) {
  20800. if (isRelative(source)) {
  20801. return error(errUnresolvedImport(source, importer));
  20802. }
  20803. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  20804. return {
  20805. external: true,
  20806. id: source,
  20807. meta: {},
  20808. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20809. syntheticNamedExports: false
  20810. };
  20811. }
  20812. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20813. this.options.onwarn(errExternalSyntheticExports(source, importer));
  20814. }
  20815. return resolvedId;
  20816. }
  20817. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  20818. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
  20819. if (resolveIdResult == null) {
  20820. return error(implicitlyLoadedBefore === null
  20821. ? errUnresolvedEntry(unresolvedId)
  20822. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20823. }
  20824. if (resolveIdResult === false ||
  20825. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  20826. return error(implicitlyLoadedBefore === null
  20827. ? errEntryCannotBeExternal(unresolvedId)
  20828. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20829. }
  20830. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20831. ? resolveIdResult
  20832. : { id: resolveIdResult }), undefined, isEntry, false);
  20833. }
  20834. async resolveDynamicImport(module, specifier, importer) {
  20835. var _a;
  20836. var _b;
  20837. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20838. specifier,
  20839. importer
  20840. ]);
  20841. if (typeof specifier !== 'string') {
  20842. if (typeof resolution === 'string') {
  20843. return resolution;
  20844. }
  20845. if (!resolution) {
  20846. return null;
  20847. }
  20848. return {
  20849. external: false,
  20850. moduleSideEffects: true,
  20851. ...resolution
  20852. };
  20853. }
  20854. if (resolution == null) {
  20855. return ((_a = (_b = module.resolvedIds)[specifier]) !== null && _a !== void 0 ? _a : (_b[specifier] = this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false), specifier, module.id)));
  20856. }
  20857. return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  20858. }
  20859. }
  20860. function normalizeRelativeExternalId(source, importer) {
  20861. return isRelative(source)
  20862. ? importer
  20863. ? resolve(importer, '..', source)
  20864. : resolve(source)
  20865. : source;
  20866. }
  20867. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20868. var _a;
  20869. if (fileName !== null) {
  20870. module.chunkFileNames.add(fileName);
  20871. }
  20872. else if (name !== null) {
  20873. // Always keep chunkNames sorted by priority
  20874. let namePosition = 0;
  20875. while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
  20876. namePosition++;
  20877. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20878. }
  20879. }
  20880. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20881. return (makeAbsoluteExternalsRelative === true ||
  20882. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20883. !isAbsolute(id));
  20884. }
  20885. async function waitForDependencyResolution(loadPromise) {
  20886. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20887. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20888. }
  20889. class GlobalScope extends Scope$1 {
  20890. constructor() {
  20891. super();
  20892. this.parent = null;
  20893. this.variables.set('undefined', new UndefinedVariable());
  20894. }
  20895. findVariable(name) {
  20896. let variable = this.variables.get(name);
  20897. if (!variable) {
  20898. variable = new GlobalVariable(name);
  20899. this.variables.set(name, variable);
  20900. }
  20901. return variable;
  20902. }
  20903. }
  20904. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  20905. let deprecationWarningShown = false;
  20906. return ((...args) => {
  20907. if (!deprecationWarningShown) {
  20908. deprecationWarningShown = true;
  20909. warnDeprecation({
  20910. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  20911. plugin: pluginName
  20912. }, activeDeprecation, options);
  20913. }
  20914. return handler(...args);
  20915. });
  20916. }
  20917. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  20918. let cacheable = true;
  20919. if (typeof plugin.cacheKey !== 'string') {
  20920. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20921. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  20922. existingPluginNames.has(plugin.name)) {
  20923. cacheable = false;
  20924. }
  20925. else {
  20926. existingPluginNames.add(plugin.name);
  20927. }
  20928. }
  20929. let cacheInstance;
  20930. if (!pluginCache) {
  20931. cacheInstance = NO_CACHE;
  20932. }
  20933. else if (cacheable) {
  20934. const cacheKey = plugin.cacheKey || plugin.name;
  20935. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  20936. }
  20937. else {
  20938. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  20939. }
  20940. const context = {
  20941. addWatchFile(id) {
  20942. if (graph.phase >= BuildPhase.GENERATE) {
  20943. return this.error(errInvalidRollupPhaseForAddWatchFile());
  20944. }
  20945. graph.watchFiles[id] = true;
  20946. },
  20947. cache: cacheInstance,
  20948. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  20949. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  20950. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  20951. error(err) {
  20952. return throwPluginError(err, plugin.name);
  20953. },
  20954. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  20955. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  20956. getFileName: fileEmitter.getFileName,
  20957. getModuleIds: () => graph.modulesById.keys(),
  20958. getModuleInfo: graph.getModuleInfo,
  20959. getWatchFiles: () => Object.keys(graph.watchFiles),
  20960. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  20961. load(resolvedId) {
  20962. return graph.moduleLoader.preloadModule(resolvedId);
  20963. },
  20964. meta: {
  20965. rollupVersion: version$1,
  20966. watchMode: graph.watchMode
  20967. },
  20968. get moduleIds() {
  20969. function* wrappedModuleIds() {
  20970. // We are wrapping this in a generator to only show the message once we are actually iterating
  20971. warnDeprecation({
  20972. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  20973. plugin: plugin.name
  20974. }, false, options);
  20975. yield* moduleIds;
  20976. }
  20977. const moduleIds = graph.modulesById.keys();
  20978. return wrappedModuleIds();
  20979. },
  20980. parse: graph.contextParse.bind(graph),
  20981. resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
  20982. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
  20983. },
  20984. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  20985. .resolveId(source, importer, BLANK, undefined)
  20986. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  20987. setAssetSource: fileEmitter.setAssetSource,
  20988. warn(warning) {
  20989. if (typeof warning === 'string')
  20990. warning = { message: warning };
  20991. if (warning.code)
  20992. warning.pluginCode = warning.code;
  20993. warning.code = 'PLUGIN_WARNING';
  20994. warning.plugin = plugin.name;
  20995. options.onwarn(warning);
  20996. }
  20997. };
  20998. return context;
  20999. }
  21000. const inputHookNames = {
  21001. buildEnd: 1,
  21002. buildStart: 1,
  21003. closeBundle: 1,
  21004. closeWatcher: 1,
  21005. load: 1,
  21006. moduleParsed: 1,
  21007. options: 1,
  21008. resolveDynamicImport: 1,
  21009. resolveId: 1,
  21010. shouldTransformCachedModule: 1,
  21011. transform: 1,
  21012. watchChange: 1
  21013. };
  21014. const inputHooks = Object.keys(inputHookNames);
  21015. function throwInvalidHookError(hookName, pluginName) {
  21016. return error({
  21017. code: 'INVALID_PLUGIN_HOOK',
  21018. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  21019. });
  21020. }
  21021. class PluginDriver {
  21022. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21023. this.graph = graph;
  21024. this.options = options;
  21025. this.unfulfilledActions = new Set();
  21026. warnDeprecatedHooks(userPlugins, options);
  21027. this.pluginCache = pluginCache;
  21028. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21029. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21030. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21031. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  21032. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21033. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  21034. const existingPluginNames = new Set();
  21035. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21036. plugin,
  21037. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21038. ]));
  21039. if (basePluginDriver) {
  21040. for (const plugin of userPlugins) {
  21041. for (const hook of inputHooks) {
  21042. if (hook in plugin) {
  21043. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  21044. }
  21045. }
  21046. }
  21047. }
  21048. }
  21049. createOutputPluginDriver(plugins) {
  21050. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21051. }
  21052. getUnfulfilledHookActions() {
  21053. return this.unfulfilledActions;
  21054. }
  21055. // chains, first non-null result stops and returns
  21056. hookFirst(hookName, args, replaceContext, skipped) {
  21057. let promise = Promise.resolve(undefined);
  21058. for (const plugin of this.plugins) {
  21059. if (skipped && skipped.has(plugin))
  21060. continue;
  21061. promise = promise.then(result => {
  21062. if (result != null)
  21063. return result;
  21064. return this.runHook(hookName, args, plugin, false, replaceContext);
  21065. });
  21066. }
  21067. return promise;
  21068. }
  21069. // chains synchronously, first non-null result stops and returns
  21070. hookFirstSync(hookName, args, replaceContext) {
  21071. for (const plugin of this.plugins) {
  21072. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21073. if (result != null)
  21074. return result;
  21075. }
  21076. return null;
  21077. }
  21078. // parallel, ignores returns
  21079. hookParallel(hookName, args, replaceContext) {
  21080. const promises = [];
  21081. for (const plugin of this.plugins) {
  21082. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  21083. if (!hookPromise)
  21084. continue;
  21085. promises.push(hookPromise);
  21086. }
  21087. return Promise.all(promises).then(() => { });
  21088. }
  21089. // chains, reduces returned value, handling the reduced value as the first hook argument
  21090. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  21091. let promise = Promise.resolve(arg0);
  21092. for (const plugin of this.plugins) {
  21093. promise = promise.then(arg0 => {
  21094. const args = [arg0, ...rest];
  21095. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  21096. if (!hookPromise)
  21097. return arg0;
  21098. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
  21099. });
  21100. }
  21101. return promise;
  21102. }
  21103. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21104. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  21105. for (const plugin of this.plugins) {
  21106. const args = [arg0, ...rest];
  21107. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21108. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  21109. }
  21110. return arg0;
  21111. }
  21112. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21113. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  21114. let promise = Promise.resolve(initialValue);
  21115. for (const plugin of this.plugins) {
  21116. promise = promise.then(value => {
  21117. const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
  21118. if (!hookPromise)
  21119. return value;
  21120. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
  21121. });
  21122. }
  21123. return promise;
  21124. }
  21125. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21126. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  21127. let acc = initialValue;
  21128. for (const plugin of this.plugins) {
  21129. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21130. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  21131. }
  21132. return acc;
  21133. }
  21134. // chains, ignores returns
  21135. hookSeq(hookName, args, replaceContext) {
  21136. let promise = Promise.resolve();
  21137. for (const plugin of this.plugins) {
  21138. promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
  21139. }
  21140. return promise;
  21141. }
  21142. runHook(hookName, args, plugin, permitValues, hookContext) {
  21143. const hook = plugin[hookName];
  21144. if (!hook)
  21145. return undefined;
  21146. let context = this.pluginContexts.get(plugin);
  21147. if (hookContext) {
  21148. context = hookContext(context, plugin);
  21149. }
  21150. let action = null;
  21151. return Promise.resolve()
  21152. .then(() => {
  21153. // permit values allows values to be returned instead of a functional hook
  21154. if (typeof hook !== 'function') {
  21155. if (permitValues)
  21156. return hook;
  21157. return throwInvalidHookError(hookName, plugin.name);
  21158. }
  21159. // eslint-disable-next-line @typescript-eslint/ban-types
  21160. const hookResult = hook.apply(context, args);
  21161. if (!hookResult || !hookResult.then) {
  21162. // short circuit for non-thenables and non-Promises
  21163. return hookResult;
  21164. }
  21165. // Track pending hook actions to properly error out when
  21166. // unfulfilled promises cause rollup to abruptly and confusingly
  21167. // exit with a successful 0 return code but without producing any
  21168. // output, errors or warnings.
  21169. action = [plugin.name, hookName, args];
  21170. this.unfulfilledActions.add(action);
  21171. // Although it would be more elegant to just return hookResult here
  21172. // and put the .then() handler just above the .catch() handler below,
  21173. // doing so would subtly change the defacto async event dispatch order
  21174. // which at least one test and some plugins in the wild may depend on.
  21175. return Promise.resolve(hookResult).then(result => {
  21176. // action was fulfilled
  21177. this.unfulfilledActions.delete(action);
  21178. return result;
  21179. });
  21180. })
  21181. .catch(err => {
  21182. if (action !== null) {
  21183. // action considered to be fulfilled since error being handled
  21184. this.unfulfilledActions.delete(action);
  21185. }
  21186. return throwPluginError(err, plugin.name, { hook: hookName });
  21187. });
  21188. }
  21189. /**
  21190. * Run a sync plugin hook and return the result.
  21191. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21192. * @param args Arguments passed to the plugin hook.
  21193. * @param plugin The acutal plugin
  21194. * @param hookContext When passed, the plugin context can be overridden.
  21195. */
  21196. runHookSync(hookName, args, plugin, hookContext) {
  21197. const hook = plugin[hookName];
  21198. if (!hook)
  21199. return undefined;
  21200. let context = this.pluginContexts.get(plugin);
  21201. if (hookContext) {
  21202. context = hookContext(context, plugin);
  21203. }
  21204. try {
  21205. // permit values allows values to be returned instead of a functional hook
  21206. if (typeof hook !== 'function') {
  21207. return throwInvalidHookError(hookName, plugin.name);
  21208. }
  21209. // eslint-disable-next-line @typescript-eslint/ban-types
  21210. return hook.apply(context, args);
  21211. }
  21212. catch (err) {
  21213. return throwPluginError(err, plugin.name, { hook: hookName });
  21214. }
  21215. }
  21216. }
  21217. class Queue {
  21218. constructor(maxParallel) {
  21219. this.maxParallel = maxParallel;
  21220. this.queue = [];
  21221. this.workerCount = 0;
  21222. }
  21223. run(task) {
  21224. return new Promise((resolve, reject) => {
  21225. this.queue.push({ reject, resolve, task });
  21226. this.work();
  21227. });
  21228. }
  21229. async work() {
  21230. if (this.workerCount >= this.maxParallel)
  21231. return;
  21232. this.workerCount++;
  21233. let entry;
  21234. while ((entry = this.queue.shift())) {
  21235. const { reject, resolve, task } = entry;
  21236. try {
  21237. const result = await task();
  21238. resolve(result);
  21239. }
  21240. catch (err) {
  21241. reject(err);
  21242. }
  21243. }
  21244. this.workerCount--;
  21245. }
  21246. }
  21247. function normalizeEntryModules(entryModules) {
  21248. if (Array.isArray(entryModules)) {
  21249. return entryModules.map(id => ({
  21250. fileName: null,
  21251. id,
  21252. implicitlyLoadedAfter: [],
  21253. importer: undefined,
  21254. name: null
  21255. }));
  21256. }
  21257. return Object.entries(entryModules).map(([name, id]) => ({
  21258. fileName: null,
  21259. id,
  21260. implicitlyLoadedAfter: [],
  21261. importer: undefined,
  21262. name
  21263. }));
  21264. }
  21265. class Graph {
  21266. constructor(options, watcher) {
  21267. var _a, _b;
  21268. this.options = options;
  21269. this.cachedModules = new Map();
  21270. this.deoptimizationTracker = new PathTracker();
  21271. this.entryModules = [];
  21272. this.modulesById = new Map();
  21273. this.needsTreeshakingPass = false;
  21274. this.phase = BuildPhase.LOAD_AND_PARSE;
  21275. this.scope = new GlobalScope();
  21276. this.watchFiles = Object.create(null);
  21277. this.watchMode = false;
  21278. this.externalModules = [];
  21279. this.implicitEntryModules = [];
  21280. this.modules = [];
  21281. this.getModuleInfo = (moduleId) => {
  21282. const foundModule = this.modulesById.get(moduleId);
  21283. if (!foundModule)
  21284. return null;
  21285. return foundModule.info;
  21286. };
  21287. if (options.cache !== false) {
  21288. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  21289. for (const module of options.cache.modules)
  21290. this.cachedModules.set(module.id, module);
  21291. }
  21292. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  21293. // increment access counter
  21294. for (const name in this.pluginCache) {
  21295. const cache = this.pluginCache[name];
  21296. for (const value of Object.values(cache))
  21297. value[0]++;
  21298. }
  21299. }
  21300. if (watcher) {
  21301. this.watchMode = true;
  21302. const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
  21303. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21304. watcher.onCurrentAwaited('change', handleChange);
  21305. watcher.onCurrentAwaited('close', handleClose);
  21306. }
  21307. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21308. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  21309. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21310. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21311. }
  21312. async build() {
  21313. timeStart('generate module graph', 2);
  21314. await this.generateModuleGraph();
  21315. timeEnd('generate module graph', 2);
  21316. timeStart('sort modules', 2);
  21317. this.phase = BuildPhase.ANALYSE;
  21318. this.sortModules();
  21319. timeEnd('sort modules', 2);
  21320. timeStart('mark included statements', 2);
  21321. this.includeStatements();
  21322. timeEnd('mark included statements', 2);
  21323. this.phase = BuildPhase.GENERATE;
  21324. }
  21325. contextParse(code, options = {}) {
  21326. const onCommentOrig = options.onComment;
  21327. const comments = [];
  21328. if (onCommentOrig && typeof onCommentOrig == 'function') {
  21329. options.onComment = (block, text, start, end, ...args) => {
  21330. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  21331. return onCommentOrig.call(options, block, text, start, end, ...args);
  21332. };
  21333. }
  21334. else {
  21335. options.onComment = comments;
  21336. }
  21337. const ast = this.acornParser.parse(code, {
  21338. ...this.options.acorn,
  21339. ...options
  21340. });
  21341. if (typeof onCommentOrig == 'object') {
  21342. onCommentOrig.push(...comments);
  21343. }
  21344. options.onComment = onCommentOrig;
  21345. addAnnotations(comments, ast, code);
  21346. return ast;
  21347. }
  21348. getCache() {
  21349. // handle plugin cache eviction
  21350. for (const name in this.pluginCache) {
  21351. const cache = this.pluginCache[name];
  21352. let allDeleted = true;
  21353. for (const [key, value] of Object.entries(cache)) {
  21354. if (value[0] >= this.options.experimentalCacheExpiry)
  21355. delete cache[key];
  21356. else
  21357. allDeleted = false;
  21358. }
  21359. if (allDeleted)
  21360. delete this.pluginCache[name];
  21361. }
  21362. return {
  21363. modules: this.modules.map(module => module.toJSON()),
  21364. plugins: this.pluginCache
  21365. };
  21366. }
  21367. async generateModuleGraph() {
  21368. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21369. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21370. if (this.entryModules.length === 0) {
  21371. throw new Error('You must supply options.input to rollup');
  21372. }
  21373. for (const module of this.modulesById.values()) {
  21374. if (module instanceof Module) {
  21375. this.modules.push(module);
  21376. }
  21377. else {
  21378. this.externalModules.push(module);
  21379. }
  21380. }
  21381. }
  21382. includeStatements() {
  21383. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21384. markModuleAndImpureDependenciesAsExecuted(module);
  21385. }
  21386. if (this.options.treeshake) {
  21387. let treeshakingPass = 1;
  21388. do {
  21389. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21390. this.needsTreeshakingPass = false;
  21391. for (const module of this.modules) {
  21392. if (module.isExecuted) {
  21393. if (module.info.moduleSideEffects === 'no-treeshake') {
  21394. module.includeAllInBundle();
  21395. }
  21396. else {
  21397. module.include();
  21398. }
  21399. }
  21400. }
  21401. if (treeshakingPass === 1) {
  21402. // We only include exports after the first pass to avoid issues with
  21403. // the TDZ detection logic
  21404. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21405. if (module.preserveSignature !== false) {
  21406. module.includeAllExports(false);
  21407. this.needsTreeshakingPass = true;
  21408. }
  21409. }
  21410. }
  21411. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21412. } while (this.needsTreeshakingPass);
  21413. }
  21414. else {
  21415. for (const module of this.modules)
  21416. module.includeAllInBundle();
  21417. }
  21418. for (const externalModule of this.externalModules)
  21419. externalModule.warnUnusedImports();
  21420. for (const module of this.implicitEntryModules) {
  21421. for (const dependant of module.implicitlyLoadedAfter) {
  21422. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21423. error(errImplicitDependantIsNotIncluded(dependant));
  21424. }
  21425. }
  21426. }
  21427. }
  21428. sortModules() {
  21429. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21430. for (const cyclePath of cyclePaths) {
  21431. this.options.onwarn({
  21432. code: 'CIRCULAR_DEPENDENCY',
  21433. cycle: cyclePath,
  21434. importer: cyclePath[0],
  21435. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  21436. });
  21437. }
  21438. this.modules = orderedModules;
  21439. for (const module of this.modules) {
  21440. module.bindReferences();
  21441. }
  21442. this.warnForMissingExports();
  21443. }
  21444. warnForMissingExports() {
  21445. for (const module of this.modules) {
  21446. for (const importDescription of module.importDescriptions.values()) {
  21447. if (importDescription.name !== '*' &&
  21448. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21449. module.warn({
  21450. code: 'NON_EXISTENT_EXPORT',
  21451. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  21452. name: importDescription.name,
  21453. source: importDescription.module.id
  21454. }, importDescription.start);
  21455. }
  21456. }
  21457. }
  21458. }
  21459. }
  21460. function ensureArray(items) {
  21461. if (Array.isArray(items)) {
  21462. return items.filter(Boolean);
  21463. }
  21464. if (items) {
  21465. return [items];
  21466. }
  21467. return [];
  21468. }
  21469. function formatAction([pluginName, hookName, args]) {
  21470. const action = `(${pluginName}) ${hookName}`;
  21471. const s = JSON.stringify;
  21472. switch (hookName) {
  21473. case 'resolveId':
  21474. return `${action} ${s(args[0])} ${s(args[1])}`;
  21475. case 'load':
  21476. return `${action} ${s(args[0])}`;
  21477. case 'transform':
  21478. return `${action} ${s(args[1])}`;
  21479. case 'shouldTransformCachedModule':
  21480. return `${action} ${s(args[0].id)}`;
  21481. case 'moduleParsed':
  21482. return `${action} ${s(args[0].id)}`;
  21483. }
  21484. return action;
  21485. }
  21486. // We do not directly listen on process to avoid max listeners warnings for
  21487. // complicated build processes
  21488. const beforeExitEvent = 'beforeExit';
  21489. const beforeExitEmitter = new EventEmitter();
  21490. beforeExitEmitter.setMaxListeners(0);
  21491. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  21492. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21493. let handleEmptyEventLoop;
  21494. const emptyEventLoopPromise = new Promise((_, reject) => {
  21495. handleEmptyEventLoop = () => {
  21496. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21497. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21498. [...unfulfilledActions].map(formatAction).join('\n')));
  21499. };
  21500. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  21501. });
  21502. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  21503. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  21504. return result;
  21505. }
  21506. const defaultOnWarn = warning => console.warn(warning.message || warning);
  21507. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  21508. const validOptionSet = new Set(validOptions);
  21509. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  21510. if (unknownOptions.length > 0) {
  21511. warn({
  21512. code: 'UNKNOWN_OPTION',
  21513. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  21514. ...validOptionSet
  21515. ]
  21516. .sort()
  21517. .join(', ')}`
  21518. });
  21519. }
  21520. }
  21521. const treeshakePresets = {
  21522. recommended: {
  21523. annotations: true,
  21524. correctVarValueBeforeDeclaration: false,
  21525. moduleSideEffects: () => true,
  21526. propertyReadSideEffects: true,
  21527. tryCatchDeoptimization: true,
  21528. unknownGlobalSideEffects: false
  21529. },
  21530. safest: {
  21531. annotations: true,
  21532. correctVarValueBeforeDeclaration: true,
  21533. moduleSideEffects: () => true,
  21534. propertyReadSideEffects: true,
  21535. tryCatchDeoptimization: true,
  21536. unknownGlobalSideEffects: true
  21537. },
  21538. smallest: {
  21539. annotations: true,
  21540. correctVarValueBeforeDeclaration: false,
  21541. moduleSideEffects: () => false,
  21542. propertyReadSideEffects: false,
  21543. tryCatchDeoptimization: false,
  21544. unknownGlobalSideEffects: false
  21545. }
  21546. };
  21547. const generatedCodePresets = {
  21548. es2015: {
  21549. arrowFunctions: true,
  21550. constBindings: true,
  21551. objectShorthand: true,
  21552. reservedNamesAsProps: true,
  21553. symbols: true
  21554. },
  21555. es5: {
  21556. arrowFunctions: false,
  21557. constBindings: false,
  21558. objectShorthand: false,
  21559. reservedNamesAsProps: true,
  21560. symbols: false
  21561. }
  21562. };
  21563. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  21564. const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
  21565. if (typeof value === 'string') {
  21566. const preset = presets[value];
  21567. if (preset) {
  21568. return preset;
  21569. }
  21570. error(errInvalidOption(optionName, getHashFromObjectOption(optionName), `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  21571. }
  21572. return objectifyOption(value);
  21573. };
  21574. const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
  21575. const presetName = value === null || value === void 0 ? void 0 : value.preset;
  21576. if (presetName) {
  21577. const preset = presets[presetName];
  21578. if (preset) {
  21579. return { ...preset, ...value };
  21580. }
  21581. else {
  21582. error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  21583. }
  21584. }
  21585. return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
  21586. };
  21587. const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
  21588. function normalizeInputOptions(config) {
  21589. var _a, _b, _c;
  21590. // These are options that may trigger special warnings or behaviour later
  21591. // if the user did not select an explicit value
  21592. const unsetOptions = new Set();
  21593. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  21594. const onwarn = getOnwarn(config);
  21595. const strictDeprecations = config.strictDeprecations || false;
  21596. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  21597. const options = {
  21598. acorn: getAcorn(config),
  21599. acornInjectPlugins: getAcornInjectPlugins(config),
  21600. cache: getCache(config),
  21601. context,
  21602. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  21603. external: getIdMatcher(config.external),
  21604. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  21605. input: getInput(config),
  21606. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  21607. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  21608. maxParallelFileOps,
  21609. maxParallelFileReads: maxParallelFileOps,
  21610. moduleContext: getModuleContext(config, context),
  21611. onwarn,
  21612. perf: config.perf || false,
  21613. plugins: ensureArray(config.plugins),
  21614. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  21615. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  21616. preserveSymlinks: config.preserveSymlinks || false,
  21617. shimMissingExports: config.shimMissingExports || false,
  21618. strictDeprecations,
  21619. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  21620. };
  21621. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  21622. return { options, unsetOptions };
  21623. }
  21624. const getOnwarn = (config) => {
  21625. const { onwarn } = config;
  21626. return onwarn
  21627. ? warning => {
  21628. warning.toString = () => {
  21629. let str = '';
  21630. if (warning.plugin)
  21631. str += `(${warning.plugin} plugin) `;
  21632. if (warning.loc)
  21633. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  21634. str += warning.message;
  21635. return str;
  21636. };
  21637. onwarn(warning, defaultOnWarn);
  21638. }
  21639. : defaultOnWarn;
  21640. };
  21641. const getAcorn = (config) => ({
  21642. allowAwaitOutsideFunction: true,
  21643. ecmaVersion: 'latest',
  21644. preserveParens: false,
  21645. sourceType: 'module',
  21646. ...config.acorn
  21647. });
  21648. const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
  21649. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  21650. const getIdMatcher = (option) => {
  21651. if (option === true) {
  21652. return () => true;
  21653. }
  21654. if (typeof option === 'function') {
  21655. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  21656. }
  21657. if (option) {
  21658. const ids = new Set();
  21659. const matchers = [];
  21660. for (const value of ensureArray(option)) {
  21661. if (value instanceof RegExp) {
  21662. matchers.push(value);
  21663. }
  21664. else {
  21665. ids.add(value);
  21666. }
  21667. }
  21668. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21669. }
  21670. return () => false;
  21671. };
  21672. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  21673. const configInlineDynamicImports = config.inlineDynamicImports;
  21674. if (configInlineDynamicImports) {
  21675. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  21676. }
  21677. return configInlineDynamicImports;
  21678. };
  21679. const getInput = (config) => {
  21680. const configInput = config.input;
  21681. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21682. };
  21683. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  21684. const configManualChunks = config.manualChunks;
  21685. if (configManualChunks) {
  21686. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  21687. }
  21688. return configManualChunks;
  21689. };
  21690. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  21691. var _a;
  21692. const maxParallelFileReads = config.maxParallelFileReads;
  21693. if (typeof maxParallelFileReads === 'number') {
  21694. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
  21695. }
  21696. const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
  21697. if (typeof maxParallelFileOps === 'number') {
  21698. if (maxParallelFileOps <= 0)
  21699. return Infinity;
  21700. return maxParallelFileOps;
  21701. }
  21702. return 20;
  21703. };
  21704. const getModuleContext = (config, context) => {
  21705. const configModuleContext = config.moduleContext;
  21706. if (typeof configModuleContext === 'function') {
  21707. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  21708. }
  21709. if (configModuleContext) {
  21710. const contextByModuleId = Object.create(null);
  21711. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21712. contextByModuleId[resolve(key)] = moduleContext;
  21713. }
  21714. return id => contextByModuleId[id] || context;
  21715. }
  21716. return () => context;
  21717. };
  21718. const getPreserveEntrySignatures = (config, unsetOptions) => {
  21719. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  21720. if (configPreserveEntrySignatures == null) {
  21721. unsetOptions.add('preserveEntrySignatures');
  21722. }
  21723. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  21724. };
  21725. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  21726. const configPreserveModules = config.preserveModules;
  21727. if (configPreserveModules) {
  21728. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  21729. }
  21730. return configPreserveModules;
  21731. };
  21732. const getTreeshake = (config, warn, strictDeprecations) => {
  21733. const configTreeshake = config.treeshake;
  21734. if (configTreeshake === false) {
  21735. return false;
  21736. }
  21737. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
  21738. if (typeof configWithPreset.pureExternalModules !== 'undefined') {
  21739. warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
  21740. }
  21741. return {
  21742. annotations: configWithPreset.annotations !== false,
  21743. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21744. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  21745. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  21746. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  21747. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21748. ? 'always'
  21749. : configWithPreset.propertyReadSideEffects !== false,
  21750. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21751. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21752. };
  21753. };
  21754. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  21755. if (typeof moduleSideEffectsOption === 'boolean') {
  21756. return () => moduleSideEffectsOption;
  21757. }
  21758. if (moduleSideEffectsOption === 'no-external') {
  21759. return (_id, external) => !external;
  21760. }
  21761. if (typeof moduleSideEffectsOption === 'function') {
  21762. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  21763. }
  21764. if (Array.isArray(moduleSideEffectsOption)) {
  21765. const ids = new Set(moduleSideEffectsOption);
  21766. return id => ids.has(id);
  21767. }
  21768. if (moduleSideEffectsOption) {
  21769. error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
  21770. }
  21771. const isPureExternalModule = getIdMatcher(pureExternalModules);
  21772. return (id, external) => !(external && isPureExternalModule(id));
  21773. };
  21774. // https://datatracker.ietf.org/doc/html/rfc2396
  21775. // eslint-disable-next-line no-control-regex
  21776. const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
  21777. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21778. function sanitizeFileName(name) {
  21779. const match = DRIVE_LETTER_REGEX.exec(name);
  21780. const driveLetter = match ? match[0] : '';
  21781. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21782. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21783. return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21784. }
  21785. function isValidUrl(url) {
  21786. try {
  21787. new URL(url);
  21788. }
  21789. catch (_) {
  21790. return false;
  21791. }
  21792. return true;
  21793. }
  21794. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21795. var _a, _b, _c, _d, _e, _f, _g;
  21796. // These are options that may trigger special warnings or behaviour later
  21797. // if the user did not select an explicit value
  21798. const unsetOptions = new Set(unsetInputOptions);
  21799. const compact = config.compact || false;
  21800. const format = getFormat(config);
  21801. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21802. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21803. const file = getFile(config, preserveModules, inputOptions);
  21804. const preferConst = getPreferConst(config, inputOptions);
  21805. const generatedCode = getGeneratedCode(config, preferConst);
  21806. const outputOptions = {
  21807. amd: getAmd(config),
  21808. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  21809. banner: getAddon(config, 'banner'),
  21810. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  21811. compact,
  21812. dir: getDir(config, file),
  21813. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  21814. entryFileNames: getEntryFileNames(config, unsetOptions),
  21815. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  21816. exports: getExports(config, unsetOptions),
  21817. extend: config.extend || false,
  21818. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  21819. file,
  21820. footer: getAddon(config, 'footer'),
  21821. format,
  21822. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  21823. generatedCode,
  21824. globals: config.globals || {},
  21825. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  21826. indent: getIndent(config, compact),
  21827. inlineDynamicImports,
  21828. interop: getInterop(config, inputOptions),
  21829. intro: getAddon(config, 'intro'),
  21830. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  21831. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21832. name: config.name,
  21833. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  21834. noConflict: config.noConflict || false,
  21835. outro: getAddon(config, 'outro'),
  21836. paths: config.paths || {},
  21837. plugins: ensureArray(config.plugins),
  21838. preferConst,
  21839. preserveModules,
  21840. preserveModulesRoot: getPreserveModulesRoot(config),
  21841. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21842. ? config.sanitizeFileName
  21843. : config.sanitizeFileName === false
  21844. ? id => id
  21845. : sanitizeFileName,
  21846. sourcemap: config.sourcemap || false,
  21847. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21848. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21849. sourcemapFile: config.sourcemapFile,
  21850. sourcemapPathTransform: config.sourcemapPathTransform,
  21851. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  21852. systemNullSetters: config.systemNullSetters || false,
  21853. validate: config.validate || false
  21854. };
  21855. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  21856. return { options: outputOptions, unsetOptions };
  21857. }
  21858. const getFile = (config, preserveModules, inputOptions) => {
  21859. const { file } = config;
  21860. if (typeof file === 'string') {
  21861. if (preserveModules) {
  21862. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21863. }
  21864. if (!Array.isArray(inputOptions.input))
  21865. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21866. }
  21867. return file;
  21868. };
  21869. const getFormat = (config) => {
  21870. const configFormat = config.format;
  21871. switch (configFormat) {
  21872. case undefined:
  21873. case 'es':
  21874. case 'esm':
  21875. case 'module':
  21876. return 'es';
  21877. case 'cjs':
  21878. case 'commonjs':
  21879. return 'cjs';
  21880. case 'system':
  21881. case 'systemjs':
  21882. return 'system';
  21883. case 'amd':
  21884. case 'iife':
  21885. case 'umd':
  21886. return configFormat;
  21887. default:
  21888. return error({
  21889. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  21890. url: `https://rollupjs.org/guide/en/#outputformat`
  21891. });
  21892. }
  21893. };
  21894. const getInlineDynamicImports = (config, inputOptions) => {
  21895. var _a;
  21896. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  21897. const { input } = inputOptions;
  21898. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21899. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21900. }
  21901. return inlineDynamicImports;
  21902. };
  21903. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21904. var _a;
  21905. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  21906. if (preserveModules) {
  21907. if (inlineDynamicImports) {
  21908. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
  21909. }
  21910. if (inputOptions.preserveEntrySignatures === false) {
  21911. return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
  21912. }
  21913. }
  21914. return preserveModules;
  21915. };
  21916. const getPreferConst = (config, inputOptions) => {
  21917. const configPreferConst = config.preferConst;
  21918. if (configPreferConst != null) {
  21919. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
  21920. }
  21921. return !!configPreferConst;
  21922. };
  21923. const getPreserveModulesRoot = (config) => {
  21924. const { preserveModulesRoot } = config;
  21925. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21926. return undefined;
  21927. }
  21928. return resolve(preserveModulesRoot);
  21929. };
  21930. const getAmd = (config) => {
  21931. const mergedOption = {
  21932. autoId: false,
  21933. basePath: '',
  21934. define: 'define',
  21935. ...config.amd
  21936. };
  21937. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  21938. return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  21939. }
  21940. if (mergedOption.basePath && !mergedOption.autoId) {
  21941. return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
  21942. }
  21943. let normalized;
  21944. if (mergedOption.autoId) {
  21945. normalized = {
  21946. autoId: true,
  21947. basePath: mergedOption.basePath,
  21948. define: mergedOption.define
  21949. };
  21950. }
  21951. else {
  21952. normalized = {
  21953. autoId: false,
  21954. define: mergedOption.define,
  21955. id: mergedOption.id
  21956. };
  21957. }
  21958. return normalized;
  21959. };
  21960. const getAddon = (config, name) => {
  21961. const configAddon = config[name];
  21962. if (typeof configAddon === 'function') {
  21963. return configAddon;
  21964. }
  21965. return () => configAddon || '';
  21966. };
  21967. const getDir = (config, file) => {
  21968. const { dir } = config;
  21969. if (typeof dir === 'string' && typeof file === 'string') {
  21970. return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  21971. }
  21972. return dir;
  21973. };
  21974. const getDynamicImportFunction = (config, inputOptions) => {
  21975. const configDynamicImportFunction = config.dynamicImportFunction;
  21976. if (configDynamicImportFunction) {
  21977. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  21978. }
  21979. return configDynamicImportFunction;
  21980. };
  21981. const getEntryFileNames = (config, unsetOptions) => {
  21982. const configEntryFileNames = config.entryFileNames;
  21983. if (configEntryFileNames == null) {
  21984. unsetOptions.add('entryFileNames');
  21985. }
  21986. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  21987. };
  21988. function getExports(config, unsetOptions) {
  21989. const configExports = config.exports;
  21990. if (configExports == null) {
  21991. unsetOptions.add('exports');
  21992. }
  21993. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  21994. return error(errInvalidExportOptionValue(configExports));
  21995. }
  21996. return configExports || 'auto';
  21997. }
  21998. const getGeneratedCode = (config, preferConst) => {
  21999. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
  22000. return {
  22001. arrowFunctions: configWithPreset.arrowFunctions === true,
  22002. constBindings: configWithPreset.constBindings === true || preferConst,
  22003. objectShorthand: configWithPreset.objectShorthand === true,
  22004. reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
  22005. symbols: configWithPreset.symbols === true
  22006. };
  22007. };
  22008. const getIndent = (config, compact) => {
  22009. if (compact) {
  22010. return '';
  22011. }
  22012. const configIndent = config.indent;
  22013. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  22014. };
  22015. const ALLOWED_INTEROP_TYPES = new Set([
  22016. 'auto',
  22017. 'esModule',
  22018. 'default',
  22019. 'defaultOnly',
  22020. true,
  22021. false
  22022. ]);
  22023. const getInterop = (config, inputOptions) => {
  22024. const configInterop = config.interop;
  22025. const validatedInteropTypes = new Set();
  22026. const validateInterop = (interop) => {
  22027. if (!validatedInteropTypes.has(interop)) {
  22028. validatedInteropTypes.add(interop);
  22029. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22030. return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22031. }
  22032. if (typeof interop === 'boolean') {
  22033. warnDeprecation({
  22034. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  22035. url: 'https://rollupjs.org/guide/en/#outputinterop'
  22036. }, false, inputOptions);
  22037. }
  22038. }
  22039. return interop;
  22040. };
  22041. if (typeof configInterop === 'function') {
  22042. const interopPerId = Object.create(null);
  22043. let defaultInterop = null;
  22044. return id => id === null
  22045. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22046. : id in interopPerId
  22047. ? interopPerId[id]
  22048. : validateInterop((interopPerId[id] = configInterop(id)));
  22049. }
  22050. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  22051. };
  22052. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  22053. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  22054. if (configManualChunks) {
  22055. if (inlineDynamicImports) {
  22056. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
  22057. }
  22058. if (preserveModules) {
  22059. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
  22060. }
  22061. }
  22062. return configManualChunks || {};
  22063. };
  22064. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  22065. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  22066. const configNamespaceToStringTag = config.namespaceToStringTag;
  22067. if (configNamespaceToStringTag != null) {
  22068. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
  22069. return configNamespaceToStringTag;
  22070. }
  22071. return generatedCode.symbols || false;
  22072. };
  22073. const getSourcemapBaseUrl = (config) => {
  22074. const { sourcemapBaseUrl } = config;
  22075. if (sourcemapBaseUrl) {
  22076. if (isValidUrl(sourcemapBaseUrl)) {
  22077. return sourcemapBaseUrl;
  22078. }
  22079. return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22080. }
  22081. };
  22082. function rollup(rawInputOptions) {
  22083. return rollupInternal(rawInputOptions, null);
  22084. }
  22085. async function rollupInternal(rawInputOptions, watcher) {
  22086. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22087. initialiseTimers(inputOptions);
  22088. const graph = new Graph(inputOptions, watcher);
  22089. // remove the cache option from the memory after graph creation (cache is not used anymore)
  22090. const useCache = rawInputOptions.cache !== false;
  22091. delete inputOptions.cache;
  22092. delete rawInputOptions.cache;
  22093. timeStart('BUILD', 1);
  22094. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22095. try {
  22096. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22097. await graph.build();
  22098. }
  22099. catch (err) {
  22100. const watchFiles = Object.keys(graph.watchFiles);
  22101. if (watchFiles.length > 0) {
  22102. err.watchFiles = watchFiles;
  22103. }
  22104. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  22105. await graph.pluginDriver.hookParallel('closeBundle', []);
  22106. throw err;
  22107. }
  22108. await graph.pluginDriver.hookParallel('buildEnd', []);
  22109. });
  22110. timeEnd('BUILD', 1);
  22111. const result = {
  22112. cache: useCache ? graph.getCache() : undefined,
  22113. async close() {
  22114. if (result.closed)
  22115. return;
  22116. result.closed = true;
  22117. await graph.pluginDriver.hookParallel('closeBundle', []);
  22118. },
  22119. closed: false,
  22120. async generate(rawOutputOptions) {
  22121. if (result.closed)
  22122. return error(errAlreadyClosed());
  22123. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22124. },
  22125. watchFiles: Object.keys(graph.watchFiles),
  22126. async write(rawOutputOptions) {
  22127. if (result.closed)
  22128. return error(errAlreadyClosed());
  22129. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22130. }
  22131. };
  22132. if (inputOptions.perf)
  22133. result.getTimings = getTimings;
  22134. return result;
  22135. }
  22136. async function getInputOptions(rawInputOptions, watchMode) {
  22137. if (!rawInputOptions) {
  22138. throw new Error('You must supply an options object to rollup');
  22139. }
  22140. const rawPlugins = ensureArray(rawInputOptions.plugins);
  22141. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  22142. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22143. return { options, unsetOptions };
  22144. }
  22145. function applyOptionHook(watchMode) {
  22146. return async (inputOptions, plugin) => {
  22147. if (plugin.options) {
  22148. return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  22149. }
  22150. return inputOptions;
  22151. };
  22152. }
  22153. function normalizePlugins(plugins, anonymousPrefix) {
  22154. plugins.forEach((plugin, index) => {
  22155. if (!plugin.name) {
  22156. plugin.name = `${anonymousPrefix}${index + 1}`;
  22157. }
  22158. });
  22159. }
  22160. function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22161. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22162. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22163. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22164. const generated = await bundle.generate(isWrite);
  22165. if (isWrite) {
  22166. if (!outputOptions.dir && !outputOptions.file) {
  22167. return error({
  22168. code: 'MISSING_OPTION',
  22169. message: 'You must specify "output.file" or "output.dir" for the build.'
  22170. });
  22171. }
  22172. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22173. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22174. }
  22175. return createOutput(generated);
  22176. });
  22177. }
  22178. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22179. if (!rawOutputOptions) {
  22180. throw new Error('You must supply an options object');
  22181. }
  22182. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  22183. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22184. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22185. return {
  22186. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  22187. outputPluginDriver
  22188. };
  22189. }
  22190. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22191. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22192. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  22193. return {
  22194. ...pluginContext,
  22195. emitFile: emitError,
  22196. setAssetSource: emitError
  22197. };
  22198. }), inputOptions, unsetInputOptions);
  22199. }
  22200. function createOutput(outputBundle) {
  22201. return {
  22202. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  22203. const fileTypeA = getSortingFileType(outputFileA);
  22204. const fileTypeB = getSortingFileType(outputFileB);
  22205. if (fileTypeA === fileTypeB)
  22206. return 0;
  22207. return fileTypeA < fileTypeB ? -1 : 1;
  22208. })
  22209. };
  22210. }
  22211. var SortingFileType;
  22212. (function (SortingFileType) {
  22213. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22214. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22215. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22216. })(SortingFileType || (SortingFileType = {}));
  22217. function getSortingFileType(file) {
  22218. if (file.type === 'asset') {
  22219. return SortingFileType.ASSET;
  22220. }
  22221. if (file.isEntry) {
  22222. return SortingFileType.ENTRY_CHUNK;
  22223. }
  22224. return SortingFileType.SECONDARY_CHUNK;
  22225. }
  22226. async function writeOutputFile(outputFile, outputOptions) {
  22227. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22228. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22229. await promises.mkdir(dirname(fileName), { recursive: true });
  22230. let writeSourceMapPromise;
  22231. let source;
  22232. if (outputFile.type === 'asset') {
  22233. source = outputFile.source;
  22234. }
  22235. else {
  22236. source = outputFile.code;
  22237. if (outputOptions.sourcemap && outputFile.map) {
  22238. let url;
  22239. if (outputOptions.sourcemap === 'inline') {
  22240. url = outputFile.map.toUrl();
  22241. }
  22242. else {
  22243. const { sourcemapBaseUrl } = outputOptions;
  22244. const sourcemapFileName = `${basename(outputFile.fileName)}.map`;
  22245. url = sourcemapBaseUrl
  22246. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  22247. : sourcemapFileName;
  22248. writeSourceMapPromise = promises.writeFile(`${fileName}.map`, outputFile.map.toString());
  22249. }
  22250. if (outputOptions.sourcemap !== 'hidden') {
  22251. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  22252. }
  22253. }
  22254. }
  22255. return Promise.all([promises.writeFile(fileName, source), writeSourceMapPromise]);
  22256. }
  22257. /**
  22258. * Auxiliary function for defining rollup configuration
  22259. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  22260. * @param options
  22261. */
  22262. function defineConfig(options) {
  22263. return options;
  22264. }
  22265. class WatchEmitter extends EventEmitter {
  22266. constructor() {
  22267. super();
  22268. this.awaitedHandlers = Object.create(null);
  22269. // Allows more than 10 bundles to be watched without
  22270. // showing the `MaxListenersExceededWarning` to the user.
  22271. this.setMaxListeners(Infinity);
  22272. }
  22273. // Will be overwritten by Rollup
  22274. async close() { }
  22275. emitAndAwait(event, ...args) {
  22276. this.emit(event, ...args);
  22277. return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
  22278. }
  22279. onCurrentAwaited(event, listener) {
  22280. this.getHandlers(event).push(listener);
  22281. return this;
  22282. }
  22283. removeAwaited() {
  22284. this.awaitedHandlers = {};
  22285. return this;
  22286. }
  22287. getHandlers(event) {
  22288. return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
  22289. }
  22290. }
  22291. let fsEvents;
  22292. let fsEventsImportError;
  22293. async function loadFsEvents() {
  22294. try {
  22295. ({ default: fsEvents } = await import('fsevents'));
  22296. }
  22297. catch (err) {
  22298. fsEventsImportError = err;
  22299. }
  22300. }
  22301. // A call to this function will be injected into the chokidar code
  22302. function getFsEvents() {
  22303. if (fsEventsImportError)
  22304. throw fsEventsImportError;
  22305. return fsEvents;
  22306. }
  22307. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22308. __proto__: null,
  22309. loadFsEvents,
  22310. getFsEvents
  22311. }, Symbol.toStringTag, { value: 'Module' });
  22312. function watch(configs) {
  22313. const emitter = new WatchEmitter();
  22314. const configArray = ensureArray(configs);
  22315. const watchConfigs = configArray.filter(config => config.watch !== false);
  22316. if (watchConfigs.length === 0) {
  22317. return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
  22318. }
  22319. loadFsEvents()
  22320. .then(() => import('./watch.js'))
  22321. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  22322. return emitter;
  22323. }
  22324. export { createFilter, defaultOnWarn, defineConfig, ensureArray, fseventsImporter, generatedCodePresets, getAugmentedNamespace, objectifyOption, objectifyOptionWithPresets, picomatch$1 as picomatch, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };