rollup.js 871 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912
  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. 'use strict';
  9. const require$$0 = require('path');
  10. const process$1 = require('process');
  11. const perf_hooks = require('perf_hooks');
  12. const crypto = require('crypto');
  13. const require$$0$1 = require('fs');
  14. const require$$0$2 = require('events');
  15. function _interopNamespaceDefault(e) {
  16. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  17. if (e) {
  18. for (const k in e) {
  19. n[k] = e[k];
  20. }
  21. }
  22. n.default = e;
  23. return n;
  24. }
  25. var version$1 = "2.77.3";
  26. function ensureArray$1(items) {
  27. if (Array.isArray(items)) {
  28. return items.filter(Boolean);
  29. }
  30. if (items) {
  31. return [items];
  32. }
  33. return [];
  34. }
  35. function getLocator$1(source, options) {
  36. if (options === void 0) { options = {}; }
  37. var offsetLine = options.offsetLine || 0;
  38. var offsetColumn = options.offsetColumn || 0;
  39. var originalLines = source.split('\n');
  40. var start = 0;
  41. var lineRanges = originalLines.map(function (line, i) {
  42. var end = start + line.length + 1;
  43. var range = { start: start, end: end, line: i };
  44. start = end;
  45. return range;
  46. });
  47. var i = 0;
  48. function rangeContains(range, index) {
  49. return range.start <= index && index < range.end;
  50. }
  51. function getLocation(range, index) {
  52. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  53. }
  54. function locate(search, startIndex) {
  55. if (typeof search === 'string') {
  56. search = source.indexOf(search, startIndex || 0);
  57. }
  58. var range = lineRanges[i];
  59. var d = search >= range.end ? 1 : -1;
  60. while (range) {
  61. if (rangeContains(range, search))
  62. return getLocation(range, search);
  63. i += d;
  64. range = lineRanges[i];
  65. }
  66. }
  67. return locate;
  68. }
  69. function locate(source, search, options) {
  70. if (typeof options === 'number') {
  71. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  72. }
  73. return getLocator$1(source, options)(search, options && options.startIndex);
  74. }
  75. function spaces(i) {
  76. let result = '';
  77. while (i--)
  78. result += ' ';
  79. return result;
  80. }
  81. function tabsToSpaces(str) {
  82. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  83. }
  84. function getCodeFrame(source, line, column) {
  85. let lines = source.split('\n');
  86. const frameStart = Math.max(0, line - 3);
  87. let frameEnd = Math.min(line + 2, lines.length);
  88. lines = lines.slice(frameStart, frameEnd);
  89. while (!/\S/.test(lines[lines.length - 1])) {
  90. lines.pop();
  91. frameEnd -= 1;
  92. }
  93. const digits = String(frameEnd).length;
  94. return lines
  95. .map((str, i) => {
  96. const isErrorLine = frameStart + i + 1 === line;
  97. let lineNum = String(i + frameStart + 1);
  98. while (lineNum.length < digits)
  99. lineNum = ` ${lineNum}`;
  100. if (isErrorLine) {
  101. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  102. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  103. }
  104. return `${lineNum}: ${tabsToSpaces(str)}`;
  105. })
  106. .join('\n');
  107. }
  108. function printQuotedStringList(list, verbs) {
  109. const isSingleItem = list.length <= 1;
  110. const quotedList = list.map(item => `"${item}"`);
  111. let output = isSingleItem
  112. ? quotedList[0]
  113. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  114. if (verbs) {
  115. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  116. }
  117. return output;
  118. }
  119. const ANY_SLASH_REGEX = /[/\\]/;
  120. function relative(from, to) {
  121. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  122. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  123. if (fromParts[0] === '.')
  124. fromParts.shift();
  125. if (toParts[0] === '.')
  126. toParts.shift();
  127. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  128. fromParts.shift();
  129. toParts.shift();
  130. }
  131. while (toParts[0] === '..' && fromParts.length > 0) {
  132. toParts.shift();
  133. fromParts.pop();
  134. }
  135. while (fromParts.pop()) {
  136. toParts.unshift('..');
  137. }
  138. return toParts.join('/');
  139. }
  140. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  141. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  142. function isAbsolute(path) {
  143. return ABSOLUTE_PATH_REGEX.test(path);
  144. }
  145. function isRelative(path) {
  146. return RELATIVE_PATH_REGEX.test(path);
  147. }
  148. const BACKSLASH_REGEX = /\\/g;
  149. function normalize(path) {
  150. return path.replace(BACKSLASH_REGEX, '/');
  151. }
  152. function getAliasName(id) {
  153. const base = require$$0.basename(id);
  154. return base.substring(0, base.length - require$$0.extname(id).length);
  155. }
  156. function relativeId(id) {
  157. if (!isAbsolute(id))
  158. return id;
  159. return relative(require$$0.resolve(), id);
  160. }
  161. function isPathFragment(name) {
  162. // starting with "/", "./", "../", "C:/"
  163. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  164. }
  165. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  166. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  167. let relativePath = normalize(relative(require$$0.dirname(importerId), targetPath));
  168. if (stripJsExtension && relativePath.endsWith('.js')) {
  169. relativePath = relativePath.slice(0, -3);
  170. }
  171. if (ensureFileName) {
  172. if (relativePath === '')
  173. return '../' + require$$0.basename(targetPath);
  174. if (UPPER_DIR_REGEX.test(relativePath)) {
  175. return relativePath
  176. .split('/')
  177. .concat(['..', require$$0.basename(targetPath)])
  178. .join('/');
  179. }
  180. }
  181. return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
  182. }
  183. function error(base) {
  184. if (!(base instanceof Error))
  185. base = Object.assign(new Error(base.message), base);
  186. throw base;
  187. }
  188. function augmentCodeLocation(props, pos, source, id) {
  189. if (typeof pos === 'object') {
  190. const { line, column } = pos;
  191. props.loc = { column, file: id, line };
  192. }
  193. else {
  194. props.pos = pos;
  195. const { line, column } = locate(source, pos, { offsetLine: 1 });
  196. props.loc = { column, file: id, line };
  197. }
  198. if (props.frame === undefined) {
  199. const { line, column } = props.loc;
  200. props.frame = getCodeFrame(source, line, column);
  201. }
  202. }
  203. var Errors;
  204. (function (Errors) {
  205. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  206. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  207. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  208. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  209. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  210. Errors["BAD_LOADER"] = "BAD_LOADER";
  211. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  212. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  213. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  214. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  215. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  216. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  217. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  218. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  219. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  220. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  221. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  222. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  223. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  224. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  225. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  226. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  227. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  228. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  229. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  230. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  231. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  232. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  233. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  234. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  235. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  236. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  237. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  238. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  239. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  240. })(Errors || (Errors = {}));
  241. function errAssetNotFinalisedForFileName(name) {
  242. return {
  243. code: Errors.ASSET_NOT_FINALISED,
  244. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  245. };
  246. }
  247. function errCannotEmitFromOptionsHook() {
  248. return {
  249. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  250. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  251. };
  252. }
  253. function errChunkNotGeneratedForFileName(name) {
  254. return {
  255. code: Errors.CHUNK_NOT_GENERATED,
  256. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  257. };
  258. }
  259. function errChunkInvalid({ fileName, code }, exception) {
  260. const errorProps = {
  261. code: Errors.CHUNK_INVALID,
  262. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  263. };
  264. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  265. return errorProps;
  266. }
  267. function errCircularReexport(exportName, importedModule) {
  268. return {
  269. code: Errors.CIRCULAR_REEXPORT,
  270. id: importedModule,
  271. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  272. };
  273. }
  274. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  275. return {
  276. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  277. exporter,
  278. importer,
  279. 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.`,
  280. reexporter
  281. };
  282. }
  283. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  284. return {
  285. code: Errors.ASSET_NOT_FOUND,
  286. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  287. };
  288. }
  289. function errAssetSourceAlreadySet(name) {
  290. return {
  291. code: Errors.ASSET_SOURCE_ALREADY_SET,
  292. message: `Unable to set the source for asset "${name}", source already set.`
  293. };
  294. }
  295. function errNoAssetSourceSet(assetName) {
  296. return {
  297. code: Errors.ASSET_SOURCE_MISSING,
  298. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  299. };
  300. }
  301. function errBadLoader(id) {
  302. return {
  303. code: Errors.BAD_LOADER,
  304. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  305. };
  306. }
  307. function errDeprecation(deprecation) {
  308. return {
  309. code: Errors.DEPRECATED_FEATURE,
  310. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  311. };
  312. }
  313. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  314. return {
  315. code: Errors.FILE_NOT_FOUND,
  316. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  317. };
  318. }
  319. function errFileNameConflict(fileName) {
  320. return {
  321. code: Errors.FILE_NAME_CONFLICT,
  322. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  323. };
  324. }
  325. function errInputHookInOutputPlugin(pluginName, hookName) {
  326. return {
  327. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  328. 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.`
  329. };
  330. }
  331. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  332. return {
  333. code: Errors.INVALID_CHUNK,
  334. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  335. };
  336. }
  337. function errInvalidExportOptionValue(optionValue) {
  338. return {
  339. code: Errors.INVALID_EXPORT_OPTION,
  340. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  341. url: `https://rollupjs.org/guide/en/#outputexports`
  342. };
  343. }
  344. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  345. return {
  346. code: 'INVALID_EXPORT_OPTION',
  347. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  348. };
  349. }
  350. function errInternalIdCannotBeExternal(source, importer) {
  351. return {
  352. code: Errors.INVALID_EXTERNAL_ID,
  353. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  354. };
  355. }
  356. function errInvalidOption(option, urlHash, explanation, value) {
  357. return {
  358. code: Errors.INVALID_OPTION,
  359. message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
  360. url: `https://rollupjs.org/guide/en/#${urlHash}`
  361. };
  362. }
  363. function errInvalidRollupPhaseForAddWatchFile() {
  364. return {
  365. code: Errors.INVALID_ROLLUP_PHASE,
  366. message: `Cannot call addWatchFile after the build has finished.`
  367. };
  368. }
  369. function errInvalidRollupPhaseForChunkEmission() {
  370. return {
  371. code: Errors.INVALID_ROLLUP_PHASE,
  372. message: `Cannot emit chunks after module loading has finished.`
  373. };
  374. }
  375. function errMissingExport(exportName, importingModule, importedModule) {
  376. return {
  377. code: Errors.MISSING_EXPORT,
  378. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  379. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  380. };
  381. }
  382. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  383. return {
  384. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  385. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  386. };
  387. }
  388. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  389. return {
  390. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  391. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  392. };
  393. }
  394. function errImplicitDependantIsNotIncluded(module) {
  395. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  396. return {
  397. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  398. 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.`
  399. };
  400. }
  401. function errMixedExport(facadeModuleId, name) {
  402. return {
  403. code: Errors.MIXED_EXPORTS,
  404. id: facadeModuleId,
  405. 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`,
  406. url: `https://rollupjs.org/guide/en/#outputexports`
  407. };
  408. }
  409. function errNamespaceConflict(name, reexportingModuleId, sources) {
  410. return {
  411. code: Errors.NAMESPACE_CONFLICT,
  412. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
  413. name,
  414. reexporter: reexportingModuleId,
  415. sources
  416. };
  417. }
  418. function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
  419. return {
  420. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  421. 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)}".`,
  422. name,
  423. reexporter: reexportingModule,
  424. sources
  425. };
  426. }
  427. function errNoTransformMapOrAstWithoutCode(pluginName) {
  428. return {
  429. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  430. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  431. 'a "code". This will be ignored.'
  432. };
  433. }
  434. function errPreferNamedExports(facadeModuleId) {
  435. const file = relativeId(facadeModuleId);
  436. return {
  437. code: Errors.PREFER_NAMED_EXPORTS,
  438. id: facadeModuleId,
  439. 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.`,
  440. url: `https://rollupjs.org/guide/en/#outputexports`
  441. };
  442. }
  443. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  444. return {
  445. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  446. id,
  447. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  448. ? `an explicit export named "${syntheticNamedExportsOption}"`
  449. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  450. };
  451. }
  452. function errUnexpectedNamedImport(id, imported, isReexport) {
  453. const importType = isReexport ? 'reexport' : 'import';
  454. return {
  455. code: Errors.UNEXPECTED_NAMED_IMPORT,
  456. id,
  457. 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.`,
  458. url: 'https://rollupjs.org/guide/en/#outputinterop'
  459. };
  460. }
  461. function errUnexpectedNamespaceReexport(id) {
  462. return {
  463. code: Errors.UNEXPECTED_NAMED_IMPORT,
  464. id,
  465. 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.`,
  466. url: 'https://rollupjs.org/guide/en/#outputinterop'
  467. };
  468. }
  469. function errEntryCannotBeExternal(unresolvedId) {
  470. return {
  471. code: Errors.UNRESOLVED_ENTRY,
  472. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  473. };
  474. }
  475. function errUnresolvedEntry(unresolvedId) {
  476. return {
  477. code: Errors.UNRESOLVED_ENTRY,
  478. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  479. };
  480. }
  481. function errUnresolvedImport(source, importer) {
  482. return {
  483. code: Errors.UNRESOLVED_IMPORT,
  484. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  485. };
  486. }
  487. function errUnresolvedImportTreatedAsExternal(source, importer) {
  488. return {
  489. code: Errors.UNRESOLVED_IMPORT,
  490. importer: relativeId(importer),
  491. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  492. source,
  493. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  494. };
  495. }
  496. function errExternalSyntheticExports(source, importer) {
  497. return {
  498. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  499. importer: relativeId(importer),
  500. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  501. source
  502. };
  503. }
  504. function errFailedValidation(message) {
  505. return {
  506. code: Errors.VALIDATION_ERROR,
  507. message
  508. };
  509. }
  510. function errAlreadyClosed() {
  511. return {
  512. code: Errors.ALREADY_CLOSED,
  513. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  514. };
  515. }
  516. function warnDeprecation(deprecation, activeDeprecation, options) {
  517. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  518. }
  519. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  520. if (activeDeprecation || strictDeprecations) {
  521. const warning = errDeprecation(deprecation);
  522. if (strictDeprecations) {
  523. return error(warning);
  524. }
  525. warn(warning);
  526. }
  527. }
  528. const defaultOnWarn = warning => console.warn(warning.message || warning);
  529. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  530. const validOptionSet = new Set(validOptions);
  531. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  532. if (unknownOptions.length > 0) {
  533. warn({
  534. code: 'UNKNOWN_OPTION',
  535. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  536. ...validOptionSet
  537. ]
  538. .sort()
  539. .join(', ')}`
  540. });
  541. }
  542. }
  543. const treeshakePresets = {
  544. recommended: {
  545. annotations: true,
  546. correctVarValueBeforeDeclaration: false,
  547. moduleSideEffects: () => true,
  548. propertyReadSideEffects: true,
  549. tryCatchDeoptimization: true,
  550. unknownGlobalSideEffects: false
  551. },
  552. safest: {
  553. annotations: true,
  554. correctVarValueBeforeDeclaration: true,
  555. moduleSideEffects: () => true,
  556. propertyReadSideEffects: true,
  557. tryCatchDeoptimization: true,
  558. unknownGlobalSideEffects: true
  559. },
  560. smallest: {
  561. annotations: true,
  562. correctVarValueBeforeDeclaration: false,
  563. moduleSideEffects: () => false,
  564. propertyReadSideEffects: false,
  565. tryCatchDeoptimization: false,
  566. unknownGlobalSideEffects: false
  567. }
  568. };
  569. const generatedCodePresets = {
  570. es2015: {
  571. arrowFunctions: true,
  572. constBindings: true,
  573. objectShorthand: true,
  574. reservedNamesAsProps: true,
  575. symbols: true
  576. },
  577. es5: {
  578. arrowFunctions: false,
  579. constBindings: false,
  580. objectShorthand: false,
  581. reservedNamesAsProps: true,
  582. symbols: false
  583. }
  584. };
  585. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  586. const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
  587. if (typeof value === 'string') {
  588. const preset = presets[value];
  589. if (preset) {
  590. return preset;
  591. }
  592. 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));
  593. }
  594. return objectifyOption(value);
  595. };
  596. const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
  597. const presetName = value === null || value === void 0 ? void 0 : value.preset;
  598. if (presetName) {
  599. const preset = presets[presetName];
  600. if (preset) {
  601. return { ...preset, ...value };
  602. }
  603. else {
  604. error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  605. }
  606. }
  607. return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
  608. };
  609. const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
  610. let fsEvents;
  611. let fsEventsImportError;
  612. async function loadFsEvents() {
  613. try {
  614. ({ default: fsEvents } = await Promise.resolve().then(() => /*#__PURE__*/_interopNamespaceDefault(require('fsevents'))));
  615. }
  616. catch (err) {
  617. fsEventsImportError = err;
  618. }
  619. }
  620. // A call to this function will be injected into the chokidar code
  621. function getFsEvents() {
  622. if (fsEventsImportError)
  623. throw fsEventsImportError;
  624. return fsEvents;
  625. }
  626. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  627. __proto__: null,
  628. loadFsEvents,
  629. getFsEvents
  630. }, Symbol.toStringTag, { value: 'Module' });
  631. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  632. function getDefaultExportFromCjs (x) {
  633. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  634. }
  635. function getAugmentedNamespace(n) {
  636. var f = n.default;
  637. if (typeof f == "function") {
  638. var a = function () {
  639. return f.apply(this, arguments);
  640. };
  641. a.prototype = f.prototype;
  642. } else a = {};
  643. Object.defineProperty(a, '__esModule', {value: true});
  644. Object.keys(n).forEach(function (k) {
  645. var d = Object.getOwnPropertyDescriptor(n, k);
  646. Object.defineProperty(a, k, d.get ? d : {
  647. enumerable: true,
  648. get: function () {
  649. return n[k];
  650. }
  651. });
  652. });
  653. return a;
  654. }
  655. var charToInteger = {};
  656. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  657. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  658. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  659. }
  660. function decode(mappings) {
  661. var decoded = [];
  662. var line = [];
  663. var segment = [
  664. 0,
  665. 0,
  666. 0,
  667. 0,
  668. 0,
  669. ];
  670. var j = 0;
  671. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  672. var c = mappings.charCodeAt(i);
  673. if (c === 44) { // ","
  674. segmentify(line, segment, j);
  675. j = 0;
  676. }
  677. else if (c === 59) { // ";"
  678. segmentify(line, segment, j);
  679. j = 0;
  680. decoded.push(line);
  681. line = [];
  682. segment[0] = 0;
  683. }
  684. else {
  685. var integer = charToInteger[c];
  686. if (integer === undefined) {
  687. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  688. }
  689. var hasContinuationBit = integer & 32;
  690. integer &= 31;
  691. value += integer << shift;
  692. if (hasContinuationBit) {
  693. shift += 5;
  694. }
  695. else {
  696. var shouldNegate = value & 1;
  697. value >>>= 1;
  698. if (shouldNegate) {
  699. value = value === 0 ? -0x80000000 : -value;
  700. }
  701. segment[j] += value;
  702. j++;
  703. value = shift = 0; // reset
  704. }
  705. }
  706. }
  707. segmentify(line, segment, j);
  708. decoded.push(line);
  709. return decoded;
  710. }
  711. function segmentify(line, segment, j) {
  712. // This looks ugly, but we're creating specialized arrays with a specific
  713. // length. This is much faster than creating a new array (which v8 expands to
  714. // a capacity of 17 after pushing the first item), or slicing out a subarray
  715. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  716. // length 5 (since not everything will have an associated name), followed by
  717. // length 1 (it's probably rare for a source substring to not have an
  718. // associated segment data).
  719. if (j === 4)
  720. line.push([segment[0], segment[1], segment[2], segment[3]]);
  721. else if (j === 5)
  722. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  723. else if (j === 1)
  724. line.push([segment[0]]);
  725. }
  726. function encode(decoded) {
  727. var sourceFileIndex = 0; // second field
  728. var sourceCodeLine = 0; // third field
  729. var sourceCodeColumn = 0; // fourth field
  730. var nameIndex = 0; // fifth field
  731. var mappings = '';
  732. for (var i = 0; i < decoded.length; i++) {
  733. var line = decoded[i];
  734. if (i > 0)
  735. mappings += ';';
  736. if (line.length === 0)
  737. continue;
  738. var generatedCodeColumn = 0; // first field
  739. var lineMappings = [];
  740. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  741. var segment = line_1[_i];
  742. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  743. generatedCodeColumn = segment[0];
  744. if (segment.length > 1) {
  745. segmentMappings +=
  746. encodeInteger(segment[1] - sourceFileIndex) +
  747. encodeInteger(segment[2] - sourceCodeLine) +
  748. encodeInteger(segment[3] - sourceCodeColumn);
  749. sourceFileIndex = segment[1];
  750. sourceCodeLine = segment[2];
  751. sourceCodeColumn = segment[3];
  752. }
  753. if (segment.length === 5) {
  754. segmentMappings += encodeInteger(segment[4] - nameIndex);
  755. nameIndex = segment[4];
  756. }
  757. lineMappings.push(segmentMappings);
  758. }
  759. mappings += lineMappings.join(',');
  760. }
  761. return mappings;
  762. }
  763. function encodeInteger(num) {
  764. var result = '';
  765. num = num < 0 ? (-num << 1) | 1 : num << 1;
  766. do {
  767. var clamped = num & 31;
  768. num >>>= 5;
  769. if (num > 0) {
  770. clamped |= 32;
  771. }
  772. result += chars$1[clamped];
  773. } while (num > 0);
  774. return result;
  775. }
  776. class BitSet {
  777. constructor(arg) {
  778. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  779. }
  780. add(n) {
  781. this.bits[n >> 5] |= 1 << (n & 31);
  782. }
  783. has(n) {
  784. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  785. }
  786. }
  787. class Chunk$1 {
  788. constructor(start, end, content) {
  789. this.start = start;
  790. this.end = end;
  791. this.original = content;
  792. this.intro = '';
  793. this.outro = '';
  794. this.content = content;
  795. this.storeName = false;
  796. this.edited = false;
  797. // we make these non-enumerable, for sanity while debugging
  798. Object.defineProperties(this, {
  799. previous: { writable: true, value: null },
  800. next: { writable: true, value: null },
  801. });
  802. }
  803. appendLeft(content) {
  804. this.outro += content;
  805. }
  806. appendRight(content) {
  807. this.intro = this.intro + content;
  808. }
  809. clone() {
  810. const chunk = new Chunk$1(this.start, this.end, this.original);
  811. chunk.intro = this.intro;
  812. chunk.outro = this.outro;
  813. chunk.content = this.content;
  814. chunk.storeName = this.storeName;
  815. chunk.edited = this.edited;
  816. return chunk;
  817. }
  818. contains(index) {
  819. return this.start < index && index < this.end;
  820. }
  821. eachNext(fn) {
  822. let chunk = this;
  823. while (chunk) {
  824. fn(chunk);
  825. chunk = chunk.next;
  826. }
  827. }
  828. eachPrevious(fn) {
  829. let chunk = this;
  830. while (chunk) {
  831. fn(chunk);
  832. chunk = chunk.previous;
  833. }
  834. }
  835. edit(content, storeName, contentOnly) {
  836. this.content = content;
  837. if (!contentOnly) {
  838. this.intro = '';
  839. this.outro = '';
  840. }
  841. this.storeName = storeName;
  842. this.edited = true;
  843. return this;
  844. }
  845. prependLeft(content) {
  846. this.outro = content + this.outro;
  847. }
  848. prependRight(content) {
  849. this.intro = content + this.intro;
  850. }
  851. split(index) {
  852. const sliceIndex = index - this.start;
  853. const originalBefore = this.original.slice(0, sliceIndex);
  854. const originalAfter = this.original.slice(sliceIndex);
  855. this.original = originalBefore;
  856. const newChunk = new Chunk$1(index, this.end, originalAfter);
  857. newChunk.outro = this.outro;
  858. this.outro = '';
  859. this.end = index;
  860. if (this.edited) {
  861. // TODO is this block necessary?...
  862. newChunk.edit('', false);
  863. this.content = '';
  864. } else {
  865. this.content = originalBefore;
  866. }
  867. newChunk.next = this.next;
  868. if (newChunk.next) newChunk.next.previous = newChunk;
  869. newChunk.previous = this;
  870. this.next = newChunk;
  871. return newChunk;
  872. }
  873. toString() {
  874. return this.intro + this.content + this.outro;
  875. }
  876. trimEnd(rx) {
  877. this.outro = this.outro.replace(rx, '');
  878. if (this.outro.length) return true;
  879. const trimmed = this.content.replace(rx, '');
  880. if (trimmed.length) {
  881. if (trimmed !== this.content) {
  882. this.split(this.start + trimmed.length).edit('', undefined, true);
  883. }
  884. return true;
  885. } else {
  886. this.edit('', undefined, true);
  887. this.intro = this.intro.replace(rx, '');
  888. if (this.intro.length) return true;
  889. }
  890. }
  891. trimStart(rx) {
  892. this.intro = this.intro.replace(rx, '');
  893. if (this.intro.length) return true;
  894. const trimmed = this.content.replace(rx, '');
  895. if (trimmed.length) {
  896. if (trimmed !== this.content) {
  897. this.split(this.end - trimmed.length);
  898. this.edit('', undefined, true);
  899. }
  900. return true;
  901. } else {
  902. this.edit('', undefined, true);
  903. this.outro = this.outro.replace(rx, '');
  904. if (this.outro.length) return true;
  905. }
  906. }
  907. }
  908. let btoa = () => {
  909. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  910. };
  911. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  912. btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
  913. } else if (typeof Buffer === 'function') {
  914. btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
  915. }
  916. class SourceMap {
  917. constructor(properties) {
  918. this.version = 3;
  919. this.file = properties.file;
  920. this.sources = properties.sources;
  921. this.sourcesContent = properties.sourcesContent;
  922. this.names = properties.names;
  923. this.mappings = encode(properties.mappings);
  924. }
  925. toString() {
  926. return JSON.stringify(this);
  927. }
  928. toUrl() {
  929. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  930. }
  931. }
  932. function guessIndent(code) {
  933. const lines = code.split('\n');
  934. const tabbed = lines.filter((line) => /^\t+/.test(line));
  935. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  936. if (tabbed.length === 0 && spaced.length === 0) {
  937. return null;
  938. }
  939. // More lines tabbed than spaced? Assume tabs, and
  940. // default to tabs in the case of a tie (or nothing
  941. // to go on)
  942. if (tabbed.length >= spaced.length) {
  943. return '\t';
  944. }
  945. // Otherwise, we need to guess the multiple
  946. const min = spaced.reduce((previous, current) => {
  947. const numSpaces = /^ +/.exec(current)[0].length;
  948. return Math.min(numSpaces, previous);
  949. }, Infinity);
  950. return new Array(min + 1).join(' ');
  951. }
  952. function getRelativePath(from, to) {
  953. const fromParts = from.split(/[/\\]/);
  954. const toParts = to.split(/[/\\]/);
  955. fromParts.pop(); // get dirname
  956. while (fromParts[0] === toParts[0]) {
  957. fromParts.shift();
  958. toParts.shift();
  959. }
  960. if (fromParts.length) {
  961. let i = fromParts.length;
  962. while (i--) fromParts[i] = '..';
  963. }
  964. return fromParts.concat(toParts).join('/');
  965. }
  966. const toString$1 = Object.prototype.toString;
  967. function isObject$1(thing) {
  968. return toString$1.call(thing) === '[object Object]';
  969. }
  970. function getLocator(source) {
  971. const originalLines = source.split('\n');
  972. const lineOffsets = [];
  973. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  974. lineOffsets.push(pos);
  975. pos += originalLines[i].length + 1;
  976. }
  977. return function locate(index) {
  978. let i = 0;
  979. let j = lineOffsets.length;
  980. while (i < j) {
  981. const m = (i + j) >> 1;
  982. if (index < lineOffsets[m]) {
  983. j = m;
  984. } else {
  985. i = m + 1;
  986. }
  987. }
  988. const line = i - 1;
  989. const column = index - lineOffsets[line];
  990. return { line, column };
  991. };
  992. }
  993. class Mappings {
  994. constructor(hires) {
  995. this.hires = hires;
  996. this.generatedCodeLine = 0;
  997. this.generatedCodeColumn = 0;
  998. this.raw = [];
  999. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  1000. this.pending = null;
  1001. }
  1002. addEdit(sourceIndex, content, loc, nameIndex) {
  1003. if (content.length) {
  1004. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  1005. if (nameIndex >= 0) {
  1006. segment.push(nameIndex);
  1007. }
  1008. this.rawSegments.push(segment);
  1009. } else if (this.pending) {
  1010. this.rawSegments.push(this.pending);
  1011. }
  1012. this.advance(content);
  1013. this.pending = null;
  1014. }
  1015. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  1016. let originalCharIndex = chunk.start;
  1017. let first = true;
  1018. while (originalCharIndex < chunk.end) {
  1019. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  1020. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  1021. }
  1022. if (original[originalCharIndex] === '\n') {
  1023. loc.line += 1;
  1024. loc.column = 0;
  1025. this.generatedCodeLine += 1;
  1026. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1027. this.generatedCodeColumn = 0;
  1028. first = true;
  1029. } else {
  1030. loc.column += 1;
  1031. this.generatedCodeColumn += 1;
  1032. first = false;
  1033. }
  1034. originalCharIndex += 1;
  1035. }
  1036. this.pending = null;
  1037. }
  1038. advance(str) {
  1039. if (!str) return;
  1040. const lines = str.split('\n');
  1041. if (lines.length > 1) {
  1042. for (let i = 0; i < lines.length - 1; i++) {
  1043. this.generatedCodeLine++;
  1044. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  1045. }
  1046. this.generatedCodeColumn = 0;
  1047. }
  1048. this.generatedCodeColumn += lines[lines.length - 1].length;
  1049. }
  1050. }
  1051. const n = '\n';
  1052. const warned = {
  1053. insertLeft: false,
  1054. insertRight: false,
  1055. storeName: false,
  1056. };
  1057. class MagicString {
  1058. constructor(string, options = {}) {
  1059. const chunk = new Chunk$1(0, string.length, string);
  1060. Object.defineProperties(this, {
  1061. original: { writable: true, value: string },
  1062. outro: { writable: true, value: '' },
  1063. intro: { writable: true, value: '' },
  1064. firstChunk: { writable: true, value: chunk },
  1065. lastChunk: { writable: true, value: chunk },
  1066. lastSearchedChunk: { writable: true, value: chunk },
  1067. byStart: { writable: true, value: {} },
  1068. byEnd: { writable: true, value: {} },
  1069. filename: { writable: true, value: options.filename },
  1070. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  1071. sourcemapLocations: { writable: true, value: new BitSet() },
  1072. storedNames: { writable: true, value: {} },
  1073. indentStr: { writable: true, value: guessIndent(string) },
  1074. });
  1075. this.byStart[0] = chunk;
  1076. this.byEnd[string.length] = chunk;
  1077. }
  1078. addSourcemapLocation(char) {
  1079. this.sourcemapLocations.add(char);
  1080. }
  1081. append(content) {
  1082. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1083. this.outro += content;
  1084. return this;
  1085. }
  1086. appendLeft(index, content) {
  1087. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1088. this._split(index);
  1089. const chunk = this.byEnd[index];
  1090. if (chunk) {
  1091. chunk.appendLeft(content);
  1092. } else {
  1093. this.intro += content;
  1094. }
  1095. return this;
  1096. }
  1097. appendRight(index, content) {
  1098. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1099. this._split(index);
  1100. const chunk = this.byStart[index];
  1101. if (chunk) {
  1102. chunk.appendRight(content);
  1103. } else {
  1104. this.outro += content;
  1105. }
  1106. return this;
  1107. }
  1108. clone() {
  1109. const cloned = new MagicString(this.original, { filename: this.filename });
  1110. let originalChunk = this.firstChunk;
  1111. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  1112. while (originalChunk) {
  1113. cloned.byStart[clonedChunk.start] = clonedChunk;
  1114. cloned.byEnd[clonedChunk.end] = clonedChunk;
  1115. const nextOriginalChunk = originalChunk.next;
  1116. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  1117. if (nextClonedChunk) {
  1118. clonedChunk.next = nextClonedChunk;
  1119. nextClonedChunk.previous = clonedChunk;
  1120. clonedChunk = nextClonedChunk;
  1121. }
  1122. originalChunk = nextOriginalChunk;
  1123. }
  1124. cloned.lastChunk = clonedChunk;
  1125. if (this.indentExclusionRanges) {
  1126. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  1127. }
  1128. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  1129. cloned.intro = this.intro;
  1130. cloned.outro = this.outro;
  1131. return cloned;
  1132. }
  1133. generateDecodedMap(options) {
  1134. options = options || {};
  1135. const sourceIndex = 0;
  1136. const names = Object.keys(this.storedNames);
  1137. const mappings = new Mappings(options.hires);
  1138. const locate = getLocator(this.original);
  1139. if (this.intro) {
  1140. mappings.advance(this.intro);
  1141. }
  1142. this.firstChunk.eachNext((chunk) => {
  1143. const loc = locate(chunk.start);
  1144. if (chunk.intro.length) mappings.advance(chunk.intro);
  1145. if (chunk.edited) {
  1146. mappings.addEdit(
  1147. sourceIndex,
  1148. chunk.content,
  1149. loc,
  1150. chunk.storeName ? names.indexOf(chunk.original) : -1
  1151. );
  1152. } else {
  1153. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  1154. }
  1155. if (chunk.outro.length) mappings.advance(chunk.outro);
  1156. });
  1157. return {
  1158. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1159. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  1160. sourcesContent: options.includeContent ? [this.original] : [null],
  1161. names,
  1162. mappings: mappings.raw,
  1163. };
  1164. }
  1165. generateMap(options) {
  1166. return new SourceMap(this.generateDecodedMap(options));
  1167. }
  1168. getIndentString() {
  1169. return this.indentStr === null ? '\t' : this.indentStr;
  1170. }
  1171. indent(indentStr, options) {
  1172. const pattern = /^[^\r\n]/gm;
  1173. if (isObject$1(indentStr)) {
  1174. options = indentStr;
  1175. indentStr = undefined;
  1176. }
  1177. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  1178. if (indentStr === '') return this; // noop
  1179. options = options || {};
  1180. // Process exclusion ranges
  1181. const isExcluded = {};
  1182. if (options.exclude) {
  1183. const exclusions =
  1184. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  1185. exclusions.forEach((exclusion) => {
  1186. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  1187. isExcluded[i] = true;
  1188. }
  1189. });
  1190. }
  1191. let shouldIndentNextCharacter = options.indentStart !== false;
  1192. const replacer = (match) => {
  1193. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  1194. shouldIndentNextCharacter = true;
  1195. return match;
  1196. };
  1197. this.intro = this.intro.replace(pattern, replacer);
  1198. let charIndex = 0;
  1199. let chunk = this.firstChunk;
  1200. while (chunk) {
  1201. const end = chunk.end;
  1202. if (chunk.edited) {
  1203. if (!isExcluded[charIndex]) {
  1204. chunk.content = chunk.content.replace(pattern, replacer);
  1205. if (chunk.content.length) {
  1206. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  1207. }
  1208. }
  1209. } else {
  1210. charIndex = chunk.start;
  1211. while (charIndex < end) {
  1212. if (!isExcluded[charIndex]) {
  1213. const char = this.original[charIndex];
  1214. if (char === '\n') {
  1215. shouldIndentNextCharacter = true;
  1216. } else if (char !== '\r' && shouldIndentNextCharacter) {
  1217. shouldIndentNextCharacter = false;
  1218. if (charIndex === chunk.start) {
  1219. chunk.prependRight(indentStr);
  1220. } else {
  1221. this._splitChunk(chunk, charIndex);
  1222. chunk = chunk.next;
  1223. chunk.prependRight(indentStr);
  1224. }
  1225. }
  1226. }
  1227. charIndex += 1;
  1228. }
  1229. }
  1230. charIndex = chunk.end;
  1231. chunk = chunk.next;
  1232. }
  1233. this.outro = this.outro.replace(pattern, replacer);
  1234. return this;
  1235. }
  1236. insert() {
  1237. throw new Error(
  1238. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  1239. );
  1240. }
  1241. insertLeft(index, content) {
  1242. if (!warned.insertLeft) {
  1243. console.warn(
  1244. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  1245. ); // eslint-disable-line no-console
  1246. warned.insertLeft = true;
  1247. }
  1248. return this.appendLeft(index, content);
  1249. }
  1250. insertRight(index, content) {
  1251. if (!warned.insertRight) {
  1252. console.warn(
  1253. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  1254. ); // eslint-disable-line no-console
  1255. warned.insertRight = true;
  1256. }
  1257. return this.prependRight(index, content);
  1258. }
  1259. move(start, end, index) {
  1260. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  1261. this._split(start);
  1262. this._split(end);
  1263. this._split(index);
  1264. const first = this.byStart[start];
  1265. const last = this.byEnd[end];
  1266. const oldLeft = first.previous;
  1267. const oldRight = last.next;
  1268. const newRight = this.byStart[index];
  1269. if (!newRight && last === this.lastChunk) return this;
  1270. const newLeft = newRight ? newRight.previous : this.lastChunk;
  1271. if (oldLeft) oldLeft.next = oldRight;
  1272. if (oldRight) oldRight.previous = oldLeft;
  1273. if (newLeft) newLeft.next = first;
  1274. if (newRight) newRight.previous = last;
  1275. if (!first.previous) this.firstChunk = last.next;
  1276. if (!last.next) {
  1277. this.lastChunk = first.previous;
  1278. this.lastChunk.next = null;
  1279. }
  1280. first.previous = newLeft;
  1281. last.next = newRight || null;
  1282. if (!newLeft) this.firstChunk = first;
  1283. if (!newRight) this.lastChunk = last;
  1284. return this;
  1285. }
  1286. overwrite(start, end, content, options) {
  1287. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  1288. while (start < 0) start += this.original.length;
  1289. while (end < 0) end += this.original.length;
  1290. if (end > this.original.length) throw new Error('end is out of bounds');
  1291. if (start === end)
  1292. throw new Error(
  1293. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  1294. );
  1295. this._split(start);
  1296. this._split(end);
  1297. if (options === true) {
  1298. if (!warned.storeName) {
  1299. console.warn(
  1300. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  1301. ); // eslint-disable-line no-console
  1302. warned.storeName = true;
  1303. }
  1304. options = { storeName: true };
  1305. }
  1306. const storeName = options !== undefined ? options.storeName : false;
  1307. const contentOnly = options !== undefined ? options.contentOnly : false;
  1308. if (storeName) {
  1309. const original = this.original.slice(start, end);
  1310. Object.defineProperty(this.storedNames, original, {
  1311. writable: true,
  1312. value: true,
  1313. enumerable: true,
  1314. });
  1315. }
  1316. const first = this.byStart[start];
  1317. const last = this.byEnd[end];
  1318. if (first) {
  1319. let chunk = first;
  1320. while (chunk !== last) {
  1321. if (chunk.next !== this.byStart[chunk.end]) {
  1322. throw new Error('Cannot overwrite across a split point');
  1323. }
  1324. chunk = chunk.next;
  1325. chunk.edit('', false);
  1326. }
  1327. first.edit(content, storeName, contentOnly);
  1328. } else {
  1329. // must be inserting at the end
  1330. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  1331. // TODO last chunk in the array may not be the last chunk, if it's moved...
  1332. last.next = newChunk;
  1333. newChunk.previous = last;
  1334. }
  1335. return this;
  1336. }
  1337. prepend(content) {
  1338. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  1339. this.intro = content + this.intro;
  1340. return this;
  1341. }
  1342. prependLeft(index, content) {
  1343. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1344. this._split(index);
  1345. const chunk = this.byEnd[index];
  1346. if (chunk) {
  1347. chunk.prependLeft(content);
  1348. } else {
  1349. this.intro = content + this.intro;
  1350. }
  1351. return this;
  1352. }
  1353. prependRight(index, content) {
  1354. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  1355. this._split(index);
  1356. const chunk = this.byStart[index];
  1357. if (chunk) {
  1358. chunk.prependRight(content);
  1359. } else {
  1360. this.outro = content + this.outro;
  1361. }
  1362. return this;
  1363. }
  1364. remove(start, end) {
  1365. while (start < 0) start += this.original.length;
  1366. while (end < 0) end += this.original.length;
  1367. if (start === end) return this;
  1368. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  1369. if (start > end) throw new Error('end must be greater than start');
  1370. this._split(start);
  1371. this._split(end);
  1372. let chunk = this.byStart[start];
  1373. while (chunk) {
  1374. chunk.intro = '';
  1375. chunk.outro = '';
  1376. chunk.edit('');
  1377. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  1378. }
  1379. return this;
  1380. }
  1381. lastChar() {
  1382. if (this.outro.length) return this.outro[this.outro.length - 1];
  1383. let chunk = this.lastChunk;
  1384. do {
  1385. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  1386. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  1387. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  1388. } while ((chunk = chunk.previous));
  1389. if (this.intro.length) return this.intro[this.intro.length - 1];
  1390. return '';
  1391. }
  1392. lastLine() {
  1393. let lineIndex = this.outro.lastIndexOf(n);
  1394. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  1395. let lineStr = this.outro;
  1396. let chunk = this.lastChunk;
  1397. do {
  1398. if (chunk.outro.length > 0) {
  1399. lineIndex = chunk.outro.lastIndexOf(n);
  1400. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  1401. lineStr = chunk.outro + lineStr;
  1402. }
  1403. if (chunk.content.length > 0) {
  1404. lineIndex = chunk.content.lastIndexOf(n);
  1405. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  1406. lineStr = chunk.content + lineStr;
  1407. }
  1408. if (chunk.intro.length > 0) {
  1409. lineIndex = chunk.intro.lastIndexOf(n);
  1410. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  1411. lineStr = chunk.intro + lineStr;
  1412. }
  1413. } while ((chunk = chunk.previous));
  1414. lineIndex = this.intro.lastIndexOf(n);
  1415. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  1416. return this.intro + lineStr;
  1417. }
  1418. slice(start = 0, end = this.original.length) {
  1419. while (start < 0) start += this.original.length;
  1420. while (end < 0) end += this.original.length;
  1421. let result = '';
  1422. // find start chunk
  1423. let chunk = this.firstChunk;
  1424. while (chunk && (chunk.start > start || chunk.end <= start)) {
  1425. // found end chunk before start
  1426. if (chunk.start < end && chunk.end >= end) {
  1427. return result;
  1428. }
  1429. chunk = chunk.next;
  1430. }
  1431. if (chunk && chunk.edited && chunk.start !== start)
  1432. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  1433. const startChunk = chunk;
  1434. while (chunk) {
  1435. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  1436. result += chunk.intro;
  1437. }
  1438. const containsEnd = chunk.start < end && chunk.end >= end;
  1439. if (containsEnd && chunk.edited && chunk.end !== end)
  1440. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  1441. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  1442. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  1443. result += chunk.content.slice(sliceStart, sliceEnd);
  1444. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  1445. result += chunk.outro;
  1446. }
  1447. if (containsEnd) {
  1448. break;
  1449. }
  1450. chunk = chunk.next;
  1451. }
  1452. return result;
  1453. }
  1454. // TODO deprecate this? not really very useful
  1455. snip(start, end) {
  1456. const clone = this.clone();
  1457. clone.remove(0, start);
  1458. clone.remove(end, clone.original.length);
  1459. return clone;
  1460. }
  1461. _split(index) {
  1462. if (this.byStart[index] || this.byEnd[index]) return;
  1463. let chunk = this.lastSearchedChunk;
  1464. const searchForward = index > chunk.end;
  1465. while (chunk) {
  1466. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1467. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1468. }
  1469. }
  1470. _splitChunk(chunk, index) {
  1471. if (chunk.edited && chunk.content.length) {
  1472. // zero-length edited chunks are a special case (overlapping replacements)
  1473. const loc = getLocator(this.original)(index);
  1474. throw new Error(
  1475. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  1476. );
  1477. }
  1478. const newChunk = chunk.split(index);
  1479. this.byEnd[index] = chunk;
  1480. this.byStart[index] = newChunk;
  1481. this.byEnd[newChunk.end] = newChunk;
  1482. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1483. this.lastSearchedChunk = chunk;
  1484. return true;
  1485. }
  1486. toString() {
  1487. let str = this.intro;
  1488. let chunk = this.firstChunk;
  1489. while (chunk) {
  1490. str += chunk.toString();
  1491. chunk = chunk.next;
  1492. }
  1493. return str + this.outro;
  1494. }
  1495. isEmpty() {
  1496. let chunk = this.firstChunk;
  1497. do {
  1498. if (
  1499. (chunk.intro.length && chunk.intro.trim()) ||
  1500. (chunk.content.length && chunk.content.trim()) ||
  1501. (chunk.outro.length && chunk.outro.trim())
  1502. )
  1503. return false;
  1504. } while ((chunk = chunk.next));
  1505. return true;
  1506. }
  1507. length() {
  1508. let chunk = this.firstChunk;
  1509. let length = 0;
  1510. do {
  1511. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1512. } while ((chunk = chunk.next));
  1513. return length;
  1514. }
  1515. trimLines() {
  1516. return this.trim('[\\r\\n]');
  1517. }
  1518. trim(charType) {
  1519. return this.trimStart(charType).trimEnd(charType);
  1520. }
  1521. trimEndAborted(charType) {
  1522. const rx = new RegExp((charType || '\\s') + '+$');
  1523. this.outro = this.outro.replace(rx, '');
  1524. if (this.outro.length) return true;
  1525. let chunk = this.lastChunk;
  1526. do {
  1527. const end = chunk.end;
  1528. const aborted = chunk.trimEnd(rx);
  1529. // if chunk was trimmed, we have a new lastChunk
  1530. if (chunk.end !== end) {
  1531. if (this.lastChunk === chunk) {
  1532. this.lastChunk = chunk.next;
  1533. }
  1534. this.byEnd[chunk.end] = chunk;
  1535. this.byStart[chunk.next.start] = chunk.next;
  1536. this.byEnd[chunk.next.end] = chunk.next;
  1537. }
  1538. if (aborted) return true;
  1539. chunk = chunk.previous;
  1540. } while (chunk);
  1541. return false;
  1542. }
  1543. trimEnd(charType) {
  1544. this.trimEndAborted(charType);
  1545. return this;
  1546. }
  1547. trimStartAborted(charType) {
  1548. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1549. this.intro = this.intro.replace(rx, '');
  1550. if (this.intro.length) return true;
  1551. let chunk = this.firstChunk;
  1552. do {
  1553. const end = chunk.end;
  1554. const aborted = chunk.trimStart(rx);
  1555. if (chunk.end !== end) {
  1556. // special case...
  1557. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1558. this.byEnd[chunk.end] = chunk;
  1559. this.byStart[chunk.next.start] = chunk.next;
  1560. this.byEnd[chunk.next.end] = chunk.next;
  1561. }
  1562. if (aborted) return true;
  1563. chunk = chunk.next;
  1564. } while (chunk);
  1565. return false;
  1566. }
  1567. trimStart(charType) {
  1568. this.trimStartAborted(charType);
  1569. return this;
  1570. }
  1571. hasChanged() {
  1572. return this.original !== this.toString();
  1573. }
  1574. replace(searchValue, replacement) {
  1575. function getReplacement(match, str) {
  1576. if (typeof replacement === 'string') {
  1577. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1578. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1579. if (i === '$') return '$';
  1580. if (i === '&') return match[0];
  1581. const num = +i;
  1582. if (num < match.length) return match[+i];
  1583. return `$${i}`;
  1584. });
  1585. } else {
  1586. return replacement(...match, match.index, str, match.groups);
  1587. }
  1588. }
  1589. function matchAll(re, str) {
  1590. let match;
  1591. const matches = [];
  1592. while ((match = re.exec(str))) {
  1593. matches.push(match);
  1594. }
  1595. return matches;
  1596. }
  1597. if (typeof searchValue !== 'string' && searchValue.global) {
  1598. const matches = matchAll(searchValue, this.original);
  1599. matches.forEach((match) => {
  1600. if (match.index != null)
  1601. this.overwrite(
  1602. match.index,
  1603. match.index + match[0].length,
  1604. getReplacement(match, this.original)
  1605. );
  1606. });
  1607. } else {
  1608. const match = this.original.match(searchValue);
  1609. if (match && match.index != null)
  1610. this.overwrite(
  1611. match.index,
  1612. match.index + match[0].length,
  1613. getReplacement(match, this.original)
  1614. );
  1615. }
  1616. return this;
  1617. }
  1618. }
  1619. const hasOwnProp = Object.prototype.hasOwnProperty;
  1620. class Bundle$1 {
  1621. constructor(options = {}) {
  1622. this.intro = options.intro || '';
  1623. this.separator = options.separator !== undefined ? options.separator : '\n';
  1624. this.sources = [];
  1625. this.uniqueSources = [];
  1626. this.uniqueSourceIndexByFilename = {};
  1627. }
  1628. addSource(source) {
  1629. if (source instanceof MagicString) {
  1630. return this.addSource({
  1631. content: source,
  1632. filename: source.filename,
  1633. separator: this.separator,
  1634. });
  1635. }
  1636. if (!isObject$1(source) || !source.content) {
  1637. throw new Error(
  1638. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  1639. );
  1640. }
  1641. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1642. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1643. });
  1644. if (source.separator === undefined) {
  1645. // TODO there's a bunch of this sort of thing, needs cleaning up
  1646. source.separator = this.separator;
  1647. }
  1648. if (source.filename) {
  1649. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1650. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1651. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1652. } else {
  1653. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1654. if (source.content.original !== uniqueSource.content) {
  1655. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1656. }
  1657. }
  1658. }
  1659. this.sources.push(source);
  1660. return this;
  1661. }
  1662. append(str, options) {
  1663. this.addSource({
  1664. content: new MagicString(str),
  1665. separator: (options && options.separator) || '',
  1666. });
  1667. return this;
  1668. }
  1669. clone() {
  1670. const bundle = new Bundle$1({
  1671. intro: this.intro,
  1672. separator: this.separator,
  1673. });
  1674. this.sources.forEach((source) => {
  1675. bundle.addSource({
  1676. filename: source.filename,
  1677. content: source.content.clone(),
  1678. separator: source.separator,
  1679. });
  1680. });
  1681. return bundle;
  1682. }
  1683. generateDecodedMap(options = {}) {
  1684. const names = [];
  1685. this.sources.forEach((source) => {
  1686. Object.keys(source.content.storedNames).forEach((name) => {
  1687. if (!~names.indexOf(name)) names.push(name);
  1688. });
  1689. });
  1690. const mappings = new Mappings(options.hires);
  1691. if (this.intro) {
  1692. mappings.advance(this.intro);
  1693. }
  1694. this.sources.forEach((source, i) => {
  1695. if (i > 0) {
  1696. mappings.advance(this.separator);
  1697. }
  1698. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1699. const magicString = source.content;
  1700. const locate = getLocator(magicString.original);
  1701. if (magicString.intro) {
  1702. mappings.advance(magicString.intro);
  1703. }
  1704. magicString.firstChunk.eachNext((chunk) => {
  1705. const loc = locate(chunk.start);
  1706. if (chunk.intro.length) mappings.advance(chunk.intro);
  1707. if (source.filename) {
  1708. if (chunk.edited) {
  1709. mappings.addEdit(
  1710. sourceIndex,
  1711. chunk.content,
  1712. loc,
  1713. chunk.storeName ? names.indexOf(chunk.original) : -1
  1714. );
  1715. } else {
  1716. mappings.addUneditedChunk(
  1717. sourceIndex,
  1718. chunk,
  1719. magicString.original,
  1720. loc,
  1721. magicString.sourcemapLocations
  1722. );
  1723. }
  1724. } else {
  1725. mappings.advance(chunk.content);
  1726. }
  1727. if (chunk.outro.length) mappings.advance(chunk.outro);
  1728. });
  1729. if (magicString.outro) {
  1730. mappings.advance(magicString.outro);
  1731. }
  1732. });
  1733. return {
  1734. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1735. sources: this.uniqueSources.map((source) => {
  1736. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1737. }),
  1738. sourcesContent: this.uniqueSources.map((source) => {
  1739. return options.includeContent ? source.content : null;
  1740. }),
  1741. names,
  1742. mappings: mappings.raw,
  1743. };
  1744. }
  1745. generateMap(options) {
  1746. return new SourceMap(this.generateDecodedMap(options));
  1747. }
  1748. getIndentString() {
  1749. const indentStringCounts = {};
  1750. this.sources.forEach((source) => {
  1751. const indentStr = source.content.indentStr;
  1752. if (indentStr === null) return;
  1753. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1754. indentStringCounts[indentStr] += 1;
  1755. });
  1756. return (
  1757. Object.keys(indentStringCounts).sort((a, b) => {
  1758. return indentStringCounts[a] - indentStringCounts[b];
  1759. })[0] || '\t'
  1760. );
  1761. }
  1762. indent(indentStr) {
  1763. if (!arguments.length) {
  1764. indentStr = this.getIndentString();
  1765. }
  1766. if (indentStr === '') return this; // noop
  1767. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1768. this.sources.forEach((source, i) => {
  1769. const separator = source.separator !== undefined ? source.separator : this.separator;
  1770. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1771. source.content.indent(indentStr, {
  1772. exclude: source.indentExclusionRanges,
  1773. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1774. });
  1775. trailingNewline = source.content.lastChar() === '\n';
  1776. });
  1777. if (this.intro) {
  1778. this.intro =
  1779. indentStr +
  1780. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1781. return index > 0 ? indentStr + match : match;
  1782. });
  1783. }
  1784. return this;
  1785. }
  1786. prepend(str) {
  1787. this.intro = str + this.intro;
  1788. return this;
  1789. }
  1790. toString() {
  1791. const body = this.sources
  1792. .map((source, i) => {
  1793. const separator = source.separator !== undefined ? source.separator : this.separator;
  1794. const str = (i > 0 ? separator : '') + source.content.toString();
  1795. return str;
  1796. })
  1797. .join('');
  1798. return this.intro + body;
  1799. }
  1800. isEmpty() {
  1801. if (this.intro.length && this.intro.trim()) return false;
  1802. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1803. return true;
  1804. }
  1805. length() {
  1806. return this.sources.reduce(
  1807. (length, source) => length + source.content.length(),
  1808. this.intro.length
  1809. );
  1810. }
  1811. trimLines() {
  1812. return this.trim('[\\r\\n]');
  1813. }
  1814. trim(charType) {
  1815. return this.trimStart(charType).trimEnd(charType);
  1816. }
  1817. trimStart(charType) {
  1818. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1819. this.intro = this.intro.replace(rx, '');
  1820. if (!this.intro) {
  1821. let source;
  1822. let i = 0;
  1823. do {
  1824. source = this.sources[i++];
  1825. if (!source) {
  1826. break;
  1827. }
  1828. } while (!source.content.trimStartAborted(charType));
  1829. }
  1830. return this;
  1831. }
  1832. trimEnd(charType) {
  1833. const rx = new RegExp((charType || '\\s') + '+$');
  1834. let source;
  1835. let i = this.sources.length - 1;
  1836. do {
  1837. source = this.sources[i--];
  1838. if (!source) {
  1839. this.intro = this.intro.replace(rx, '');
  1840. break;
  1841. }
  1842. } while (!source.content.trimEndAborted(charType));
  1843. return this;
  1844. }
  1845. }
  1846. function getOrCreate(map, key, init) {
  1847. const existing = map.get(key);
  1848. if (existing) {
  1849. return existing;
  1850. }
  1851. const value = init();
  1852. map.set(key, value);
  1853. return value;
  1854. }
  1855. const UnknownKey = Symbol('Unknown Key');
  1856. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1857. const UnknownInteger = Symbol('Unknown Integer');
  1858. const EMPTY_PATH = [];
  1859. const UNKNOWN_PATH = [UnknownKey];
  1860. // For deoptimizations, this means we are modifying an unknown property but did
  1861. // not lose track of the object or are creating a setter/getter;
  1862. // For assignment effects it means we do not check for setter/getter effects
  1863. // but only if something is mutated that is included, which is relevant for
  1864. // Object.defineProperty
  1865. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1866. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1867. const EntitiesKey = Symbol('Entities');
  1868. class PathTracker {
  1869. constructor() {
  1870. this.entityPaths = Object.create(null, {
  1871. [EntitiesKey]: { value: new Set() }
  1872. });
  1873. }
  1874. trackEntityAtPathAndGetIfTracked(path, entity) {
  1875. const trackedEntities = this.getEntities(path);
  1876. if (trackedEntities.has(entity))
  1877. return true;
  1878. trackedEntities.add(entity);
  1879. return false;
  1880. }
  1881. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1882. const trackedEntities = this.getEntities(path);
  1883. if (trackedEntities.has(entity))
  1884. return returnIfTracked;
  1885. trackedEntities.add(entity);
  1886. const result = onUntracked();
  1887. trackedEntities.delete(entity);
  1888. return result;
  1889. }
  1890. getEntities(path) {
  1891. let currentPaths = this.entityPaths;
  1892. for (const pathSegment of path) {
  1893. currentPaths = currentPaths[pathSegment] =
  1894. currentPaths[pathSegment] ||
  1895. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1896. }
  1897. return currentPaths[EntitiesKey];
  1898. }
  1899. }
  1900. const SHARED_RECURSION_TRACKER = new PathTracker();
  1901. class DiscriminatedPathTracker {
  1902. constructor() {
  1903. this.entityPaths = Object.create(null, {
  1904. [EntitiesKey]: { value: new Map() }
  1905. });
  1906. }
  1907. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1908. let currentPaths = this.entityPaths;
  1909. for (const pathSegment of path) {
  1910. currentPaths = currentPaths[pathSegment] =
  1911. currentPaths[pathSegment] ||
  1912. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1913. }
  1914. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1915. if (trackedEntities.has(entity))
  1916. return true;
  1917. trackedEntities.add(entity);
  1918. return false;
  1919. }
  1920. }
  1921. const UnknownValue = Symbol('Unknown Value');
  1922. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1923. class ExpressionEntity {
  1924. constructor() {
  1925. this.included = false;
  1926. }
  1927. deoptimizePath(_path) { }
  1928. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  1929. thisArg.deoptimizePath(UNKNOWN_PATH);
  1930. }
  1931. /**
  1932. * If possible it returns a stringifyable literal value for this node that can be used
  1933. * for inlining or comparing values.
  1934. * Otherwise it should return UnknownValue.
  1935. */
  1936. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1937. return UnknownValue;
  1938. }
  1939. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1940. return UNKNOWN_EXPRESSION;
  1941. }
  1942. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1943. return true;
  1944. }
  1945. include(_context, _includeChildrenRecursively, _options) {
  1946. this.included = true;
  1947. }
  1948. includeCallArguments(context, args) {
  1949. for (const arg of args) {
  1950. arg.include(context, false);
  1951. }
  1952. }
  1953. shouldBeIncluded(_context) {
  1954. return true;
  1955. }
  1956. }
  1957. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1958. })();
  1959. const INTERACTION_ACCESSED = 0;
  1960. const INTERACTION_ASSIGNED = 1;
  1961. const INTERACTION_CALLED = 2;
  1962. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1963. thisArg: null,
  1964. type: INTERACTION_ACCESSED
  1965. };
  1966. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  1967. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1968. args: UNKNOWN_ARG,
  1969. thisArg: null,
  1970. type: INTERACTION_ASSIGNED
  1971. };
  1972. const NO_ARGS = [];
  1973. // While this is technically a call without arguments, we can compare against
  1974. // this reference in places where precise values or thisArg would make a
  1975. // difference
  1976. const NODE_INTERACTION_UNKNOWN_CALL = {
  1977. args: NO_ARGS,
  1978. thisArg: null,
  1979. type: INTERACTION_CALLED,
  1980. withNew: false
  1981. };
  1982. class Variable extends ExpressionEntity {
  1983. constructor(name) {
  1984. super();
  1985. this.name = name;
  1986. this.alwaysRendered = false;
  1987. this.initReached = false;
  1988. this.isId = false;
  1989. this.isReassigned = false;
  1990. this.kind = null;
  1991. this.renderBaseName = null;
  1992. this.renderName = null;
  1993. }
  1994. /**
  1995. * Binds identifiers that reference this variable to this variable.
  1996. * Necessary to be able to change variable names.
  1997. */
  1998. addReference(_identifier) { }
  1999. getBaseVariableName() {
  2000. return this.renderBaseName || this.renderName || this.name;
  2001. }
  2002. getName(getPropertyAccess) {
  2003. const name = this.renderName || this.name;
  2004. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2005. }
  2006. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2007. return type !== INTERACTION_ACCESSED || path.length > 0;
  2008. }
  2009. /**
  2010. * Marks this variable as being part of the bundle, which is usually the case when one of
  2011. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2012. * previously.
  2013. * Once a variable is included, it should take care all its declarations are included.
  2014. */
  2015. include() {
  2016. this.included = true;
  2017. }
  2018. markCalledFromTryStatement() { }
  2019. setRenderNames(baseName, name) {
  2020. this.renderBaseName = baseName;
  2021. this.renderName = name;
  2022. }
  2023. }
  2024. class ExternalVariable extends Variable {
  2025. constructor(module, name) {
  2026. super(name);
  2027. this.referenced = false;
  2028. this.module = module;
  2029. this.isNamespace = name === '*';
  2030. }
  2031. addReference(identifier) {
  2032. this.referenced = true;
  2033. if (this.name === 'default' || this.name === '*') {
  2034. this.module.suggestName(identifier.name);
  2035. }
  2036. }
  2037. hasEffectsOnInteractionAtPath(path, { type }) {
  2038. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2039. }
  2040. include() {
  2041. if (!this.included) {
  2042. this.included = true;
  2043. this.module.used = true;
  2044. }
  2045. }
  2046. }
  2047. const BLANK = Object.freeze(Object.create(null));
  2048. const EMPTY_OBJECT = Object.freeze({});
  2049. const EMPTY_ARRAY = Object.freeze([]);
  2050. const RESERVED_NAMES = new Set([
  2051. 'await',
  2052. 'break',
  2053. 'case',
  2054. 'catch',
  2055. 'class',
  2056. 'const',
  2057. 'continue',
  2058. 'debugger',
  2059. 'default',
  2060. 'delete',
  2061. 'do',
  2062. 'else',
  2063. 'enum',
  2064. 'eval',
  2065. 'export',
  2066. 'extends',
  2067. 'false',
  2068. 'finally',
  2069. 'for',
  2070. 'function',
  2071. 'if',
  2072. 'implements',
  2073. 'import',
  2074. 'in',
  2075. 'instanceof',
  2076. 'interface',
  2077. 'let',
  2078. 'NaN',
  2079. 'new',
  2080. 'null',
  2081. 'package',
  2082. 'private',
  2083. 'protected',
  2084. 'public',
  2085. 'return',
  2086. 'static',
  2087. 'super',
  2088. 'switch',
  2089. 'this',
  2090. 'throw',
  2091. 'true',
  2092. 'try',
  2093. 'typeof',
  2094. 'undefined',
  2095. 'var',
  2096. 'void',
  2097. 'while',
  2098. 'with',
  2099. 'yield'
  2100. ]);
  2101. const RESERVED_NAMES$1 = RESERVED_NAMES;
  2102. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  2103. const startsWithDigit = (str) => /\d/.test(str[0]);
  2104. function isLegal(str) {
  2105. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str)) {
  2106. return false;
  2107. }
  2108. return !illegalCharacters.test(str);
  2109. }
  2110. function makeLegal(str) {
  2111. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  2112. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str))
  2113. str = `_${str}`;
  2114. return str || '_';
  2115. }
  2116. class ExternalModule {
  2117. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
  2118. this.options = options;
  2119. this.id = id;
  2120. this.renormalizeRenderPath = renormalizeRenderPath;
  2121. this.declarations = new Map();
  2122. this.defaultVariableName = '';
  2123. this.dynamicImporters = [];
  2124. this.execIndex = Infinity;
  2125. this.exportedVariables = new Map();
  2126. this.importers = [];
  2127. this.mostCommonSuggestion = 0;
  2128. this.nameSuggestions = new Map();
  2129. this.namespaceVariableName = '';
  2130. this.reexported = false;
  2131. this.renderPath = undefined;
  2132. this.used = false;
  2133. this.variableName = '';
  2134. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  2135. const { importers, dynamicImporters } = this;
  2136. const info = (this.info = {
  2137. ast: null,
  2138. code: null,
  2139. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2140. dynamicallyImportedIds: EMPTY_ARRAY,
  2141. get dynamicImporters() {
  2142. return dynamicImporters.sort();
  2143. },
  2144. hasDefaultExport: null,
  2145. get hasModuleSideEffects() {
  2146. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  2147. return info.moduleSideEffects;
  2148. },
  2149. id,
  2150. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2151. implicitlyLoadedBefore: EMPTY_ARRAY,
  2152. importedIdResolutions: EMPTY_ARRAY,
  2153. importedIds: EMPTY_ARRAY,
  2154. get importers() {
  2155. return importers.sort();
  2156. },
  2157. isEntry: false,
  2158. isExternal: true,
  2159. isIncluded: null,
  2160. meta,
  2161. moduleSideEffects,
  2162. syntheticNamedExports: false
  2163. });
  2164. // Hide the deprecated key so that it only warns when accessed explicitly
  2165. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2166. enumerable: false
  2167. });
  2168. }
  2169. getVariableForExportName(name) {
  2170. const declaration = this.declarations.get(name);
  2171. if (declaration)
  2172. return [declaration];
  2173. const externalVariable = new ExternalVariable(this, name);
  2174. this.declarations.set(name, externalVariable);
  2175. this.exportedVariables.set(externalVariable, name);
  2176. return [externalVariable];
  2177. }
  2178. setRenderPath(options, inputBase) {
  2179. this.renderPath =
  2180. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2181. if (!this.renderPath) {
  2182. this.renderPath = this.renormalizeRenderPath
  2183. ? normalize(require$$0.relative(inputBase, this.id))
  2184. : this.id;
  2185. }
  2186. }
  2187. suggestName(name) {
  2188. var _a;
  2189. const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
  2190. this.nameSuggestions.set(name, value);
  2191. if (value > this.mostCommonSuggestion) {
  2192. this.mostCommonSuggestion = value;
  2193. this.suggestedVariableName = name;
  2194. }
  2195. }
  2196. warnUnusedImports() {
  2197. const unused = Array.from(this.declarations)
  2198. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2199. .map(([name]) => name);
  2200. if (unused.length === 0)
  2201. return;
  2202. const importersSet = new Set();
  2203. for (const name of unused) {
  2204. for (const importer of this.declarations.get(name).module.importers) {
  2205. importersSet.add(importer);
  2206. }
  2207. }
  2208. const importersArray = [...importersSet];
  2209. this.options.onwarn({
  2210. code: 'UNUSED_EXTERNAL_IMPORT',
  2211. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2212. names: unused,
  2213. source: this.id,
  2214. sources: importersArray
  2215. });
  2216. }
  2217. }
  2218. var picomatch$1 = {exports: {}};
  2219. var utils$3 = {};
  2220. const path$1 = require$$0;
  2221. const WIN_SLASH = '\\\\/';
  2222. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2223. /**
  2224. * Posix glob regex
  2225. */
  2226. const DOT_LITERAL = '\\.';
  2227. const PLUS_LITERAL = '\\+';
  2228. const QMARK_LITERAL = '\\?';
  2229. const SLASH_LITERAL = '\\/';
  2230. const ONE_CHAR = '(?=.)';
  2231. const QMARK = '[^/]';
  2232. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2233. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2234. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2235. const NO_DOT = `(?!${DOT_LITERAL})`;
  2236. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2237. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2238. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2239. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2240. const STAR = `${QMARK}*?`;
  2241. const POSIX_CHARS = {
  2242. DOT_LITERAL,
  2243. PLUS_LITERAL,
  2244. QMARK_LITERAL,
  2245. SLASH_LITERAL,
  2246. ONE_CHAR,
  2247. QMARK,
  2248. END_ANCHOR,
  2249. DOTS_SLASH,
  2250. NO_DOT,
  2251. NO_DOTS,
  2252. NO_DOT_SLASH,
  2253. NO_DOTS_SLASH,
  2254. QMARK_NO_DOT,
  2255. STAR,
  2256. START_ANCHOR
  2257. };
  2258. /**
  2259. * Windows glob regex
  2260. */
  2261. const WINDOWS_CHARS = {
  2262. ...POSIX_CHARS,
  2263. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2264. QMARK: WIN_NO_SLASH,
  2265. STAR: `${WIN_NO_SLASH}*?`,
  2266. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2267. NO_DOT: `(?!${DOT_LITERAL})`,
  2268. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2269. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2270. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2271. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2272. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2273. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2274. };
  2275. /**
  2276. * POSIX Bracket Regex
  2277. */
  2278. const POSIX_REGEX_SOURCE$1 = {
  2279. alnum: 'a-zA-Z0-9',
  2280. alpha: 'a-zA-Z',
  2281. ascii: '\\x00-\\x7F',
  2282. blank: ' \\t',
  2283. cntrl: '\\x00-\\x1F\\x7F',
  2284. digit: '0-9',
  2285. graph: '\\x21-\\x7E',
  2286. lower: 'a-z',
  2287. print: '\\x20-\\x7E ',
  2288. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2289. space: ' \\t\\r\\n\\v\\f',
  2290. upper: 'A-Z',
  2291. word: 'A-Za-z0-9_',
  2292. xdigit: 'A-Fa-f0-9'
  2293. };
  2294. var constants$2 = {
  2295. MAX_LENGTH: 1024 * 64,
  2296. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2297. // regular expressions
  2298. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2299. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2300. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2301. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2302. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2303. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2304. // Replace globs with equivalent patterns to reduce parsing time.
  2305. REPLACEMENTS: {
  2306. '***': '*',
  2307. '**/**': '**',
  2308. '**/**/**': '**'
  2309. },
  2310. // Digits
  2311. CHAR_0: 48, /* 0 */
  2312. CHAR_9: 57, /* 9 */
  2313. // Alphabet chars.
  2314. CHAR_UPPERCASE_A: 65, /* A */
  2315. CHAR_LOWERCASE_A: 97, /* a */
  2316. CHAR_UPPERCASE_Z: 90, /* Z */
  2317. CHAR_LOWERCASE_Z: 122, /* z */
  2318. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2319. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2320. CHAR_ASTERISK: 42, /* * */
  2321. // Non-alphabetic chars.
  2322. CHAR_AMPERSAND: 38, /* & */
  2323. CHAR_AT: 64, /* @ */
  2324. CHAR_BACKWARD_SLASH: 92, /* \ */
  2325. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2326. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2327. CHAR_COLON: 58, /* : */
  2328. CHAR_COMMA: 44, /* , */
  2329. CHAR_DOT: 46, /* . */
  2330. CHAR_DOUBLE_QUOTE: 34, /* " */
  2331. CHAR_EQUAL: 61, /* = */
  2332. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2333. CHAR_FORM_FEED: 12, /* \f */
  2334. CHAR_FORWARD_SLASH: 47, /* / */
  2335. CHAR_GRAVE_ACCENT: 96, /* ` */
  2336. CHAR_HASH: 35, /* # */
  2337. CHAR_HYPHEN_MINUS: 45, /* - */
  2338. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2339. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2340. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2341. CHAR_LINE_FEED: 10, /* \n */
  2342. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2343. CHAR_PERCENT: 37, /* % */
  2344. CHAR_PLUS: 43, /* + */
  2345. CHAR_QUESTION_MARK: 63, /* ? */
  2346. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2347. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2348. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2349. CHAR_SEMICOLON: 59, /* ; */
  2350. CHAR_SINGLE_QUOTE: 39, /* ' */
  2351. CHAR_SPACE: 32, /* */
  2352. CHAR_TAB: 9, /* \t */
  2353. CHAR_UNDERSCORE: 95, /* _ */
  2354. CHAR_VERTICAL_LINE: 124, /* | */
  2355. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2356. SEP: path$1.sep,
  2357. /**
  2358. * Create EXTGLOB_CHARS
  2359. */
  2360. extglobChars(chars) {
  2361. return {
  2362. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2363. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2364. '+': { type: 'plus', open: '(?:', close: ')+' },
  2365. '*': { type: 'star', open: '(?:', close: ')*' },
  2366. '@': { type: 'at', open: '(?:', close: ')' }
  2367. };
  2368. },
  2369. /**
  2370. * Create GLOB_CHARS
  2371. */
  2372. globChars(win32) {
  2373. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2374. }
  2375. };
  2376. (function (exports) {
  2377. const path = require$$0;
  2378. const win32 = process.platform === 'win32';
  2379. const {
  2380. REGEX_BACKSLASH,
  2381. REGEX_REMOVE_BACKSLASH,
  2382. REGEX_SPECIAL_CHARS,
  2383. REGEX_SPECIAL_CHARS_GLOBAL
  2384. } = constants$2;
  2385. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2386. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2387. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2388. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2389. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2390. exports.removeBackslashes = str => {
  2391. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2392. return match === '\\' ? '' : match;
  2393. });
  2394. };
  2395. exports.supportsLookbehinds = () => {
  2396. const segs = process.version.slice(1).split('.').map(Number);
  2397. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2398. return true;
  2399. }
  2400. return false;
  2401. };
  2402. exports.isWindows = options => {
  2403. if (options && typeof options.windows === 'boolean') {
  2404. return options.windows;
  2405. }
  2406. return win32 === true || path.sep === '\\';
  2407. };
  2408. exports.escapeLast = (input, char, lastIdx) => {
  2409. const idx = input.lastIndexOf(char, lastIdx);
  2410. if (idx === -1) return input;
  2411. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2412. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2413. };
  2414. exports.removePrefix = (input, state = {}) => {
  2415. let output = input;
  2416. if (output.startsWith('./')) {
  2417. output = output.slice(2);
  2418. state.prefix = './';
  2419. }
  2420. return output;
  2421. };
  2422. exports.wrapOutput = (input, state = {}, options = {}) => {
  2423. const prepend = options.contains ? '' : '^';
  2424. const append = options.contains ? '' : '$';
  2425. let output = `${prepend}(?:${input})${append}`;
  2426. if (state.negated === true) {
  2427. output = `(?:^(?!${output}).*$)`;
  2428. }
  2429. return output;
  2430. };
  2431. } (utils$3));
  2432. const utils$2 = utils$3;
  2433. const {
  2434. CHAR_ASTERISK, /* * */
  2435. CHAR_AT, /* @ */
  2436. CHAR_BACKWARD_SLASH, /* \ */
  2437. CHAR_COMMA, /* , */
  2438. CHAR_DOT, /* . */
  2439. CHAR_EXCLAMATION_MARK, /* ! */
  2440. CHAR_FORWARD_SLASH, /* / */
  2441. CHAR_LEFT_CURLY_BRACE, /* { */
  2442. CHAR_LEFT_PARENTHESES, /* ( */
  2443. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2444. CHAR_PLUS, /* + */
  2445. CHAR_QUESTION_MARK, /* ? */
  2446. CHAR_RIGHT_CURLY_BRACE, /* } */
  2447. CHAR_RIGHT_PARENTHESES, /* ) */
  2448. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2449. } = constants$2;
  2450. const isPathSeparator = code => {
  2451. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2452. };
  2453. const depth = token => {
  2454. if (token.isPrefix !== true) {
  2455. token.depth = token.isGlobstar ? Infinity : 1;
  2456. }
  2457. };
  2458. /**
  2459. * Quickly scans a glob pattern and returns an object with a handful of
  2460. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2461. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2462. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2463. *
  2464. * ```js
  2465. * const pm = require('picomatch');
  2466. * console.log(pm.scan('foo/bar/*.js'));
  2467. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2468. * ```
  2469. * @param {String} `str`
  2470. * @param {Object} `options`
  2471. * @return {Object} Returns an object with tokens and regex source string.
  2472. * @api public
  2473. */
  2474. const scan$1 = (input, options) => {
  2475. const opts = options || {};
  2476. const length = input.length - 1;
  2477. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2478. const slashes = [];
  2479. const tokens = [];
  2480. const parts = [];
  2481. let str = input;
  2482. let index = -1;
  2483. let start = 0;
  2484. let lastIndex = 0;
  2485. let isBrace = false;
  2486. let isBracket = false;
  2487. let isGlob = false;
  2488. let isExtglob = false;
  2489. let isGlobstar = false;
  2490. let braceEscaped = false;
  2491. let backslashes = false;
  2492. let negated = false;
  2493. let negatedExtglob = false;
  2494. let finished = false;
  2495. let braces = 0;
  2496. let prev;
  2497. let code;
  2498. let token = { value: '', depth: 0, isGlob: false };
  2499. const eos = () => index >= length;
  2500. const peek = () => str.charCodeAt(index + 1);
  2501. const advance = () => {
  2502. prev = code;
  2503. return str.charCodeAt(++index);
  2504. };
  2505. while (index < length) {
  2506. code = advance();
  2507. let next;
  2508. if (code === CHAR_BACKWARD_SLASH) {
  2509. backslashes = token.backslashes = true;
  2510. code = advance();
  2511. if (code === CHAR_LEFT_CURLY_BRACE) {
  2512. braceEscaped = true;
  2513. }
  2514. continue;
  2515. }
  2516. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2517. braces++;
  2518. while (eos() !== true && (code = advance())) {
  2519. if (code === CHAR_BACKWARD_SLASH) {
  2520. backslashes = token.backslashes = true;
  2521. advance();
  2522. continue;
  2523. }
  2524. if (code === CHAR_LEFT_CURLY_BRACE) {
  2525. braces++;
  2526. continue;
  2527. }
  2528. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2529. isBrace = token.isBrace = true;
  2530. isGlob = token.isGlob = true;
  2531. finished = true;
  2532. if (scanToEnd === true) {
  2533. continue;
  2534. }
  2535. break;
  2536. }
  2537. if (braceEscaped !== true && code === CHAR_COMMA) {
  2538. isBrace = token.isBrace = true;
  2539. isGlob = token.isGlob = true;
  2540. finished = true;
  2541. if (scanToEnd === true) {
  2542. continue;
  2543. }
  2544. break;
  2545. }
  2546. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2547. braces--;
  2548. if (braces === 0) {
  2549. braceEscaped = false;
  2550. isBrace = token.isBrace = true;
  2551. finished = true;
  2552. break;
  2553. }
  2554. }
  2555. }
  2556. if (scanToEnd === true) {
  2557. continue;
  2558. }
  2559. break;
  2560. }
  2561. if (code === CHAR_FORWARD_SLASH) {
  2562. slashes.push(index);
  2563. tokens.push(token);
  2564. token = { value: '', depth: 0, isGlob: false };
  2565. if (finished === true) continue;
  2566. if (prev === CHAR_DOT && index === (start + 1)) {
  2567. start += 2;
  2568. continue;
  2569. }
  2570. lastIndex = index + 1;
  2571. continue;
  2572. }
  2573. if (opts.noext !== true) {
  2574. const isExtglobChar = code === CHAR_PLUS
  2575. || code === CHAR_AT
  2576. || code === CHAR_ASTERISK
  2577. || code === CHAR_QUESTION_MARK
  2578. || code === CHAR_EXCLAMATION_MARK;
  2579. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2580. isGlob = token.isGlob = true;
  2581. isExtglob = token.isExtglob = true;
  2582. finished = true;
  2583. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2584. negatedExtglob = true;
  2585. }
  2586. if (scanToEnd === true) {
  2587. while (eos() !== true && (code = advance())) {
  2588. if (code === CHAR_BACKWARD_SLASH) {
  2589. backslashes = token.backslashes = true;
  2590. code = advance();
  2591. continue;
  2592. }
  2593. if (code === CHAR_RIGHT_PARENTHESES) {
  2594. isGlob = token.isGlob = true;
  2595. finished = true;
  2596. break;
  2597. }
  2598. }
  2599. continue;
  2600. }
  2601. break;
  2602. }
  2603. }
  2604. if (code === CHAR_ASTERISK) {
  2605. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2606. isGlob = token.isGlob = true;
  2607. finished = true;
  2608. if (scanToEnd === true) {
  2609. continue;
  2610. }
  2611. break;
  2612. }
  2613. if (code === CHAR_QUESTION_MARK) {
  2614. isGlob = token.isGlob = true;
  2615. finished = true;
  2616. if (scanToEnd === true) {
  2617. continue;
  2618. }
  2619. break;
  2620. }
  2621. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2622. while (eos() !== true && (next = advance())) {
  2623. if (next === CHAR_BACKWARD_SLASH) {
  2624. backslashes = token.backslashes = true;
  2625. advance();
  2626. continue;
  2627. }
  2628. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2629. isBracket = token.isBracket = true;
  2630. isGlob = token.isGlob = true;
  2631. finished = true;
  2632. break;
  2633. }
  2634. }
  2635. if (scanToEnd === true) {
  2636. continue;
  2637. }
  2638. break;
  2639. }
  2640. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2641. negated = token.negated = true;
  2642. start++;
  2643. continue;
  2644. }
  2645. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2646. isGlob = token.isGlob = true;
  2647. if (scanToEnd === true) {
  2648. while (eos() !== true && (code = advance())) {
  2649. if (code === CHAR_LEFT_PARENTHESES) {
  2650. backslashes = token.backslashes = true;
  2651. code = advance();
  2652. continue;
  2653. }
  2654. if (code === CHAR_RIGHT_PARENTHESES) {
  2655. finished = true;
  2656. break;
  2657. }
  2658. }
  2659. continue;
  2660. }
  2661. break;
  2662. }
  2663. if (isGlob === true) {
  2664. finished = true;
  2665. if (scanToEnd === true) {
  2666. continue;
  2667. }
  2668. break;
  2669. }
  2670. }
  2671. if (opts.noext === true) {
  2672. isExtglob = false;
  2673. isGlob = false;
  2674. }
  2675. let base = str;
  2676. let prefix = '';
  2677. let glob = '';
  2678. if (start > 0) {
  2679. prefix = str.slice(0, start);
  2680. str = str.slice(start);
  2681. lastIndex -= start;
  2682. }
  2683. if (base && isGlob === true && lastIndex > 0) {
  2684. base = str.slice(0, lastIndex);
  2685. glob = str.slice(lastIndex);
  2686. } else if (isGlob === true) {
  2687. base = '';
  2688. glob = str;
  2689. } else {
  2690. base = str;
  2691. }
  2692. if (base && base !== '' && base !== '/' && base !== str) {
  2693. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2694. base = base.slice(0, -1);
  2695. }
  2696. }
  2697. if (opts.unescape === true) {
  2698. if (glob) glob = utils$2.removeBackslashes(glob);
  2699. if (base && backslashes === true) {
  2700. base = utils$2.removeBackslashes(base);
  2701. }
  2702. }
  2703. const state = {
  2704. prefix,
  2705. input,
  2706. start,
  2707. base,
  2708. glob,
  2709. isBrace,
  2710. isBracket,
  2711. isGlob,
  2712. isExtglob,
  2713. isGlobstar,
  2714. negated,
  2715. negatedExtglob
  2716. };
  2717. if (opts.tokens === true) {
  2718. state.maxDepth = 0;
  2719. if (!isPathSeparator(code)) {
  2720. tokens.push(token);
  2721. }
  2722. state.tokens = tokens;
  2723. }
  2724. if (opts.parts === true || opts.tokens === true) {
  2725. let prevIndex;
  2726. for (let idx = 0; idx < slashes.length; idx++) {
  2727. const n = prevIndex ? prevIndex + 1 : start;
  2728. const i = slashes[idx];
  2729. const value = input.slice(n, i);
  2730. if (opts.tokens) {
  2731. if (idx === 0 && start !== 0) {
  2732. tokens[idx].isPrefix = true;
  2733. tokens[idx].value = prefix;
  2734. } else {
  2735. tokens[idx].value = value;
  2736. }
  2737. depth(tokens[idx]);
  2738. state.maxDepth += tokens[idx].depth;
  2739. }
  2740. if (idx !== 0 || value !== '') {
  2741. parts.push(value);
  2742. }
  2743. prevIndex = i;
  2744. }
  2745. if (prevIndex && prevIndex + 1 < input.length) {
  2746. const value = input.slice(prevIndex + 1);
  2747. parts.push(value);
  2748. if (opts.tokens) {
  2749. tokens[tokens.length - 1].value = value;
  2750. depth(tokens[tokens.length - 1]);
  2751. state.maxDepth += tokens[tokens.length - 1].depth;
  2752. }
  2753. }
  2754. state.slashes = slashes;
  2755. state.parts = parts;
  2756. }
  2757. return state;
  2758. };
  2759. var scan_1 = scan$1;
  2760. const constants$1 = constants$2;
  2761. const utils$1 = utils$3;
  2762. /**
  2763. * Constants
  2764. */
  2765. const {
  2766. MAX_LENGTH,
  2767. POSIX_REGEX_SOURCE,
  2768. REGEX_NON_SPECIAL_CHARS,
  2769. REGEX_SPECIAL_CHARS_BACKREF,
  2770. REPLACEMENTS
  2771. } = constants$1;
  2772. /**
  2773. * Helpers
  2774. */
  2775. const expandRange = (args, options) => {
  2776. if (typeof options.expandRange === 'function') {
  2777. return options.expandRange(...args, options);
  2778. }
  2779. args.sort();
  2780. const value = `[${args.join('-')}]`;
  2781. return value;
  2782. };
  2783. /**
  2784. * Create the message for a syntax error
  2785. */
  2786. const syntaxError = (type, char) => {
  2787. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2788. };
  2789. /**
  2790. * Parse the given input string.
  2791. * @param {String} input
  2792. * @param {Object} options
  2793. * @return {Object}
  2794. */
  2795. const parse$1 = (input, options) => {
  2796. if (typeof input !== 'string') {
  2797. throw new TypeError('Expected a string');
  2798. }
  2799. input = REPLACEMENTS[input] || input;
  2800. const opts = { ...options };
  2801. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2802. let len = input.length;
  2803. if (len > max) {
  2804. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2805. }
  2806. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2807. const tokens = [bos];
  2808. const capture = opts.capture ? '' : '?:';
  2809. const win32 = utils$1.isWindows(options);
  2810. // create constants based on platform, for windows or posix
  2811. const PLATFORM_CHARS = constants$1.globChars(win32);
  2812. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2813. const {
  2814. DOT_LITERAL,
  2815. PLUS_LITERAL,
  2816. SLASH_LITERAL,
  2817. ONE_CHAR,
  2818. DOTS_SLASH,
  2819. NO_DOT,
  2820. NO_DOT_SLASH,
  2821. NO_DOTS_SLASH,
  2822. QMARK,
  2823. QMARK_NO_DOT,
  2824. STAR,
  2825. START_ANCHOR
  2826. } = PLATFORM_CHARS;
  2827. const globstar = opts => {
  2828. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2829. };
  2830. const nodot = opts.dot ? '' : NO_DOT;
  2831. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2832. let star = opts.bash === true ? globstar(opts) : STAR;
  2833. if (opts.capture) {
  2834. star = `(${star})`;
  2835. }
  2836. // minimatch options support
  2837. if (typeof opts.noext === 'boolean') {
  2838. opts.noextglob = opts.noext;
  2839. }
  2840. const state = {
  2841. input,
  2842. index: -1,
  2843. start: 0,
  2844. dot: opts.dot === true,
  2845. consumed: '',
  2846. output: '',
  2847. prefix: '',
  2848. backtrack: false,
  2849. negated: false,
  2850. brackets: 0,
  2851. braces: 0,
  2852. parens: 0,
  2853. quotes: 0,
  2854. globstar: false,
  2855. tokens
  2856. };
  2857. input = utils$1.removePrefix(input, state);
  2858. len = input.length;
  2859. const extglobs = [];
  2860. const braces = [];
  2861. const stack = [];
  2862. let prev = bos;
  2863. let value;
  2864. /**
  2865. * Tokenizing helpers
  2866. */
  2867. const eos = () => state.index === len - 1;
  2868. const peek = state.peek = (n = 1) => input[state.index + n];
  2869. const advance = state.advance = () => input[++state.index] || '';
  2870. const remaining = () => input.slice(state.index + 1);
  2871. const consume = (value = '', num = 0) => {
  2872. state.consumed += value;
  2873. state.index += num;
  2874. };
  2875. const append = token => {
  2876. state.output += token.output != null ? token.output : token.value;
  2877. consume(token.value);
  2878. };
  2879. const negate = () => {
  2880. let count = 1;
  2881. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2882. advance();
  2883. state.start++;
  2884. count++;
  2885. }
  2886. if (count % 2 === 0) {
  2887. return false;
  2888. }
  2889. state.negated = true;
  2890. state.start++;
  2891. return true;
  2892. };
  2893. const increment = type => {
  2894. state[type]++;
  2895. stack.push(type);
  2896. };
  2897. const decrement = type => {
  2898. state[type]--;
  2899. stack.pop();
  2900. };
  2901. /**
  2902. * Push tokens onto the tokens array. This helper speeds up
  2903. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2904. * and 2) helping us avoid creating extra tokens when consecutive
  2905. * characters are plain text. This improves performance and simplifies
  2906. * lookbehinds.
  2907. */
  2908. const push = tok => {
  2909. if (prev.type === 'globstar') {
  2910. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2911. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2912. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2913. state.output = state.output.slice(0, -prev.output.length);
  2914. prev.type = 'star';
  2915. prev.value = '*';
  2916. prev.output = star;
  2917. state.output += prev.output;
  2918. }
  2919. }
  2920. if (extglobs.length && tok.type !== 'paren') {
  2921. extglobs[extglobs.length - 1].inner += tok.value;
  2922. }
  2923. if (tok.value || tok.output) append(tok);
  2924. if (prev && prev.type === 'text' && tok.type === 'text') {
  2925. prev.value += tok.value;
  2926. prev.output = (prev.output || '') + tok.value;
  2927. return;
  2928. }
  2929. tok.prev = prev;
  2930. tokens.push(tok);
  2931. prev = tok;
  2932. };
  2933. const extglobOpen = (type, value) => {
  2934. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2935. token.prev = prev;
  2936. token.parens = state.parens;
  2937. token.output = state.output;
  2938. const output = (opts.capture ? '(' : '') + token.open;
  2939. increment('parens');
  2940. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2941. push({ type: 'paren', extglob: true, value: advance(), output });
  2942. extglobs.push(token);
  2943. };
  2944. const extglobClose = token => {
  2945. let output = token.close + (opts.capture ? ')' : '');
  2946. let rest;
  2947. if (token.type === 'negate') {
  2948. let extglobStar = star;
  2949. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2950. extglobStar = globstar(opts);
  2951. }
  2952. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2953. output = token.close = `)$))${extglobStar}`;
  2954. }
  2955. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2956. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2957. // In this case, we need to parse the string and use it in the output of the original pattern.
  2958. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2959. //
  2960. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2961. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2962. output = token.close = `)${expression})${extglobStar})`;
  2963. }
  2964. if (token.prev.type === 'bos') {
  2965. state.negatedExtglob = true;
  2966. }
  2967. }
  2968. push({ type: 'paren', extglob: true, value, output });
  2969. decrement('parens');
  2970. };
  2971. /**
  2972. * Fast paths
  2973. */
  2974. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2975. let backslashes = false;
  2976. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2977. if (first === '\\') {
  2978. backslashes = true;
  2979. return m;
  2980. }
  2981. if (first === '?') {
  2982. if (esc) {
  2983. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2984. }
  2985. if (index === 0) {
  2986. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2987. }
  2988. return QMARK.repeat(chars.length);
  2989. }
  2990. if (first === '.') {
  2991. return DOT_LITERAL.repeat(chars.length);
  2992. }
  2993. if (first === '*') {
  2994. if (esc) {
  2995. return esc + first + (rest ? star : '');
  2996. }
  2997. return star;
  2998. }
  2999. return esc ? m : `\\${m}`;
  3000. });
  3001. if (backslashes === true) {
  3002. if (opts.unescape === true) {
  3003. output = output.replace(/\\/g, '');
  3004. } else {
  3005. output = output.replace(/\\+/g, m => {
  3006. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3007. });
  3008. }
  3009. }
  3010. if (output === input && opts.contains === true) {
  3011. state.output = input;
  3012. return state;
  3013. }
  3014. state.output = utils$1.wrapOutput(output, state, options);
  3015. return state;
  3016. }
  3017. /**
  3018. * Tokenize input until we reach end-of-string
  3019. */
  3020. while (!eos()) {
  3021. value = advance();
  3022. if (value === '\u0000') {
  3023. continue;
  3024. }
  3025. /**
  3026. * Escaped characters
  3027. */
  3028. if (value === '\\') {
  3029. const next = peek();
  3030. if (next === '/' && opts.bash !== true) {
  3031. continue;
  3032. }
  3033. if (next === '.' || next === ';') {
  3034. continue;
  3035. }
  3036. if (!next) {
  3037. value += '\\';
  3038. push({ type: 'text', value });
  3039. continue;
  3040. }
  3041. // collapse slashes to reduce potential for exploits
  3042. const match = /^\\+/.exec(remaining());
  3043. let slashes = 0;
  3044. if (match && match[0].length > 2) {
  3045. slashes = match[0].length;
  3046. state.index += slashes;
  3047. if (slashes % 2 !== 0) {
  3048. value += '\\';
  3049. }
  3050. }
  3051. if (opts.unescape === true) {
  3052. value = advance();
  3053. } else {
  3054. value += advance();
  3055. }
  3056. if (state.brackets === 0) {
  3057. push({ type: 'text', value });
  3058. continue;
  3059. }
  3060. }
  3061. /**
  3062. * If we're inside a regex character class, continue
  3063. * until we reach the closing bracket.
  3064. */
  3065. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3066. if (opts.posix !== false && value === ':') {
  3067. const inner = prev.value.slice(1);
  3068. if (inner.includes('[')) {
  3069. prev.posix = true;
  3070. if (inner.includes(':')) {
  3071. const idx = prev.value.lastIndexOf('[');
  3072. const pre = prev.value.slice(0, idx);
  3073. const rest = prev.value.slice(idx + 2);
  3074. const posix = POSIX_REGEX_SOURCE[rest];
  3075. if (posix) {
  3076. prev.value = pre + posix;
  3077. state.backtrack = true;
  3078. advance();
  3079. if (!bos.output && tokens.indexOf(prev) === 1) {
  3080. bos.output = ONE_CHAR;
  3081. }
  3082. continue;
  3083. }
  3084. }
  3085. }
  3086. }
  3087. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3088. value = `\\${value}`;
  3089. }
  3090. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3091. value = `\\${value}`;
  3092. }
  3093. if (opts.posix === true && value === '!' && prev.value === '[') {
  3094. value = '^';
  3095. }
  3096. prev.value += value;
  3097. append({ value });
  3098. continue;
  3099. }
  3100. /**
  3101. * If we're inside a quoted string, continue
  3102. * until we reach the closing double quote.
  3103. */
  3104. if (state.quotes === 1 && value !== '"') {
  3105. value = utils$1.escapeRegex(value);
  3106. prev.value += value;
  3107. append({ value });
  3108. continue;
  3109. }
  3110. /**
  3111. * Double quotes
  3112. */
  3113. if (value === '"') {
  3114. state.quotes = state.quotes === 1 ? 0 : 1;
  3115. if (opts.keepQuotes === true) {
  3116. push({ type: 'text', value });
  3117. }
  3118. continue;
  3119. }
  3120. /**
  3121. * Parentheses
  3122. */
  3123. if (value === '(') {
  3124. increment('parens');
  3125. push({ type: 'paren', value });
  3126. continue;
  3127. }
  3128. if (value === ')') {
  3129. if (state.parens === 0 && opts.strictBrackets === true) {
  3130. throw new SyntaxError(syntaxError('opening', '('));
  3131. }
  3132. const extglob = extglobs[extglobs.length - 1];
  3133. if (extglob && state.parens === extglob.parens + 1) {
  3134. extglobClose(extglobs.pop());
  3135. continue;
  3136. }
  3137. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3138. decrement('parens');
  3139. continue;
  3140. }
  3141. /**
  3142. * Square brackets
  3143. */
  3144. if (value === '[') {
  3145. if (opts.nobracket === true || !remaining().includes(']')) {
  3146. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3147. throw new SyntaxError(syntaxError('closing', ']'));
  3148. }
  3149. value = `\\${value}`;
  3150. } else {
  3151. increment('brackets');
  3152. }
  3153. push({ type: 'bracket', value });
  3154. continue;
  3155. }
  3156. if (value === ']') {
  3157. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3158. push({ type: 'text', value, output: `\\${value}` });
  3159. continue;
  3160. }
  3161. if (state.brackets === 0) {
  3162. if (opts.strictBrackets === true) {
  3163. throw new SyntaxError(syntaxError('opening', '['));
  3164. }
  3165. push({ type: 'text', value, output: `\\${value}` });
  3166. continue;
  3167. }
  3168. decrement('brackets');
  3169. const prevValue = prev.value.slice(1);
  3170. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3171. value = `/${value}`;
  3172. }
  3173. prev.value += value;
  3174. append({ value });
  3175. // when literal brackets are explicitly disabled
  3176. // assume we should match with a regex character class
  3177. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3178. continue;
  3179. }
  3180. const escaped = utils$1.escapeRegex(prev.value);
  3181. state.output = state.output.slice(0, -prev.value.length);
  3182. // when literal brackets are explicitly enabled
  3183. // assume we should escape the brackets to match literal characters
  3184. if (opts.literalBrackets === true) {
  3185. state.output += escaped;
  3186. prev.value = escaped;
  3187. continue;
  3188. }
  3189. // when the user specifies nothing, try to match both
  3190. prev.value = `(${capture}${escaped}|${prev.value})`;
  3191. state.output += prev.value;
  3192. continue;
  3193. }
  3194. /**
  3195. * Braces
  3196. */
  3197. if (value === '{' && opts.nobrace !== true) {
  3198. increment('braces');
  3199. const open = {
  3200. type: 'brace',
  3201. value,
  3202. output: '(',
  3203. outputIndex: state.output.length,
  3204. tokensIndex: state.tokens.length
  3205. };
  3206. braces.push(open);
  3207. push(open);
  3208. continue;
  3209. }
  3210. if (value === '}') {
  3211. const brace = braces[braces.length - 1];
  3212. if (opts.nobrace === true || !brace) {
  3213. push({ type: 'text', value, output: value });
  3214. continue;
  3215. }
  3216. let output = ')';
  3217. if (brace.dots === true) {
  3218. const arr = tokens.slice();
  3219. const range = [];
  3220. for (let i = arr.length - 1; i >= 0; i--) {
  3221. tokens.pop();
  3222. if (arr[i].type === 'brace') {
  3223. break;
  3224. }
  3225. if (arr[i].type !== 'dots') {
  3226. range.unshift(arr[i].value);
  3227. }
  3228. }
  3229. output = expandRange(range, opts);
  3230. state.backtrack = true;
  3231. }
  3232. if (brace.comma !== true && brace.dots !== true) {
  3233. const out = state.output.slice(0, brace.outputIndex);
  3234. const toks = state.tokens.slice(brace.tokensIndex);
  3235. brace.value = brace.output = '\\{';
  3236. value = output = '\\}';
  3237. state.output = out;
  3238. for (const t of toks) {
  3239. state.output += (t.output || t.value);
  3240. }
  3241. }
  3242. push({ type: 'brace', value, output });
  3243. decrement('braces');
  3244. braces.pop();
  3245. continue;
  3246. }
  3247. /**
  3248. * Pipes
  3249. */
  3250. if (value === '|') {
  3251. if (extglobs.length > 0) {
  3252. extglobs[extglobs.length - 1].conditions++;
  3253. }
  3254. push({ type: 'text', value });
  3255. continue;
  3256. }
  3257. /**
  3258. * Commas
  3259. */
  3260. if (value === ',') {
  3261. let output = value;
  3262. const brace = braces[braces.length - 1];
  3263. if (brace && stack[stack.length - 1] === 'braces') {
  3264. brace.comma = true;
  3265. output = '|';
  3266. }
  3267. push({ type: 'comma', value, output });
  3268. continue;
  3269. }
  3270. /**
  3271. * Slashes
  3272. */
  3273. if (value === '/') {
  3274. // if the beginning of the glob is "./", advance the start
  3275. // to the current index, and don't add the "./" characters
  3276. // to the state. This greatly simplifies lookbehinds when
  3277. // checking for BOS characters like "!" and "." (not "./")
  3278. if (prev.type === 'dot' && state.index === state.start + 1) {
  3279. state.start = state.index + 1;
  3280. state.consumed = '';
  3281. state.output = '';
  3282. tokens.pop();
  3283. prev = bos; // reset "prev" to the first token
  3284. continue;
  3285. }
  3286. push({ type: 'slash', value, output: SLASH_LITERAL });
  3287. continue;
  3288. }
  3289. /**
  3290. * Dots
  3291. */
  3292. if (value === '.') {
  3293. if (state.braces > 0 && prev.type === 'dot') {
  3294. if (prev.value === '.') prev.output = DOT_LITERAL;
  3295. const brace = braces[braces.length - 1];
  3296. prev.type = 'dots';
  3297. prev.output += value;
  3298. prev.value += value;
  3299. brace.dots = true;
  3300. continue;
  3301. }
  3302. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3303. push({ type: 'text', value, output: DOT_LITERAL });
  3304. continue;
  3305. }
  3306. push({ type: 'dot', value, output: DOT_LITERAL });
  3307. continue;
  3308. }
  3309. /**
  3310. * Question marks
  3311. */
  3312. if (value === '?') {
  3313. const isGroup = prev && prev.value === '(';
  3314. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3315. extglobOpen('qmark', value);
  3316. continue;
  3317. }
  3318. if (prev && prev.type === 'paren') {
  3319. const next = peek();
  3320. let output = value;
  3321. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3322. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3323. }
  3324. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3325. output = `\\${value}`;
  3326. }
  3327. push({ type: 'text', value, output });
  3328. continue;
  3329. }
  3330. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3331. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3332. continue;
  3333. }
  3334. push({ type: 'qmark', value, output: QMARK });
  3335. continue;
  3336. }
  3337. /**
  3338. * Exclamation
  3339. */
  3340. if (value === '!') {
  3341. if (opts.noextglob !== true && peek() === '(') {
  3342. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3343. extglobOpen('negate', value);
  3344. continue;
  3345. }
  3346. }
  3347. if (opts.nonegate !== true && state.index === 0) {
  3348. negate();
  3349. continue;
  3350. }
  3351. }
  3352. /**
  3353. * Plus
  3354. */
  3355. if (value === '+') {
  3356. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3357. extglobOpen('plus', value);
  3358. continue;
  3359. }
  3360. if ((prev && prev.value === '(') || opts.regex === false) {
  3361. push({ type: 'plus', value, output: PLUS_LITERAL });
  3362. continue;
  3363. }
  3364. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3365. push({ type: 'plus', value });
  3366. continue;
  3367. }
  3368. push({ type: 'plus', value: PLUS_LITERAL });
  3369. continue;
  3370. }
  3371. /**
  3372. * Plain text
  3373. */
  3374. if (value === '@') {
  3375. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3376. push({ type: 'at', extglob: true, value, output: '' });
  3377. continue;
  3378. }
  3379. push({ type: 'text', value });
  3380. continue;
  3381. }
  3382. /**
  3383. * Plain text
  3384. */
  3385. if (value !== '*') {
  3386. if (value === '$' || value === '^') {
  3387. value = `\\${value}`;
  3388. }
  3389. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3390. if (match) {
  3391. value += match[0];
  3392. state.index += match[0].length;
  3393. }
  3394. push({ type: 'text', value });
  3395. continue;
  3396. }
  3397. /**
  3398. * Stars
  3399. */
  3400. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3401. prev.type = 'star';
  3402. prev.star = true;
  3403. prev.value += value;
  3404. prev.output = star;
  3405. state.backtrack = true;
  3406. state.globstar = true;
  3407. consume(value);
  3408. continue;
  3409. }
  3410. let rest = remaining();
  3411. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3412. extglobOpen('star', value);
  3413. continue;
  3414. }
  3415. if (prev.type === 'star') {
  3416. if (opts.noglobstar === true) {
  3417. consume(value);
  3418. continue;
  3419. }
  3420. const prior = prev.prev;
  3421. const before = prior.prev;
  3422. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3423. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3424. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3425. push({ type: 'star', value, output: '' });
  3426. continue;
  3427. }
  3428. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3429. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3430. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3431. push({ type: 'star', value, output: '' });
  3432. continue;
  3433. }
  3434. // strip consecutive `/**/`
  3435. while (rest.slice(0, 3) === '/**') {
  3436. const after = input[state.index + 4];
  3437. if (after && after !== '/') {
  3438. break;
  3439. }
  3440. rest = rest.slice(3);
  3441. consume('/**', 3);
  3442. }
  3443. if (prior.type === 'bos' && eos()) {
  3444. prev.type = 'globstar';
  3445. prev.value += value;
  3446. prev.output = globstar(opts);
  3447. state.output = prev.output;
  3448. state.globstar = true;
  3449. consume(value);
  3450. continue;
  3451. }
  3452. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3453. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3454. prior.output = `(?:${prior.output}`;
  3455. prev.type = 'globstar';
  3456. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3457. prev.value += value;
  3458. state.globstar = true;
  3459. state.output += prior.output + prev.output;
  3460. consume(value);
  3461. continue;
  3462. }
  3463. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3464. const end = rest[1] !== void 0 ? '|$' : '';
  3465. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3466. prior.output = `(?:${prior.output}`;
  3467. prev.type = 'globstar';
  3468. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3469. prev.value += value;
  3470. state.output += prior.output + prev.output;
  3471. state.globstar = true;
  3472. consume(value + advance());
  3473. push({ type: 'slash', value: '/', output: '' });
  3474. continue;
  3475. }
  3476. if (prior.type === 'bos' && rest[0] === '/') {
  3477. prev.type = 'globstar';
  3478. prev.value += value;
  3479. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3480. state.output = prev.output;
  3481. state.globstar = true;
  3482. consume(value + advance());
  3483. push({ type: 'slash', value: '/', output: '' });
  3484. continue;
  3485. }
  3486. // remove single star from output
  3487. state.output = state.output.slice(0, -prev.output.length);
  3488. // reset previous token to globstar
  3489. prev.type = 'globstar';
  3490. prev.output = globstar(opts);
  3491. prev.value += value;
  3492. // reset output with globstar
  3493. state.output += prev.output;
  3494. state.globstar = true;
  3495. consume(value);
  3496. continue;
  3497. }
  3498. const token = { type: 'star', value, output: star };
  3499. if (opts.bash === true) {
  3500. token.output = '.*?';
  3501. if (prev.type === 'bos' || prev.type === 'slash') {
  3502. token.output = nodot + token.output;
  3503. }
  3504. push(token);
  3505. continue;
  3506. }
  3507. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3508. token.output = value;
  3509. push(token);
  3510. continue;
  3511. }
  3512. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3513. if (prev.type === 'dot') {
  3514. state.output += NO_DOT_SLASH;
  3515. prev.output += NO_DOT_SLASH;
  3516. } else if (opts.dot === true) {
  3517. state.output += NO_DOTS_SLASH;
  3518. prev.output += NO_DOTS_SLASH;
  3519. } else {
  3520. state.output += nodot;
  3521. prev.output += nodot;
  3522. }
  3523. if (peek() !== '*') {
  3524. state.output += ONE_CHAR;
  3525. prev.output += ONE_CHAR;
  3526. }
  3527. }
  3528. push(token);
  3529. }
  3530. while (state.brackets > 0) {
  3531. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3532. state.output = utils$1.escapeLast(state.output, '[');
  3533. decrement('brackets');
  3534. }
  3535. while (state.parens > 0) {
  3536. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3537. state.output = utils$1.escapeLast(state.output, '(');
  3538. decrement('parens');
  3539. }
  3540. while (state.braces > 0) {
  3541. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3542. state.output = utils$1.escapeLast(state.output, '{');
  3543. decrement('braces');
  3544. }
  3545. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3546. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3547. }
  3548. // rebuild the output if we had to backtrack at any point
  3549. if (state.backtrack === true) {
  3550. state.output = '';
  3551. for (const token of state.tokens) {
  3552. state.output += token.output != null ? token.output : token.value;
  3553. if (token.suffix) {
  3554. state.output += token.suffix;
  3555. }
  3556. }
  3557. }
  3558. return state;
  3559. };
  3560. /**
  3561. * Fast paths for creating regular expressions for common glob patterns.
  3562. * This can significantly speed up processing and has very little downside
  3563. * impact when none of the fast paths match.
  3564. */
  3565. parse$1.fastpaths = (input, options) => {
  3566. const opts = { ...options };
  3567. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3568. const len = input.length;
  3569. if (len > max) {
  3570. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3571. }
  3572. input = REPLACEMENTS[input] || input;
  3573. const win32 = utils$1.isWindows(options);
  3574. // create constants based on platform, for windows or posix
  3575. const {
  3576. DOT_LITERAL,
  3577. SLASH_LITERAL,
  3578. ONE_CHAR,
  3579. DOTS_SLASH,
  3580. NO_DOT,
  3581. NO_DOTS,
  3582. NO_DOTS_SLASH,
  3583. STAR,
  3584. START_ANCHOR
  3585. } = constants$1.globChars(win32);
  3586. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3587. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3588. const capture = opts.capture ? '' : '?:';
  3589. const state = { negated: false, prefix: '' };
  3590. let star = opts.bash === true ? '.*?' : STAR;
  3591. if (opts.capture) {
  3592. star = `(${star})`;
  3593. }
  3594. const globstar = opts => {
  3595. if (opts.noglobstar === true) return star;
  3596. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3597. };
  3598. const create = str => {
  3599. switch (str) {
  3600. case '*':
  3601. return `${nodot}${ONE_CHAR}${star}`;
  3602. case '.*':
  3603. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3604. case '*.*':
  3605. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3606. case '*/*':
  3607. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3608. case '**':
  3609. return nodot + globstar(opts);
  3610. case '**/*':
  3611. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3612. case '**/*.*':
  3613. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3614. case '**/.*':
  3615. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3616. default: {
  3617. const match = /^(.*?)\.(\w+)$/.exec(str);
  3618. if (!match) return;
  3619. const source = create(match[1]);
  3620. if (!source) return;
  3621. return source + DOT_LITERAL + match[2];
  3622. }
  3623. }
  3624. };
  3625. const output = utils$1.removePrefix(input, state);
  3626. let source = create(output);
  3627. if (source && opts.strictSlashes !== true) {
  3628. source += `${SLASH_LITERAL}?`;
  3629. }
  3630. return source;
  3631. };
  3632. var parse_1 = parse$1;
  3633. const path = require$$0;
  3634. const scan = scan_1;
  3635. const parse = parse_1;
  3636. const utils = utils$3;
  3637. const constants = constants$2;
  3638. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3639. /**
  3640. * Creates a matcher function from one or more glob patterns. The
  3641. * returned function takes a string to match as its first argument,
  3642. * and returns true if the string is a match. The returned matcher
  3643. * function also takes a boolean as the second argument that, when true,
  3644. * returns an object with additional information.
  3645. *
  3646. * ```js
  3647. * const picomatch = require('picomatch');
  3648. * // picomatch(glob[, options]);
  3649. *
  3650. * const isMatch = picomatch('*.!(*a)');
  3651. * console.log(isMatch('a.a')); //=> false
  3652. * console.log(isMatch('a.b')); //=> true
  3653. * ```
  3654. * @name picomatch
  3655. * @param {String|Array} `globs` One or more glob patterns.
  3656. * @param {Object=} `options`
  3657. * @return {Function=} Returns a matcher function.
  3658. * @api public
  3659. */
  3660. const picomatch = (glob, options, returnState = false) => {
  3661. if (Array.isArray(glob)) {
  3662. const fns = glob.map(input => picomatch(input, options, returnState));
  3663. const arrayMatcher = str => {
  3664. for (const isMatch of fns) {
  3665. const state = isMatch(str);
  3666. if (state) return state;
  3667. }
  3668. return false;
  3669. };
  3670. return arrayMatcher;
  3671. }
  3672. const isState = isObject(glob) && glob.tokens && glob.input;
  3673. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3674. throw new TypeError('Expected pattern to be a non-empty string');
  3675. }
  3676. const opts = options || {};
  3677. const posix = utils.isWindows(options);
  3678. const regex = isState
  3679. ? picomatch.compileRe(glob, options)
  3680. : picomatch.makeRe(glob, options, false, true);
  3681. const state = regex.state;
  3682. delete regex.state;
  3683. let isIgnored = () => false;
  3684. if (opts.ignore) {
  3685. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3686. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3687. }
  3688. const matcher = (input, returnObject = false) => {
  3689. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3690. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3691. if (typeof opts.onResult === 'function') {
  3692. opts.onResult(result);
  3693. }
  3694. if (isMatch === false) {
  3695. result.isMatch = false;
  3696. return returnObject ? result : false;
  3697. }
  3698. if (isIgnored(input)) {
  3699. if (typeof opts.onIgnore === 'function') {
  3700. opts.onIgnore(result);
  3701. }
  3702. result.isMatch = false;
  3703. return returnObject ? result : false;
  3704. }
  3705. if (typeof opts.onMatch === 'function') {
  3706. opts.onMatch(result);
  3707. }
  3708. return returnObject ? result : true;
  3709. };
  3710. if (returnState) {
  3711. matcher.state = state;
  3712. }
  3713. return matcher;
  3714. };
  3715. /**
  3716. * Test `input` with the given `regex`. This is used by the main
  3717. * `picomatch()` function to test the input string.
  3718. *
  3719. * ```js
  3720. * const picomatch = require('picomatch');
  3721. * // picomatch.test(input, regex[, options]);
  3722. *
  3723. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3724. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3725. * ```
  3726. * @param {String} `input` String to test.
  3727. * @param {RegExp} `regex`
  3728. * @return {Object} Returns an object with matching info.
  3729. * @api public
  3730. */
  3731. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3732. if (typeof input !== 'string') {
  3733. throw new TypeError('Expected input to be a string');
  3734. }
  3735. if (input === '') {
  3736. return { isMatch: false, output: '' };
  3737. }
  3738. const opts = options || {};
  3739. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3740. let match = input === glob;
  3741. let output = (match && format) ? format(input) : input;
  3742. if (match === false) {
  3743. output = format ? format(input) : input;
  3744. match = output === glob;
  3745. }
  3746. if (match === false || opts.capture === true) {
  3747. if (opts.matchBase === true || opts.basename === true) {
  3748. match = picomatch.matchBase(input, regex, options, posix);
  3749. } else {
  3750. match = regex.exec(output);
  3751. }
  3752. }
  3753. return { isMatch: Boolean(match), match, output };
  3754. };
  3755. /**
  3756. * Match the basename of a filepath.
  3757. *
  3758. * ```js
  3759. * const picomatch = require('picomatch');
  3760. * // picomatch.matchBase(input, glob[, options]);
  3761. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3762. * ```
  3763. * @param {String} `input` String to test.
  3764. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3765. * @return {Boolean}
  3766. * @api public
  3767. */
  3768. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3769. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3770. return regex.test(path.basename(input));
  3771. };
  3772. /**
  3773. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3774. *
  3775. * ```js
  3776. * const picomatch = require('picomatch');
  3777. * // picomatch.isMatch(string, patterns[, options]);
  3778. *
  3779. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3780. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3781. * ```
  3782. * @param {String|Array} str The string to test.
  3783. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3784. * @param {Object} [options] See available [options](#options).
  3785. * @return {Boolean} Returns true if any patterns match `str`
  3786. * @api public
  3787. */
  3788. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3789. /**
  3790. * Parse a glob pattern to create the source string for a regular
  3791. * expression.
  3792. *
  3793. * ```js
  3794. * const picomatch = require('picomatch');
  3795. * const result = picomatch.parse(pattern[, options]);
  3796. * ```
  3797. * @param {String} `pattern`
  3798. * @param {Object} `options`
  3799. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3800. * @api public
  3801. */
  3802. picomatch.parse = (pattern, options) => {
  3803. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3804. return parse(pattern, { ...options, fastpaths: false });
  3805. };
  3806. /**
  3807. * Scan a glob pattern to separate the pattern into segments.
  3808. *
  3809. * ```js
  3810. * const picomatch = require('picomatch');
  3811. * // picomatch.scan(input[, options]);
  3812. *
  3813. * const result = picomatch.scan('!./foo/*.js');
  3814. * console.log(result);
  3815. * { prefix: '!./',
  3816. * input: '!./foo/*.js',
  3817. * start: 3,
  3818. * base: 'foo',
  3819. * glob: '*.js',
  3820. * isBrace: false,
  3821. * isBracket: false,
  3822. * isGlob: true,
  3823. * isExtglob: false,
  3824. * isGlobstar: false,
  3825. * negated: true }
  3826. * ```
  3827. * @param {String} `input` Glob pattern to scan.
  3828. * @param {Object} `options`
  3829. * @return {Object} Returns an object with
  3830. * @api public
  3831. */
  3832. picomatch.scan = (input, options) => scan(input, options);
  3833. /**
  3834. * Compile a regular expression from the `state` object returned by the
  3835. * [parse()](#parse) method.
  3836. *
  3837. * @param {Object} `state`
  3838. * @param {Object} `options`
  3839. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3840. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3841. * @return {RegExp}
  3842. * @api public
  3843. */
  3844. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3845. if (returnOutput === true) {
  3846. return state.output;
  3847. }
  3848. const opts = options || {};
  3849. const prepend = opts.contains ? '' : '^';
  3850. const append = opts.contains ? '' : '$';
  3851. let source = `${prepend}(?:${state.output})${append}`;
  3852. if (state && state.negated === true) {
  3853. source = `^(?!${source}).*$`;
  3854. }
  3855. const regex = picomatch.toRegex(source, options);
  3856. if (returnState === true) {
  3857. regex.state = state;
  3858. }
  3859. return regex;
  3860. };
  3861. /**
  3862. * Create a regular expression from a parsed glob pattern.
  3863. *
  3864. * ```js
  3865. * const picomatch = require('picomatch');
  3866. * const state = picomatch.parse('*.js');
  3867. * // picomatch.compileRe(state[, options]);
  3868. *
  3869. * console.log(picomatch.compileRe(state));
  3870. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3871. * ```
  3872. * @param {String} `state` The object returned from the `.parse` method.
  3873. * @param {Object} `options`
  3874. * @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.
  3875. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3876. * @return {RegExp} Returns a regex created from the given pattern.
  3877. * @api public
  3878. */
  3879. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3880. if (!input || typeof input !== 'string') {
  3881. throw new TypeError('Expected a non-empty string');
  3882. }
  3883. let parsed = { negated: false, fastpaths: true };
  3884. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3885. parsed.output = parse.fastpaths(input, options);
  3886. }
  3887. if (!parsed.output) {
  3888. parsed = parse(input, options);
  3889. }
  3890. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3891. };
  3892. /**
  3893. * Create a regular expression from the given regex source string.
  3894. *
  3895. * ```js
  3896. * const picomatch = require('picomatch');
  3897. * // picomatch.toRegex(source[, options]);
  3898. *
  3899. * const { output } = picomatch.parse('*.js');
  3900. * console.log(picomatch.toRegex(output));
  3901. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3902. * ```
  3903. * @param {String} `source` Regular expression source string.
  3904. * @param {Object} `options`
  3905. * @return {RegExp}
  3906. * @api public
  3907. */
  3908. picomatch.toRegex = (source, options) => {
  3909. try {
  3910. const opts = options || {};
  3911. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3912. } catch (err) {
  3913. if (options && options.debug === true) throw err;
  3914. return /$^/;
  3915. }
  3916. };
  3917. /**
  3918. * Picomatch constants.
  3919. * @return {Object}
  3920. */
  3921. picomatch.constants = constants;
  3922. /**
  3923. * Expose "picomatch"
  3924. */
  3925. var picomatch_1 = picomatch;
  3926. (function (module) {
  3927. module.exports = picomatch_1;
  3928. } (picomatch$1));
  3929. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
  3930. const extractors = {
  3931. ArrayPattern(names, param) {
  3932. for (const element of param.elements) {
  3933. if (element)
  3934. extractors[element.type](names, element);
  3935. }
  3936. },
  3937. AssignmentPattern(names, param) {
  3938. extractors[param.left.type](names, param.left);
  3939. },
  3940. Identifier(names, param) {
  3941. names.push(param.name);
  3942. },
  3943. MemberExpression() { },
  3944. ObjectPattern(names, param) {
  3945. for (const prop of param.properties) {
  3946. // @ts-ignore Typescript reports that this is not a valid type
  3947. if (prop.type === 'RestElement') {
  3948. extractors.RestElement(names, prop);
  3949. }
  3950. else {
  3951. extractors[prop.value.type](names, prop.value);
  3952. }
  3953. }
  3954. },
  3955. RestElement(names, param) {
  3956. extractors[param.argument.type](names, param.argument);
  3957. }
  3958. };
  3959. const extractAssignedNames = function extractAssignedNames(param) {
  3960. const names = [];
  3961. extractors[param.type](names, param);
  3962. return names;
  3963. };
  3964. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3965. function isArray$1(arg) {
  3966. return Array.isArray(arg);
  3967. }
  3968. function ensureArray(thing) {
  3969. if (isArray$1(thing))
  3970. return thing;
  3971. if (thing == null)
  3972. return [];
  3973. return [thing];
  3974. }
  3975. const normalizePath = function normalizePath(filename) {
  3976. return filename.split(require$$0.win32.sep).join(require$$0.posix.sep);
  3977. };
  3978. function getMatcherString(id, resolutionBase) {
  3979. if (resolutionBase === false || require$$0.isAbsolute(id) || id.startsWith('*')) {
  3980. return normalizePath(id);
  3981. }
  3982. // resolve('') is valid and will default to process.cwd()
  3983. const basePath = normalizePath(require$$0.resolve(resolutionBase || ''))
  3984. // escape all possible (posix + win) path characters that might interfere with regex
  3985. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  3986. // Note that we use posix.join because:
  3987. // 1. the basePath has been normalized to use /
  3988. // 2. the incoming glob (id) matcher, also uses /
  3989. // otherwise Node will force backslash (\) on windows
  3990. return require$$0.posix.join(basePath, normalizePath(id));
  3991. }
  3992. const createFilter = function createFilter(include, exclude, options) {
  3993. const resolutionBase = options && options.resolve;
  3994. const getMatcher = (id) => id instanceof RegExp
  3995. ? id
  3996. : {
  3997. test: (what) => {
  3998. // this refactor is a tad overly verbose but makes for easy debugging
  3999. const pattern = getMatcherString(id, resolutionBase);
  4000. const fn = pm(pattern, { dot: true });
  4001. const result = fn(what);
  4002. return result;
  4003. }
  4004. };
  4005. const includeMatchers = ensureArray(include).map(getMatcher);
  4006. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  4007. return function result(id) {
  4008. if (typeof id !== 'string')
  4009. return false;
  4010. if (/\0/.test(id))
  4011. return false;
  4012. const pathId = normalizePath(id);
  4013. for (let i = 0; i < excludeMatchers.length; ++i) {
  4014. const matcher = excludeMatchers[i];
  4015. if (matcher.test(pathId))
  4016. return false;
  4017. }
  4018. for (let i = 0; i < includeMatchers.length; ++i) {
  4019. const matcher = includeMatchers[i];
  4020. if (matcher.test(pathId))
  4021. return true;
  4022. }
  4023. return !includeMatchers.length;
  4024. };
  4025. };
  4026. 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';
  4027. 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';
  4028. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  4029. forbiddenIdentifiers.add('');
  4030. const BROKEN_FLOW_NONE = 0;
  4031. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  4032. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  4033. function createInclusionContext() {
  4034. return {
  4035. brokenFlow: BROKEN_FLOW_NONE,
  4036. includedCallArguments: new Set(),
  4037. includedLabels: new Set()
  4038. };
  4039. }
  4040. function createHasEffectsContext() {
  4041. return {
  4042. accessed: new PathTracker(),
  4043. assigned: new PathTracker(),
  4044. brokenFlow: BROKEN_FLOW_NONE,
  4045. called: new DiscriminatedPathTracker(),
  4046. ignore: {
  4047. breaks: false,
  4048. continues: false,
  4049. labels: new Set(),
  4050. returnYield: false
  4051. },
  4052. includedLabels: new Set(),
  4053. instantiated: new DiscriminatedPathTracker(),
  4054. replacedVariableInits: new Map()
  4055. };
  4056. }
  4057. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4058. return Object.create(inheritedDescriptions, memberDescriptions);
  4059. }
  4060. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4061. getLiteralValueAtPath() {
  4062. return undefined;
  4063. }
  4064. })();
  4065. const returnsUnknown = {
  4066. value: {
  4067. hasEffectsWhenCalled: null,
  4068. returns: UNKNOWN_EXPRESSION
  4069. }
  4070. };
  4071. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4072. getReturnExpressionWhenCalledAtPath(path) {
  4073. if (path.length === 1) {
  4074. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4075. }
  4076. return UNKNOWN_EXPRESSION;
  4077. }
  4078. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4079. if (interaction.type === INTERACTION_ACCESSED) {
  4080. return path.length > 1;
  4081. }
  4082. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4083. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4084. }
  4085. return true;
  4086. }
  4087. })();
  4088. const returnsBoolean = {
  4089. value: {
  4090. hasEffectsWhenCalled: null,
  4091. returns: UNKNOWN_LITERAL_BOOLEAN
  4092. }
  4093. };
  4094. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4095. getReturnExpressionWhenCalledAtPath(path) {
  4096. if (path.length === 1) {
  4097. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4098. }
  4099. return UNKNOWN_EXPRESSION;
  4100. }
  4101. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4102. if (interaction.type === INTERACTION_ACCESSED) {
  4103. return path.length > 1;
  4104. }
  4105. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4106. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4107. }
  4108. return true;
  4109. }
  4110. })();
  4111. const returnsNumber = {
  4112. value: {
  4113. hasEffectsWhenCalled: null,
  4114. returns: UNKNOWN_LITERAL_NUMBER
  4115. }
  4116. };
  4117. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4118. getReturnExpressionWhenCalledAtPath(path) {
  4119. if (path.length === 1) {
  4120. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4121. }
  4122. return UNKNOWN_EXPRESSION;
  4123. }
  4124. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4125. if (interaction.type === INTERACTION_ACCESSED) {
  4126. return path.length > 1;
  4127. }
  4128. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4129. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4130. }
  4131. return true;
  4132. }
  4133. })();
  4134. const returnsString = {
  4135. value: {
  4136. hasEffectsWhenCalled: null,
  4137. returns: UNKNOWN_LITERAL_STRING
  4138. }
  4139. };
  4140. const stringReplace = {
  4141. value: {
  4142. hasEffectsWhenCalled({ args }, context) {
  4143. const arg1 = args[1];
  4144. return (args.length < 2 ||
  4145. (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4146. deoptimizeCache() { }
  4147. }) === 'symbol' &&
  4148. arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4149. },
  4150. returns: UNKNOWN_LITERAL_STRING
  4151. }
  4152. };
  4153. const objectMembers = assembleMemberDescriptions({
  4154. hasOwnProperty: returnsBoolean,
  4155. isPrototypeOf: returnsBoolean,
  4156. propertyIsEnumerable: returnsBoolean,
  4157. toLocaleString: returnsString,
  4158. toString: returnsString,
  4159. valueOf: returnsUnknown
  4160. });
  4161. const literalBooleanMembers = assembleMemberDescriptions({
  4162. valueOf: returnsBoolean
  4163. }, objectMembers);
  4164. const literalNumberMembers = assembleMemberDescriptions({
  4165. toExponential: returnsString,
  4166. toFixed: returnsString,
  4167. toLocaleString: returnsString,
  4168. toPrecision: returnsString,
  4169. valueOf: returnsNumber
  4170. }, objectMembers);
  4171. const literalStringMembers = assembleMemberDescriptions({
  4172. anchor: returnsString,
  4173. at: returnsUnknown,
  4174. big: returnsString,
  4175. blink: returnsString,
  4176. bold: returnsString,
  4177. charAt: returnsString,
  4178. charCodeAt: returnsNumber,
  4179. codePointAt: returnsUnknown,
  4180. concat: returnsString,
  4181. endsWith: returnsBoolean,
  4182. fixed: returnsString,
  4183. fontcolor: returnsString,
  4184. fontsize: returnsString,
  4185. includes: returnsBoolean,
  4186. indexOf: returnsNumber,
  4187. italics: returnsString,
  4188. lastIndexOf: returnsNumber,
  4189. link: returnsString,
  4190. localeCompare: returnsNumber,
  4191. match: returnsUnknown,
  4192. matchAll: returnsUnknown,
  4193. normalize: returnsString,
  4194. padEnd: returnsString,
  4195. padStart: returnsString,
  4196. repeat: returnsString,
  4197. replace: stringReplace,
  4198. replaceAll: stringReplace,
  4199. search: returnsNumber,
  4200. slice: returnsString,
  4201. small: returnsString,
  4202. split: returnsUnknown,
  4203. startsWith: returnsBoolean,
  4204. strike: returnsString,
  4205. sub: returnsString,
  4206. substr: returnsString,
  4207. substring: returnsString,
  4208. sup: returnsString,
  4209. toLocaleLowerCase: returnsString,
  4210. toLocaleUpperCase: returnsString,
  4211. toLowerCase: returnsString,
  4212. toString: returnsString,
  4213. toUpperCase: returnsString,
  4214. trim: returnsString,
  4215. trimEnd: returnsString,
  4216. trimLeft: returnsString,
  4217. trimRight: returnsString,
  4218. trimStart: returnsString,
  4219. valueOf: returnsString
  4220. }, objectMembers);
  4221. function getLiteralMembersForValue(value) {
  4222. switch (typeof value) {
  4223. case 'boolean':
  4224. return literalBooleanMembers;
  4225. case 'number':
  4226. return literalNumberMembers;
  4227. case 'string':
  4228. return literalStringMembers;
  4229. }
  4230. return Object.create(null);
  4231. }
  4232. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4233. var _a, _b;
  4234. if (typeof memberName !== 'string' || !members[memberName]) {
  4235. return true;
  4236. }
  4237. return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
  4238. }
  4239. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4240. if (typeof memberName !== 'string' || !members[memberName])
  4241. return UNKNOWN_EXPRESSION;
  4242. return members[memberName].returns;
  4243. }
  4244. // AST walker module for Mozilla Parser API compatible trees
  4245. function skipThrough(node, st, c) { c(node, st); }
  4246. function ignore(_node, _st, _c) {}
  4247. // Node walkers.
  4248. var base$1 = {};
  4249. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4250. for (var i = 0, list = node.body; i < list.length; i += 1)
  4251. {
  4252. var stmt = list[i];
  4253. c(stmt, st, "Statement");
  4254. }
  4255. };
  4256. base$1.Statement = skipThrough;
  4257. base$1.EmptyStatement = ignore;
  4258. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4259. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4260. base$1.IfStatement = function (node, st, c) {
  4261. c(node.test, st, "Expression");
  4262. c(node.consequent, st, "Statement");
  4263. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4264. };
  4265. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4266. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4267. base$1.WithStatement = function (node, st, c) {
  4268. c(node.object, st, "Expression");
  4269. c(node.body, st, "Statement");
  4270. };
  4271. base$1.SwitchStatement = function (node, st, c) {
  4272. c(node.discriminant, st, "Expression");
  4273. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4274. var cs = list$1[i$1];
  4275. if (cs.test) { c(cs.test, st, "Expression"); }
  4276. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4277. {
  4278. var cons = list[i];
  4279. c(cons, st, "Statement");
  4280. }
  4281. }
  4282. };
  4283. base$1.SwitchCase = function (node, st, c) {
  4284. if (node.test) { c(node.test, st, "Expression"); }
  4285. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4286. {
  4287. var cons = list[i];
  4288. c(cons, st, "Statement");
  4289. }
  4290. };
  4291. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4292. if (node.argument) { c(node.argument, st, "Expression"); }
  4293. };
  4294. base$1.ThrowStatement = base$1.SpreadElement =
  4295. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4296. base$1.TryStatement = function (node, st, c) {
  4297. c(node.block, st, "Statement");
  4298. if (node.handler) { c(node.handler, st); }
  4299. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4300. };
  4301. base$1.CatchClause = function (node, st, c) {
  4302. if (node.param) { c(node.param, st, "Pattern"); }
  4303. c(node.body, st, "Statement");
  4304. };
  4305. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4306. c(node.test, st, "Expression");
  4307. c(node.body, st, "Statement");
  4308. };
  4309. base$1.ForStatement = function (node, st, c) {
  4310. if (node.init) { c(node.init, st, "ForInit"); }
  4311. if (node.test) { c(node.test, st, "Expression"); }
  4312. if (node.update) { c(node.update, st, "Expression"); }
  4313. c(node.body, st, "Statement");
  4314. };
  4315. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4316. c(node.left, st, "ForInit");
  4317. c(node.right, st, "Expression");
  4318. c(node.body, st, "Statement");
  4319. };
  4320. base$1.ForInit = function (node, st, c) {
  4321. if (node.type === "VariableDeclaration") { c(node, st); }
  4322. else { c(node, st, "Expression"); }
  4323. };
  4324. base$1.DebuggerStatement = ignore;
  4325. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4326. base$1.VariableDeclaration = function (node, st, c) {
  4327. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4328. {
  4329. var decl = list[i];
  4330. c(decl, st);
  4331. }
  4332. };
  4333. base$1.VariableDeclarator = function (node, st, c) {
  4334. c(node.id, st, "Pattern");
  4335. if (node.init) { c(node.init, st, "Expression"); }
  4336. };
  4337. base$1.Function = function (node, st, c) {
  4338. if (node.id) { c(node.id, st, "Pattern"); }
  4339. for (var i = 0, list = node.params; i < list.length; i += 1)
  4340. {
  4341. var param = list[i];
  4342. c(param, st, "Pattern");
  4343. }
  4344. c(node.body, st, node.expression ? "Expression" : "Statement");
  4345. };
  4346. base$1.Pattern = function (node, st, c) {
  4347. if (node.type === "Identifier")
  4348. { c(node, st, "VariablePattern"); }
  4349. else if (node.type === "MemberExpression")
  4350. { c(node, st, "MemberPattern"); }
  4351. else
  4352. { c(node, st); }
  4353. };
  4354. base$1.VariablePattern = ignore;
  4355. base$1.MemberPattern = skipThrough;
  4356. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4357. base$1.ArrayPattern = function (node, st, c) {
  4358. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4359. var elt = list[i];
  4360. if (elt) { c(elt, st, "Pattern"); }
  4361. }
  4362. };
  4363. base$1.ObjectPattern = function (node, st, c) {
  4364. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4365. var prop = list[i];
  4366. if (prop.type === "Property") {
  4367. if (prop.computed) { c(prop.key, st, "Expression"); }
  4368. c(prop.value, st, "Pattern");
  4369. } else if (prop.type === "RestElement") {
  4370. c(prop.argument, st, "Pattern");
  4371. }
  4372. }
  4373. };
  4374. base$1.Expression = skipThrough;
  4375. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4376. base$1.ArrayExpression = function (node, st, c) {
  4377. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4378. var elt = list[i];
  4379. if (elt) { c(elt, st, "Expression"); }
  4380. }
  4381. };
  4382. base$1.ObjectExpression = function (node, st, c) {
  4383. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4384. {
  4385. var prop = list[i];
  4386. c(prop, st);
  4387. }
  4388. };
  4389. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4390. base$1.SequenceExpression = function (node, st, c) {
  4391. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4392. {
  4393. var expr = list[i];
  4394. c(expr, st, "Expression");
  4395. }
  4396. };
  4397. base$1.TemplateLiteral = function (node, st, c) {
  4398. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4399. {
  4400. var quasi = list[i];
  4401. c(quasi, st);
  4402. }
  4403. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4404. {
  4405. var expr = list$1[i$1];
  4406. c(expr, st, "Expression");
  4407. }
  4408. };
  4409. base$1.TemplateElement = ignore;
  4410. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4411. c(node.argument, st, "Expression");
  4412. };
  4413. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4414. c(node.left, st, "Expression");
  4415. c(node.right, st, "Expression");
  4416. };
  4417. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4418. c(node.left, st, "Pattern");
  4419. c(node.right, st, "Expression");
  4420. };
  4421. base$1.ConditionalExpression = function (node, st, c) {
  4422. c(node.test, st, "Expression");
  4423. c(node.consequent, st, "Expression");
  4424. c(node.alternate, st, "Expression");
  4425. };
  4426. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4427. c(node.callee, st, "Expression");
  4428. if (node.arguments)
  4429. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4430. {
  4431. var arg = list[i];
  4432. c(arg, st, "Expression");
  4433. } }
  4434. };
  4435. base$1.MemberExpression = function (node, st, c) {
  4436. c(node.object, st, "Expression");
  4437. if (node.computed) { c(node.property, st, "Expression"); }
  4438. };
  4439. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4440. if (node.declaration)
  4441. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4442. if (node.source) { c(node.source, st, "Expression"); }
  4443. };
  4444. base$1.ExportAllDeclaration = function (node, st, c) {
  4445. if (node.exported)
  4446. { c(node.exported, st); }
  4447. c(node.source, st, "Expression");
  4448. };
  4449. base$1.ImportDeclaration = function (node, st, c) {
  4450. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4451. {
  4452. var spec = list[i];
  4453. c(spec, st);
  4454. }
  4455. c(node.source, st, "Expression");
  4456. };
  4457. base$1.ImportExpression = function (node, st, c) {
  4458. c(node.source, st, "Expression");
  4459. };
  4460. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4461. base$1.TaggedTemplateExpression = function (node, st, c) {
  4462. c(node.tag, st, "Expression");
  4463. c(node.quasi, st, "Expression");
  4464. };
  4465. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4466. base$1.Class = function (node, st, c) {
  4467. if (node.id) { c(node.id, st, "Pattern"); }
  4468. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4469. c(node.body, st);
  4470. };
  4471. base$1.ClassBody = function (node, st, c) {
  4472. for (var i = 0, list = node.body; i < list.length; i += 1)
  4473. {
  4474. var elt = list[i];
  4475. c(elt, st);
  4476. }
  4477. };
  4478. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4479. if (node.computed) { c(node.key, st, "Expression"); }
  4480. if (node.value) { c(node.value, st, "Expression"); }
  4481. };
  4482. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4483. const BinaryExpression$1 = 'BinaryExpression';
  4484. const BlockStatement$1 = 'BlockStatement';
  4485. const CallExpression$1 = 'CallExpression';
  4486. const ChainExpression$1 = 'ChainExpression';
  4487. const ConditionalExpression$1 = 'ConditionalExpression';
  4488. const ExpressionStatement$1 = 'ExpressionStatement';
  4489. const Identifier$1 = 'Identifier';
  4490. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  4491. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  4492. const LogicalExpression$1 = 'LogicalExpression';
  4493. const NewExpression$1 = 'NewExpression';
  4494. const Program$1 = 'Program';
  4495. const Property$1 = 'Property';
  4496. const ReturnStatement$1 = 'ReturnStatement';
  4497. const SequenceExpression$1 = 'SequenceExpression';
  4498. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4499. // this for an actual sourceMappingURL
  4500. exports.SOURCEMAPPING_URL = 'sourceMa';
  4501. exports.SOURCEMAPPING_URL += 'ppingURL';
  4502. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4503. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${exports.SOURCEMAPPING_URL}=.+`);
  4504. const ANNOTATION_KEY = '_rollupAnnotations';
  4505. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4506. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4507. const { annotations } = state;
  4508. let comment = annotations[state.annotationIndex];
  4509. while (comment && node.start >= comment.end) {
  4510. markPureNode(node, comment, state.code);
  4511. comment = annotations[++state.annotationIndex];
  4512. }
  4513. if (comment && comment.end <= node.end) {
  4514. base$1[type](node, state, handlePureAnnotationsOfNode);
  4515. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4516. ++state.annotationIndex;
  4517. annotateNode(node, comment, false);
  4518. }
  4519. }
  4520. }
  4521. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4522. const noWhitespace = /\S/g;
  4523. function markPureNode(node, comment, code) {
  4524. const annotatedNodes = [];
  4525. let invalidAnnotation;
  4526. const codeInBetween = code.slice(comment.end, node.start);
  4527. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4528. const parentStart = node.start;
  4529. while (true) {
  4530. annotatedNodes.push(node);
  4531. switch (node.type) {
  4532. case ExpressionStatement$1:
  4533. case ChainExpression$1:
  4534. node = node.expression;
  4535. continue;
  4536. case SequenceExpression$1:
  4537. // if there are parentheses, the annotation would apply to the entire expression
  4538. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4539. node = node.expressions[0];
  4540. continue;
  4541. }
  4542. invalidAnnotation = true;
  4543. break;
  4544. case ConditionalExpression$1:
  4545. // if there are parentheses, the annotation would apply to the entire expression
  4546. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4547. node = node.test;
  4548. continue;
  4549. }
  4550. invalidAnnotation = true;
  4551. break;
  4552. case LogicalExpression$1:
  4553. case BinaryExpression$1:
  4554. // if there are parentheses, the annotation would apply to the entire expression
  4555. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4556. node = node.left;
  4557. continue;
  4558. }
  4559. invalidAnnotation = true;
  4560. break;
  4561. case CallExpression$1:
  4562. case NewExpression$1:
  4563. break;
  4564. default:
  4565. invalidAnnotation = true;
  4566. }
  4567. break;
  4568. }
  4569. }
  4570. else {
  4571. invalidAnnotation = true;
  4572. }
  4573. if (invalidAnnotation) {
  4574. annotateNode(node, comment, false);
  4575. }
  4576. else {
  4577. for (const node of annotatedNodes) {
  4578. annotateNode(node, comment, true);
  4579. }
  4580. }
  4581. }
  4582. function doesNotMatchOutsideComment(code, forbiddenChars) {
  4583. let nextMatch;
  4584. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  4585. if (nextMatch[0] === '/') {
  4586. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  4587. if (charCodeAfterSlash === 42 /*"*"*/) {
  4588. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  4589. continue;
  4590. }
  4591. else if (charCodeAfterSlash === 47 /*"/"*/) {
  4592. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  4593. continue;
  4594. }
  4595. }
  4596. forbiddenChars.lastIndex = 0;
  4597. return false;
  4598. }
  4599. return true;
  4600. }
  4601. const pureCommentRegex = /[@#]__PURE__/;
  4602. function addAnnotations(comments, esTreeAst, code) {
  4603. const annotations = [];
  4604. const sourceMappingComments = [];
  4605. for (const comment of comments) {
  4606. if (pureCommentRegex.test(comment.value)) {
  4607. annotations.push(comment);
  4608. }
  4609. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  4610. sourceMappingComments.push(comment);
  4611. }
  4612. }
  4613. for (const comment of sourceMappingComments) {
  4614. annotateNode(esTreeAst, comment, false);
  4615. }
  4616. handlePureAnnotationsOfNode(esTreeAst, {
  4617. annotationIndex: 0,
  4618. annotations,
  4619. code
  4620. });
  4621. }
  4622. function annotateNode(node, comment, valid) {
  4623. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  4624. const property = node[key];
  4625. if (property) {
  4626. property.push(comment);
  4627. }
  4628. else {
  4629. node[key] = [comment];
  4630. }
  4631. }
  4632. const keys = {
  4633. Literal: [],
  4634. Program: ['body']
  4635. };
  4636. function getAndCreateKeys(esTreeNode) {
  4637. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4638. return keys[esTreeNode.type];
  4639. }
  4640. const INCLUDE_PARAMETERS = 'variables';
  4641. class NodeBase extends ExpressionEntity {
  4642. constructor(esTreeNode, parent, parentScope) {
  4643. super();
  4644. /**
  4645. * Nodes can apply custom deoptimizations once they become part of the
  4646. * executed code. To do this, they must initialize this as false, implement
  4647. * applyDeoptimizations and call this from include and hasEffects if they have
  4648. * custom handlers
  4649. */
  4650. this.deoptimized = false;
  4651. this.esTreeNode = esTreeNode;
  4652. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  4653. this.parent = parent;
  4654. this.context = parent.context;
  4655. this.createScope(parentScope);
  4656. this.parseNode(esTreeNode);
  4657. this.initialise();
  4658. this.context.magicString.addSourcemapLocation(this.start);
  4659. this.context.magicString.addSourcemapLocation(this.end);
  4660. }
  4661. addExportedVariables(_variables, _exportNamesByVariable) { }
  4662. /**
  4663. * Override this to bind assignments to variables and do any initialisations that
  4664. * require the scopes to be populated with variables.
  4665. */
  4666. bind() {
  4667. for (const key of this.keys) {
  4668. const value = this[key];
  4669. if (value === null)
  4670. continue;
  4671. if (Array.isArray(value)) {
  4672. for (const child of value) {
  4673. child === null || child === void 0 ? void 0 : child.bind();
  4674. }
  4675. }
  4676. else {
  4677. value.bind();
  4678. }
  4679. }
  4680. }
  4681. /**
  4682. * Override if this node should receive a different scope than the parent scope.
  4683. */
  4684. createScope(parentScope) {
  4685. this.scope = parentScope;
  4686. }
  4687. hasEffects(context) {
  4688. if (!this.deoptimized)
  4689. this.applyDeoptimizations();
  4690. for (const key of this.keys) {
  4691. const value = this[key];
  4692. if (value === null)
  4693. continue;
  4694. if (Array.isArray(value)) {
  4695. for (const child of value) {
  4696. if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
  4697. return true;
  4698. }
  4699. }
  4700. else if (value.hasEffects(context))
  4701. return true;
  4702. }
  4703. return false;
  4704. }
  4705. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4706. return (this.hasEffects(context) ||
  4707. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4708. }
  4709. include(context, includeChildrenRecursively, _options) {
  4710. if (!this.deoptimized)
  4711. this.applyDeoptimizations();
  4712. this.included = true;
  4713. for (const key of this.keys) {
  4714. const value = this[key];
  4715. if (value === null)
  4716. continue;
  4717. if (Array.isArray(value)) {
  4718. for (const child of value) {
  4719. child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
  4720. }
  4721. }
  4722. else {
  4723. value.include(context, includeChildrenRecursively);
  4724. }
  4725. }
  4726. }
  4727. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4728. this.include(context, includeChildrenRecursively);
  4729. }
  4730. /**
  4731. * Override to perform special initialisation steps after the scope is initialised
  4732. */
  4733. initialise() { }
  4734. insertSemicolon(code) {
  4735. if (code.original[this.end - 1] !== ';') {
  4736. code.appendLeft(this.end, ';');
  4737. }
  4738. }
  4739. parseNode(esTreeNode) {
  4740. for (const [key, value] of Object.entries(esTreeNode)) {
  4741. // That way, we can override this function to add custom initialisation and then call super.parseNode
  4742. if (this.hasOwnProperty(key))
  4743. continue;
  4744. if (key.charCodeAt(0) === 95 /* _ */) {
  4745. if (key === ANNOTATION_KEY) {
  4746. this.annotations = value;
  4747. }
  4748. else if (key === INVALID_COMMENT_KEY) {
  4749. for (const { start, end } of value)
  4750. this.context.magicString.remove(start, end);
  4751. }
  4752. }
  4753. else if (typeof value !== 'object' || value === null) {
  4754. this[key] = value;
  4755. }
  4756. else if (Array.isArray(value)) {
  4757. this[key] = [];
  4758. for (const child of value) {
  4759. this[key].push(child === null
  4760. ? null
  4761. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
  4762. }
  4763. }
  4764. else {
  4765. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
  4766. }
  4767. }
  4768. }
  4769. render(code, options) {
  4770. for (const key of this.keys) {
  4771. const value = this[key];
  4772. if (value === null)
  4773. continue;
  4774. if (Array.isArray(value)) {
  4775. for (const child of value) {
  4776. child === null || child === void 0 ? void 0 : child.render(code, options);
  4777. }
  4778. }
  4779. else {
  4780. value.render(code, options);
  4781. }
  4782. }
  4783. }
  4784. setAssignedValue(value) {
  4785. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  4786. }
  4787. shouldBeIncluded(context) {
  4788. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4789. }
  4790. /**
  4791. * Just deoptimize everything by default so that when e.g. we do not track
  4792. * something properly, it is deoptimized.
  4793. * @protected
  4794. */
  4795. applyDeoptimizations() {
  4796. this.deoptimized = true;
  4797. for (const key of this.keys) {
  4798. const value = this[key];
  4799. if (value === null)
  4800. continue;
  4801. if (Array.isArray(value)) {
  4802. for (const child of value) {
  4803. child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
  4804. }
  4805. }
  4806. else {
  4807. value.deoptimizePath(UNKNOWN_PATH);
  4808. }
  4809. }
  4810. this.context.requestTreeshakingPass();
  4811. }
  4812. }
  4813. class SpreadElement extends NodeBase {
  4814. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4815. if (path.length > 0) {
  4816. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4817. }
  4818. }
  4819. hasEffects(context) {
  4820. if (!this.deoptimized)
  4821. this.applyDeoptimizations();
  4822. const { propertyReadSideEffects } = this.context.options
  4823. .treeshake;
  4824. return (this.argument.hasEffects(context) ||
  4825. (propertyReadSideEffects &&
  4826. (propertyReadSideEffects === 'always' ||
  4827. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4828. }
  4829. applyDeoptimizations() {
  4830. this.deoptimized = true;
  4831. // Only properties of properties of the argument could become subject to reassignment
  4832. // This will also reassign the return values of iterators
  4833. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4834. this.context.requestTreeshakingPass();
  4835. }
  4836. }
  4837. class Method extends ExpressionEntity {
  4838. constructor(description) {
  4839. super();
  4840. this.description = description;
  4841. }
  4842. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  4843. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4844. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4845. }
  4846. }
  4847. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  4848. if (path.length > 0) {
  4849. return UNKNOWN_EXPRESSION;
  4850. }
  4851. return (this.description.returnsPrimitive ||
  4852. (this.description.returns === 'self'
  4853. ? thisArg || UNKNOWN_EXPRESSION
  4854. : this.description.returns()));
  4855. }
  4856. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4857. var _a, _b;
  4858. const { type } = interaction;
  4859. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4860. return true;
  4861. }
  4862. if (type === INTERACTION_CALLED) {
  4863. if (this.description.mutatesSelfAsArray === true &&
  4864. ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
  4865. return true;
  4866. }
  4867. if (this.description.callsArgs) {
  4868. for (const argIndex of this.description.callsArgs) {
  4869. if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4870. return true;
  4871. }
  4872. }
  4873. }
  4874. }
  4875. return false;
  4876. }
  4877. }
  4878. const METHOD_RETURNS_BOOLEAN = [
  4879. new Method({
  4880. callsArgs: null,
  4881. mutatesSelfAsArray: false,
  4882. returns: null,
  4883. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4884. })
  4885. ];
  4886. const METHOD_RETURNS_STRING = [
  4887. new Method({
  4888. callsArgs: null,
  4889. mutatesSelfAsArray: false,
  4890. returns: null,
  4891. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4892. })
  4893. ];
  4894. const METHOD_RETURNS_NUMBER = [
  4895. new Method({
  4896. callsArgs: null,
  4897. mutatesSelfAsArray: false,
  4898. returns: null,
  4899. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4900. })
  4901. ];
  4902. const METHOD_RETURNS_UNKNOWN = [
  4903. new Method({
  4904. callsArgs: null,
  4905. mutatesSelfAsArray: false,
  4906. returns: null,
  4907. returnsPrimitive: UNKNOWN_EXPRESSION
  4908. })
  4909. ];
  4910. const INTEGER_REG_EXP = /^\d+$/;
  4911. class ObjectEntity extends ExpressionEntity {
  4912. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4913. // and we assume there are no setters or getters
  4914. constructor(properties, prototypeExpression, immutable = false) {
  4915. super();
  4916. this.prototypeExpression = prototypeExpression;
  4917. this.immutable = immutable;
  4918. this.allProperties = [];
  4919. this.deoptimizedPaths = Object.create(null);
  4920. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4921. this.gettersByKey = Object.create(null);
  4922. this.hasLostTrack = false;
  4923. this.hasUnknownDeoptimizedInteger = false;
  4924. this.hasUnknownDeoptimizedProperty = false;
  4925. this.propertiesAndGettersByKey = Object.create(null);
  4926. this.propertiesAndSettersByKey = Object.create(null);
  4927. this.settersByKey = Object.create(null);
  4928. this.thisParametersToBeDeoptimized = new Set();
  4929. this.unknownIntegerProps = [];
  4930. this.unmatchableGetters = [];
  4931. this.unmatchablePropertiesAndGetters = [];
  4932. this.unmatchableSetters = [];
  4933. if (Array.isArray(properties)) {
  4934. this.buildPropertyMaps(properties);
  4935. }
  4936. else {
  4937. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4938. for (const propertiesForKey of Object.values(properties)) {
  4939. this.allProperties.push(...propertiesForKey);
  4940. }
  4941. }
  4942. }
  4943. deoptimizeAllProperties(noAccessors) {
  4944. var _a;
  4945. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4946. if (noAccessors) {
  4947. this.hasUnknownDeoptimizedProperty = true;
  4948. }
  4949. else {
  4950. this.hasLostTrack = true;
  4951. }
  4952. if (isDeoptimized) {
  4953. return;
  4954. }
  4955. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4956. for (const property of properties) {
  4957. property.deoptimizePath(UNKNOWN_PATH);
  4958. }
  4959. }
  4960. // While the prototype itself cannot be mutated, each property can
  4961. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4962. this.deoptimizeCachedEntities();
  4963. }
  4964. deoptimizeIntegerProperties() {
  4965. if (this.hasLostTrack ||
  4966. this.hasUnknownDeoptimizedProperty ||
  4967. this.hasUnknownDeoptimizedInteger) {
  4968. return;
  4969. }
  4970. this.hasUnknownDeoptimizedInteger = true;
  4971. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4972. if (INTEGER_REG_EXP.test(key)) {
  4973. for (const property of propertiesAndGetters) {
  4974. property.deoptimizePath(UNKNOWN_PATH);
  4975. }
  4976. }
  4977. }
  4978. this.deoptimizeCachedIntegerEntities();
  4979. }
  4980. // Assumption: If only a specific path is deoptimized, no accessors are created
  4981. deoptimizePath(path) {
  4982. var _a;
  4983. if (this.hasLostTrack || this.immutable) {
  4984. return;
  4985. }
  4986. const key = path[0];
  4987. if (path.length === 1) {
  4988. if (typeof key !== 'string') {
  4989. if (key === UnknownInteger) {
  4990. return this.deoptimizeIntegerProperties();
  4991. }
  4992. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4993. }
  4994. if (!this.deoptimizedPaths[key]) {
  4995. this.deoptimizedPaths[key] = true;
  4996. // we only deoptimizeCache exact matches as in all other cases,
  4997. // we do not return a literal value or return expression
  4998. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4999. if (expressionsToBeDeoptimized) {
  5000. for (const expression of expressionsToBeDeoptimized) {
  5001. expression.deoptimizeCache();
  5002. }
  5003. }
  5004. }
  5005. }
  5006. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  5007. for (const property of typeof key === 'string'
  5008. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  5009. : this.allProperties) {
  5010. property.deoptimizePath(subPath);
  5011. }
  5012. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  5013. }
  5014. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5015. var _a;
  5016. const [key, ...subPath] = path;
  5017. if (this.hasLostTrack ||
  5018. // single paths that are deoptimized will not become getters or setters
  5019. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  5020. (this.hasUnknownDeoptimizedProperty ||
  5021. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  5022. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5023. return;
  5024. }
  5025. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  5026. ? [
  5027. this.propertiesAndGettersByKey,
  5028. this.propertiesAndGettersByKey,
  5029. this.unmatchablePropertiesAndGetters
  5030. ]
  5031. : interaction.type === INTERACTION_ACCESSED
  5032. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5033. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5034. if (typeof key === 'string') {
  5035. if (propertiesForExactMatchByKey[key]) {
  5036. const properties = relevantPropertiesByKey[key];
  5037. if (properties) {
  5038. for (const property of properties) {
  5039. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5040. }
  5041. }
  5042. if (!this.immutable) {
  5043. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5044. }
  5045. return;
  5046. }
  5047. for (const property of relevantUnmatchableProperties) {
  5048. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5049. }
  5050. if (INTEGER_REG_EXP.test(key)) {
  5051. for (const property of this.unknownIntegerProps) {
  5052. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5053. }
  5054. }
  5055. }
  5056. else {
  5057. for (const properties of Object.values(relevantPropertiesByKey).concat([
  5058. relevantUnmatchableProperties
  5059. ])) {
  5060. for (const property of properties) {
  5061. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5062. }
  5063. }
  5064. for (const property of this.unknownIntegerProps) {
  5065. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  5066. }
  5067. }
  5068. if (!this.immutable) {
  5069. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  5070. }
  5071. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5072. }
  5073. getLiteralValueAtPath(path, recursionTracker, origin) {
  5074. if (path.length === 0) {
  5075. return UnknownTruthyValue;
  5076. }
  5077. const key = path[0];
  5078. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5079. if (expressionAtPath) {
  5080. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  5081. }
  5082. if (this.prototypeExpression) {
  5083. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  5084. }
  5085. if (path.length === 1) {
  5086. return undefined;
  5087. }
  5088. return UnknownValue;
  5089. }
  5090. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5091. if (path.length === 0) {
  5092. return UNKNOWN_EXPRESSION;
  5093. }
  5094. const [key, ...subPath] = path;
  5095. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5096. if (expressionAtPath) {
  5097. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  5098. }
  5099. if (this.prototypeExpression) {
  5100. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5101. }
  5102. return UNKNOWN_EXPRESSION;
  5103. }
  5104. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5105. const [key, ...subPath] = path;
  5106. if (subPath.length || interaction.type === INTERACTION_CALLED) {
  5107. const expressionAtPath = this.getMemberExpression(key);
  5108. if (expressionAtPath) {
  5109. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5110. }
  5111. if (this.prototypeExpression) {
  5112. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5113. }
  5114. return true;
  5115. }
  5116. if (key === UnknownNonAccessorKey)
  5117. return false;
  5118. if (this.hasLostTrack)
  5119. return true;
  5120. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5121. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5122. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5123. if (typeof key === 'string') {
  5124. if (propertiesAndAccessorsByKey[key]) {
  5125. const accessors = accessorsByKey[key];
  5126. if (accessors) {
  5127. for (const accessor of accessors) {
  5128. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5129. return true;
  5130. }
  5131. }
  5132. return false;
  5133. }
  5134. for (const accessor of unmatchableAccessors) {
  5135. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5136. return true;
  5137. }
  5138. }
  5139. }
  5140. else {
  5141. for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
  5142. for (const accessor of accessors) {
  5143. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5144. return true;
  5145. }
  5146. }
  5147. }
  5148. if (this.prototypeExpression) {
  5149. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5150. }
  5151. return false;
  5152. }
  5153. buildPropertyMaps(properties) {
  5154. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5155. const unmatchablePropertiesAndSetters = [];
  5156. for (let index = properties.length - 1; index >= 0; index--) {
  5157. const { key, kind, property } = properties[index];
  5158. allProperties.push(property);
  5159. if (typeof key !== 'string') {
  5160. if (key === UnknownInteger) {
  5161. unknownIntegerProps.push(property);
  5162. continue;
  5163. }
  5164. if (kind === 'set')
  5165. unmatchableSetters.push(property);
  5166. if (kind === 'get')
  5167. unmatchableGetters.push(property);
  5168. if (kind !== 'get')
  5169. unmatchablePropertiesAndSetters.push(property);
  5170. if (kind !== 'set')
  5171. unmatchablePropertiesAndGetters.push(property);
  5172. }
  5173. else {
  5174. if (kind === 'set') {
  5175. if (!propertiesAndSettersByKey[key]) {
  5176. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5177. settersByKey[key] = [property, ...unmatchableSetters];
  5178. }
  5179. }
  5180. else if (kind === 'get') {
  5181. if (!propertiesAndGettersByKey[key]) {
  5182. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5183. gettersByKey[key] = [property, ...unmatchableGetters];
  5184. }
  5185. }
  5186. else {
  5187. if (!propertiesAndSettersByKey[key]) {
  5188. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5189. }
  5190. if (!propertiesAndGettersByKey[key]) {
  5191. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5192. }
  5193. }
  5194. }
  5195. }
  5196. }
  5197. deoptimizeCachedEntities() {
  5198. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5199. for (const expression of expressionsToBeDeoptimized) {
  5200. expression.deoptimizeCache();
  5201. }
  5202. }
  5203. for (const expression of this.thisParametersToBeDeoptimized) {
  5204. expression.deoptimizePath(UNKNOWN_PATH);
  5205. }
  5206. }
  5207. deoptimizeCachedIntegerEntities() {
  5208. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5209. if (INTEGER_REG_EXP.test(key)) {
  5210. for (const expression of expressionsToBeDeoptimized) {
  5211. expression.deoptimizeCache();
  5212. }
  5213. }
  5214. }
  5215. for (const expression of this.thisParametersToBeDeoptimized) {
  5216. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5217. }
  5218. }
  5219. getMemberExpression(key) {
  5220. if (this.hasLostTrack ||
  5221. this.hasUnknownDeoptimizedProperty ||
  5222. typeof key !== 'string' ||
  5223. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5224. this.deoptimizedPaths[key]) {
  5225. return UNKNOWN_EXPRESSION;
  5226. }
  5227. const properties = this.propertiesAndGettersByKey[key];
  5228. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  5229. return properties[0];
  5230. }
  5231. if (properties ||
  5232. this.unmatchablePropertiesAndGetters.length > 0 ||
  5233. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  5234. return UNKNOWN_EXPRESSION;
  5235. }
  5236. return null;
  5237. }
  5238. getMemberExpressionAndTrackDeopt(key, origin) {
  5239. if (typeof key !== 'string') {
  5240. return UNKNOWN_EXPRESSION;
  5241. }
  5242. const expression = this.getMemberExpression(key);
  5243. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5244. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5245. this.expressionsToBeDeoptimizedByKey[key] || []);
  5246. expressionsToBeDeoptimized.push(origin);
  5247. }
  5248. return expression;
  5249. }
  5250. }
  5251. const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
  5252. // This makes sure unknown properties are not handled as "undefined" but as
  5253. // "unknown" but without access side effects. An exception is done for numeric
  5254. // properties as we do not expect new builtin properties to be numbers, this
  5255. // will improve tree-shaking for out-of-bounds array properties
  5256. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5257. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5258. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5259. thisArg.deoptimizePath(UNKNOWN_PATH);
  5260. }
  5261. }
  5262. getLiteralValueAtPath(path) {
  5263. // We ignore number properties as we do not expect new properties to be
  5264. // numbers and also want to keep handling out-of-bound array elements as
  5265. // "undefined"
  5266. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5267. }
  5268. hasEffectsOnInteractionAtPath(path, { type }) {
  5269. return path.length > 1 || type === INTERACTION_CALLED;
  5270. }
  5271. })();
  5272. const OBJECT_PROTOTYPE = new ObjectEntity({
  5273. __proto__: null,
  5274. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5275. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5276. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5277. toLocaleString: METHOD_RETURNS_STRING,
  5278. toString: METHOD_RETURNS_STRING,
  5279. valueOf: METHOD_RETURNS_UNKNOWN
  5280. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5281. const NEW_ARRAY_PROPERTIES = [
  5282. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5283. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5284. ];
  5285. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5286. new Method({
  5287. callsArgs: [0],
  5288. mutatesSelfAsArray: 'deopt-only',
  5289. returns: null,
  5290. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5291. })
  5292. ];
  5293. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5294. new Method({
  5295. callsArgs: [0],
  5296. mutatesSelfAsArray: 'deopt-only',
  5297. returns: null,
  5298. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5299. })
  5300. ];
  5301. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5302. new Method({
  5303. callsArgs: null,
  5304. mutatesSelfAsArray: true,
  5305. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5306. returnsPrimitive: null
  5307. })
  5308. ];
  5309. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5310. new Method({
  5311. callsArgs: null,
  5312. mutatesSelfAsArray: 'deopt-only',
  5313. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5314. returnsPrimitive: null
  5315. })
  5316. ];
  5317. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5318. new Method({
  5319. callsArgs: [0],
  5320. mutatesSelfAsArray: 'deopt-only',
  5321. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5322. returnsPrimitive: null
  5323. })
  5324. ];
  5325. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5326. new Method({
  5327. callsArgs: null,
  5328. mutatesSelfAsArray: true,
  5329. returns: null,
  5330. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5331. })
  5332. ];
  5333. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5334. new Method({
  5335. callsArgs: null,
  5336. mutatesSelfAsArray: true,
  5337. returns: null,
  5338. returnsPrimitive: UNKNOWN_EXPRESSION
  5339. })
  5340. ];
  5341. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5342. new Method({
  5343. callsArgs: null,
  5344. mutatesSelfAsArray: 'deopt-only',
  5345. returns: null,
  5346. returnsPrimitive: UNKNOWN_EXPRESSION
  5347. })
  5348. ];
  5349. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5350. new Method({
  5351. callsArgs: [0],
  5352. mutatesSelfAsArray: 'deopt-only',
  5353. returns: null,
  5354. returnsPrimitive: UNKNOWN_EXPRESSION
  5355. })
  5356. ];
  5357. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5358. new Method({
  5359. callsArgs: null,
  5360. mutatesSelfAsArray: true,
  5361. returns: 'self',
  5362. returnsPrimitive: null
  5363. })
  5364. ];
  5365. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5366. new Method({
  5367. callsArgs: [0],
  5368. mutatesSelfAsArray: true,
  5369. returns: 'self',
  5370. returnsPrimitive: null
  5371. })
  5372. ];
  5373. const ARRAY_PROTOTYPE = new ObjectEntity({
  5374. __proto__: null,
  5375. // We assume that accessors have effects as we do not track the accessed value afterwards
  5376. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5377. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5378. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5379. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5380. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5381. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5382. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5383. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5384. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5385. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5386. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5387. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5388. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5389. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5390. group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5391. groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5392. includes: METHOD_RETURNS_BOOLEAN,
  5393. indexOf: METHOD_RETURNS_NUMBER,
  5394. join: METHOD_RETURNS_STRING,
  5395. keys: METHOD_RETURNS_UNKNOWN,
  5396. lastIndexOf: METHOD_RETURNS_NUMBER,
  5397. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5398. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5399. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5400. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5401. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5402. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5403. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5404. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5405. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5406. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5407. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5408. toLocaleString: METHOD_RETURNS_STRING,
  5409. toString: METHOD_RETURNS_STRING,
  5410. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5411. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5412. }, OBJECT_PROTOTYPE, true);
  5413. class ArrayExpression extends NodeBase {
  5414. constructor() {
  5415. super(...arguments);
  5416. this.objectEntity = null;
  5417. }
  5418. deoptimizePath(path) {
  5419. this.getObjectEntity().deoptimizePath(path);
  5420. }
  5421. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5422. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5423. }
  5424. getLiteralValueAtPath(path, recursionTracker, origin) {
  5425. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5426. }
  5427. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5428. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5429. }
  5430. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5431. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5432. }
  5433. applyDeoptimizations() {
  5434. this.deoptimized = true;
  5435. let hasSpread = false;
  5436. for (let index = 0; index < this.elements.length; index++) {
  5437. const element = this.elements[index];
  5438. if (element) {
  5439. if (hasSpread || element instanceof SpreadElement) {
  5440. hasSpread = true;
  5441. element.deoptimizePath(UNKNOWN_PATH);
  5442. }
  5443. }
  5444. }
  5445. this.context.requestTreeshakingPass();
  5446. }
  5447. getObjectEntity() {
  5448. if (this.objectEntity !== null) {
  5449. return this.objectEntity;
  5450. }
  5451. const properties = [
  5452. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5453. ];
  5454. let hasSpread = false;
  5455. for (let index = 0; index < this.elements.length; index++) {
  5456. const element = this.elements[index];
  5457. if (hasSpread || element instanceof SpreadElement) {
  5458. if (element) {
  5459. hasSpread = true;
  5460. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5461. }
  5462. }
  5463. else if (!element) {
  5464. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5465. }
  5466. else {
  5467. properties.push({ key: String(index), kind: 'init', property: element });
  5468. }
  5469. }
  5470. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5471. }
  5472. }
  5473. class ArrayPattern extends NodeBase {
  5474. addExportedVariables(variables, exportNamesByVariable) {
  5475. for (const element of this.elements) {
  5476. element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
  5477. }
  5478. }
  5479. declare(kind) {
  5480. const variables = [];
  5481. for (const element of this.elements) {
  5482. if (element !== null) {
  5483. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5484. }
  5485. }
  5486. return variables;
  5487. }
  5488. // Patterns can only be deoptimized at the empty path at the moment
  5489. deoptimizePath() {
  5490. for (const element of this.elements) {
  5491. element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
  5492. }
  5493. }
  5494. // Patterns are only checked at the emtpy path at the moment
  5495. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5496. for (const element of this.elements) {
  5497. if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5498. return true;
  5499. }
  5500. return false;
  5501. }
  5502. markDeclarationReached() {
  5503. for (const element of this.elements) {
  5504. element === null || element === void 0 ? void 0 : element.markDeclarationReached();
  5505. }
  5506. }
  5507. }
  5508. class LocalVariable extends Variable {
  5509. constructor(name, declarator, init, context) {
  5510. super(name);
  5511. this.calledFromTryStatement = false;
  5512. this.additionalInitializers = null;
  5513. this.expressionsToBeDeoptimized = [];
  5514. this.declarations = declarator ? [declarator] : [];
  5515. this.init = init;
  5516. this.deoptimizationTracker = context.deoptimizationTracker;
  5517. this.module = context.module;
  5518. }
  5519. addDeclaration(identifier, init) {
  5520. this.declarations.push(identifier);
  5521. const additionalInitializers = this.markInitializersForDeoptimization();
  5522. if (init !== null) {
  5523. additionalInitializers.push(init);
  5524. }
  5525. }
  5526. consolidateInitializers() {
  5527. if (this.additionalInitializers !== null) {
  5528. for (const initializer of this.additionalInitializers) {
  5529. initializer.deoptimizePath(UNKNOWN_PATH);
  5530. }
  5531. this.additionalInitializers = null;
  5532. }
  5533. }
  5534. deoptimizePath(path) {
  5535. var _a, _b;
  5536. if (this.isReassigned ||
  5537. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5538. return;
  5539. }
  5540. if (path.length === 0) {
  5541. if (!this.isReassigned) {
  5542. this.isReassigned = true;
  5543. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5544. this.expressionsToBeDeoptimized = [];
  5545. for (const expression of expressionsToBeDeoptimized) {
  5546. expression.deoptimizeCache();
  5547. }
  5548. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  5549. }
  5550. }
  5551. else {
  5552. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  5553. }
  5554. }
  5555. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5556. if (this.isReassigned || !this.init) {
  5557. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5558. }
  5559. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5560. }
  5561. getLiteralValueAtPath(path, recursionTracker, origin) {
  5562. if (this.isReassigned || !this.init) {
  5563. return UnknownValue;
  5564. }
  5565. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5566. this.expressionsToBeDeoptimized.push(origin);
  5567. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5568. }, UnknownValue);
  5569. }
  5570. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5571. if (this.isReassigned || !this.init) {
  5572. return UNKNOWN_EXPRESSION;
  5573. }
  5574. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5575. this.expressionsToBeDeoptimized.push(origin);
  5576. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5577. }, UNKNOWN_EXPRESSION);
  5578. }
  5579. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5580. switch (interaction.type) {
  5581. case INTERACTION_ACCESSED:
  5582. if (this.isReassigned)
  5583. return true;
  5584. return (this.init &&
  5585. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5586. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5587. case INTERACTION_ASSIGNED:
  5588. if (this.included)
  5589. return true;
  5590. if (path.length === 0)
  5591. return false;
  5592. if (this.isReassigned)
  5593. return true;
  5594. return (this.init &&
  5595. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5596. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5597. case INTERACTION_CALLED:
  5598. if (this.isReassigned)
  5599. return true;
  5600. return (this.init &&
  5601. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5602. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5603. }
  5604. }
  5605. include() {
  5606. if (!this.included) {
  5607. this.included = true;
  5608. for (const declaration of this.declarations) {
  5609. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5610. if (!declaration.included)
  5611. declaration.include(createInclusionContext(), false);
  5612. let node = declaration.parent;
  5613. while (!node.included) {
  5614. // We do not want to properly include parents in case they are part of a dead branch
  5615. // in which case .include() might pull in more dead code
  5616. node.included = true;
  5617. if (node.type === Program$1)
  5618. break;
  5619. node = node.parent;
  5620. }
  5621. }
  5622. }
  5623. }
  5624. includeCallArguments(context, args) {
  5625. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  5626. for (const arg of args) {
  5627. arg.include(context, false);
  5628. }
  5629. }
  5630. else if (this.init) {
  5631. context.includedCallArguments.add(this.init);
  5632. this.init.includeCallArguments(context, args);
  5633. context.includedCallArguments.delete(this.init);
  5634. }
  5635. }
  5636. markCalledFromTryStatement() {
  5637. this.calledFromTryStatement = true;
  5638. }
  5639. markInitializersForDeoptimization() {
  5640. if (this.additionalInitializers === null) {
  5641. this.additionalInitializers = this.init === null ? [] : [this.init];
  5642. this.init = UNKNOWN_EXPRESSION;
  5643. this.isReassigned = true;
  5644. }
  5645. return this.additionalInitializers;
  5646. }
  5647. }
  5648. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5649. const base = 64;
  5650. function toBase64(num) {
  5651. let outStr = '';
  5652. do {
  5653. const curDigit = num % base;
  5654. num = Math.floor(num / base);
  5655. outStr = chars[curDigit] + outStr;
  5656. } while (num !== 0);
  5657. return outStr;
  5658. }
  5659. function getSafeName(baseName, usedNames) {
  5660. let safeName = baseName;
  5661. let count = 1;
  5662. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
  5663. safeName = `${baseName}$${toBase64(count++)}`;
  5664. }
  5665. usedNames.add(safeName);
  5666. return safeName;
  5667. }
  5668. class Scope$1 {
  5669. constructor() {
  5670. this.children = [];
  5671. this.variables = new Map();
  5672. }
  5673. addDeclaration(identifier, context, init, _isHoisted) {
  5674. const name = identifier.name;
  5675. let variable = this.variables.get(name);
  5676. if (variable) {
  5677. variable.addDeclaration(identifier, init);
  5678. }
  5679. else {
  5680. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  5681. this.variables.set(name, variable);
  5682. }
  5683. return variable;
  5684. }
  5685. contains(name) {
  5686. return this.variables.has(name);
  5687. }
  5688. findVariable(_name) {
  5689. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5690. }
  5691. }
  5692. class ChildScope extends Scope$1 {
  5693. constructor(parent) {
  5694. super();
  5695. this.accessedOutsideVariables = new Map();
  5696. this.parent = parent;
  5697. parent.children.push(this);
  5698. }
  5699. addAccessedDynamicImport(importExpression) {
  5700. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5701. if (this.parent instanceof ChildScope) {
  5702. this.parent.addAccessedDynamicImport(importExpression);
  5703. }
  5704. }
  5705. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5706. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5707. for (const name of globals) {
  5708. accessedGlobals.add(name);
  5709. }
  5710. accessedGlobalsByScope.set(this, accessedGlobals);
  5711. if (this.parent instanceof ChildScope) {
  5712. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5713. }
  5714. }
  5715. addNamespaceMemberAccess(name, variable) {
  5716. this.accessedOutsideVariables.set(name, variable);
  5717. this.parent.addNamespaceMemberAccess(name, variable);
  5718. }
  5719. addReturnExpression(expression) {
  5720. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5721. }
  5722. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5723. for (const variable of this.accessedOutsideVariables.values()) {
  5724. if (variable.included) {
  5725. usedNames.add(variable.getBaseVariableName());
  5726. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5727. usedNames.add('exports');
  5728. }
  5729. }
  5730. }
  5731. const accessedGlobals = accessedGlobalsByScope.get(this);
  5732. if (accessedGlobals) {
  5733. for (const name of accessedGlobals) {
  5734. usedNames.add(name);
  5735. }
  5736. }
  5737. }
  5738. contains(name) {
  5739. return this.variables.has(name) || this.parent.contains(name);
  5740. }
  5741. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5742. const usedNames = new Set();
  5743. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5744. if (this.accessedDynamicImports) {
  5745. for (const importExpression of this.accessedDynamicImports) {
  5746. if (importExpression.inlineNamespace) {
  5747. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5748. }
  5749. }
  5750. }
  5751. for (const [name, variable] of this.variables) {
  5752. if (variable.included || variable.alwaysRendered) {
  5753. variable.setRenderNames(null, getSafeName(name, usedNames));
  5754. }
  5755. }
  5756. for (const scope of this.children) {
  5757. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5758. }
  5759. }
  5760. findLexicalBoundary() {
  5761. return this.parent.findLexicalBoundary();
  5762. }
  5763. findVariable(name) {
  5764. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5765. if (knownVariable) {
  5766. return knownVariable;
  5767. }
  5768. const variable = this.parent.findVariable(name);
  5769. this.accessedOutsideVariables.set(name, variable);
  5770. return variable;
  5771. }
  5772. }
  5773. class ParameterScope extends ChildScope {
  5774. constructor(parent, context) {
  5775. super(parent);
  5776. this.parameters = [];
  5777. this.hasRest = false;
  5778. this.context = context;
  5779. this.hoistedBodyVarScope = new ChildScope(this);
  5780. }
  5781. /**
  5782. * Adds a parameter to this scope. Parameters must be added in the correct
  5783. * order, e.g. from left to right.
  5784. */
  5785. addParameterDeclaration(identifier) {
  5786. const name = identifier.name;
  5787. let variable = this.hoistedBodyVarScope.variables.get(name);
  5788. if (variable) {
  5789. variable.addDeclaration(identifier, null);
  5790. }
  5791. else {
  5792. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5793. }
  5794. this.variables.set(name, variable);
  5795. return variable;
  5796. }
  5797. addParameterVariables(parameters, hasRest) {
  5798. this.parameters = parameters;
  5799. for (const parameterList of parameters) {
  5800. for (const parameter of parameterList) {
  5801. parameter.alwaysRendered = true;
  5802. }
  5803. }
  5804. this.hasRest = hasRest;
  5805. }
  5806. includeCallArguments(context, args) {
  5807. let calledFromTryStatement = false;
  5808. let argIncluded = false;
  5809. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5810. for (const checkedArg of args) {
  5811. if (checkedArg instanceof SpreadElement) {
  5812. for (const arg of args) {
  5813. arg.include(context, false);
  5814. }
  5815. break;
  5816. }
  5817. }
  5818. for (let index = args.length - 1; index >= 0; index--) {
  5819. const paramVars = this.parameters[index] || restParam;
  5820. const arg = args[index];
  5821. if (paramVars) {
  5822. calledFromTryStatement = false;
  5823. if (paramVars.length === 0) {
  5824. // handle empty destructuring
  5825. argIncluded = true;
  5826. }
  5827. else {
  5828. for (const variable of paramVars) {
  5829. if (variable.included) {
  5830. argIncluded = true;
  5831. }
  5832. if (variable.calledFromTryStatement) {
  5833. calledFromTryStatement = true;
  5834. }
  5835. }
  5836. }
  5837. }
  5838. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5839. argIncluded = true;
  5840. }
  5841. if (argIncluded) {
  5842. arg.include(context, calledFromTryStatement);
  5843. }
  5844. }
  5845. }
  5846. }
  5847. class ReturnValueScope extends ParameterScope {
  5848. constructor() {
  5849. super(...arguments);
  5850. this.returnExpression = null;
  5851. this.returnExpressions = [];
  5852. }
  5853. addReturnExpression(expression) {
  5854. this.returnExpressions.push(expression);
  5855. }
  5856. getReturnExpression() {
  5857. if (this.returnExpression === null)
  5858. this.updateReturnExpression();
  5859. return this.returnExpression;
  5860. }
  5861. updateReturnExpression() {
  5862. if (this.returnExpressions.length === 1) {
  5863. this.returnExpression = this.returnExpressions[0];
  5864. }
  5865. else {
  5866. this.returnExpression = UNKNOWN_EXPRESSION;
  5867. for (const expression of this.returnExpressions) {
  5868. expression.deoptimizePath(UNKNOWN_PATH);
  5869. }
  5870. }
  5871. }
  5872. }
  5873. //@ts-check
  5874. /** @typedef { import('estree').Node} Node */
  5875. /** @typedef {Node | {
  5876. * type: 'PropertyDefinition';
  5877. * computed: boolean;
  5878. * value: Node
  5879. * }} NodeWithPropertyDefinition */
  5880. /**
  5881. *
  5882. * @param {NodeWithPropertyDefinition} node
  5883. * @param {NodeWithPropertyDefinition} parent
  5884. * @returns boolean
  5885. */
  5886. function is_reference (node, parent) {
  5887. if (node.type === 'MemberExpression') {
  5888. return !node.computed && is_reference(node.object, node);
  5889. }
  5890. if (node.type === 'Identifier') {
  5891. if (!parent) return true;
  5892. switch (parent.type) {
  5893. // disregard `bar` in `foo.bar`
  5894. case 'MemberExpression': return parent.computed || node === parent.object;
  5895. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5896. case 'MethodDefinition': return parent.computed;
  5897. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5898. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5899. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5900. case 'Property': return parent.computed || node === parent.value;
  5901. // disregard the `bar` in `export { foo as bar }` or
  5902. // the foo in `import { foo as bar }`
  5903. case 'ExportSpecifier':
  5904. case 'ImportSpecifier': return node === parent.local;
  5905. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5906. case 'LabeledStatement':
  5907. case 'BreakStatement':
  5908. case 'ContinueStatement': return false;
  5909. default: return true;
  5910. }
  5911. }
  5912. return false;
  5913. }
  5914. /* eslint sort-keys: "off" */
  5915. const ValueProperties = Symbol('Value Properties');
  5916. const PURE = {
  5917. hasEffectsWhenCalled() {
  5918. return false;
  5919. }
  5920. };
  5921. const IMPURE = {
  5922. hasEffectsWhenCalled() {
  5923. return true;
  5924. }
  5925. };
  5926. // We use shortened variables to reduce file size here
  5927. /* OBJECT */
  5928. const O = {
  5929. __proto__: null,
  5930. [ValueProperties]: IMPURE
  5931. };
  5932. /* PURE FUNCTION */
  5933. const PF = {
  5934. __proto__: null,
  5935. [ValueProperties]: PURE
  5936. };
  5937. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5938. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5939. __proto__: null,
  5940. [ValueProperties]: {
  5941. hasEffectsWhenCalled({ args }, context) {
  5942. return (!args.length ||
  5943. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5944. }
  5945. }
  5946. };
  5947. /* CONSTRUCTOR */
  5948. const C = {
  5949. __proto__: null,
  5950. [ValueProperties]: IMPURE,
  5951. prototype: O
  5952. };
  5953. /* PURE CONSTRUCTOR */
  5954. const PC = {
  5955. __proto__: null,
  5956. [ValueProperties]: PURE,
  5957. prototype: O
  5958. };
  5959. const ARRAY_TYPE = {
  5960. __proto__: null,
  5961. [ValueProperties]: PURE,
  5962. from: PF,
  5963. of: PF,
  5964. prototype: O
  5965. };
  5966. const INTL_MEMBER = {
  5967. __proto__: null,
  5968. [ValueProperties]: PURE,
  5969. supportedLocalesOf: PC
  5970. };
  5971. const knownGlobals = {
  5972. // Placeholders for global objects to avoid shape mutations
  5973. global: O,
  5974. globalThis: O,
  5975. self: O,
  5976. window: O,
  5977. // Common globals
  5978. __proto__: null,
  5979. [ValueProperties]: IMPURE,
  5980. Array: {
  5981. __proto__: null,
  5982. [ValueProperties]: IMPURE,
  5983. from: O,
  5984. isArray: PF,
  5985. of: PF,
  5986. prototype: O
  5987. },
  5988. ArrayBuffer: {
  5989. __proto__: null,
  5990. [ValueProperties]: PURE,
  5991. isView: PF,
  5992. prototype: O
  5993. },
  5994. Atomics: O,
  5995. BigInt: C,
  5996. BigInt64Array: C,
  5997. BigUint64Array: C,
  5998. Boolean: PC,
  5999. constructor: C,
  6000. DataView: PC,
  6001. Date: {
  6002. __proto__: null,
  6003. [ValueProperties]: PURE,
  6004. now: PF,
  6005. parse: PF,
  6006. prototype: O,
  6007. UTC: PF
  6008. },
  6009. decodeURI: PF,
  6010. decodeURIComponent: PF,
  6011. encodeURI: PF,
  6012. encodeURIComponent: PF,
  6013. Error: PC,
  6014. escape: PF,
  6015. eval: O,
  6016. EvalError: PC,
  6017. Float32Array: ARRAY_TYPE,
  6018. Float64Array: ARRAY_TYPE,
  6019. Function: C,
  6020. hasOwnProperty: O,
  6021. Infinity: O,
  6022. Int16Array: ARRAY_TYPE,
  6023. Int32Array: ARRAY_TYPE,
  6024. Int8Array: ARRAY_TYPE,
  6025. isFinite: PF,
  6026. isNaN: PF,
  6027. isPrototypeOf: O,
  6028. JSON: O,
  6029. Map: PC,
  6030. Math: {
  6031. __proto__: null,
  6032. [ValueProperties]: IMPURE,
  6033. abs: PF,
  6034. acos: PF,
  6035. acosh: PF,
  6036. asin: PF,
  6037. asinh: PF,
  6038. atan: PF,
  6039. atan2: PF,
  6040. atanh: PF,
  6041. cbrt: PF,
  6042. ceil: PF,
  6043. clz32: PF,
  6044. cos: PF,
  6045. cosh: PF,
  6046. exp: PF,
  6047. expm1: PF,
  6048. floor: PF,
  6049. fround: PF,
  6050. hypot: PF,
  6051. imul: PF,
  6052. log: PF,
  6053. log10: PF,
  6054. log1p: PF,
  6055. log2: PF,
  6056. max: PF,
  6057. min: PF,
  6058. pow: PF,
  6059. random: PF,
  6060. round: PF,
  6061. sign: PF,
  6062. sin: PF,
  6063. sinh: PF,
  6064. sqrt: PF,
  6065. tan: PF,
  6066. tanh: PF,
  6067. trunc: PF
  6068. },
  6069. NaN: O,
  6070. Number: {
  6071. __proto__: null,
  6072. [ValueProperties]: PURE,
  6073. isFinite: PF,
  6074. isInteger: PF,
  6075. isNaN: PF,
  6076. isSafeInteger: PF,
  6077. parseFloat: PF,
  6078. parseInt: PF,
  6079. prototype: O
  6080. },
  6081. Object: {
  6082. __proto__: null,
  6083. [ValueProperties]: PURE,
  6084. create: PF,
  6085. // Technically those can throw in certain situations, but we ignore this as
  6086. // code that relies on this will hopefully wrap this in a try-catch, which
  6087. // deoptimizes everything anyway
  6088. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  6089. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  6090. getOwnPropertyDescriptor: PF,
  6091. getOwnPropertyNames: PF,
  6092. getOwnPropertySymbols: PF,
  6093. getPrototypeOf: PF,
  6094. hasOwn: PF,
  6095. is: PF,
  6096. isExtensible: PF,
  6097. isFrozen: PF,
  6098. isSealed: PF,
  6099. keys: PF,
  6100. fromEntries: PF,
  6101. entries: PF,
  6102. prototype: O
  6103. },
  6104. parseFloat: PF,
  6105. parseInt: PF,
  6106. Promise: {
  6107. __proto__: null,
  6108. [ValueProperties]: IMPURE,
  6109. all: O,
  6110. prototype: O,
  6111. race: O,
  6112. reject: O,
  6113. resolve: O
  6114. },
  6115. propertyIsEnumerable: O,
  6116. Proxy: O,
  6117. RangeError: PC,
  6118. ReferenceError: PC,
  6119. Reflect: O,
  6120. RegExp: PC,
  6121. Set: PC,
  6122. SharedArrayBuffer: C,
  6123. String: {
  6124. __proto__: null,
  6125. [ValueProperties]: PURE,
  6126. fromCharCode: PF,
  6127. fromCodePoint: PF,
  6128. prototype: O,
  6129. raw: PF
  6130. },
  6131. Symbol: {
  6132. __proto__: null,
  6133. [ValueProperties]: PURE,
  6134. for: PF,
  6135. keyFor: PF,
  6136. prototype: O
  6137. },
  6138. SyntaxError: PC,
  6139. toLocaleString: O,
  6140. toString: O,
  6141. TypeError: PC,
  6142. Uint16Array: ARRAY_TYPE,
  6143. Uint32Array: ARRAY_TYPE,
  6144. Uint8Array: ARRAY_TYPE,
  6145. Uint8ClampedArray: ARRAY_TYPE,
  6146. // Technically, this is a global, but it needs special handling
  6147. // undefined: ?,
  6148. unescape: PF,
  6149. URIError: PC,
  6150. valueOf: O,
  6151. WeakMap: PC,
  6152. WeakSet: PC,
  6153. // Additional globals shared by Node and Browser that are not strictly part of the language
  6154. clearInterval: C,
  6155. clearTimeout: C,
  6156. console: O,
  6157. Intl: {
  6158. __proto__: null,
  6159. [ValueProperties]: IMPURE,
  6160. Collator: INTL_MEMBER,
  6161. DateTimeFormat: INTL_MEMBER,
  6162. ListFormat: INTL_MEMBER,
  6163. NumberFormat: INTL_MEMBER,
  6164. PluralRules: INTL_MEMBER,
  6165. RelativeTimeFormat: INTL_MEMBER
  6166. },
  6167. setInterval: C,
  6168. setTimeout: C,
  6169. TextDecoder: C,
  6170. TextEncoder: C,
  6171. URL: C,
  6172. URLSearchParams: C,
  6173. // Browser specific globals
  6174. AbortController: C,
  6175. AbortSignal: C,
  6176. addEventListener: O,
  6177. alert: O,
  6178. AnalyserNode: C,
  6179. Animation: C,
  6180. AnimationEvent: C,
  6181. applicationCache: O,
  6182. ApplicationCache: C,
  6183. ApplicationCacheErrorEvent: C,
  6184. atob: O,
  6185. Attr: C,
  6186. Audio: C,
  6187. AudioBuffer: C,
  6188. AudioBufferSourceNode: C,
  6189. AudioContext: C,
  6190. AudioDestinationNode: C,
  6191. AudioListener: C,
  6192. AudioNode: C,
  6193. AudioParam: C,
  6194. AudioProcessingEvent: C,
  6195. AudioScheduledSourceNode: C,
  6196. AudioWorkletNode: C,
  6197. BarProp: C,
  6198. BaseAudioContext: C,
  6199. BatteryManager: C,
  6200. BeforeUnloadEvent: C,
  6201. BiquadFilterNode: C,
  6202. Blob: C,
  6203. BlobEvent: C,
  6204. blur: O,
  6205. BroadcastChannel: C,
  6206. btoa: O,
  6207. ByteLengthQueuingStrategy: C,
  6208. Cache: C,
  6209. caches: O,
  6210. CacheStorage: C,
  6211. cancelAnimationFrame: O,
  6212. cancelIdleCallback: O,
  6213. CanvasCaptureMediaStreamTrack: C,
  6214. CanvasGradient: C,
  6215. CanvasPattern: C,
  6216. CanvasRenderingContext2D: C,
  6217. ChannelMergerNode: C,
  6218. ChannelSplitterNode: C,
  6219. CharacterData: C,
  6220. clientInformation: O,
  6221. ClipboardEvent: C,
  6222. close: O,
  6223. closed: O,
  6224. CloseEvent: C,
  6225. Comment: C,
  6226. CompositionEvent: C,
  6227. confirm: O,
  6228. ConstantSourceNode: C,
  6229. ConvolverNode: C,
  6230. CountQueuingStrategy: C,
  6231. createImageBitmap: O,
  6232. Credential: C,
  6233. CredentialsContainer: C,
  6234. crypto: O,
  6235. Crypto: C,
  6236. CryptoKey: C,
  6237. CSS: C,
  6238. CSSConditionRule: C,
  6239. CSSFontFaceRule: C,
  6240. CSSGroupingRule: C,
  6241. CSSImportRule: C,
  6242. CSSKeyframeRule: C,
  6243. CSSKeyframesRule: C,
  6244. CSSMediaRule: C,
  6245. CSSNamespaceRule: C,
  6246. CSSPageRule: C,
  6247. CSSRule: C,
  6248. CSSRuleList: C,
  6249. CSSStyleDeclaration: C,
  6250. CSSStyleRule: C,
  6251. CSSStyleSheet: C,
  6252. CSSSupportsRule: C,
  6253. CustomElementRegistry: C,
  6254. customElements: O,
  6255. CustomEvent: C,
  6256. DataTransfer: C,
  6257. DataTransferItem: C,
  6258. DataTransferItemList: C,
  6259. defaultstatus: O,
  6260. defaultStatus: O,
  6261. DelayNode: C,
  6262. DeviceMotionEvent: C,
  6263. DeviceOrientationEvent: C,
  6264. devicePixelRatio: O,
  6265. dispatchEvent: O,
  6266. document: O,
  6267. Document: C,
  6268. DocumentFragment: C,
  6269. DocumentType: C,
  6270. DOMError: C,
  6271. DOMException: C,
  6272. DOMImplementation: C,
  6273. DOMMatrix: C,
  6274. DOMMatrixReadOnly: C,
  6275. DOMParser: C,
  6276. DOMPoint: C,
  6277. DOMPointReadOnly: C,
  6278. DOMQuad: C,
  6279. DOMRect: C,
  6280. DOMRectReadOnly: C,
  6281. DOMStringList: C,
  6282. DOMStringMap: C,
  6283. DOMTokenList: C,
  6284. DragEvent: C,
  6285. DynamicsCompressorNode: C,
  6286. Element: C,
  6287. ErrorEvent: C,
  6288. Event: C,
  6289. EventSource: C,
  6290. EventTarget: C,
  6291. external: O,
  6292. fetch: O,
  6293. File: C,
  6294. FileList: C,
  6295. FileReader: C,
  6296. find: O,
  6297. focus: O,
  6298. FocusEvent: C,
  6299. FontFace: C,
  6300. FontFaceSetLoadEvent: C,
  6301. FormData: C,
  6302. frames: O,
  6303. GainNode: C,
  6304. Gamepad: C,
  6305. GamepadButton: C,
  6306. GamepadEvent: C,
  6307. getComputedStyle: O,
  6308. getSelection: O,
  6309. HashChangeEvent: C,
  6310. Headers: C,
  6311. history: O,
  6312. History: C,
  6313. HTMLAllCollection: C,
  6314. HTMLAnchorElement: C,
  6315. HTMLAreaElement: C,
  6316. HTMLAudioElement: C,
  6317. HTMLBaseElement: C,
  6318. HTMLBodyElement: C,
  6319. HTMLBRElement: C,
  6320. HTMLButtonElement: C,
  6321. HTMLCanvasElement: C,
  6322. HTMLCollection: C,
  6323. HTMLContentElement: C,
  6324. HTMLDataElement: C,
  6325. HTMLDataListElement: C,
  6326. HTMLDetailsElement: C,
  6327. HTMLDialogElement: C,
  6328. HTMLDirectoryElement: C,
  6329. HTMLDivElement: C,
  6330. HTMLDListElement: C,
  6331. HTMLDocument: C,
  6332. HTMLElement: C,
  6333. HTMLEmbedElement: C,
  6334. HTMLFieldSetElement: C,
  6335. HTMLFontElement: C,
  6336. HTMLFormControlsCollection: C,
  6337. HTMLFormElement: C,
  6338. HTMLFrameElement: C,
  6339. HTMLFrameSetElement: C,
  6340. HTMLHeadElement: C,
  6341. HTMLHeadingElement: C,
  6342. HTMLHRElement: C,
  6343. HTMLHtmlElement: C,
  6344. HTMLIFrameElement: C,
  6345. HTMLImageElement: C,
  6346. HTMLInputElement: C,
  6347. HTMLLabelElement: C,
  6348. HTMLLegendElement: C,
  6349. HTMLLIElement: C,
  6350. HTMLLinkElement: C,
  6351. HTMLMapElement: C,
  6352. HTMLMarqueeElement: C,
  6353. HTMLMediaElement: C,
  6354. HTMLMenuElement: C,
  6355. HTMLMetaElement: C,
  6356. HTMLMeterElement: C,
  6357. HTMLModElement: C,
  6358. HTMLObjectElement: C,
  6359. HTMLOListElement: C,
  6360. HTMLOptGroupElement: C,
  6361. HTMLOptionElement: C,
  6362. HTMLOptionsCollection: C,
  6363. HTMLOutputElement: C,
  6364. HTMLParagraphElement: C,
  6365. HTMLParamElement: C,
  6366. HTMLPictureElement: C,
  6367. HTMLPreElement: C,
  6368. HTMLProgressElement: C,
  6369. HTMLQuoteElement: C,
  6370. HTMLScriptElement: C,
  6371. HTMLSelectElement: C,
  6372. HTMLShadowElement: C,
  6373. HTMLSlotElement: C,
  6374. HTMLSourceElement: C,
  6375. HTMLSpanElement: C,
  6376. HTMLStyleElement: C,
  6377. HTMLTableCaptionElement: C,
  6378. HTMLTableCellElement: C,
  6379. HTMLTableColElement: C,
  6380. HTMLTableElement: C,
  6381. HTMLTableRowElement: C,
  6382. HTMLTableSectionElement: C,
  6383. HTMLTemplateElement: C,
  6384. HTMLTextAreaElement: C,
  6385. HTMLTimeElement: C,
  6386. HTMLTitleElement: C,
  6387. HTMLTrackElement: C,
  6388. HTMLUListElement: C,
  6389. HTMLUnknownElement: C,
  6390. HTMLVideoElement: C,
  6391. IDBCursor: C,
  6392. IDBCursorWithValue: C,
  6393. IDBDatabase: C,
  6394. IDBFactory: C,
  6395. IDBIndex: C,
  6396. IDBKeyRange: C,
  6397. IDBObjectStore: C,
  6398. IDBOpenDBRequest: C,
  6399. IDBRequest: C,
  6400. IDBTransaction: C,
  6401. IDBVersionChangeEvent: C,
  6402. IdleDeadline: C,
  6403. IIRFilterNode: C,
  6404. Image: C,
  6405. ImageBitmap: C,
  6406. ImageBitmapRenderingContext: C,
  6407. ImageCapture: C,
  6408. ImageData: C,
  6409. indexedDB: O,
  6410. innerHeight: O,
  6411. innerWidth: O,
  6412. InputEvent: C,
  6413. IntersectionObserver: C,
  6414. IntersectionObserverEntry: C,
  6415. isSecureContext: O,
  6416. KeyboardEvent: C,
  6417. KeyframeEffect: C,
  6418. length: O,
  6419. localStorage: O,
  6420. location: O,
  6421. Location: C,
  6422. locationbar: O,
  6423. matchMedia: O,
  6424. MediaDeviceInfo: C,
  6425. MediaDevices: C,
  6426. MediaElementAudioSourceNode: C,
  6427. MediaEncryptedEvent: C,
  6428. MediaError: C,
  6429. MediaKeyMessageEvent: C,
  6430. MediaKeySession: C,
  6431. MediaKeyStatusMap: C,
  6432. MediaKeySystemAccess: C,
  6433. MediaList: C,
  6434. MediaQueryList: C,
  6435. MediaQueryListEvent: C,
  6436. MediaRecorder: C,
  6437. MediaSettingsRange: C,
  6438. MediaSource: C,
  6439. MediaStream: C,
  6440. MediaStreamAudioDestinationNode: C,
  6441. MediaStreamAudioSourceNode: C,
  6442. MediaStreamEvent: C,
  6443. MediaStreamTrack: C,
  6444. MediaStreamTrackEvent: C,
  6445. menubar: O,
  6446. MessageChannel: C,
  6447. MessageEvent: C,
  6448. MessagePort: C,
  6449. MIDIAccess: C,
  6450. MIDIConnectionEvent: C,
  6451. MIDIInput: C,
  6452. MIDIInputMap: C,
  6453. MIDIMessageEvent: C,
  6454. MIDIOutput: C,
  6455. MIDIOutputMap: C,
  6456. MIDIPort: C,
  6457. MimeType: C,
  6458. MimeTypeArray: C,
  6459. MouseEvent: C,
  6460. moveBy: O,
  6461. moveTo: O,
  6462. MutationEvent: C,
  6463. MutationObserver: C,
  6464. MutationRecord: C,
  6465. name: O,
  6466. NamedNodeMap: C,
  6467. NavigationPreloadManager: C,
  6468. navigator: O,
  6469. Navigator: C,
  6470. NetworkInformation: C,
  6471. Node: C,
  6472. NodeFilter: O,
  6473. NodeIterator: C,
  6474. NodeList: C,
  6475. Notification: C,
  6476. OfflineAudioCompletionEvent: C,
  6477. OfflineAudioContext: C,
  6478. offscreenBuffering: O,
  6479. OffscreenCanvas: C,
  6480. open: O,
  6481. openDatabase: O,
  6482. Option: C,
  6483. origin: O,
  6484. OscillatorNode: C,
  6485. outerHeight: O,
  6486. outerWidth: O,
  6487. PageTransitionEvent: C,
  6488. pageXOffset: O,
  6489. pageYOffset: O,
  6490. PannerNode: C,
  6491. parent: O,
  6492. Path2D: C,
  6493. PaymentAddress: C,
  6494. PaymentRequest: C,
  6495. PaymentRequestUpdateEvent: C,
  6496. PaymentResponse: C,
  6497. performance: O,
  6498. Performance: C,
  6499. PerformanceEntry: C,
  6500. PerformanceLongTaskTiming: C,
  6501. PerformanceMark: C,
  6502. PerformanceMeasure: C,
  6503. PerformanceNavigation: C,
  6504. PerformanceNavigationTiming: C,
  6505. PerformanceObserver: C,
  6506. PerformanceObserverEntryList: C,
  6507. PerformancePaintTiming: C,
  6508. PerformanceResourceTiming: C,
  6509. PerformanceTiming: C,
  6510. PeriodicWave: C,
  6511. Permissions: C,
  6512. PermissionStatus: C,
  6513. personalbar: O,
  6514. PhotoCapabilities: C,
  6515. Plugin: C,
  6516. PluginArray: C,
  6517. PointerEvent: C,
  6518. PopStateEvent: C,
  6519. postMessage: O,
  6520. Presentation: C,
  6521. PresentationAvailability: C,
  6522. PresentationConnection: C,
  6523. PresentationConnectionAvailableEvent: C,
  6524. PresentationConnectionCloseEvent: C,
  6525. PresentationConnectionList: C,
  6526. PresentationReceiver: C,
  6527. PresentationRequest: C,
  6528. print: O,
  6529. ProcessingInstruction: C,
  6530. ProgressEvent: C,
  6531. PromiseRejectionEvent: C,
  6532. prompt: O,
  6533. PushManager: C,
  6534. PushSubscription: C,
  6535. PushSubscriptionOptions: C,
  6536. queueMicrotask: O,
  6537. RadioNodeList: C,
  6538. Range: C,
  6539. ReadableStream: C,
  6540. RemotePlayback: C,
  6541. removeEventListener: O,
  6542. Request: C,
  6543. requestAnimationFrame: O,
  6544. requestIdleCallback: O,
  6545. resizeBy: O,
  6546. ResizeObserver: C,
  6547. ResizeObserverEntry: C,
  6548. resizeTo: O,
  6549. Response: C,
  6550. RTCCertificate: C,
  6551. RTCDataChannel: C,
  6552. RTCDataChannelEvent: C,
  6553. RTCDtlsTransport: C,
  6554. RTCIceCandidate: C,
  6555. RTCIceTransport: C,
  6556. RTCPeerConnection: C,
  6557. RTCPeerConnectionIceEvent: C,
  6558. RTCRtpReceiver: C,
  6559. RTCRtpSender: C,
  6560. RTCSctpTransport: C,
  6561. RTCSessionDescription: C,
  6562. RTCStatsReport: C,
  6563. RTCTrackEvent: C,
  6564. screen: O,
  6565. Screen: C,
  6566. screenLeft: O,
  6567. ScreenOrientation: C,
  6568. screenTop: O,
  6569. screenX: O,
  6570. screenY: O,
  6571. ScriptProcessorNode: C,
  6572. scroll: O,
  6573. scrollbars: O,
  6574. scrollBy: O,
  6575. scrollTo: O,
  6576. scrollX: O,
  6577. scrollY: O,
  6578. SecurityPolicyViolationEvent: C,
  6579. Selection: C,
  6580. ServiceWorker: C,
  6581. ServiceWorkerContainer: C,
  6582. ServiceWorkerRegistration: C,
  6583. sessionStorage: O,
  6584. ShadowRoot: C,
  6585. SharedWorker: C,
  6586. SourceBuffer: C,
  6587. SourceBufferList: C,
  6588. speechSynthesis: O,
  6589. SpeechSynthesisEvent: C,
  6590. SpeechSynthesisUtterance: C,
  6591. StaticRange: C,
  6592. status: O,
  6593. statusbar: O,
  6594. StereoPannerNode: C,
  6595. stop: O,
  6596. Storage: C,
  6597. StorageEvent: C,
  6598. StorageManager: C,
  6599. styleMedia: O,
  6600. StyleSheet: C,
  6601. StyleSheetList: C,
  6602. SubtleCrypto: C,
  6603. SVGAElement: C,
  6604. SVGAngle: C,
  6605. SVGAnimatedAngle: C,
  6606. SVGAnimatedBoolean: C,
  6607. SVGAnimatedEnumeration: C,
  6608. SVGAnimatedInteger: C,
  6609. SVGAnimatedLength: C,
  6610. SVGAnimatedLengthList: C,
  6611. SVGAnimatedNumber: C,
  6612. SVGAnimatedNumberList: C,
  6613. SVGAnimatedPreserveAspectRatio: C,
  6614. SVGAnimatedRect: C,
  6615. SVGAnimatedString: C,
  6616. SVGAnimatedTransformList: C,
  6617. SVGAnimateElement: C,
  6618. SVGAnimateMotionElement: C,
  6619. SVGAnimateTransformElement: C,
  6620. SVGAnimationElement: C,
  6621. SVGCircleElement: C,
  6622. SVGClipPathElement: C,
  6623. SVGComponentTransferFunctionElement: C,
  6624. SVGDefsElement: C,
  6625. SVGDescElement: C,
  6626. SVGDiscardElement: C,
  6627. SVGElement: C,
  6628. SVGEllipseElement: C,
  6629. SVGFEBlendElement: C,
  6630. SVGFEColorMatrixElement: C,
  6631. SVGFEComponentTransferElement: C,
  6632. SVGFECompositeElement: C,
  6633. SVGFEConvolveMatrixElement: C,
  6634. SVGFEDiffuseLightingElement: C,
  6635. SVGFEDisplacementMapElement: C,
  6636. SVGFEDistantLightElement: C,
  6637. SVGFEDropShadowElement: C,
  6638. SVGFEFloodElement: C,
  6639. SVGFEFuncAElement: C,
  6640. SVGFEFuncBElement: C,
  6641. SVGFEFuncGElement: C,
  6642. SVGFEFuncRElement: C,
  6643. SVGFEGaussianBlurElement: C,
  6644. SVGFEImageElement: C,
  6645. SVGFEMergeElement: C,
  6646. SVGFEMergeNodeElement: C,
  6647. SVGFEMorphologyElement: C,
  6648. SVGFEOffsetElement: C,
  6649. SVGFEPointLightElement: C,
  6650. SVGFESpecularLightingElement: C,
  6651. SVGFESpotLightElement: C,
  6652. SVGFETileElement: C,
  6653. SVGFETurbulenceElement: C,
  6654. SVGFilterElement: C,
  6655. SVGForeignObjectElement: C,
  6656. SVGGElement: C,
  6657. SVGGeometryElement: C,
  6658. SVGGradientElement: C,
  6659. SVGGraphicsElement: C,
  6660. SVGImageElement: C,
  6661. SVGLength: C,
  6662. SVGLengthList: C,
  6663. SVGLinearGradientElement: C,
  6664. SVGLineElement: C,
  6665. SVGMarkerElement: C,
  6666. SVGMaskElement: C,
  6667. SVGMatrix: C,
  6668. SVGMetadataElement: C,
  6669. SVGMPathElement: C,
  6670. SVGNumber: C,
  6671. SVGNumberList: C,
  6672. SVGPathElement: C,
  6673. SVGPatternElement: C,
  6674. SVGPoint: C,
  6675. SVGPointList: C,
  6676. SVGPolygonElement: C,
  6677. SVGPolylineElement: C,
  6678. SVGPreserveAspectRatio: C,
  6679. SVGRadialGradientElement: C,
  6680. SVGRect: C,
  6681. SVGRectElement: C,
  6682. SVGScriptElement: C,
  6683. SVGSetElement: C,
  6684. SVGStopElement: C,
  6685. SVGStringList: C,
  6686. SVGStyleElement: C,
  6687. SVGSVGElement: C,
  6688. SVGSwitchElement: C,
  6689. SVGSymbolElement: C,
  6690. SVGTextContentElement: C,
  6691. SVGTextElement: C,
  6692. SVGTextPathElement: C,
  6693. SVGTextPositioningElement: C,
  6694. SVGTitleElement: C,
  6695. SVGTransform: C,
  6696. SVGTransformList: C,
  6697. SVGTSpanElement: C,
  6698. SVGUnitTypes: C,
  6699. SVGUseElement: C,
  6700. SVGViewElement: C,
  6701. TaskAttributionTiming: C,
  6702. Text: C,
  6703. TextEvent: C,
  6704. TextMetrics: C,
  6705. TextTrack: C,
  6706. TextTrackCue: C,
  6707. TextTrackCueList: C,
  6708. TextTrackList: C,
  6709. TimeRanges: C,
  6710. toolbar: O,
  6711. top: O,
  6712. Touch: C,
  6713. TouchEvent: C,
  6714. TouchList: C,
  6715. TrackEvent: C,
  6716. TransitionEvent: C,
  6717. TreeWalker: C,
  6718. UIEvent: C,
  6719. ValidityState: C,
  6720. visualViewport: O,
  6721. VisualViewport: C,
  6722. VTTCue: C,
  6723. WaveShaperNode: C,
  6724. WebAssembly: O,
  6725. WebGL2RenderingContext: C,
  6726. WebGLActiveInfo: C,
  6727. WebGLBuffer: C,
  6728. WebGLContextEvent: C,
  6729. WebGLFramebuffer: C,
  6730. WebGLProgram: C,
  6731. WebGLQuery: C,
  6732. WebGLRenderbuffer: C,
  6733. WebGLRenderingContext: C,
  6734. WebGLSampler: C,
  6735. WebGLShader: C,
  6736. WebGLShaderPrecisionFormat: C,
  6737. WebGLSync: C,
  6738. WebGLTexture: C,
  6739. WebGLTransformFeedback: C,
  6740. WebGLUniformLocation: C,
  6741. WebGLVertexArrayObject: C,
  6742. WebSocket: C,
  6743. WheelEvent: C,
  6744. Window: C,
  6745. Worker: C,
  6746. WritableStream: C,
  6747. XMLDocument: C,
  6748. XMLHttpRequest: C,
  6749. XMLHttpRequestEventTarget: C,
  6750. XMLHttpRequestUpload: C,
  6751. XMLSerializer: C,
  6752. XPathEvaluator: C,
  6753. XPathExpression: C,
  6754. XPathResult: C,
  6755. XSLTProcessor: C
  6756. };
  6757. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6758. knownGlobals[global] = knownGlobals;
  6759. }
  6760. function getGlobalAtPath(path) {
  6761. let currentGlobal = knownGlobals;
  6762. for (const pathSegment of path) {
  6763. if (typeof pathSegment !== 'string') {
  6764. return null;
  6765. }
  6766. currentGlobal = currentGlobal[pathSegment];
  6767. if (!currentGlobal) {
  6768. return null;
  6769. }
  6770. }
  6771. return currentGlobal[ValueProperties];
  6772. }
  6773. class GlobalVariable extends Variable {
  6774. constructor() {
  6775. super(...arguments);
  6776. // Ensure we use live-bindings for globals as we do not know if they have
  6777. // been reassigned
  6778. this.isReassigned = true;
  6779. }
  6780. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6781. return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
  6782. }
  6783. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6784. switch (interaction.type) {
  6785. case INTERACTION_ACCESSED:
  6786. if (path.length === 0) {
  6787. // Technically, "undefined" is a global variable of sorts
  6788. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6789. }
  6790. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6791. case INTERACTION_ASSIGNED:
  6792. return true;
  6793. case INTERACTION_CALLED: {
  6794. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6795. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6796. }
  6797. }
  6798. }
  6799. }
  6800. const tdzVariableKinds = {
  6801. __proto__: null,
  6802. class: true,
  6803. const: true,
  6804. let: true,
  6805. var: true
  6806. };
  6807. class Identifier extends NodeBase {
  6808. constructor() {
  6809. super(...arguments);
  6810. this.variable = null;
  6811. this.isTDZAccess = null;
  6812. }
  6813. addExportedVariables(variables, exportNamesByVariable) {
  6814. if (exportNamesByVariable.has(this.variable)) {
  6815. variables.push(this.variable);
  6816. }
  6817. }
  6818. bind() {
  6819. if (!this.variable && is_reference(this, this.parent)) {
  6820. this.variable = this.scope.findVariable(this.name);
  6821. this.variable.addReference(this);
  6822. }
  6823. }
  6824. declare(kind, init) {
  6825. let variable;
  6826. const { treeshake } = this.context.options;
  6827. switch (kind) {
  6828. case 'var':
  6829. variable = this.scope.addDeclaration(this, this.context, init, true);
  6830. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6831. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6832. variable.markInitializersForDeoptimization();
  6833. }
  6834. break;
  6835. case 'function':
  6836. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6837. variable = this.scope.addDeclaration(this, this.context, init, false);
  6838. break;
  6839. case 'let':
  6840. case 'const':
  6841. case 'class':
  6842. variable = this.scope.addDeclaration(this, this.context, init, false);
  6843. break;
  6844. case 'parameter':
  6845. variable = this.scope.addParameterDeclaration(this);
  6846. break;
  6847. /* istanbul ignore next */
  6848. default:
  6849. /* istanbul ignore next */
  6850. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6851. }
  6852. variable.kind = kind;
  6853. return [(this.variable = variable)];
  6854. }
  6855. deoptimizePath(path) {
  6856. var _a;
  6857. if (path.length === 0 && !this.scope.contains(this.name)) {
  6858. this.disallowImportReassignment();
  6859. }
  6860. // We keep conditional chaining because an unknown Node could have an
  6861. // Identifier as property that might be deoptimized by default
  6862. (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  6863. }
  6864. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6865. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6866. }
  6867. getLiteralValueAtPath(path, recursionTracker, origin) {
  6868. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6869. }
  6870. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6871. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6872. }
  6873. hasEffects(context) {
  6874. if (!this.deoptimized)
  6875. this.applyDeoptimizations();
  6876. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6877. return true;
  6878. }
  6879. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  6880. this.variable instanceof GlobalVariable &&
  6881. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6882. }
  6883. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6884. switch (interaction.type) {
  6885. case INTERACTION_ACCESSED:
  6886. return (this.variable !== null &&
  6887. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6888. case INTERACTION_ASSIGNED:
  6889. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6890. case INTERACTION_CALLED:
  6891. return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
  6892. }
  6893. }
  6894. include() {
  6895. if (!this.deoptimized)
  6896. this.applyDeoptimizations();
  6897. if (!this.included) {
  6898. this.included = true;
  6899. if (this.variable !== null) {
  6900. this.context.includeVariableInModule(this.variable);
  6901. }
  6902. }
  6903. }
  6904. includeCallArguments(context, args) {
  6905. this.variable.includeCallArguments(context, args);
  6906. }
  6907. isPossibleTDZ() {
  6908. // return cached value to avoid issues with the next tree-shaking pass
  6909. if (this.isTDZAccess !== null)
  6910. return this.isTDZAccess;
  6911. if (!(this.variable instanceof LocalVariable) ||
  6912. !this.variable.kind ||
  6913. !(this.variable.kind in tdzVariableKinds)) {
  6914. return (this.isTDZAccess = false);
  6915. }
  6916. let decl_id;
  6917. if (this.variable.declarations &&
  6918. this.variable.declarations.length === 1 &&
  6919. (decl_id = this.variable.declarations[0]) &&
  6920. this.start < decl_id.start &&
  6921. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6922. // a variable accessed before its declaration
  6923. // in the same function or at top level of module
  6924. return (this.isTDZAccess = true);
  6925. }
  6926. if (!this.variable.initReached) {
  6927. // Either a const/let TDZ violation or
  6928. // var use before declaration was encountered.
  6929. return (this.isTDZAccess = true);
  6930. }
  6931. return (this.isTDZAccess = false);
  6932. }
  6933. markDeclarationReached() {
  6934. this.variable.initReached = true;
  6935. }
  6936. render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6937. if (this.variable) {
  6938. const name = this.variable.getName(getPropertyAccess);
  6939. if (name !== this.name) {
  6940. code.overwrite(this.start, this.end, name, {
  6941. contentOnly: true,
  6942. storeName: true
  6943. });
  6944. if (isShorthandProperty) {
  6945. code.prependRight(this.start, `${this.name}: `);
  6946. }
  6947. }
  6948. // In strict mode, any variable named "eval" must be the actual "eval" function
  6949. if (name === 'eval' &&
  6950. renderedParentType === CallExpression$1 &&
  6951. isCalleeOfRenderedParent) {
  6952. code.appendRight(this.start, '0, ');
  6953. }
  6954. }
  6955. }
  6956. applyDeoptimizations() {
  6957. this.deoptimized = true;
  6958. if (this.variable instanceof LocalVariable) {
  6959. this.variable.consolidateInitializers();
  6960. this.context.requestTreeshakingPass();
  6961. }
  6962. }
  6963. disallowImportReassignment() {
  6964. return this.context.error({
  6965. code: 'ILLEGAL_REASSIGNMENT',
  6966. message: `Illegal reassignment to import '${this.name}'`
  6967. }, this.start);
  6968. }
  6969. getVariableRespectingTDZ() {
  6970. if (this.isPossibleTDZ()) {
  6971. return UNKNOWN_EXPRESSION;
  6972. }
  6973. return this.variable;
  6974. }
  6975. }
  6976. function closestParentFunctionOrProgram(node) {
  6977. while (node && !/^Program|Function/.test(node.type)) {
  6978. node = node.parent;
  6979. }
  6980. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6981. return node;
  6982. }
  6983. function treeshakeNode(node, code, start, end) {
  6984. code.remove(start, end);
  6985. if (node.annotations) {
  6986. for (const annotation of node.annotations) {
  6987. if (annotation.start < start) {
  6988. code.remove(annotation.start, annotation.end);
  6989. }
  6990. else {
  6991. return;
  6992. }
  6993. }
  6994. }
  6995. }
  6996. function removeAnnotations(node, code) {
  6997. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  6998. node = node.parent;
  6999. }
  7000. if (node.annotations) {
  7001. for (const annotation of node.annotations) {
  7002. code.remove(annotation.start, annotation.end);
  7003. }
  7004. }
  7005. }
  7006. const NO_SEMICOLON = { isNoStatement: true };
  7007. // This assumes there are only white-space and comments between start and the string we are looking for
  7008. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  7009. let searchPos, charCodeAfterSlash;
  7010. searchPos = code.indexOf(searchString, start);
  7011. while (true) {
  7012. start = code.indexOf('/', start);
  7013. if (start === -1 || start >= searchPos)
  7014. return searchPos;
  7015. charCodeAfterSlash = code.charCodeAt(++start);
  7016. ++start;
  7017. // With our assumption, '/' always starts a comment. Determine comment type:
  7018. start =
  7019. charCodeAfterSlash === 47 /*"/"*/
  7020. ? code.indexOf('\n', start) + 1
  7021. : code.indexOf('*/', start) + 2;
  7022. if (start > searchPos) {
  7023. searchPos = code.indexOf(searchString, start);
  7024. }
  7025. }
  7026. }
  7027. const NON_WHITESPACE = /\S/g;
  7028. function findNonWhiteSpace(code, index) {
  7029. NON_WHITESPACE.lastIndex = index;
  7030. const result = NON_WHITESPACE.exec(code);
  7031. return result.index;
  7032. }
  7033. // This assumes "code" only contains white-space and comments
  7034. // Returns position of line-comment if applicable
  7035. function findFirstLineBreakOutsideComment(code) {
  7036. let lineBreakPos, charCodeAfterSlash, start = 0;
  7037. lineBreakPos = code.indexOf('\n', start);
  7038. while (true) {
  7039. start = code.indexOf('/', start);
  7040. if (start === -1 || start > lineBreakPos)
  7041. return [lineBreakPos, lineBreakPos + 1];
  7042. // With our assumption, '/' always starts a comment. Determine comment type:
  7043. charCodeAfterSlash = code.charCodeAt(start + 1);
  7044. if (charCodeAfterSlash === 47 /*"/"*/)
  7045. return [start, lineBreakPos + 1];
  7046. start = code.indexOf('*/', start + 3) + 2;
  7047. if (start > lineBreakPos) {
  7048. lineBreakPos = code.indexOf('\n', start);
  7049. }
  7050. }
  7051. }
  7052. function renderStatementList(statements, code, start, end, options) {
  7053. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  7054. let nextNode = statements[0];
  7055. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  7056. if (nextNodeNeedsBoundaries) {
  7057. nextNodeStart =
  7058. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  7059. }
  7060. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  7061. currentNode = nextNode;
  7062. currentNodeStart = nextNodeStart;
  7063. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  7064. nextNode = statements[nextIndex];
  7065. nextNodeNeedsBoundaries =
  7066. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  7067. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  7068. nextNodeStart =
  7069. currentNode.end +
  7070. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  7071. if (currentNode.included) {
  7072. currentNodeNeedsBoundaries
  7073. ? currentNode.render(code, options, {
  7074. end: nextNodeStart,
  7075. start: currentNodeStart
  7076. })
  7077. : currentNode.render(code, options);
  7078. }
  7079. else {
  7080. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  7081. }
  7082. }
  7083. else {
  7084. currentNode.render(code, options);
  7085. }
  7086. }
  7087. }
  7088. // This assumes that the first character is not part of the first node
  7089. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  7090. const splitUpNodes = [];
  7091. let node, nextNode, nextNodeStart, contentEnd, char;
  7092. let separator = start - 1;
  7093. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  7094. nextNode = nodes[nextIndex];
  7095. if (node !== undefined) {
  7096. separator =
  7097. node.end +
  7098. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  7099. }
  7100. nextNodeStart = contentEnd =
  7101. separator +
  7102. 1 +
  7103. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  7104. while (((char = code.original.charCodeAt(nextNodeStart)),
  7105. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  7106. nextNodeStart++;
  7107. if (node !== undefined) {
  7108. splitUpNodes.push({
  7109. contentEnd,
  7110. end: nextNodeStart,
  7111. node,
  7112. separator,
  7113. start
  7114. });
  7115. }
  7116. node = nextNode;
  7117. start = nextNodeStart;
  7118. }
  7119. splitUpNodes.push({
  7120. contentEnd: end,
  7121. end,
  7122. node: node,
  7123. separator: null,
  7124. start
  7125. });
  7126. return splitUpNodes;
  7127. }
  7128. // This assumes there are only white-space and comments between start and end
  7129. function removeLineBreaks(code, start, end) {
  7130. while (true) {
  7131. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7132. if (removeStart === -1) {
  7133. break;
  7134. }
  7135. code.remove(start + removeStart, (start += removeEnd));
  7136. }
  7137. }
  7138. class BlockScope extends ChildScope {
  7139. addDeclaration(identifier, context, init, isHoisted) {
  7140. if (isHoisted) {
  7141. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7142. // Necessary to make sure the init is deoptimized for conditional declarations.
  7143. // We cannot call deoptimizePath here.
  7144. variable.markInitializersForDeoptimization();
  7145. return variable;
  7146. }
  7147. else {
  7148. return super.addDeclaration(identifier, context, init, false);
  7149. }
  7150. }
  7151. }
  7152. class ExpressionStatement extends NodeBase {
  7153. initialise() {
  7154. if (this.directive &&
  7155. this.directive !== 'use strict' &&
  7156. this.parent.type === Program$1) {
  7157. this.context.warn(
  7158. // This is necessary, because either way (deleting or not) can lead to errors.
  7159. {
  7160. code: 'MODULE_LEVEL_DIRECTIVE',
  7161. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  7162. }, this.start);
  7163. }
  7164. }
  7165. render(code, options) {
  7166. super.render(code, options);
  7167. if (this.included)
  7168. this.insertSemicolon(code);
  7169. }
  7170. shouldBeIncluded(context) {
  7171. if (this.directive && this.directive !== 'use strict')
  7172. return this.parent.type !== Program$1;
  7173. return super.shouldBeIncluded(context);
  7174. }
  7175. applyDeoptimizations() { }
  7176. }
  7177. class BlockStatement extends NodeBase {
  7178. constructor() {
  7179. super(...arguments);
  7180. this.directlyIncluded = false;
  7181. }
  7182. addImplicitReturnExpressionToScope() {
  7183. const lastStatement = this.body[this.body.length - 1];
  7184. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7185. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7186. }
  7187. }
  7188. createScope(parentScope) {
  7189. this.scope = this.parent.preventChildBlockScope
  7190. ? parentScope
  7191. : new BlockScope(parentScope);
  7192. }
  7193. hasEffects(context) {
  7194. if (this.deoptimizeBody)
  7195. return true;
  7196. for (const node of this.body) {
  7197. if (context.brokenFlow)
  7198. break;
  7199. if (node.hasEffects(context))
  7200. return true;
  7201. }
  7202. return false;
  7203. }
  7204. include(context, includeChildrenRecursively) {
  7205. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7206. this.included = true;
  7207. this.directlyIncluded = true;
  7208. if (this.deoptimizeBody)
  7209. includeChildrenRecursively = true;
  7210. for (const node of this.body) {
  7211. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7212. node.include(context, includeChildrenRecursively);
  7213. }
  7214. }
  7215. }
  7216. initialise() {
  7217. const firstBodyStatement = this.body[0];
  7218. this.deoptimizeBody =
  7219. firstBodyStatement instanceof ExpressionStatement &&
  7220. firstBodyStatement.directive === 'use asm';
  7221. }
  7222. render(code, options) {
  7223. if (this.body.length) {
  7224. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7225. }
  7226. else {
  7227. super.render(code, options);
  7228. }
  7229. }
  7230. }
  7231. class RestElement extends NodeBase {
  7232. constructor() {
  7233. super(...arguments);
  7234. this.declarationInit = null;
  7235. }
  7236. addExportedVariables(variables, exportNamesByVariable) {
  7237. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7238. }
  7239. declare(kind, init) {
  7240. this.declarationInit = init;
  7241. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7242. }
  7243. deoptimizePath(path) {
  7244. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7245. }
  7246. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7247. return (path.length > 0 ||
  7248. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7249. }
  7250. markDeclarationReached() {
  7251. this.argument.markDeclarationReached();
  7252. }
  7253. applyDeoptimizations() {
  7254. this.deoptimized = true;
  7255. if (this.declarationInit !== null) {
  7256. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7257. this.context.requestTreeshakingPass();
  7258. }
  7259. }
  7260. }
  7261. class FunctionBase extends NodeBase {
  7262. constructor() {
  7263. super(...arguments);
  7264. this.objectEntity = null;
  7265. this.deoptimizedReturn = false;
  7266. }
  7267. deoptimizePath(path) {
  7268. this.getObjectEntity().deoptimizePath(path);
  7269. if (path.length === 1 && path[0] === UnknownKey) {
  7270. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7271. // which means the return expression needs to be reassigned
  7272. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7273. }
  7274. }
  7275. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7276. if (path.length > 0) {
  7277. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7278. }
  7279. }
  7280. getLiteralValueAtPath(path, recursionTracker, origin) {
  7281. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7282. }
  7283. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7284. if (path.length > 0) {
  7285. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7286. }
  7287. if (this.async) {
  7288. if (!this.deoptimizedReturn) {
  7289. this.deoptimizedReturn = true;
  7290. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7291. this.context.requestTreeshakingPass();
  7292. }
  7293. return UNKNOWN_EXPRESSION;
  7294. }
  7295. return this.scope.getReturnExpression();
  7296. }
  7297. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7298. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7299. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7300. }
  7301. if (this.async) {
  7302. const { propertyReadSideEffects } = this.context.options
  7303. .treeshake;
  7304. const returnExpression = this.scope.getReturnExpression();
  7305. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7306. (propertyReadSideEffects &&
  7307. (propertyReadSideEffects === 'always' ||
  7308. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7309. return true;
  7310. }
  7311. }
  7312. for (const param of this.params) {
  7313. if (param.hasEffects(context))
  7314. return true;
  7315. }
  7316. return false;
  7317. }
  7318. include(context, includeChildrenRecursively) {
  7319. if (!this.deoptimized)
  7320. this.applyDeoptimizations();
  7321. this.included = true;
  7322. const { brokenFlow } = context;
  7323. context.brokenFlow = BROKEN_FLOW_NONE;
  7324. this.body.include(context, includeChildrenRecursively);
  7325. context.brokenFlow = brokenFlow;
  7326. }
  7327. includeCallArguments(context, args) {
  7328. this.scope.includeCallArguments(context, args);
  7329. }
  7330. initialise() {
  7331. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  7332. if (this.body instanceof BlockStatement) {
  7333. this.body.addImplicitReturnExpressionToScope();
  7334. }
  7335. else {
  7336. this.scope.addReturnExpression(this.body);
  7337. }
  7338. }
  7339. parseNode(esTreeNode) {
  7340. if (esTreeNode.body.type === BlockStatement$1) {
  7341. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  7342. }
  7343. super.parseNode(esTreeNode);
  7344. }
  7345. applyDeoptimizations() { }
  7346. }
  7347. FunctionBase.prototype.preventChildBlockScope = true;
  7348. class ArrowFunctionExpression extends FunctionBase {
  7349. constructor() {
  7350. super(...arguments);
  7351. this.objectEntity = null;
  7352. }
  7353. createScope(parentScope) {
  7354. this.scope = new ReturnValueScope(parentScope, this.context);
  7355. }
  7356. hasEffects() {
  7357. if (!this.deoptimized)
  7358. this.applyDeoptimizations();
  7359. return false;
  7360. }
  7361. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7362. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7363. return true;
  7364. if (interaction.type === INTERACTION_CALLED) {
  7365. const { ignore, brokenFlow } = context;
  7366. context.ignore = {
  7367. breaks: false,
  7368. continues: false,
  7369. labels: new Set(),
  7370. returnYield: true
  7371. };
  7372. if (this.body.hasEffects(context))
  7373. return true;
  7374. context.ignore = ignore;
  7375. context.brokenFlow = brokenFlow;
  7376. }
  7377. return false;
  7378. }
  7379. include(context, includeChildrenRecursively) {
  7380. super.include(context, includeChildrenRecursively);
  7381. for (const param of this.params) {
  7382. if (!(param instanceof Identifier)) {
  7383. param.include(context, includeChildrenRecursively);
  7384. }
  7385. }
  7386. }
  7387. getObjectEntity() {
  7388. if (this.objectEntity !== null) {
  7389. return this.objectEntity;
  7390. }
  7391. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7392. }
  7393. }
  7394. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7395. if (exportedVariables.length === 1 &&
  7396. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7397. const variable = exportedVariables[0];
  7398. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7399. }
  7400. else {
  7401. const fields = [];
  7402. for (const variable of exportedVariables) {
  7403. for (const exportName of exportNamesByVariable.get(variable)) {
  7404. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7405. }
  7406. }
  7407. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7408. }
  7409. }
  7410. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7411. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  7412. code.appendLeft(expressionEnd, ')');
  7413. }
  7414. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7415. const { _, getDirectReturnIifeLeft } = options.snippets;
  7416. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7417. code.appendLeft(expressionEnd, ')');
  7418. }
  7419. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7420. const { _, getPropertyAccess } = options.snippets;
  7421. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7422. if (needsParens) {
  7423. code.prependRight(expressionStart, '(');
  7424. code.appendLeft(expressionEnd, ')');
  7425. }
  7426. }
  7427. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7428. const { _ } = options.snippets;
  7429. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7430. if (needsParens) {
  7431. code.prependRight(expressionStart, '(');
  7432. code.appendLeft(expressionEnd, ')');
  7433. }
  7434. }
  7435. class ObjectPattern extends NodeBase {
  7436. addExportedVariables(variables, exportNamesByVariable) {
  7437. for (const property of this.properties) {
  7438. if (property.type === Property$1) {
  7439. property.value.addExportedVariables(variables, exportNamesByVariable);
  7440. }
  7441. else {
  7442. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7443. }
  7444. }
  7445. }
  7446. declare(kind, init) {
  7447. const variables = [];
  7448. for (const property of this.properties) {
  7449. variables.push(...property.declare(kind, init));
  7450. }
  7451. return variables;
  7452. }
  7453. deoptimizePath(path) {
  7454. if (path.length === 0) {
  7455. for (const property of this.properties) {
  7456. property.deoptimizePath(path);
  7457. }
  7458. }
  7459. }
  7460. hasEffectsOnInteractionAtPath(
  7461. // At the moment, this is only triggered for assignment left-hand sides,
  7462. // where the path is empty
  7463. _path, interaction, context) {
  7464. for (const property of this.properties) {
  7465. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7466. return true;
  7467. }
  7468. return false;
  7469. }
  7470. markDeclarationReached() {
  7471. for (const property of this.properties) {
  7472. property.markDeclarationReached();
  7473. }
  7474. }
  7475. }
  7476. class AssignmentExpression extends NodeBase {
  7477. hasEffects(context) {
  7478. const { deoptimized, left, right } = this;
  7479. if (!deoptimized)
  7480. this.applyDeoptimizations();
  7481. // MemberExpressions do not access the property before assignments if the
  7482. // operator is '='.
  7483. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
  7484. }
  7485. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7486. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7487. }
  7488. include(context, includeChildrenRecursively) {
  7489. const { deoptimized, left, right, operator } = this;
  7490. if (!deoptimized)
  7491. this.applyDeoptimizations();
  7492. this.included = true;
  7493. if (includeChildrenRecursively ||
  7494. operator !== '=' ||
  7495. left.included ||
  7496. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7497. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7498. }
  7499. right.include(context, includeChildrenRecursively);
  7500. }
  7501. initialise() {
  7502. this.left.setAssignedValue(this.right);
  7503. }
  7504. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7505. const { left, right, start, end, parent } = this;
  7506. if (left.included) {
  7507. left.render(code, options);
  7508. right.render(code, options);
  7509. }
  7510. else {
  7511. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7512. code.remove(start, inclusionStart);
  7513. if (preventASI) {
  7514. removeLineBreaks(code, inclusionStart, right.start);
  7515. }
  7516. right.render(code, options, {
  7517. renderedParentType: renderedParentType || parent.type,
  7518. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7519. });
  7520. }
  7521. if (options.format === 'system') {
  7522. if (left instanceof Identifier) {
  7523. const variable = left.variable;
  7524. const exportNames = options.exportNamesByVariable.get(variable);
  7525. if (exportNames) {
  7526. if (exportNames.length === 1) {
  7527. renderSystemExportExpression(variable, start, end, code, options);
  7528. }
  7529. else {
  7530. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7531. }
  7532. return;
  7533. }
  7534. }
  7535. else {
  7536. const systemPatternExports = [];
  7537. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7538. if (systemPatternExports.length > 0) {
  7539. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7540. return;
  7541. }
  7542. }
  7543. }
  7544. if (left.included &&
  7545. left instanceof ObjectPattern &&
  7546. (renderedSurroundingElement === ExpressionStatement$1 ||
  7547. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7548. code.appendRight(start, '(');
  7549. code.prependLeft(end, ')');
  7550. }
  7551. }
  7552. applyDeoptimizations() {
  7553. this.deoptimized = true;
  7554. this.left.deoptimizePath(EMPTY_PATH);
  7555. this.right.deoptimizePath(UNKNOWN_PATH);
  7556. this.context.requestTreeshakingPass();
  7557. }
  7558. }
  7559. class AssignmentPattern extends NodeBase {
  7560. addExportedVariables(variables, exportNamesByVariable) {
  7561. this.left.addExportedVariables(variables, exportNamesByVariable);
  7562. }
  7563. declare(kind, init) {
  7564. return this.left.declare(kind, init);
  7565. }
  7566. deoptimizePath(path) {
  7567. path.length === 0 && this.left.deoptimizePath(path);
  7568. }
  7569. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7570. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7571. }
  7572. markDeclarationReached() {
  7573. this.left.markDeclarationReached();
  7574. }
  7575. render(code, options, { isShorthandProperty } = BLANK) {
  7576. this.left.render(code, options, { isShorthandProperty });
  7577. this.right.render(code, options);
  7578. }
  7579. applyDeoptimizations() {
  7580. this.deoptimized = true;
  7581. this.left.deoptimizePath(EMPTY_PATH);
  7582. this.right.deoptimizePath(UNKNOWN_PATH);
  7583. this.context.requestTreeshakingPass();
  7584. }
  7585. }
  7586. class ArgumentsVariable extends LocalVariable {
  7587. constructor(context) {
  7588. super('arguments', null, UNKNOWN_EXPRESSION, context);
  7589. }
  7590. hasEffectsOnInteractionAtPath(path, { type }) {
  7591. return type !== INTERACTION_ACCESSED || path.length > 1;
  7592. }
  7593. }
  7594. class ThisVariable extends LocalVariable {
  7595. constructor(context) {
  7596. super('this', null, null, context);
  7597. this.deoptimizedPaths = [];
  7598. this.entitiesToBeDeoptimized = new Set();
  7599. this.thisDeoptimizationList = [];
  7600. this.thisDeoptimizations = new DiscriminatedPathTracker();
  7601. }
  7602. addEntityToBeDeoptimized(entity) {
  7603. for (const path of this.deoptimizedPaths) {
  7604. entity.deoptimizePath(path);
  7605. }
  7606. for (const { interaction, path } of this.thisDeoptimizationList) {
  7607. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7608. }
  7609. this.entitiesToBeDeoptimized.add(entity);
  7610. }
  7611. deoptimizePath(path) {
  7612. if (path.length === 0 ||
  7613. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7614. return;
  7615. }
  7616. this.deoptimizedPaths.push(path);
  7617. for (const entity of this.entitiesToBeDeoptimized) {
  7618. entity.deoptimizePath(path);
  7619. }
  7620. }
  7621. deoptimizeThisOnInteractionAtPath(interaction, path) {
  7622. const thisDeoptimization = {
  7623. interaction,
  7624. path
  7625. };
  7626. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  7627. for (const entity of this.entitiesToBeDeoptimized) {
  7628. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7629. }
  7630. this.thisDeoptimizationList.push(thisDeoptimization);
  7631. }
  7632. }
  7633. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7634. return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
  7635. super.hasEffectsOnInteractionAtPath(path, interaction, context));
  7636. }
  7637. getInit(context) {
  7638. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  7639. }
  7640. }
  7641. class FunctionScope extends ReturnValueScope {
  7642. constructor(parent, context) {
  7643. super(parent, context);
  7644. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7645. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7646. }
  7647. findLexicalBoundary() {
  7648. return this;
  7649. }
  7650. includeCallArguments(context, args) {
  7651. super.includeCallArguments(context, args);
  7652. if (this.argumentsVariable.included) {
  7653. for (const arg of args) {
  7654. if (!arg.included) {
  7655. arg.include(context, false);
  7656. }
  7657. }
  7658. }
  7659. }
  7660. }
  7661. class FunctionNode extends FunctionBase {
  7662. constructor() {
  7663. super(...arguments);
  7664. this.objectEntity = null;
  7665. }
  7666. createScope(parentScope) {
  7667. this.scope = new FunctionScope(parentScope, this.context);
  7668. }
  7669. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7670. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7671. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7672. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  7673. }
  7674. }
  7675. hasEffects(context) {
  7676. var _a;
  7677. if (!this.deoptimized)
  7678. this.applyDeoptimizations();
  7679. return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  7680. }
  7681. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7682. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7683. return true;
  7684. if (interaction.type === INTERACTION_CALLED) {
  7685. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7686. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
  7687. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  7688. : UNKNOWN_EXPRESSION);
  7689. const { brokenFlow, ignore } = context;
  7690. context.ignore = {
  7691. breaks: false,
  7692. continues: false,
  7693. labels: new Set(),
  7694. returnYield: true
  7695. };
  7696. if (this.body.hasEffects(context))
  7697. return true;
  7698. context.brokenFlow = brokenFlow;
  7699. if (thisInit) {
  7700. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7701. }
  7702. else {
  7703. context.replacedVariableInits.delete(this.scope.thisVariable);
  7704. }
  7705. context.ignore = ignore;
  7706. }
  7707. return false;
  7708. }
  7709. include(context, includeChildrenRecursively) {
  7710. var _a;
  7711. super.include(context, includeChildrenRecursively);
  7712. (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
  7713. const hasArguments = this.scope.argumentsVariable.included;
  7714. for (const param of this.params) {
  7715. if (!(param instanceof Identifier) || hasArguments) {
  7716. param.include(context, includeChildrenRecursively);
  7717. }
  7718. }
  7719. }
  7720. initialise() {
  7721. var _a;
  7722. super.initialise();
  7723. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
  7724. }
  7725. getObjectEntity() {
  7726. if (this.objectEntity !== null) {
  7727. return this.objectEntity;
  7728. }
  7729. return (this.objectEntity = new ObjectEntity([
  7730. {
  7731. key: 'prototype',
  7732. kind: 'init',
  7733. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7734. }
  7735. ], OBJECT_PROTOTYPE));
  7736. }
  7737. }
  7738. class AwaitExpression extends NodeBase {
  7739. hasEffects() {
  7740. if (!this.deoptimized)
  7741. this.applyDeoptimizations();
  7742. return true;
  7743. }
  7744. include(context, includeChildrenRecursively) {
  7745. if (!this.deoptimized)
  7746. this.applyDeoptimizations();
  7747. if (!this.included) {
  7748. this.included = true;
  7749. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  7750. let parent = this.parent;
  7751. do {
  7752. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7753. break checkTopLevelAwait;
  7754. } while ((parent = parent.parent));
  7755. this.context.usesTopLevelAwait = true;
  7756. }
  7757. }
  7758. this.argument.include(context, includeChildrenRecursively);
  7759. }
  7760. }
  7761. const binaryOperators = {
  7762. '!=': (left, right) => left != right,
  7763. '!==': (left, right) => left !== right,
  7764. '%': (left, right) => left % right,
  7765. '&': (left, right) => left & right,
  7766. '*': (left, right) => left * right,
  7767. // At the moment, "**" will be transpiled to Math.pow
  7768. '**': (left, right) => left ** right,
  7769. '+': (left, right) => left + right,
  7770. '-': (left, right) => left - right,
  7771. '/': (left, right) => left / right,
  7772. '<': (left, right) => left < right,
  7773. '<<': (left, right) => left << right,
  7774. '<=': (left, right) => left <= right,
  7775. '==': (left, right) => left == right,
  7776. '===': (left, right) => left === right,
  7777. '>': (left, right) => left > right,
  7778. '>=': (left, right) => left >= right,
  7779. '>>': (left, right) => left >> right,
  7780. '>>>': (left, right) => left >>> right,
  7781. '^': (left, right) => left ^ right,
  7782. '|': (left, right) => left | right
  7783. // We use the fallback for cases where we return something unknown
  7784. // in: () => UnknownValue,
  7785. // instanceof: () => UnknownValue,
  7786. };
  7787. class BinaryExpression extends NodeBase {
  7788. deoptimizeCache() { }
  7789. getLiteralValueAtPath(path, recursionTracker, origin) {
  7790. if (path.length > 0)
  7791. return UnknownValue;
  7792. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7793. if (typeof leftValue === 'symbol')
  7794. return UnknownValue;
  7795. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7796. if (typeof rightValue === 'symbol')
  7797. return UnknownValue;
  7798. const operatorFn = binaryOperators[this.operator];
  7799. if (!operatorFn)
  7800. return UnknownValue;
  7801. return operatorFn(leftValue, rightValue);
  7802. }
  7803. hasEffects(context) {
  7804. // support some implicit type coercion runtime errors
  7805. if (this.operator === '+' &&
  7806. this.parent instanceof ExpressionStatement &&
  7807. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7808. return true;
  7809. }
  7810. return super.hasEffects(context);
  7811. }
  7812. hasEffectsOnInteractionAtPath(path, { type }) {
  7813. return type !== INTERACTION_ACCESSED || path.length > 1;
  7814. }
  7815. render(code, options, { renderedSurroundingElement } = BLANK) {
  7816. this.left.render(code, options, { renderedSurroundingElement });
  7817. this.right.render(code, options);
  7818. }
  7819. }
  7820. class BreakStatement extends NodeBase {
  7821. hasEffects(context) {
  7822. if (this.label) {
  7823. if (!context.ignore.labels.has(this.label.name))
  7824. return true;
  7825. context.includedLabels.add(this.label.name);
  7826. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7827. }
  7828. else {
  7829. if (!context.ignore.breaks)
  7830. return true;
  7831. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7832. }
  7833. return false;
  7834. }
  7835. include(context) {
  7836. this.included = true;
  7837. if (this.label) {
  7838. this.label.include();
  7839. context.includedLabels.add(this.label.name);
  7840. }
  7841. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7842. }
  7843. }
  7844. function renderCallArguments(code, options, node) {
  7845. if (node.arguments.length > 0) {
  7846. if (node.arguments[node.arguments.length - 1].included) {
  7847. for (const arg of node.arguments) {
  7848. arg.render(code, options);
  7849. }
  7850. }
  7851. else {
  7852. let lastIncludedIndex = node.arguments.length - 2;
  7853. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7854. lastIncludedIndex--;
  7855. }
  7856. if (lastIncludedIndex >= 0) {
  7857. for (let index = 0; index <= lastIncludedIndex; index++) {
  7858. node.arguments[index].render(code, options);
  7859. }
  7860. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7861. }
  7862. else {
  7863. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7864. }
  7865. }
  7866. }
  7867. }
  7868. class Literal extends NodeBase {
  7869. deoptimizeThisOnInteractionAtPath() { }
  7870. getLiteralValueAtPath(path) {
  7871. if (path.length > 0 ||
  7872. // unknown literals can also be null but do not start with an "n"
  7873. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  7874. typeof this.value === 'bigint' ||
  7875. // to support shims for regular expressions
  7876. this.context.code.charCodeAt(this.start) === 47) {
  7877. return UnknownValue;
  7878. }
  7879. return this.value;
  7880. }
  7881. getReturnExpressionWhenCalledAtPath(path) {
  7882. if (path.length !== 1)
  7883. return UNKNOWN_EXPRESSION;
  7884. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7885. }
  7886. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7887. switch (interaction.type) {
  7888. case INTERACTION_ACCESSED:
  7889. return path.length > (this.value === null ? 0 : 1);
  7890. case INTERACTION_ASSIGNED:
  7891. return true;
  7892. case INTERACTION_CALLED:
  7893. return (path.length !== 1 ||
  7894. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7895. }
  7896. }
  7897. initialise() {
  7898. this.members = getLiteralMembersForValue(this.value);
  7899. }
  7900. parseNode(esTreeNode) {
  7901. this.value = esTreeNode.value;
  7902. this.regex = esTreeNode.regex;
  7903. super.parseNode(esTreeNode);
  7904. }
  7905. render(code) {
  7906. if (typeof this.value === 'string') {
  7907. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7908. }
  7909. }
  7910. }
  7911. // To avoid infinite recursions
  7912. const MAX_PATH_DEPTH = 7;
  7913. function getResolvablePropertyKey(memberExpression) {
  7914. return memberExpression.computed
  7915. ? getResolvableComputedPropertyKey(memberExpression.property)
  7916. : memberExpression.property.name;
  7917. }
  7918. function getResolvableComputedPropertyKey(propertyKey) {
  7919. if (propertyKey instanceof Literal) {
  7920. return String(propertyKey.value);
  7921. }
  7922. return null;
  7923. }
  7924. function getPathIfNotComputed(memberExpression) {
  7925. const nextPathKey = memberExpression.propertyKey;
  7926. const object = memberExpression.object;
  7927. if (typeof nextPathKey === 'string') {
  7928. if (object instanceof Identifier) {
  7929. return [
  7930. { key: object.name, pos: object.start },
  7931. { key: nextPathKey, pos: memberExpression.property.start }
  7932. ];
  7933. }
  7934. if (object instanceof MemberExpression) {
  7935. const parentPath = getPathIfNotComputed(object);
  7936. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7937. }
  7938. }
  7939. return null;
  7940. }
  7941. function getStringFromPath(path) {
  7942. let pathString = path[0].key;
  7943. for (let index = 1; index < path.length; index++) {
  7944. pathString += '.' + path[index].key;
  7945. }
  7946. return pathString;
  7947. }
  7948. class MemberExpression extends NodeBase {
  7949. constructor() {
  7950. super(...arguments);
  7951. this.variable = null;
  7952. this.assignmentDeoptimized = false;
  7953. this.bound = false;
  7954. this.expressionsToBeDeoptimized = [];
  7955. this.replacement = null;
  7956. }
  7957. bind() {
  7958. this.bound = true;
  7959. const path = getPathIfNotComputed(this);
  7960. const baseVariable = path && this.scope.findVariable(path[0].key);
  7961. if (baseVariable && baseVariable.isNamespace) {
  7962. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  7963. if (!resolvedVariable) {
  7964. super.bind();
  7965. }
  7966. else if (typeof resolvedVariable === 'string') {
  7967. this.replacement = resolvedVariable;
  7968. }
  7969. else {
  7970. this.variable = resolvedVariable;
  7971. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7972. }
  7973. }
  7974. else {
  7975. super.bind();
  7976. }
  7977. }
  7978. deoptimizeCache() {
  7979. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7980. this.expressionsToBeDeoptimized = [];
  7981. this.propertyKey = UnknownKey;
  7982. this.object.deoptimizePath(UNKNOWN_PATH);
  7983. for (const expression of expressionsToBeDeoptimized) {
  7984. expression.deoptimizeCache();
  7985. }
  7986. }
  7987. deoptimizePath(path) {
  7988. if (path.length === 0)
  7989. this.disallowNamespaceReassignment();
  7990. if (this.variable) {
  7991. this.variable.deoptimizePath(path);
  7992. }
  7993. else if (!this.replacement) {
  7994. if (path.length < MAX_PATH_DEPTH) {
  7995. const propertyKey = this.getPropertyKey();
  7996. this.object.deoptimizePath([
  7997. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7998. ...path
  7999. ]);
  8000. }
  8001. }
  8002. }
  8003. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8004. if (this.variable) {
  8005. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8006. }
  8007. else if (!this.replacement) {
  8008. if (path.length < MAX_PATH_DEPTH) {
  8009. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  8010. }
  8011. else {
  8012. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8013. }
  8014. }
  8015. }
  8016. getLiteralValueAtPath(path, recursionTracker, origin) {
  8017. if (this.variable) {
  8018. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8019. }
  8020. if (this.replacement) {
  8021. return UnknownValue;
  8022. }
  8023. this.expressionsToBeDeoptimized.push(origin);
  8024. if (path.length < MAX_PATH_DEPTH) {
  8025. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  8026. }
  8027. return UnknownValue;
  8028. }
  8029. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8030. if (this.variable) {
  8031. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8032. }
  8033. if (this.replacement) {
  8034. return UNKNOWN_EXPRESSION;
  8035. }
  8036. this.expressionsToBeDeoptimized.push(origin);
  8037. if (path.length < MAX_PATH_DEPTH) {
  8038. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  8039. }
  8040. return UNKNOWN_EXPRESSION;
  8041. }
  8042. hasEffects(context) {
  8043. if (!this.deoptimized)
  8044. this.applyDeoptimizations();
  8045. return (this.property.hasEffects(context) ||
  8046. this.object.hasEffects(context) ||
  8047. this.hasAccessEffect(context));
  8048. }
  8049. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8050. if (checkAccess && !this.deoptimized)
  8051. this.applyDeoptimizations();
  8052. if (!this.assignmentDeoptimized)
  8053. this.applyAssignmentDeoptimization();
  8054. return (this.property.hasEffects(context) ||
  8055. this.object.hasEffects(context) ||
  8056. (checkAccess && this.hasAccessEffect(context)) ||
  8057. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8058. }
  8059. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8060. if (this.variable) {
  8061. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8062. }
  8063. if (this.replacement) {
  8064. return true;
  8065. }
  8066. if (path.length < MAX_PATH_DEPTH) {
  8067. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  8068. }
  8069. return true;
  8070. }
  8071. include(context, includeChildrenRecursively) {
  8072. if (!this.deoptimized)
  8073. this.applyDeoptimizations();
  8074. this.includeProperties(context, includeChildrenRecursively);
  8075. }
  8076. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8077. if (!this.assignmentDeoptimized)
  8078. this.applyAssignmentDeoptimization();
  8079. if (deoptimizeAccess) {
  8080. this.include(context, includeChildrenRecursively);
  8081. }
  8082. else {
  8083. this.includeProperties(context, includeChildrenRecursively);
  8084. }
  8085. }
  8086. includeCallArguments(context, args) {
  8087. if (this.variable) {
  8088. this.variable.includeCallArguments(context, args);
  8089. }
  8090. else {
  8091. super.includeCallArguments(context, args);
  8092. }
  8093. }
  8094. initialise() {
  8095. this.propertyKey = getResolvablePropertyKey(this);
  8096. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  8097. }
  8098. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  8099. if (this.variable || this.replacement) {
  8100. const { snippets: { getPropertyAccess } } = options;
  8101. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
  8102. if (renderedParentType && isCalleeOfRenderedParent)
  8103. replacement = '0, ' + replacement;
  8104. code.overwrite(this.start, this.end, replacement, {
  8105. contentOnly: true,
  8106. storeName: true
  8107. });
  8108. }
  8109. else {
  8110. if (renderedParentType && isCalleeOfRenderedParent) {
  8111. code.appendRight(this.start, '0, ');
  8112. }
  8113. this.object.render(code, options, { renderedSurroundingElement });
  8114. this.property.render(code, options);
  8115. }
  8116. }
  8117. setAssignedValue(value) {
  8118. this.assignmentInteraction = {
  8119. args: [value],
  8120. thisArg: this.object,
  8121. type: INTERACTION_ASSIGNED
  8122. };
  8123. }
  8124. applyDeoptimizations() {
  8125. this.deoptimized = true;
  8126. const { propertyReadSideEffects } = this.context.options
  8127. .treeshake;
  8128. if (
  8129. // Namespaces are not bound and should not be deoptimized
  8130. this.bound &&
  8131. propertyReadSideEffects &&
  8132. !(this.variable || this.replacement)) {
  8133. const propertyKey = this.getPropertyKey();
  8134. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8135. this.context.requestTreeshakingPass();
  8136. }
  8137. }
  8138. applyAssignmentDeoptimization() {
  8139. this.assignmentDeoptimized = true;
  8140. const { propertyReadSideEffects } = this.context.options
  8141. .treeshake;
  8142. if (
  8143. // Namespaces are not bound and should not be deoptimized
  8144. this.bound &&
  8145. propertyReadSideEffects &&
  8146. !(this.variable || this.replacement)) {
  8147. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8148. this.context.requestTreeshakingPass();
  8149. }
  8150. }
  8151. disallowNamespaceReassignment() {
  8152. if (this.object instanceof Identifier) {
  8153. const variable = this.scope.findVariable(this.object.name);
  8154. if (variable.isNamespace) {
  8155. if (this.variable) {
  8156. this.context.includeVariableInModule(this.variable);
  8157. }
  8158. this.context.warn({
  8159. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  8160. message: `Illegal reassignment to import '${this.object.name}'`
  8161. }, this.start);
  8162. }
  8163. }
  8164. }
  8165. getPropertyKey() {
  8166. if (this.propertyKey === null) {
  8167. this.propertyKey = UnknownKey;
  8168. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8169. return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
  8170. }
  8171. return this.propertyKey;
  8172. }
  8173. hasAccessEffect(context) {
  8174. const { propertyReadSideEffects } = this.context.options
  8175. .treeshake;
  8176. return (!(this.variable || this.replacement) &&
  8177. propertyReadSideEffects &&
  8178. (propertyReadSideEffects === 'always' ||
  8179. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8180. }
  8181. includeProperties(context, includeChildrenRecursively) {
  8182. if (!this.included) {
  8183. this.included = true;
  8184. if (this.variable) {
  8185. this.context.includeVariableInModule(this.variable);
  8186. }
  8187. }
  8188. this.object.include(context, includeChildrenRecursively);
  8189. this.property.include(context, includeChildrenRecursively);
  8190. }
  8191. }
  8192. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8193. if (path.length === 0)
  8194. return baseVariable;
  8195. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8196. return null;
  8197. const exportName = path[0].key;
  8198. const variable = baseVariable.context.traceExport(exportName);
  8199. if (!variable) {
  8200. const fileName = baseVariable.context.fileName;
  8201. astContext.warn({
  8202. code: 'MISSING_EXPORT',
  8203. exporter: relativeId(fileName),
  8204. importer: relativeId(astContext.fileName),
  8205. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  8206. missing: exportName,
  8207. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  8208. }, path[0].pos);
  8209. return 'undefined';
  8210. }
  8211. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8212. }
  8213. class CallExpressionBase extends NodeBase {
  8214. constructor() {
  8215. super(...arguments);
  8216. this.returnExpression = null;
  8217. this.deoptimizableDependentExpressions = [];
  8218. this.expressionsToBeDeoptimized = new Set();
  8219. }
  8220. deoptimizeCache() {
  8221. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  8222. this.returnExpression = UNKNOWN_EXPRESSION;
  8223. for (const expression of this.deoptimizableDependentExpressions) {
  8224. expression.deoptimizeCache();
  8225. }
  8226. for (const expression of this.expressionsToBeDeoptimized) {
  8227. expression.deoptimizePath(UNKNOWN_PATH);
  8228. }
  8229. }
  8230. }
  8231. deoptimizePath(path) {
  8232. if (path.length === 0 ||
  8233. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8234. return;
  8235. }
  8236. const returnExpression = this.getReturnExpression();
  8237. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8238. returnExpression.deoptimizePath(path);
  8239. }
  8240. }
  8241. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8242. const returnExpression = this.getReturnExpression(recursionTracker);
  8243. if (returnExpression === UNKNOWN_EXPRESSION) {
  8244. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8245. }
  8246. else {
  8247. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8248. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  8249. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8250. }, undefined);
  8251. }
  8252. }
  8253. getLiteralValueAtPath(path, recursionTracker, origin) {
  8254. const returnExpression = this.getReturnExpression(recursionTracker);
  8255. if (returnExpression === UNKNOWN_EXPRESSION) {
  8256. return UnknownValue;
  8257. }
  8258. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8259. this.deoptimizableDependentExpressions.push(origin);
  8260. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8261. }, UnknownValue);
  8262. }
  8263. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8264. const returnExpression = this.getReturnExpression(recursionTracker);
  8265. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  8266. return UNKNOWN_EXPRESSION;
  8267. }
  8268. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8269. this.deoptimizableDependentExpressions.push(origin);
  8270. return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8271. }, UNKNOWN_EXPRESSION);
  8272. }
  8273. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8274. const { type } = interaction;
  8275. if (type === INTERACTION_CALLED) {
  8276. if ((interaction.withNew
  8277. ? context.instantiated
  8278. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
  8279. return false;
  8280. }
  8281. }
  8282. else if ((type === INTERACTION_ASSIGNED
  8283. ? context.assigned
  8284. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8285. return false;
  8286. }
  8287. return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
  8288. }
  8289. }
  8290. class CallExpression extends CallExpressionBase {
  8291. bind() {
  8292. super.bind();
  8293. if (this.callee instanceof Identifier) {
  8294. const variable = this.scope.findVariable(this.callee.name);
  8295. if (variable.isNamespace) {
  8296. this.context.warn({
  8297. code: 'CANNOT_CALL_NAMESPACE',
  8298. message: `Cannot call a namespace ('${this.callee.name}')`
  8299. }, this.start);
  8300. }
  8301. if (this.callee.name === 'eval') {
  8302. this.context.warn({
  8303. code: 'EVAL',
  8304. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8305. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8306. }, this.start);
  8307. }
  8308. }
  8309. this.interaction = {
  8310. args: this.arguments,
  8311. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  8312. ? this.callee.object
  8313. : null,
  8314. type: INTERACTION_CALLED,
  8315. withNew: false
  8316. };
  8317. }
  8318. hasEffects(context) {
  8319. try {
  8320. for (const argument of this.arguments) {
  8321. if (argument.hasEffects(context))
  8322. return true;
  8323. }
  8324. if (this.context.options.treeshake.annotations &&
  8325. this.annotations)
  8326. return false;
  8327. return (this.callee.hasEffects(context) ||
  8328. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8329. }
  8330. finally {
  8331. if (!this.deoptimized)
  8332. this.applyDeoptimizations();
  8333. }
  8334. }
  8335. include(context, includeChildrenRecursively) {
  8336. if (!this.deoptimized)
  8337. this.applyDeoptimizations();
  8338. if (includeChildrenRecursively) {
  8339. super.include(context, includeChildrenRecursively);
  8340. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8341. this.callee instanceof Identifier &&
  8342. this.callee.variable) {
  8343. this.callee.variable.markCalledFromTryStatement();
  8344. }
  8345. }
  8346. else {
  8347. this.included = true;
  8348. this.callee.include(context, false);
  8349. }
  8350. this.callee.includeCallArguments(context, this.arguments);
  8351. }
  8352. render(code, options, { renderedSurroundingElement } = BLANK) {
  8353. this.callee.render(code, options, {
  8354. isCalleeOfRenderedParent: true,
  8355. renderedSurroundingElement
  8356. });
  8357. renderCallArguments(code, options, this);
  8358. }
  8359. applyDeoptimizations() {
  8360. this.deoptimized = true;
  8361. if (this.interaction.thisArg) {
  8362. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8363. }
  8364. for (const argument of this.arguments) {
  8365. // This will make sure all properties of parameters behave as "unknown"
  8366. argument.deoptimizePath(UNKNOWN_PATH);
  8367. }
  8368. this.context.requestTreeshakingPass();
  8369. }
  8370. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8371. if (this.returnExpression === null) {
  8372. this.returnExpression = UNKNOWN_EXPRESSION;
  8373. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8374. }
  8375. return this.returnExpression;
  8376. }
  8377. }
  8378. class CatchScope extends ParameterScope {
  8379. addDeclaration(identifier, context, init, isHoisted) {
  8380. const existingParameter = this.variables.get(identifier.name);
  8381. if (existingParameter) {
  8382. // While we still create a hoisted declaration, the initializer goes to
  8383. // the parameter. Note that technically, the declaration now belongs to
  8384. // two variables, which is not correct but should not cause issues.
  8385. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  8386. existingParameter.addDeclaration(identifier, init);
  8387. return existingParameter;
  8388. }
  8389. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  8390. }
  8391. }
  8392. class CatchClause extends NodeBase {
  8393. createScope(parentScope) {
  8394. this.scope = new CatchScope(parentScope, this.context);
  8395. }
  8396. parseNode(esTreeNode) {
  8397. // Parameters need to be declared first as the logic is that initializers
  8398. // of hoisted body variables are associated with parameters of the same
  8399. // name instead of the variable
  8400. const { param } = esTreeNode;
  8401. if (param) {
  8402. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  8403. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8404. }
  8405. super.parseNode(esTreeNode);
  8406. }
  8407. }
  8408. class ChainExpression extends NodeBase {
  8409. }
  8410. class ClassBodyScope extends ChildScope {
  8411. constructor(parent, classNode, context) {
  8412. super(parent);
  8413. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  8414. this.instanceScope = new ChildScope(this);
  8415. this.instanceScope.variables.set('this', new ThisVariable(context));
  8416. }
  8417. findLexicalBoundary() {
  8418. return this;
  8419. }
  8420. }
  8421. class ClassBody extends NodeBase {
  8422. createScope(parentScope) {
  8423. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  8424. }
  8425. include(context, includeChildrenRecursively) {
  8426. this.included = true;
  8427. this.context.includeVariableInModule(this.scope.thisVariable);
  8428. for (const definition of this.body) {
  8429. definition.include(context, includeChildrenRecursively);
  8430. }
  8431. }
  8432. parseNode(esTreeNode) {
  8433. const body = (this.body = []);
  8434. for (const definition of esTreeNode.body) {
  8435. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  8436. }
  8437. super.parseNode(esTreeNode);
  8438. }
  8439. applyDeoptimizations() { }
  8440. }
  8441. class MethodBase extends NodeBase {
  8442. constructor() {
  8443. super(...arguments);
  8444. this.accessedValue = null;
  8445. }
  8446. // As getter properties directly receive their values from fixed function
  8447. // expressions, there is no known situation where a getter is deoptimized.
  8448. deoptimizeCache() { }
  8449. deoptimizePath(path) {
  8450. this.getAccessedValue().deoptimizePath(path);
  8451. }
  8452. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8453. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8454. return this.value.deoptimizeThisOnInteractionAtPath({
  8455. args: NO_ARGS,
  8456. thisArg: interaction.thisArg,
  8457. type: INTERACTION_CALLED,
  8458. withNew: false
  8459. }, EMPTY_PATH, recursionTracker);
  8460. }
  8461. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8462. return this.value.deoptimizeThisOnInteractionAtPath({
  8463. args: interaction.args,
  8464. thisArg: interaction.thisArg,
  8465. type: INTERACTION_CALLED,
  8466. withNew: false
  8467. }, EMPTY_PATH, recursionTracker);
  8468. }
  8469. this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8470. }
  8471. getLiteralValueAtPath(path, recursionTracker, origin) {
  8472. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  8473. }
  8474. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8475. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8476. }
  8477. hasEffects(context) {
  8478. return this.key.hasEffects(context);
  8479. }
  8480. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8481. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8482. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8483. args: NO_ARGS,
  8484. thisArg: interaction.thisArg,
  8485. type: INTERACTION_CALLED,
  8486. withNew: false
  8487. }, context);
  8488. }
  8489. // setters are only called for empty paths
  8490. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8491. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8492. args: interaction.args,
  8493. thisArg: interaction.thisArg,
  8494. type: INTERACTION_CALLED,
  8495. withNew: false
  8496. }, context);
  8497. }
  8498. return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
  8499. }
  8500. applyDeoptimizations() { }
  8501. getAccessedValue() {
  8502. if (this.accessedValue === null) {
  8503. if (this.kind === 'get') {
  8504. this.accessedValue = UNKNOWN_EXPRESSION;
  8505. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8506. }
  8507. else {
  8508. return (this.accessedValue = this.value);
  8509. }
  8510. }
  8511. return this.accessedValue;
  8512. }
  8513. }
  8514. class MethodDefinition extends MethodBase {
  8515. applyDeoptimizations() { }
  8516. }
  8517. class ObjectMember extends ExpressionEntity {
  8518. constructor(object, key) {
  8519. super();
  8520. this.object = object;
  8521. this.key = key;
  8522. }
  8523. deoptimizePath(path) {
  8524. this.object.deoptimizePath([this.key, ...path]);
  8525. }
  8526. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8527. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8528. }
  8529. getLiteralValueAtPath(path, recursionTracker, origin) {
  8530. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8531. }
  8532. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8533. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8534. }
  8535. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8536. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8537. }
  8538. }
  8539. class ClassNode extends NodeBase {
  8540. constructor() {
  8541. super(...arguments);
  8542. this.objectEntity = null;
  8543. }
  8544. createScope(parentScope) {
  8545. this.scope = new ChildScope(parentScope);
  8546. }
  8547. deoptimizeCache() {
  8548. this.getObjectEntity().deoptimizeAllProperties();
  8549. }
  8550. deoptimizePath(path) {
  8551. this.getObjectEntity().deoptimizePath(path);
  8552. }
  8553. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8554. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8555. }
  8556. getLiteralValueAtPath(path, recursionTracker, origin) {
  8557. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8558. }
  8559. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8560. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8561. }
  8562. hasEffects(context) {
  8563. var _a, _b;
  8564. if (!this.deoptimized)
  8565. this.applyDeoptimizations();
  8566. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  8567. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  8568. return initEffect || super.hasEffects(context);
  8569. }
  8570. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8571. var _a;
  8572. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8573. return (!interaction.withNew ||
  8574. (this.classConstructor !== null
  8575. ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
  8576. : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8577. false);
  8578. }
  8579. else {
  8580. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8581. }
  8582. }
  8583. include(context, includeChildrenRecursively) {
  8584. var _a;
  8585. if (!this.deoptimized)
  8586. this.applyDeoptimizations();
  8587. this.included = true;
  8588. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  8589. this.body.include(context, includeChildrenRecursively);
  8590. if (this.id) {
  8591. this.id.markDeclarationReached();
  8592. this.id.include();
  8593. }
  8594. }
  8595. initialise() {
  8596. var _a;
  8597. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  8598. for (const method of this.body.body) {
  8599. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8600. this.classConstructor = method;
  8601. return;
  8602. }
  8603. }
  8604. this.classConstructor = null;
  8605. }
  8606. applyDeoptimizations() {
  8607. this.deoptimized = true;
  8608. for (const definition of this.body.body) {
  8609. if (!(definition.static ||
  8610. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8611. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8612. definition.deoptimizePath(UNKNOWN_PATH);
  8613. }
  8614. }
  8615. this.context.requestTreeshakingPass();
  8616. }
  8617. getObjectEntity() {
  8618. if (this.objectEntity !== null) {
  8619. return this.objectEntity;
  8620. }
  8621. const staticProperties = [];
  8622. const dynamicMethods = [];
  8623. for (const definition of this.body.body) {
  8624. const properties = definition.static ? staticProperties : dynamicMethods;
  8625. const definitionKind = definition.kind;
  8626. // Note that class fields do not end up on the prototype
  8627. if (properties === dynamicMethods && !definitionKind)
  8628. continue;
  8629. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8630. let key;
  8631. if (definition.computed) {
  8632. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8633. if (typeof keyValue === 'symbol') {
  8634. properties.push({ key: UnknownKey, kind, property: definition });
  8635. continue;
  8636. }
  8637. else {
  8638. key = String(keyValue);
  8639. }
  8640. }
  8641. else {
  8642. key =
  8643. definition.key instanceof Identifier
  8644. ? definition.key.name
  8645. : String(definition.key.value);
  8646. }
  8647. properties.push({ key, kind, property: definition });
  8648. }
  8649. staticProperties.unshift({
  8650. key: 'prototype',
  8651. kind: 'init',
  8652. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8653. });
  8654. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8655. }
  8656. }
  8657. class ClassDeclaration extends ClassNode {
  8658. initialise() {
  8659. super.initialise();
  8660. if (this.id !== null) {
  8661. this.id.variable.isId = true;
  8662. }
  8663. }
  8664. parseNode(esTreeNode) {
  8665. if (esTreeNode.id !== null) {
  8666. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8667. }
  8668. super.parseNode(esTreeNode);
  8669. }
  8670. render(code, options) {
  8671. const { exportNamesByVariable, format, snippets: { _ } } = options;
  8672. if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
  8673. code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
  8674. }
  8675. super.render(code, options);
  8676. }
  8677. }
  8678. class ClassExpression extends ClassNode {
  8679. render(code, options, { renderedSurroundingElement } = BLANK) {
  8680. super.render(code, options);
  8681. if (renderedSurroundingElement === ExpressionStatement$1) {
  8682. code.appendRight(this.start, '(');
  8683. code.prependLeft(this.end, ')');
  8684. }
  8685. }
  8686. }
  8687. class MultiExpression extends ExpressionEntity {
  8688. constructor(expressions) {
  8689. super();
  8690. this.expressions = expressions;
  8691. this.included = false;
  8692. }
  8693. deoptimizePath(path) {
  8694. for (const expression of this.expressions) {
  8695. expression.deoptimizePath(path);
  8696. }
  8697. }
  8698. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8699. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
  8700. }
  8701. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8702. for (const expression of this.expressions) {
  8703. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8704. return true;
  8705. }
  8706. return false;
  8707. }
  8708. }
  8709. class ConditionalExpression extends NodeBase {
  8710. constructor() {
  8711. super(...arguments);
  8712. this.expressionsToBeDeoptimized = [];
  8713. this.isBranchResolutionAnalysed = false;
  8714. this.usedBranch = null;
  8715. }
  8716. deoptimizeCache() {
  8717. if (this.usedBranch !== null) {
  8718. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8719. this.usedBranch = null;
  8720. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8721. for (const expression of this.expressionsToBeDeoptimized) {
  8722. expression.deoptimizeCache();
  8723. }
  8724. }
  8725. }
  8726. deoptimizePath(path) {
  8727. const usedBranch = this.getUsedBranch();
  8728. if (!usedBranch) {
  8729. this.consequent.deoptimizePath(path);
  8730. this.alternate.deoptimizePath(path);
  8731. }
  8732. else {
  8733. usedBranch.deoptimizePath(path);
  8734. }
  8735. }
  8736. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8737. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8738. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8739. }
  8740. getLiteralValueAtPath(path, recursionTracker, origin) {
  8741. const usedBranch = this.getUsedBranch();
  8742. if (!usedBranch)
  8743. return UnknownValue;
  8744. this.expressionsToBeDeoptimized.push(origin);
  8745. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8746. }
  8747. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8748. const usedBranch = this.getUsedBranch();
  8749. if (!usedBranch)
  8750. return new MultiExpression([
  8751. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  8752. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  8753. ]);
  8754. this.expressionsToBeDeoptimized.push(origin);
  8755. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8756. }
  8757. hasEffects(context) {
  8758. if (this.test.hasEffects(context))
  8759. return true;
  8760. const usedBranch = this.getUsedBranch();
  8761. if (!usedBranch) {
  8762. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8763. }
  8764. return usedBranch.hasEffects(context);
  8765. }
  8766. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8767. const usedBranch = this.getUsedBranch();
  8768. if (!usedBranch) {
  8769. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8770. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8771. }
  8772. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8773. }
  8774. include(context, includeChildrenRecursively) {
  8775. this.included = true;
  8776. const usedBranch = this.getUsedBranch();
  8777. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8778. this.test.include(context, includeChildrenRecursively);
  8779. this.consequent.include(context, includeChildrenRecursively);
  8780. this.alternate.include(context, includeChildrenRecursively);
  8781. }
  8782. else {
  8783. usedBranch.include(context, includeChildrenRecursively);
  8784. }
  8785. }
  8786. includeCallArguments(context, args) {
  8787. const usedBranch = this.getUsedBranch();
  8788. if (!usedBranch) {
  8789. this.consequent.includeCallArguments(context, args);
  8790. this.alternate.includeCallArguments(context, args);
  8791. }
  8792. else {
  8793. usedBranch.includeCallArguments(context, args);
  8794. }
  8795. }
  8796. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8797. const usedBranch = this.getUsedBranch();
  8798. if (!this.test.included) {
  8799. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8800. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8801. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8802. : colonPos) + 1);
  8803. if (preventASI) {
  8804. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8805. }
  8806. code.remove(this.start, inclusionStart);
  8807. if (this.consequent.included) {
  8808. code.remove(colonPos, this.end);
  8809. }
  8810. removeAnnotations(this, code);
  8811. usedBranch.render(code, options, {
  8812. isCalleeOfRenderedParent,
  8813. preventASI: true,
  8814. renderedParentType: renderedParentType || this.parent.type,
  8815. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8816. });
  8817. }
  8818. else {
  8819. this.test.render(code, options, { renderedSurroundingElement });
  8820. this.consequent.render(code, options);
  8821. this.alternate.render(code, options);
  8822. }
  8823. }
  8824. getUsedBranch() {
  8825. if (this.isBranchResolutionAnalysed) {
  8826. return this.usedBranch;
  8827. }
  8828. this.isBranchResolutionAnalysed = true;
  8829. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8830. return typeof testValue === 'symbol'
  8831. ? null
  8832. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8833. }
  8834. }
  8835. class ContinueStatement extends NodeBase {
  8836. hasEffects(context) {
  8837. if (this.label) {
  8838. if (!context.ignore.labels.has(this.label.name))
  8839. return true;
  8840. context.includedLabels.add(this.label.name);
  8841. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8842. }
  8843. else {
  8844. if (!context.ignore.continues)
  8845. return true;
  8846. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8847. }
  8848. return false;
  8849. }
  8850. include(context) {
  8851. this.included = true;
  8852. if (this.label) {
  8853. this.label.include();
  8854. context.includedLabels.add(this.label.name);
  8855. }
  8856. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8857. }
  8858. }
  8859. class DoWhileStatement extends NodeBase {
  8860. hasEffects(context) {
  8861. if (this.test.hasEffects(context))
  8862. return true;
  8863. const { brokenFlow, ignore: { breaks, continues } } = context;
  8864. context.ignore.breaks = true;
  8865. context.ignore.continues = true;
  8866. if (this.body.hasEffects(context))
  8867. return true;
  8868. context.ignore.breaks = breaks;
  8869. context.ignore.continues = continues;
  8870. context.brokenFlow = brokenFlow;
  8871. return false;
  8872. }
  8873. include(context, includeChildrenRecursively) {
  8874. this.included = true;
  8875. this.test.include(context, includeChildrenRecursively);
  8876. const { brokenFlow } = context;
  8877. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8878. context.brokenFlow = brokenFlow;
  8879. }
  8880. }
  8881. class EmptyStatement extends NodeBase {
  8882. hasEffects() {
  8883. return false;
  8884. }
  8885. }
  8886. class ExportAllDeclaration extends NodeBase {
  8887. hasEffects() {
  8888. return false;
  8889. }
  8890. initialise() {
  8891. this.context.addExport(this);
  8892. }
  8893. render(code, _options, nodeRenderOptions) {
  8894. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8895. }
  8896. applyDeoptimizations() { }
  8897. }
  8898. ExportAllDeclaration.prototype.needsBoundaries = true;
  8899. class FunctionDeclaration extends FunctionNode {
  8900. initialise() {
  8901. super.initialise();
  8902. if (this.id !== null) {
  8903. this.id.variable.isId = true;
  8904. }
  8905. }
  8906. parseNode(esTreeNode) {
  8907. if (esTreeNode.id !== null) {
  8908. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8909. }
  8910. super.parseNode(esTreeNode);
  8911. }
  8912. }
  8913. // The header ends at the first non-white-space after "default"
  8914. function getDeclarationStart(code, start) {
  8915. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8916. }
  8917. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  8918. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  8919. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  8920. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8921. if (generatorStarPos === -1) {
  8922. return declarationEnd;
  8923. }
  8924. return declarationEnd + generatorStarPos + 1;
  8925. }
  8926. class ExportDefaultDeclaration extends NodeBase {
  8927. include(context, includeChildrenRecursively) {
  8928. super.include(context, includeChildrenRecursively);
  8929. if (includeChildrenRecursively) {
  8930. this.context.includeVariableInModule(this.variable);
  8931. }
  8932. }
  8933. initialise() {
  8934. const declaration = this.declaration;
  8935. this.declarationName =
  8936. (declaration.id && declaration.id.name) || this.declaration.name;
  8937. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  8938. this.context.addExport(this);
  8939. }
  8940. render(code, options, nodeRenderOptions) {
  8941. const { start, end } = nodeRenderOptions;
  8942. const declarationStart = getDeclarationStart(code.original, this.start);
  8943. if (this.declaration instanceof FunctionDeclaration) {
  8944. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  8945. }
  8946. else if (this.declaration instanceof ClassDeclaration) {
  8947. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  8948. }
  8949. else if (this.variable.getOriginalVariable() !== this.variable) {
  8950. // Remove altogether to prevent re-declaring the same variable
  8951. treeshakeNode(this, code, start, end);
  8952. return;
  8953. }
  8954. else if (this.variable.included) {
  8955. this.renderVariableDeclaration(code, declarationStart, options);
  8956. }
  8957. else {
  8958. code.remove(this.start, declarationStart);
  8959. this.declaration.render(code, options, {
  8960. renderedSurroundingElement: ExpressionStatement$1
  8961. });
  8962. if (code.original[this.end - 1] !== ';') {
  8963. code.appendLeft(this.end, ';');
  8964. }
  8965. return;
  8966. }
  8967. this.declaration.render(code, options);
  8968. }
  8969. applyDeoptimizations() { }
  8970. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  8971. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8972. const name = this.variable.getName(getPropertyAccess);
  8973. // Remove `export default`
  8974. code.remove(this.start, declarationStart);
  8975. if (needsId) {
  8976. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  8977. }
  8978. if (format === 'system' &&
  8979. this.declaration instanceof ClassDeclaration &&
  8980. exportNamesByVariable.has(this.variable)) {
  8981. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8982. }
  8983. }
  8984. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  8985. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  8986. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  8987. if (systemExportNames) {
  8988. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  8989. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  8990. }
  8991. else {
  8992. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  8993. if (!hasTrailingSemicolon) {
  8994. code.appendLeft(this.end, ';');
  8995. }
  8996. }
  8997. }
  8998. }
  8999. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9000. class ExportNamedDeclaration extends NodeBase {
  9001. bind() {
  9002. var _a;
  9003. // Do not bind specifiers
  9004. (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
  9005. }
  9006. hasEffects(context) {
  9007. var _a;
  9008. return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9009. }
  9010. initialise() {
  9011. this.context.addExport(this);
  9012. }
  9013. render(code, options, nodeRenderOptions) {
  9014. const { start, end } = nodeRenderOptions;
  9015. if (this.declaration === null) {
  9016. code.remove(start, end);
  9017. }
  9018. else {
  9019. code.remove(this.start, this.declaration.start);
  9020. this.declaration.render(code, options, { end, start });
  9021. }
  9022. }
  9023. applyDeoptimizations() { }
  9024. }
  9025. ExportNamedDeclaration.prototype.needsBoundaries = true;
  9026. class ExportSpecifier extends NodeBase {
  9027. applyDeoptimizations() { }
  9028. }
  9029. class ForInStatement extends NodeBase {
  9030. createScope(parentScope) {
  9031. this.scope = new BlockScope(parentScope);
  9032. }
  9033. hasEffects(context) {
  9034. const { deoptimized, left, right } = this;
  9035. if (!deoptimized)
  9036. this.applyDeoptimizations();
  9037. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  9038. return true;
  9039. const { brokenFlow, ignore: { breaks, continues } } = context;
  9040. context.ignore.breaks = true;
  9041. context.ignore.continues = true;
  9042. if (this.body.hasEffects(context))
  9043. return true;
  9044. context.ignore.breaks = breaks;
  9045. context.ignore.continues = continues;
  9046. context.brokenFlow = brokenFlow;
  9047. return false;
  9048. }
  9049. include(context, includeChildrenRecursively) {
  9050. const { body, deoptimized, left, right } = this;
  9051. if (!deoptimized)
  9052. this.applyDeoptimizations();
  9053. this.included = true;
  9054. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9055. right.include(context, includeChildrenRecursively);
  9056. const { brokenFlow } = context;
  9057. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9058. context.brokenFlow = brokenFlow;
  9059. }
  9060. initialise() {
  9061. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9062. }
  9063. render(code, options) {
  9064. this.left.render(code, options, NO_SEMICOLON);
  9065. this.right.render(code, options, NO_SEMICOLON);
  9066. // handle no space between "in" and the right side
  9067. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  9068. code.prependLeft(this.right.start, ' ');
  9069. }
  9070. this.body.render(code, options);
  9071. }
  9072. applyDeoptimizations() {
  9073. this.deoptimized = true;
  9074. this.left.deoptimizePath(EMPTY_PATH);
  9075. this.context.requestTreeshakingPass();
  9076. }
  9077. }
  9078. class ForOfStatement extends NodeBase {
  9079. createScope(parentScope) {
  9080. this.scope = new BlockScope(parentScope);
  9081. }
  9082. hasEffects() {
  9083. if (!this.deoptimized)
  9084. this.applyDeoptimizations();
  9085. // Placeholder until proper Symbol.Iterator support
  9086. return true;
  9087. }
  9088. include(context, includeChildrenRecursively) {
  9089. const { body, deoptimized, left, right } = this;
  9090. if (!deoptimized)
  9091. this.applyDeoptimizations();
  9092. this.included = true;
  9093. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9094. right.include(context, includeChildrenRecursively);
  9095. const { brokenFlow } = context;
  9096. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9097. context.brokenFlow = brokenFlow;
  9098. }
  9099. initialise() {
  9100. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9101. }
  9102. render(code, options) {
  9103. this.left.render(code, options, NO_SEMICOLON);
  9104. this.right.render(code, options, NO_SEMICOLON);
  9105. // handle no space between "of" and the right side
  9106. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  9107. code.prependLeft(this.right.start, ' ');
  9108. }
  9109. this.body.render(code, options);
  9110. }
  9111. applyDeoptimizations() {
  9112. this.deoptimized = true;
  9113. this.left.deoptimizePath(EMPTY_PATH);
  9114. this.context.requestTreeshakingPass();
  9115. }
  9116. }
  9117. class ForStatement extends NodeBase {
  9118. createScope(parentScope) {
  9119. this.scope = new BlockScope(parentScope);
  9120. }
  9121. hasEffects(context) {
  9122. var _a, _b, _c;
  9123. if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
  9124. ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
  9125. ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
  9126. return true;
  9127. const { brokenFlow, ignore: { breaks, continues } } = context;
  9128. context.ignore.breaks = true;
  9129. context.ignore.continues = true;
  9130. if (this.body.hasEffects(context))
  9131. return true;
  9132. context.ignore.breaks = breaks;
  9133. context.ignore.continues = continues;
  9134. context.brokenFlow = brokenFlow;
  9135. return false;
  9136. }
  9137. include(context, includeChildrenRecursively) {
  9138. var _a, _b, _c;
  9139. this.included = true;
  9140. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9141. (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  9142. const { brokenFlow } = context;
  9143. (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
  9144. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9145. context.brokenFlow = brokenFlow;
  9146. }
  9147. render(code, options) {
  9148. var _a, _b, _c;
  9149. (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
  9150. (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
  9151. (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
  9152. this.body.render(code, options);
  9153. }
  9154. }
  9155. class FunctionExpression extends FunctionNode {
  9156. render(code, options, { renderedSurroundingElement } = BLANK) {
  9157. super.render(code, options);
  9158. if (renderedSurroundingElement === ExpressionStatement$1) {
  9159. code.appendRight(this.start, '(');
  9160. code.prependLeft(this.end, ')');
  9161. }
  9162. }
  9163. }
  9164. class TrackingScope extends BlockScope {
  9165. constructor() {
  9166. super(...arguments);
  9167. this.hoistedDeclarations = [];
  9168. }
  9169. addDeclaration(identifier, context, init, isHoisted) {
  9170. this.hoistedDeclarations.push(identifier);
  9171. return super.addDeclaration(identifier, context, init, isHoisted);
  9172. }
  9173. }
  9174. const unset = Symbol('unset');
  9175. class IfStatement extends NodeBase {
  9176. constructor() {
  9177. super(...arguments);
  9178. this.testValue = unset;
  9179. }
  9180. deoptimizeCache() {
  9181. this.testValue = UnknownValue;
  9182. }
  9183. hasEffects(context) {
  9184. var _a;
  9185. if (this.test.hasEffects(context)) {
  9186. return true;
  9187. }
  9188. const testValue = this.getTestValue();
  9189. if (typeof testValue === 'symbol') {
  9190. const { brokenFlow } = context;
  9191. if (this.consequent.hasEffects(context))
  9192. return true;
  9193. const consequentBrokenFlow = context.brokenFlow;
  9194. context.brokenFlow = brokenFlow;
  9195. if (this.alternate === null)
  9196. return false;
  9197. if (this.alternate.hasEffects(context))
  9198. return true;
  9199. context.brokenFlow =
  9200. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9201. return false;
  9202. }
  9203. return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9204. }
  9205. include(context, includeChildrenRecursively) {
  9206. this.included = true;
  9207. if (includeChildrenRecursively) {
  9208. this.includeRecursively(includeChildrenRecursively, context);
  9209. }
  9210. else {
  9211. const testValue = this.getTestValue();
  9212. if (typeof testValue === 'symbol') {
  9213. this.includeUnknownTest(context);
  9214. }
  9215. else {
  9216. this.includeKnownTest(context, testValue);
  9217. }
  9218. }
  9219. }
  9220. parseNode(esTreeNode) {
  9221. this.consequentScope = new TrackingScope(this.scope);
  9222. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  9223. if (esTreeNode.alternate) {
  9224. this.alternateScope = new TrackingScope(this.scope);
  9225. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  9226. }
  9227. super.parseNode(esTreeNode);
  9228. }
  9229. render(code, options) {
  9230. const { snippets: { getPropertyAccess } } = options;
  9231. // Note that unknown test values are always included
  9232. const testValue = this.getTestValue();
  9233. const hoistedDeclarations = [];
  9234. const includesIfElse = this.test.included;
  9235. const noTreeshake = !this.context.options.treeshake;
  9236. if (includesIfElse) {
  9237. this.test.render(code, options);
  9238. }
  9239. else {
  9240. code.remove(this.start, this.consequent.start);
  9241. }
  9242. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9243. this.consequent.render(code, options);
  9244. }
  9245. else {
  9246. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9247. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9248. }
  9249. if (this.alternate) {
  9250. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9251. if (includesIfElse) {
  9252. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9253. code.prependLeft(this.alternate.start, ' ');
  9254. }
  9255. }
  9256. else {
  9257. code.remove(this.consequent.end, this.alternate.start);
  9258. }
  9259. this.alternate.render(code, options);
  9260. }
  9261. else {
  9262. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9263. code.overwrite(this.alternate.start, this.end, ';');
  9264. }
  9265. else {
  9266. code.remove(this.consequent.end, this.end);
  9267. }
  9268. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9269. }
  9270. }
  9271. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9272. }
  9273. applyDeoptimizations() { }
  9274. getTestValue() {
  9275. if (this.testValue === unset) {
  9276. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9277. }
  9278. return this.testValue;
  9279. }
  9280. includeKnownTest(context, testValue) {
  9281. var _a;
  9282. if (this.test.shouldBeIncluded(context)) {
  9283. this.test.include(context, false);
  9284. }
  9285. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9286. this.consequent.include(context, false, { asSingleStatement: true });
  9287. }
  9288. if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
  9289. this.alternate.include(context, false, { asSingleStatement: true });
  9290. }
  9291. }
  9292. includeRecursively(includeChildrenRecursively, context) {
  9293. var _a;
  9294. this.test.include(context, includeChildrenRecursively);
  9295. this.consequent.include(context, includeChildrenRecursively);
  9296. (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  9297. }
  9298. includeUnknownTest(context) {
  9299. var _a;
  9300. this.test.include(context, false);
  9301. const { brokenFlow } = context;
  9302. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  9303. if (this.consequent.shouldBeIncluded(context)) {
  9304. this.consequent.include(context, false, { asSingleStatement: true });
  9305. consequentBrokenFlow = context.brokenFlow;
  9306. context.brokenFlow = brokenFlow;
  9307. }
  9308. if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
  9309. this.alternate.include(context, false, { asSingleStatement: true });
  9310. context.brokenFlow =
  9311. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9312. }
  9313. }
  9314. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9315. const hoistedVars = [
  9316. ...new Set(hoistedDeclarations.map(identifier => {
  9317. const variable = identifier.variable;
  9318. return variable.included ? variable.getName(getPropertyAccess) : '';
  9319. }))
  9320. ]
  9321. .filter(Boolean)
  9322. .join(', ');
  9323. if (hoistedVars) {
  9324. const parentType = this.parent.type;
  9325. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9326. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  9327. if (needsBraces) {
  9328. code.appendLeft(this.end, ` }`);
  9329. }
  9330. }
  9331. }
  9332. shouldKeepAlternateBranch() {
  9333. let currentParent = this.parent;
  9334. do {
  9335. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9336. return true;
  9337. }
  9338. if (currentParent instanceof BlockStatement) {
  9339. return false;
  9340. }
  9341. currentParent = currentParent.parent;
  9342. } while (currentParent);
  9343. return false;
  9344. }
  9345. }
  9346. class ImportDeclaration extends NodeBase {
  9347. // Do not bind specifiers
  9348. bind() { }
  9349. hasEffects() {
  9350. return false;
  9351. }
  9352. initialise() {
  9353. this.context.addImport(this);
  9354. }
  9355. render(code, _options, nodeRenderOptions) {
  9356. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9357. }
  9358. applyDeoptimizations() { }
  9359. }
  9360. ImportDeclaration.prototype.needsBoundaries = true;
  9361. class ImportDefaultSpecifier extends NodeBase {
  9362. applyDeoptimizations() { }
  9363. }
  9364. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9365. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  9366. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9367. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9368. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9369. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9370. const defaultInteropHelpersByInteropType = {
  9371. auto: INTEROP_DEFAULT_VARIABLE,
  9372. default: null,
  9373. defaultOnly: null,
  9374. esModule: null,
  9375. false: null,
  9376. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  9377. };
  9378. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9379. (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
  9380. const namespaceInteropHelpersByInteropType = {
  9381. auto: INTEROP_NAMESPACE_VARIABLE,
  9382. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9383. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9384. esModule: null,
  9385. false: null,
  9386. true: INTEROP_NAMESPACE_VARIABLE
  9387. };
  9388. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
  9389. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
  9390. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9391. const usedHelpers = new Set(additionalHelpers);
  9392. for (const variable of HELPER_NAMES) {
  9393. if (accessedGlobals.has(variable)) {
  9394. usedHelpers.add(variable);
  9395. }
  9396. }
  9397. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9398. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  9399. : '').join('');
  9400. };
  9401. const HELPER_GENERATORS = {
  9402. [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
  9403. const { _, getDirectReturnFunction, n } = snippets;
  9404. const [left, right] = getDirectReturnFunction(['e'], {
  9405. functionReturn: true,
  9406. lineBreakIndent: null,
  9407. name: INTEROP_DEFAULT_LEGACY_VARIABLE
  9408. });
  9409. return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  9410. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9411. },
  9412. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9413. const { _, getDirectReturnFunction, n } = snippets;
  9414. const [left, right] = getDirectReturnFunction(['e'], {
  9415. functionReturn: true,
  9416. lineBreakIndent: null,
  9417. name: INTEROP_DEFAULT_VARIABLE
  9418. });
  9419. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9420. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9421. },
  9422. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  9423. const { getDirectReturnFunction, getObject, n } = snippets;
  9424. const [left, right] = getDirectReturnFunction(['e'], {
  9425. functionReturn: true,
  9426. lineBreakIndent: null,
  9427. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9428. });
  9429. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  9430. ['__proto__', 'null'],
  9431. ['default', 'e']
  9432. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9433. },
  9434. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9435. const { _, n } = snippets;
  9436. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9437. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9438. `}${n}${n}`);
  9439. },
  9440. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  9441. const { _, getDirectReturnFunction, n } = snippets;
  9442. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9443. const [left, right] = getDirectReturnFunction(['e'], {
  9444. functionReturn: true,
  9445. lineBreakIndent: null,
  9446. name: INTEROP_NAMESPACE_VARIABLE
  9447. });
  9448. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9449. }
  9450. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9451. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9452. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9453. `}${n}${n}`);
  9454. },
  9455. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9456. const { _, cnst, n } = snippets;
  9457. const useForEach = cnst === 'var' && liveBindings;
  9458. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9459. `${t}${loopOverNamespaces(`{${n}` +
  9460. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9461. (liveBindings
  9462. ? useForEach
  9463. ? copyOwnPropertyLiveBinding
  9464. : copyPropertyLiveBinding
  9465. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9466. `${t}${t}${t}}${n}` +
  9467. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9468. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  9469. `}${n}${n}`);
  9470. }
  9471. };
  9472. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9473. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9474. const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9475. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9476. const copyProperty = `{${n}` +
  9477. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
  9478. `${i}${t}}`;
  9479. return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  9480. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  9481. : ''});${n}` +
  9482. `${i}if${_}(e)${_}{${n}` +
  9483. `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9484. `${i}}${n}` +
  9485. `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9486. `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9487. };
  9488. const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
  9489. ? `for${_}(${cnst} k in e)${_}${body}`
  9490. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9491. isAsync: false,
  9492. name: null
  9493. })}${body})${s}`;
  9494. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9495. if (useForEach) {
  9496. const [left, right] = getDirectReturnFunction(['e'], {
  9497. functionReturn: false,
  9498. lineBreakIndent: { base: t, t },
  9499. name: null
  9500. });
  9501. return (`m.forEach(${left}` +
  9502. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9503. isAsync: false,
  9504. name: null
  9505. })}${body})${right});`);
  9506. }
  9507. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9508. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9509. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9510. };
  9511. const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
  9512. const { _, n } = snippets;
  9513. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9514. copyOwnPropertyLiveBinding(t, i + t, snippets) +
  9515. `${i}}${n}`);
  9516. };
  9517. const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9518. const [left, right] = getDirectReturnFunction([], {
  9519. functionReturn: true,
  9520. lineBreakIndent: null,
  9521. name: null
  9522. });
  9523. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9524. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9525. `${i}${t}enumerable:${_}true,${n}` +
  9526. `${i}${t}get:${_}${left}e[k]${right}${n}` +
  9527. `${i}});${n}`);
  9528. };
  9529. const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9530. const [left, right] = getDirectReturnFunction([], {
  9531. functionReturn: true,
  9532. lineBreakIndent: null,
  9533. name: null
  9534. });
  9535. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9536. `${i}if${_}(d)${_}{${n}` +
  9537. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9538. `${i}${t}${t}enumerable:${_}true,${n}` +
  9539. `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9540. `${i}${t}});${n}` +
  9541. `${i}}${n}`);
  9542. };
  9543. const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
  9544. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9545. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  9546. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9547. : fragment;
  9548. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9549. function getToStringTagValue(getObject) {
  9550. return getObject([['value', "'Module'"]], {
  9551. lineBreakIndent: null
  9552. });
  9553. }
  9554. class ImportExpression extends NodeBase {
  9555. constructor() {
  9556. super(...arguments);
  9557. this.inlineNamespace = null;
  9558. this.mechanism = null;
  9559. this.resolution = null;
  9560. }
  9561. hasEffects() {
  9562. return true;
  9563. }
  9564. include(context, includeChildrenRecursively) {
  9565. if (!this.included) {
  9566. this.included = true;
  9567. this.context.includeDynamicImport(this);
  9568. this.scope.addAccessedDynamicImport(this);
  9569. }
  9570. this.source.include(context, includeChildrenRecursively);
  9571. }
  9572. initialise() {
  9573. this.context.addDynamicImport(this);
  9574. }
  9575. render(code, options) {
  9576. if (this.inlineNamespace) {
  9577. const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
  9578. const [left, right] = getDirectReturnFunction([], {
  9579. functionReturn: true,
  9580. lineBreakIndent: null,
  9581. name: null
  9582. });
  9583. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
  9584. return;
  9585. }
  9586. if (this.mechanism) {
  9587. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  9588. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  9589. }
  9590. this.source.render(code, options);
  9591. }
  9592. renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
  9593. code.overwrite(this.source.start, this.source.end, resolution);
  9594. if (namespaceExportName) {
  9595. const [left, right] = getDirectReturnFunction(['n'], {
  9596. functionReturn: true,
  9597. lineBreakIndent: null,
  9598. name: null
  9599. });
  9600. code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
  9601. }
  9602. }
  9603. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
  9604. const { format } = options;
  9605. this.inlineNamespace = null;
  9606. this.resolution = resolution;
  9607. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9608. let helper;
  9609. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9610. if (helper) {
  9611. accessedGlobals.push(helper);
  9612. }
  9613. if (accessedGlobals.length > 0) {
  9614. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9615. }
  9616. }
  9617. setInternalResolution(inlineNamespace) {
  9618. this.inlineNamespace = inlineNamespace;
  9619. }
  9620. applyDeoptimizations() { }
  9621. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9622. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9623. {
  9624. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9625. format,
  9626. moduleId: this.context.module.id,
  9627. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9628. }
  9629. ]);
  9630. if (mechanism) {
  9631. return { helper: null, mechanism };
  9632. }
  9633. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9634. switch (format) {
  9635. case 'cjs': {
  9636. const helper = getInteropHelper(resolution, exportMode, interop);
  9637. let left = `require(`;
  9638. let right = `)`;
  9639. if (helper) {
  9640. left = `/*#__PURE__*/${helper}(${left}`;
  9641. right += ')';
  9642. }
  9643. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9644. functionReturn: true,
  9645. lineBreakIndent: null,
  9646. name: null
  9647. });
  9648. left = `Promise.resolve().then(${functionLeft}${left}`;
  9649. right += `${functionRight})`;
  9650. if (!arrowFunctions && hasDynamicTarget) {
  9651. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9652. needsArrowReturnParens: false,
  9653. needsWrappedFunction: true
  9654. });
  9655. right = ')';
  9656. }
  9657. return {
  9658. helper,
  9659. mechanism: { left, right }
  9660. };
  9661. }
  9662. case 'amd': {
  9663. const resolve = compact ? 'c' : 'resolve';
  9664. const reject = compact ? 'e' : 'reject';
  9665. const helper = getInteropHelper(resolution, exportMode, interop);
  9666. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9667. functionReturn: false,
  9668. lineBreakIndent: null,
  9669. name: null
  9670. });
  9671. const resolveNamespace = helper
  9672. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9673. : resolve;
  9674. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9675. functionReturn: false,
  9676. lineBreakIndent: null,
  9677. name: null
  9678. });
  9679. let left = `new Promise(${handlerLeft}require([`;
  9680. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9681. if (!arrowFunctions && hasDynamicTarget) {
  9682. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9683. needsArrowReturnParens: false,
  9684. needsWrappedFunction: true
  9685. });
  9686. right = ')';
  9687. }
  9688. return {
  9689. helper,
  9690. mechanism: { left, right }
  9691. };
  9692. }
  9693. case 'system':
  9694. return {
  9695. helper: null,
  9696. mechanism: {
  9697. left: 'module.import(',
  9698. right: ')'
  9699. }
  9700. };
  9701. case 'es':
  9702. if (dynamicImportFunction) {
  9703. return {
  9704. helper: null,
  9705. mechanism: {
  9706. left: `${dynamicImportFunction}(`,
  9707. right: ')'
  9708. }
  9709. };
  9710. }
  9711. }
  9712. return { helper: null, mechanism: null };
  9713. }
  9714. }
  9715. function getInteropHelper(resolution, exportMode, interop) {
  9716. return exportMode === 'external'
  9717. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  9718. : exportMode === 'default'
  9719. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9720. : null;
  9721. }
  9722. const accessedImportGlobals = {
  9723. amd: ['require'],
  9724. cjs: ['require'],
  9725. system: ['module']
  9726. };
  9727. class ImportNamespaceSpecifier extends NodeBase {
  9728. applyDeoptimizations() { }
  9729. }
  9730. class ImportSpecifier extends NodeBase {
  9731. applyDeoptimizations() { }
  9732. }
  9733. class LabeledStatement extends NodeBase {
  9734. hasEffects(context) {
  9735. const brokenFlow = context.brokenFlow;
  9736. context.ignore.labels.add(this.label.name);
  9737. if (this.body.hasEffects(context))
  9738. return true;
  9739. context.ignore.labels.delete(this.label.name);
  9740. if (context.includedLabels.has(this.label.name)) {
  9741. context.includedLabels.delete(this.label.name);
  9742. context.brokenFlow = brokenFlow;
  9743. }
  9744. return false;
  9745. }
  9746. include(context, includeChildrenRecursively) {
  9747. this.included = true;
  9748. const brokenFlow = context.brokenFlow;
  9749. this.body.include(context, includeChildrenRecursively);
  9750. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9751. this.label.include();
  9752. context.includedLabels.delete(this.label.name);
  9753. context.brokenFlow = brokenFlow;
  9754. }
  9755. }
  9756. render(code, options) {
  9757. if (this.label.included) {
  9758. this.label.render(code, options);
  9759. }
  9760. else {
  9761. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9762. }
  9763. this.body.render(code, options);
  9764. }
  9765. }
  9766. class LogicalExpression extends NodeBase {
  9767. constructor() {
  9768. super(...arguments);
  9769. // We collect deoptimization information if usedBranch !== null
  9770. this.expressionsToBeDeoptimized = [];
  9771. this.isBranchResolutionAnalysed = false;
  9772. this.usedBranch = null;
  9773. }
  9774. deoptimizeCache() {
  9775. if (this.usedBranch) {
  9776. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9777. this.usedBranch = null;
  9778. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9779. for (const expression of this.expressionsToBeDeoptimized) {
  9780. expression.deoptimizeCache();
  9781. }
  9782. // Request another pass because we need to ensure "include" runs again if
  9783. // it is rendered
  9784. this.context.requestTreeshakingPass();
  9785. }
  9786. }
  9787. deoptimizePath(path) {
  9788. const usedBranch = this.getUsedBranch();
  9789. if (!usedBranch) {
  9790. this.left.deoptimizePath(path);
  9791. this.right.deoptimizePath(path);
  9792. }
  9793. else {
  9794. usedBranch.deoptimizePath(path);
  9795. }
  9796. }
  9797. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9798. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9799. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9800. }
  9801. getLiteralValueAtPath(path, recursionTracker, origin) {
  9802. const usedBranch = this.getUsedBranch();
  9803. if (!usedBranch)
  9804. return UnknownValue;
  9805. this.expressionsToBeDeoptimized.push(origin);
  9806. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9807. }
  9808. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9809. const usedBranch = this.getUsedBranch();
  9810. if (!usedBranch)
  9811. return new MultiExpression([
  9812. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  9813. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  9814. ]);
  9815. this.expressionsToBeDeoptimized.push(origin);
  9816. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9817. }
  9818. hasEffects(context) {
  9819. if (this.left.hasEffects(context)) {
  9820. return true;
  9821. }
  9822. if (this.getUsedBranch() !== this.left) {
  9823. return this.right.hasEffects(context);
  9824. }
  9825. return false;
  9826. }
  9827. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9828. const usedBranch = this.getUsedBranch();
  9829. if (!usedBranch) {
  9830. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9831. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  9832. }
  9833. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9834. }
  9835. include(context, includeChildrenRecursively) {
  9836. this.included = true;
  9837. const usedBranch = this.getUsedBranch();
  9838. if (includeChildrenRecursively ||
  9839. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  9840. !usedBranch) {
  9841. this.left.include(context, includeChildrenRecursively);
  9842. this.right.include(context, includeChildrenRecursively);
  9843. }
  9844. else {
  9845. usedBranch.include(context, includeChildrenRecursively);
  9846. }
  9847. }
  9848. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9849. if (!this.left.included || !this.right.included) {
  9850. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  9851. if (this.right.included) {
  9852. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  9853. code.remove(this.start, removePos);
  9854. if (preventASI) {
  9855. removeLineBreaks(code, removePos, this.right.start);
  9856. }
  9857. }
  9858. else {
  9859. code.remove(operatorPos, this.end);
  9860. }
  9861. removeAnnotations(this, code);
  9862. this.getUsedBranch().render(code, options, {
  9863. isCalleeOfRenderedParent,
  9864. preventASI,
  9865. renderedParentType: renderedParentType || this.parent.type,
  9866. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9867. });
  9868. }
  9869. else {
  9870. this.left.render(code, options, {
  9871. preventASI,
  9872. renderedSurroundingElement
  9873. });
  9874. this.right.render(code, options);
  9875. }
  9876. }
  9877. getUsedBranch() {
  9878. if (!this.isBranchResolutionAnalysed) {
  9879. this.isBranchResolutionAnalysed = true;
  9880. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9881. if (typeof leftValue === 'symbol') {
  9882. return null;
  9883. }
  9884. else {
  9885. this.usedBranch =
  9886. (this.operator === '||' && leftValue) ||
  9887. (this.operator === '&&' && !leftValue) ||
  9888. (this.operator === '??' && leftValue != null)
  9889. ? this.left
  9890. : this.right;
  9891. }
  9892. }
  9893. return this.usedBranch;
  9894. }
  9895. }
  9896. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  9897. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  9898. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  9899. class MetaProperty extends NodeBase {
  9900. addAccessedGlobals(format, accessedGlobalsByScope) {
  9901. const metaProperty = this.metaProperty;
  9902. const accessedGlobals = (metaProperty &&
  9903. (metaProperty.startsWith(FILE_PREFIX) ||
  9904. metaProperty.startsWith(ASSET_PREFIX) ||
  9905. metaProperty.startsWith(CHUNK_PREFIX))
  9906. ? accessedFileUrlGlobals
  9907. : accessedMetaUrlGlobals)[format];
  9908. if (accessedGlobals.length > 0) {
  9909. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9910. }
  9911. }
  9912. getReferencedFileName(outputPluginDriver) {
  9913. const metaProperty = this.metaProperty;
  9914. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  9915. return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
  9916. }
  9917. return null;
  9918. }
  9919. hasEffects() {
  9920. return false;
  9921. }
  9922. hasEffectsOnInteractionAtPath(path, { type }) {
  9923. return path.length > 1 || type !== INTERACTION_ACCESSED;
  9924. }
  9925. include() {
  9926. if (!this.included) {
  9927. this.included = true;
  9928. if (this.meta.name === 'import') {
  9929. this.context.addImportMeta(this);
  9930. const parent = this.parent;
  9931. this.metaProperty =
  9932. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  9933. ? parent.propertyKey
  9934. : null;
  9935. }
  9936. }
  9937. }
  9938. renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
  9939. var _a;
  9940. const parent = this.parent;
  9941. const metaProperty = this.metaProperty;
  9942. if (metaProperty &&
  9943. (metaProperty.startsWith(FILE_PREFIX) ||
  9944. metaProperty.startsWith(ASSET_PREFIX) ||
  9945. metaProperty.startsWith(CHUNK_PREFIX))) {
  9946. let referenceId = null;
  9947. let assetReferenceId = null;
  9948. let chunkReferenceId = null;
  9949. let fileName;
  9950. if (metaProperty.startsWith(FILE_PREFIX)) {
  9951. referenceId = metaProperty.substring(FILE_PREFIX.length);
  9952. fileName = outputPluginDriver.getFileName(referenceId);
  9953. }
  9954. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  9955. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9956. assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
  9957. fileName = outputPluginDriver.getFileName(assetReferenceId);
  9958. }
  9959. else {
  9960. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9961. chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
  9962. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  9963. }
  9964. const relativePath = normalize(require$$0.relative(require$$0.dirname(chunkId), fileName));
  9965. let replacement;
  9966. if (assetReferenceId !== null) {
  9967. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  9968. {
  9969. assetFileName: fileName,
  9970. chunkId,
  9971. format,
  9972. moduleId: this.context.module.id,
  9973. relativeAssetPath: relativePath
  9974. }
  9975. ]);
  9976. }
  9977. if (!replacement) {
  9978. replacement =
  9979. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  9980. {
  9981. assetReferenceId,
  9982. chunkId,
  9983. chunkReferenceId,
  9984. fileName,
  9985. format,
  9986. moduleId: this.context.module.id,
  9987. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  9988. relativePath
  9989. }
  9990. ]) || relativeUrlMechanisms[format](relativePath);
  9991. }
  9992. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9993. return;
  9994. }
  9995. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  9996. metaProperty,
  9997. {
  9998. chunkId,
  9999. format,
  10000. moduleId: this.context.module.id
  10001. }
  10002. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
  10003. if (typeof replacement === 'string') {
  10004. if (parent instanceof MemberExpression) {
  10005. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10006. }
  10007. else {
  10008. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  10009. }
  10010. }
  10011. }
  10012. }
  10013. const accessedMetaUrlGlobals = {
  10014. amd: ['document', 'module', 'URL'],
  10015. cjs: ['document', 'require', 'URL'],
  10016. es: [],
  10017. iife: ['document', 'URL'],
  10018. system: ['module'],
  10019. umd: ['document', 'require', 'URL']
  10020. };
  10021. const accessedFileUrlGlobals = {
  10022. amd: ['document', 'require', 'URL'],
  10023. cjs: ['document', 'require', 'URL'],
  10024. es: [],
  10025. iife: ['document', 'URL'],
  10026. system: ['module', 'URL'],
  10027. umd: ['document', 'require', 'URL']
  10028. };
  10029. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  10030. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  10031. const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
  10032. const urlMechanism = getUrl(chunkId);
  10033. return prop === null
  10034. ? `({ url: ${urlMechanism} })`
  10035. : prop === 'url'
  10036. ? urlMechanism
  10037. : 'undefined';
  10038. };
  10039. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  10040. const relativeUrlMechanisms = {
  10041. amd: relativePath => {
  10042. if (relativePath[0] !== '.')
  10043. relativePath = './' + relativePath;
  10044. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  10045. },
  10046. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  10047. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  10048. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  10049. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  10050. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  10051. };
  10052. const importMetaMechanisms = {
  10053. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  10054. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  10055. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  10056. system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
  10057. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  10058. };
  10059. class NewExpression extends NodeBase {
  10060. hasEffects(context) {
  10061. try {
  10062. for (const argument of this.arguments) {
  10063. if (argument.hasEffects(context))
  10064. return true;
  10065. }
  10066. if (this.context.options.treeshake.annotations &&
  10067. this.annotations) {
  10068. return false;
  10069. }
  10070. return (this.callee.hasEffects(context) ||
  10071. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10072. }
  10073. finally {
  10074. if (!this.deoptimized)
  10075. this.applyDeoptimizations();
  10076. }
  10077. }
  10078. hasEffectsOnInteractionAtPath(path, { type }) {
  10079. return path.length > 0 || type !== INTERACTION_ACCESSED;
  10080. }
  10081. include(context, includeChildrenRecursively) {
  10082. if (!this.deoptimized)
  10083. this.applyDeoptimizations();
  10084. if (includeChildrenRecursively) {
  10085. super.include(context, includeChildrenRecursively);
  10086. }
  10087. else {
  10088. this.included = true;
  10089. this.callee.include(context, false);
  10090. }
  10091. this.callee.includeCallArguments(context, this.arguments);
  10092. }
  10093. initialise() {
  10094. this.interaction = {
  10095. args: this.arguments,
  10096. thisArg: null,
  10097. type: INTERACTION_CALLED,
  10098. withNew: true
  10099. };
  10100. }
  10101. render(code, options) {
  10102. this.callee.render(code, options);
  10103. renderCallArguments(code, options, this);
  10104. }
  10105. applyDeoptimizations() {
  10106. this.deoptimized = true;
  10107. for (const argument of this.arguments) {
  10108. // This will make sure all properties of parameters behave as "unknown"
  10109. argument.deoptimizePath(UNKNOWN_PATH);
  10110. }
  10111. this.context.requestTreeshakingPass();
  10112. }
  10113. }
  10114. class ObjectExpression extends NodeBase {
  10115. constructor() {
  10116. super(...arguments);
  10117. this.objectEntity = null;
  10118. }
  10119. deoptimizeCache() {
  10120. this.getObjectEntity().deoptimizeAllProperties();
  10121. }
  10122. deoptimizePath(path) {
  10123. this.getObjectEntity().deoptimizePath(path);
  10124. }
  10125. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10126. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10127. }
  10128. getLiteralValueAtPath(path, recursionTracker, origin) {
  10129. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10130. }
  10131. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10132. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10133. }
  10134. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10135. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10136. }
  10137. render(code, options, { renderedSurroundingElement } = BLANK) {
  10138. super.render(code, options);
  10139. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10140. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10141. code.appendRight(this.start, '(');
  10142. code.prependLeft(this.end, ')');
  10143. }
  10144. }
  10145. applyDeoptimizations() { }
  10146. getObjectEntity() {
  10147. if (this.objectEntity !== null) {
  10148. return this.objectEntity;
  10149. }
  10150. let prototype = OBJECT_PROTOTYPE;
  10151. const properties = [];
  10152. for (const property of this.properties) {
  10153. if (property instanceof SpreadElement) {
  10154. properties.push({ key: UnknownKey, kind: 'init', property });
  10155. continue;
  10156. }
  10157. let key;
  10158. if (property.computed) {
  10159. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10160. if (typeof keyValue === 'symbol') {
  10161. properties.push({ key: UnknownKey, kind: property.kind, property });
  10162. continue;
  10163. }
  10164. else {
  10165. key = String(keyValue);
  10166. }
  10167. }
  10168. else {
  10169. key =
  10170. property.key instanceof Identifier
  10171. ? property.key.name
  10172. : String(property.key.value);
  10173. if (key === '__proto__' && property.kind === 'init') {
  10174. prototype =
  10175. property.value instanceof Literal && property.value.value === null
  10176. ? null
  10177. : property.value;
  10178. continue;
  10179. }
  10180. }
  10181. properties.push({ key, kind: property.kind, property });
  10182. }
  10183. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10184. }
  10185. }
  10186. class PrivateIdentifier extends NodeBase {
  10187. }
  10188. class Program extends NodeBase {
  10189. constructor() {
  10190. super(...arguments);
  10191. this.hasCachedEffect = false;
  10192. }
  10193. hasEffects(context) {
  10194. // We are caching here to later more efficiently identify side-effect-free modules
  10195. if (this.hasCachedEffect)
  10196. return true;
  10197. for (const node of this.body) {
  10198. if (node.hasEffects(context)) {
  10199. return (this.hasCachedEffect = true);
  10200. }
  10201. }
  10202. return false;
  10203. }
  10204. include(context, includeChildrenRecursively) {
  10205. this.included = true;
  10206. for (const node of this.body) {
  10207. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10208. node.include(context, includeChildrenRecursively);
  10209. }
  10210. }
  10211. }
  10212. render(code, options) {
  10213. if (this.body.length) {
  10214. renderStatementList(this.body, code, this.start, this.end, options);
  10215. }
  10216. else {
  10217. super.render(code, options);
  10218. }
  10219. }
  10220. applyDeoptimizations() { }
  10221. }
  10222. class Property extends MethodBase {
  10223. constructor() {
  10224. super(...arguments);
  10225. this.declarationInit = null;
  10226. }
  10227. declare(kind, init) {
  10228. this.declarationInit = init;
  10229. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10230. }
  10231. hasEffects(context) {
  10232. if (!this.deoptimized)
  10233. this.applyDeoptimizations();
  10234. const propertyReadSideEffects = this.context.options.treeshake
  10235. .propertyReadSideEffects;
  10236. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10237. this.key.hasEffects(context) ||
  10238. this.value.hasEffects(context));
  10239. }
  10240. markDeclarationReached() {
  10241. this.value.markDeclarationReached();
  10242. }
  10243. render(code, options) {
  10244. if (!this.shorthand) {
  10245. this.key.render(code, options);
  10246. }
  10247. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10248. }
  10249. applyDeoptimizations() {
  10250. this.deoptimized = true;
  10251. if (this.declarationInit !== null) {
  10252. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10253. this.context.requestTreeshakingPass();
  10254. }
  10255. }
  10256. }
  10257. class PropertyDefinition extends NodeBase {
  10258. deoptimizePath(path) {
  10259. var _a;
  10260. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  10261. }
  10262. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10263. var _a;
  10264. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10265. }
  10266. getLiteralValueAtPath(path, recursionTracker, origin) {
  10267. return this.value
  10268. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10269. : UnknownValue;
  10270. }
  10271. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10272. return this.value
  10273. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10274. : UNKNOWN_EXPRESSION;
  10275. }
  10276. hasEffects(context) {
  10277. var _a;
  10278. return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10279. }
  10280. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10281. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10282. }
  10283. applyDeoptimizations() { }
  10284. }
  10285. class ReturnStatement extends NodeBase {
  10286. hasEffects(context) {
  10287. var _a;
  10288. if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
  10289. return true;
  10290. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10291. return false;
  10292. }
  10293. include(context, includeChildrenRecursively) {
  10294. var _a;
  10295. this.included = true;
  10296. (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10297. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10298. }
  10299. initialise() {
  10300. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10301. }
  10302. render(code, options) {
  10303. if (this.argument) {
  10304. this.argument.render(code, options, { preventASI: true });
  10305. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10306. code.prependLeft(this.start + 6, ' ');
  10307. }
  10308. }
  10309. }
  10310. }
  10311. class SequenceExpression extends NodeBase {
  10312. deoptimizePath(path) {
  10313. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10314. }
  10315. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10316. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10317. }
  10318. getLiteralValueAtPath(path, recursionTracker, origin) {
  10319. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10320. }
  10321. hasEffects(context) {
  10322. for (const expression of this.expressions) {
  10323. if (expression.hasEffects(context))
  10324. return true;
  10325. }
  10326. return false;
  10327. }
  10328. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10329. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10330. }
  10331. include(context, includeChildrenRecursively) {
  10332. this.included = true;
  10333. const lastExpression = this.expressions[this.expressions.length - 1];
  10334. for (const expression of this.expressions) {
  10335. if (includeChildrenRecursively ||
  10336. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10337. expression.shouldBeIncluded(context))
  10338. expression.include(context, includeChildrenRecursively);
  10339. }
  10340. }
  10341. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10342. let includedNodes = 0;
  10343. let lastSeparatorPos = null;
  10344. const lastNode = this.expressions[this.expressions.length - 1];
  10345. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10346. if (!node.included) {
  10347. treeshakeNode(node, code, start, end);
  10348. continue;
  10349. }
  10350. includedNodes++;
  10351. lastSeparatorPos = separator;
  10352. if (includedNodes === 1 && preventASI) {
  10353. removeLineBreaks(code, start, node.start);
  10354. }
  10355. if (includedNodes === 1) {
  10356. const parentType = renderedParentType || this.parent.type;
  10357. node.render(code, options, {
  10358. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10359. renderedParentType: parentType,
  10360. renderedSurroundingElement: parentType
  10361. });
  10362. }
  10363. else {
  10364. node.render(code, options);
  10365. }
  10366. }
  10367. if (lastSeparatorPos) {
  10368. code.remove(lastSeparatorPos, this.end);
  10369. }
  10370. }
  10371. }
  10372. class StaticBlock extends NodeBase {
  10373. createScope(parentScope) {
  10374. this.scope = new BlockScope(parentScope);
  10375. }
  10376. hasEffects(context) {
  10377. for (const node of this.body) {
  10378. if (node.hasEffects(context))
  10379. return true;
  10380. }
  10381. return false;
  10382. }
  10383. include(context, includeChildrenRecursively) {
  10384. this.included = true;
  10385. for (const node of this.body) {
  10386. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10387. node.include(context, includeChildrenRecursively);
  10388. }
  10389. }
  10390. render(code, options) {
  10391. if (this.body.length) {
  10392. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  10393. }
  10394. else {
  10395. super.render(code, options);
  10396. }
  10397. }
  10398. }
  10399. class Super extends NodeBase {
  10400. bind() {
  10401. this.variable = this.scope.findVariable('this');
  10402. }
  10403. deoptimizePath(path) {
  10404. this.variable.deoptimizePath(path);
  10405. }
  10406. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10407. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10408. }
  10409. include() {
  10410. if (!this.included) {
  10411. this.included = true;
  10412. this.context.includeVariableInModule(this.variable);
  10413. }
  10414. }
  10415. }
  10416. class SwitchCase extends NodeBase {
  10417. hasEffects(context) {
  10418. var _a;
  10419. if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
  10420. return true;
  10421. for (const node of this.consequent) {
  10422. if (context.brokenFlow)
  10423. break;
  10424. if (node.hasEffects(context))
  10425. return true;
  10426. }
  10427. return false;
  10428. }
  10429. include(context, includeChildrenRecursively) {
  10430. var _a;
  10431. this.included = true;
  10432. (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10433. for (const node of this.consequent) {
  10434. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10435. node.include(context, includeChildrenRecursively);
  10436. }
  10437. }
  10438. render(code, options, nodeRenderOptions) {
  10439. if (this.consequent.length) {
  10440. this.test && this.test.render(code, options);
  10441. const testEnd = this.test
  10442. ? this.test.end
  10443. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10444. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10445. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10446. }
  10447. else {
  10448. super.render(code, options);
  10449. }
  10450. }
  10451. }
  10452. SwitchCase.prototype.needsBoundaries = true;
  10453. class SwitchStatement extends NodeBase {
  10454. createScope(parentScope) {
  10455. this.scope = new BlockScope(parentScope);
  10456. }
  10457. hasEffects(context) {
  10458. if (this.discriminant.hasEffects(context))
  10459. return true;
  10460. const { brokenFlow, ignore: { breaks } } = context;
  10461. let minBrokenFlow = Infinity;
  10462. context.ignore.breaks = true;
  10463. for (const switchCase of this.cases) {
  10464. if (switchCase.hasEffects(context))
  10465. return true;
  10466. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  10467. context.brokenFlow = brokenFlow;
  10468. }
  10469. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10470. context.brokenFlow = minBrokenFlow;
  10471. }
  10472. context.ignore.breaks = breaks;
  10473. return false;
  10474. }
  10475. include(context, includeChildrenRecursively) {
  10476. this.included = true;
  10477. this.discriminant.include(context, includeChildrenRecursively);
  10478. const { brokenFlow } = context;
  10479. let minBrokenFlow = Infinity;
  10480. let isCaseIncluded = includeChildrenRecursively ||
  10481. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10482. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10483. const switchCase = this.cases[caseIndex];
  10484. if (switchCase.included) {
  10485. isCaseIncluded = true;
  10486. }
  10487. if (!isCaseIncluded) {
  10488. const hasEffectsContext = createHasEffectsContext();
  10489. hasEffectsContext.ignore.breaks = true;
  10490. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10491. }
  10492. if (isCaseIncluded) {
  10493. switchCase.include(context, includeChildrenRecursively);
  10494. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  10495. context.brokenFlow = brokenFlow;
  10496. }
  10497. else {
  10498. minBrokenFlow = brokenFlow;
  10499. }
  10500. }
  10501. if (isCaseIncluded &&
  10502. this.defaultCase !== null &&
  10503. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10504. context.brokenFlow = minBrokenFlow;
  10505. }
  10506. }
  10507. initialise() {
  10508. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10509. if (this.cases[caseIndex].test === null) {
  10510. this.defaultCase = caseIndex;
  10511. return;
  10512. }
  10513. }
  10514. this.defaultCase = null;
  10515. }
  10516. render(code, options) {
  10517. this.discriminant.render(code, options);
  10518. if (this.cases.length > 0) {
  10519. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10520. }
  10521. }
  10522. }
  10523. class TaggedTemplateExpression extends CallExpressionBase {
  10524. bind() {
  10525. super.bind();
  10526. if (this.tag.type === Identifier$1) {
  10527. const name = this.tag.name;
  10528. const variable = this.scope.findVariable(name);
  10529. if (variable.isNamespace) {
  10530. this.context.warn({
  10531. code: 'CANNOT_CALL_NAMESPACE',
  10532. message: `Cannot call a namespace ('${name}')`
  10533. }, this.start);
  10534. }
  10535. }
  10536. }
  10537. hasEffects(context) {
  10538. try {
  10539. for (const argument of this.quasi.expressions) {
  10540. if (argument.hasEffects(context))
  10541. return true;
  10542. }
  10543. return (this.tag.hasEffects(context) ||
  10544. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10545. }
  10546. finally {
  10547. if (!this.deoptimized)
  10548. this.applyDeoptimizations();
  10549. }
  10550. }
  10551. include(context, includeChildrenRecursively) {
  10552. if (!this.deoptimized)
  10553. this.applyDeoptimizations();
  10554. if (includeChildrenRecursively) {
  10555. super.include(context, includeChildrenRecursively);
  10556. }
  10557. else {
  10558. this.included = true;
  10559. this.tag.include(context, includeChildrenRecursively);
  10560. this.quasi.include(context, includeChildrenRecursively);
  10561. }
  10562. this.tag.includeCallArguments(context, this.interaction.args);
  10563. const returnExpression = this.getReturnExpression();
  10564. if (!returnExpression.included) {
  10565. returnExpression.include(context, false);
  10566. }
  10567. }
  10568. initialise() {
  10569. this.interaction = {
  10570. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  10571. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10572. type: INTERACTION_CALLED,
  10573. withNew: false
  10574. };
  10575. }
  10576. render(code, options) {
  10577. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10578. this.quasi.render(code, options);
  10579. }
  10580. applyDeoptimizations() {
  10581. this.deoptimized = true;
  10582. if (this.interaction.thisArg) {
  10583. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10584. }
  10585. for (const argument of this.quasi.expressions) {
  10586. // This will make sure all properties of parameters behave as "unknown"
  10587. argument.deoptimizePath(UNKNOWN_PATH);
  10588. }
  10589. this.context.requestTreeshakingPass();
  10590. }
  10591. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10592. if (this.returnExpression === null) {
  10593. this.returnExpression = UNKNOWN_EXPRESSION;
  10594. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10595. }
  10596. return this.returnExpression;
  10597. }
  10598. }
  10599. class TemplateElement extends NodeBase {
  10600. // Do not try to bind value
  10601. bind() { }
  10602. hasEffects() {
  10603. return false;
  10604. }
  10605. include() {
  10606. this.included = true;
  10607. }
  10608. parseNode(esTreeNode) {
  10609. this.value = esTreeNode.value;
  10610. super.parseNode(esTreeNode);
  10611. }
  10612. render() { }
  10613. }
  10614. class TemplateLiteral extends NodeBase {
  10615. deoptimizeThisOnInteractionAtPath() { }
  10616. getLiteralValueAtPath(path) {
  10617. if (path.length > 0 || this.quasis.length !== 1) {
  10618. return UnknownValue;
  10619. }
  10620. return this.quasis[0].value.cooked;
  10621. }
  10622. getReturnExpressionWhenCalledAtPath(path) {
  10623. if (path.length !== 1) {
  10624. return UNKNOWN_EXPRESSION;
  10625. }
  10626. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10627. }
  10628. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10629. if (interaction.type === INTERACTION_ACCESSED) {
  10630. return path.length > 1;
  10631. }
  10632. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10633. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10634. }
  10635. return true;
  10636. }
  10637. render(code, options) {
  10638. code.indentExclusionRanges.push([this.start, this.end]);
  10639. super.render(code, options);
  10640. }
  10641. }
  10642. class UndefinedVariable extends Variable {
  10643. constructor() {
  10644. super('undefined');
  10645. }
  10646. getLiteralValueAtPath() {
  10647. return undefined;
  10648. }
  10649. }
  10650. class ExportDefaultVariable extends LocalVariable {
  10651. constructor(name, exportDefaultDeclaration, context) {
  10652. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  10653. this.hasId = false;
  10654. this.originalId = null;
  10655. this.originalVariable = null;
  10656. const declaration = exportDefaultDeclaration.declaration;
  10657. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10658. declaration.id) {
  10659. this.hasId = true;
  10660. this.originalId = declaration.id;
  10661. }
  10662. else if (declaration instanceof Identifier) {
  10663. this.originalId = declaration;
  10664. }
  10665. }
  10666. addReference(identifier) {
  10667. if (!this.hasId) {
  10668. this.name = identifier.name;
  10669. }
  10670. }
  10671. getAssignedVariableName() {
  10672. return (this.originalId && this.originalId.name) || null;
  10673. }
  10674. getBaseVariableName() {
  10675. const original = this.getOriginalVariable();
  10676. if (original === this) {
  10677. return super.getBaseVariableName();
  10678. }
  10679. else {
  10680. return original.getBaseVariableName();
  10681. }
  10682. }
  10683. getDirectOriginalVariable() {
  10684. return this.originalId &&
  10685. (this.hasId ||
  10686. !(this.originalId.isPossibleTDZ() ||
  10687. this.originalId.variable.isReassigned ||
  10688. this.originalId.variable instanceof UndefinedVariable ||
  10689. // this avoids a circular dependency
  10690. 'syntheticNamespace' in this.originalId.variable))
  10691. ? this.originalId.variable
  10692. : null;
  10693. }
  10694. getName(getPropertyAccess) {
  10695. const original = this.getOriginalVariable();
  10696. if (original === this) {
  10697. return super.getName(getPropertyAccess);
  10698. }
  10699. else {
  10700. return original.getName(getPropertyAccess);
  10701. }
  10702. }
  10703. getOriginalVariable() {
  10704. if (this.originalVariable)
  10705. return this.originalVariable;
  10706. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10707. let original = this;
  10708. let currentVariable;
  10709. const checkedVariables = new Set();
  10710. do {
  10711. checkedVariables.add(original);
  10712. currentVariable = original;
  10713. original = currentVariable.getDirectOriginalVariable();
  10714. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10715. return (this.originalVariable = original || currentVariable);
  10716. }
  10717. }
  10718. class ModuleScope extends ChildScope {
  10719. constructor(parent, context) {
  10720. super(parent);
  10721. this.context = context;
  10722. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  10723. }
  10724. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10725. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10726. this.variables.set('default', variable);
  10727. return variable;
  10728. }
  10729. addNamespaceMemberAccess() { }
  10730. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10731. // all module level variables are already deconflicted when deconflicting the chunk
  10732. for (const scope of this.children)
  10733. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10734. }
  10735. findLexicalBoundary() {
  10736. return this;
  10737. }
  10738. findVariable(name) {
  10739. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  10740. if (knownVariable) {
  10741. return knownVariable;
  10742. }
  10743. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  10744. if (variable instanceof GlobalVariable) {
  10745. this.accessedOutsideVariables.set(name, variable);
  10746. }
  10747. return variable;
  10748. }
  10749. }
  10750. class ThisExpression extends NodeBase {
  10751. bind() {
  10752. this.variable = this.scope.findVariable('this');
  10753. }
  10754. deoptimizePath(path) {
  10755. this.variable.deoptimizePath(path);
  10756. }
  10757. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10758. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  10759. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  10760. }
  10761. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10762. if (path.length === 0) {
  10763. return interaction.type !== INTERACTION_ACCESSED;
  10764. }
  10765. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10766. }
  10767. include() {
  10768. if (!this.included) {
  10769. this.included = true;
  10770. this.context.includeVariableInModule(this.variable);
  10771. }
  10772. }
  10773. initialise() {
  10774. this.alias =
  10775. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  10776. if (this.alias === 'undefined') {
  10777. this.context.warn({
  10778. code: 'THIS_IS_UNDEFINED',
  10779. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  10780. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  10781. }, this.start);
  10782. }
  10783. }
  10784. render(code) {
  10785. if (this.alias !== null) {
  10786. code.overwrite(this.start, this.end, this.alias, {
  10787. contentOnly: false,
  10788. storeName: true
  10789. });
  10790. }
  10791. }
  10792. }
  10793. class ThrowStatement extends NodeBase {
  10794. hasEffects() {
  10795. return true;
  10796. }
  10797. include(context, includeChildrenRecursively) {
  10798. this.included = true;
  10799. this.argument.include(context, includeChildrenRecursively);
  10800. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10801. }
  10802. render(code, options) {
  10803. this.argument.render(code, options, { preventASI: true });
  10804. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  10805. code.prependLeft(this.start + 5, ' ');
  10806. }
  10807. }
  10808. }
  10809. class TryStatement extends NodeBase {
  10810. constructor() {
  10811. super(...arguments);
  10812. this.directlyIncluded = false;
  10813. this.includedLabelsAfterBlock = null;
  10814. }
  10815. hasEffects(context) {
  10816. var _a;
  10817. return ((this.context.options.treeshake.tryCatchDeoptimization
  10818. ? this.block.body.length > 0
  10819. : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10820. }
  10821. include(context, includeChildrenRecursively) {
  10822. var _a, _b;
  10823. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  10824. const { brokenFlow } = context;
  10825. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  10826. this.included = true;
  10827. this.directlyIncluded = true;
  10828. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  10829. if (context.includedLabels.size > 0) {
  10830. this.includedLabelsAfterBlock = [...context.includedLabels];
  10831. }
  10832. context.brokenFlow = brokenFlow;
  10833. }
  10834. else if (this.includedLabelsAfterBlock) {
  10835. for (const label of this.includedLabelsAfterBlock) {
  10836. context.includedLabels.add(label);
  10837. }
  10838. }
  10839. if (this.handler !== null) {
  10840. this.handler.include(context, includeChildrenRecursively);
  10841. context.brokenFlow = brokenFlow;
  10842. }
  10843. (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  10844. }
  10845. }
  10846. const unaryOperators = {
  10847. '!': value => !value,
  10848. '+': value => +value,
  10849. '-': value => -value,
  10850. delete: () => UnknownValue,
  10851. typeof: value => typeof value,
  10852. void: () => undefined,
  10853. '~': value => ~value
  10854. };
  10855. class UnaryExpression extends NodeBase {
  10856. getLiteralValueAtPath(path, recursionTracker, origin) {
  10857. if (path.length > 0)
  10858. return UnknownValue;
  10859. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10860. if (typeof argumentValue === 'symbol')
  10861. return UnknownValue;
  10862. return unaryOperators[this.operator](argumentValue);
  10863. }
  10864. hasEffects(context) {
  10865. if (!this.deoptimized)
  10866. this.applyDeoptimizations();
  10867. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  10868. return false;
  10869. return (this.argument.hasEffects(context) ||
  10870. (this.operator === 'delete' &&
  10871. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  10872. }
  10873. hasEffectsOnInteractionAtPath(path, { type }) {
  10874. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  10875. }
  10876. applyDeoptimizations() {
  10877. this.deoptimized = true;
  10878. if (this.operator === 'delete') {
  10879. this.argument.deoptimizePath(EMPTY_PATH);
  10880. this.context.requestTreeshakingPass();
  10881. }
  10882. }
  10883. }
  10884. class UnknownNode extends NodeBase {
  10885. hasEffects() {
  10886. return true;
  10887. }
  10888. include(context) {
  10889. super.include(context, true);
  10890. }
  10891. }
  10892. class UpdateExpression extends NodeBase {
  10893. hasEffects(context) {
  10894. if (!this.deoptimized)
  10895. this.applyDeoptimizations();
  10896. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  10897. }
  10898. hasEffectsOnInteractionAtPath(path, { type }) {
  10899. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10900. }
  10901. include(context, includeChildrenRecursively) {
  10902. if (!this.deoptimized)
  10903. this.applyDeoptimizations();
  10904. this.included = true;
  10905. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  10906. }
  10907. initialise() {
  10908. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  10909. }
  10910. render(code, options) {
  10911. const { exportNamesByVariable, format, snippets: { _ } } = options;
  10912. this.argument.render(code, options);
  10913. if (format === 'system') {
  10914. const variable = this.argument.variable;
  10915. const exportNames = exportNamesByVariable.get(variable);
  10916. if (exportNames) {
  10917. if (this.prefix) {
  10918. if (exportNames.length === 1) {
  10919. renderSystemExportExpression(variable, this.start, this.end, code, options);
  10920. }
  10921. else {
  10922. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  10923. }
  10924. }
  10925. else {
  10926. const operator = this.operator[0];
  10927. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  10928. }
  10929. }
  10930. }
  10931. }
  10932. applyDeoptimizations() {
  10933. this.deoptimized = true;
  10934. this.argument.deoptimizePath(EMPTY_PATH);
  10935. if (this.argument instanceof Identifier) {
  10936. const variable = this.scope.findVariable(this.argument.name);
  10937. variable.isReassigned = true;
  10938. }
  10939. this.context.requestTreeshakingPass();
  10940. }
  10941. }
  10942. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10943. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10944. }
  10945. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  10946. for (const declarator of declarations) {
  10947. if (!declarator.id.included)
  10948. return false;
  10949. if (declarator.id.type === Identifier$1) {
  10950. if (exportNamesByVariable.has(declarator.id.variable))
  10951. return false;
  10952. }
  10953. else {
  10954. const exportedVariables = [];
  10955. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  10956. if (exportedVariables.length > 0)
  10957. return false;
  10958. }
  10959. }
  10960. return true;
  10961. }
  10962. class VariableDeclaration extends NodeBase {
  10963. deoptimizePath() {
  10964. for (const declarator of this.declarations) {
  10965. declarator.deoptimizePath(EMPTY_PATH);
  10966. }
  10967. }
  10968. hasEffectsOnInteractionAtPath() {
  10969. return false;
  10970. }
  10971. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  10972. this.included = true;
  10973. for (const declarator of this.declarations) {
  10974. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  10975. declarator.include(context, includeChildrenRecursively);
  10976. if (asSingleStatement) {
  10977. declarator.id.include(context, includeChildrenRecursively);
  10978. }
  10979. }
  10980. }
  10981. initialise() {
  10982. for (const declarator of this.declarations) {
  10983. declarator.declareDeclarator(this.kind);
  10984. }
  10985. }
  10986. render(code, options, nodeRenderOptions = BLANK) {
  10987. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  10988. for (const declarator of this.declarations) {
  10989. declarator.render(code, options);
  10990. }
  10991. if (!nodeRenderOptions.isNoStatement &&
  10992. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  10993. code.appendLeft(this.end, ';');
  10994. }
  10995. }
  10996. else {
  10997. this.renderReplacedDeclarations(code, options);
  10998. }
  10999. }
  11000. applyDeoptimizations() { }
  11001. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  11002. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  11003. code.remove(this.end - 1, this.end);
  11004. }
  11005. separatorString += ';';
  11006. if (lastSeparatorPos !== null) {
  11007. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  11008. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  11009. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  11010. actualContentEnd--;
  11011. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  11012. actualContentEnd--;
  11013. }
  11014. }
  11015. if (actualContentEnd === lastSeparatorPos + 1) {
  11016. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  11017. }
  11018. else {
  11019. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11020. code.remove(actualContentEnd, renderedContentEnd);
  11021. }
  11022. }
  11023. else {
  11024. code.appendLeft(renderedContentEnd, separatorString);
  11025. }
  11026. if (systemPatternExports.length > 0) {
  11027. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  11028. }
  11029. }
  11030. renderReplacedDeclarations(code, options) {
  11031. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  11032. let actualContentEnd, renderedContentEnd;
  11033. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  11034. let lastSeparatorPos = renderedContentEnd - 1;
  11035. code.remove(this.start, lastSeparatorPos);
  11036. let isInDeclaration = false;
  11037. let hasRenderedContent = false;
  11038. let separatorString = '', leadingString, nextSeparatorString;
  11039. const aggregatedSystemExports = [];
  11040. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  11041. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  11042. if (!node.included) {
  11043. code.remove(start, end);
  11044. continue;
  11045. }
  11046. node.render(code, options);
  11047. leadingString = '';
  11048. nextSeparatorString = '';
  11049. if (!node.id.included ||
  11050. (node.id instanceof Identifier &&
  11051. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  11052. if (hasRenderedContent) {
  11053. separatorString += ';';
  11054. }
  11055. isInDeclaration = false;
  11056. }
  11057. else {
  11058. if (singleSystemExport && singleSystemExport === node.id.variable) {
  11059. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  11060. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  11061. }
  11062. if (isInDeclaration) {
  11063. separatorString += ',';
  11064. }
  11065. else {
  11066. if (hasRenderedContent) {
  11067. separatorString += ';';
  11068. }
  11069. leadingString += `${this.kind} `;
  11070. isInDeclaration = true;
  11071. }
  11072. }
  11073. if (renderedContentEnd === lastSeparatorPos + 1) {
  11074. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  11075. }
  11076. else {
  11077. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  11078. code.appendLeft(renderedContentEnd, leadingString);
  11079. }
  11080. actualContentEnd = contentEnd;
  11081. renderedContentEnd = end;
  11082. hasRenderedContent = true;
  11083. lastSeparatorPos = separator;
  11084. separatorString = nextSeparatorString;
  11085. }
  11086. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  11087. }
  11088. }
  11089. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  11090. var _a;
  11091. let singleSystemExport = null;
  11092. if (options.format === 'system') {
  11093. for (const { node } of separatedNodes) {
  11094. if (node.id instanceof Identifier &&
  11095. node.init &&
  11096. aggregatedSystemExports.length === 0 &&
  11097. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  11098. singleSystemExport = node.id.variable;
  11099. aggregatedSystemExports.push(singleSystemExport);
  11100. }
  11101. else {
  11102. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  11103. }
  11104. }
  11105. if (aggregatedSystemExports.length > 1) {
  11106. singleSystemExport = null;
  11107. }
  11108. else if (singleSystemExport) {
  11109. aggregatedSystemExports.length = 0;
  11110. }
  11111. }
  11112. return singleSystemExport;
  11113. }
  11114. class VariableDeclarator extends NodeBase {
  11115. declareDeclarator(kind) {
  11116. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11117. }
  11118. deoptimizePath(path) {
  11119. this.id.deoptimizePath(path);
  11120. }
  11121. hasEffects(context) {
  11122. var _a;
  11123. const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
  11124. this.id.markDeclarationReached();
  11125. return initEffect || this.id.hasEffects(context);
  11126. }
  11127. include(context, includeChildrenRecursively) {
  11128. var _a;
  11129. this.included = true;
  11130. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  11131. this.id.markDeclarationReached();
  11132. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  11133. this.id.include(context, includeChildrenRecursively);
  11134. }
  11135. }
  11136. render(code, options) {
  11137. const { exportNamesByVariable, snippets: { _ } } = options;
  11138. const renderId = this.id.included;
  11139. if (renderId) {
  11140. this.id.render(code, options);
  11141. }
  11142. else {
  11143. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  11144. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  11145. }
  11146. if (this.init) {
  11147. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11148. }
  11149. else if (this.id instanceof Identifier &&
  11150. isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
  11151. code.appendLeft(this.end, `${_}=${_}void 0`);
  11152. }
  11153. }
  11154. applyDeoptimizations() { }
  11155. }
  11156. class WhileStatement extends NodeBase {
  11157. hasEffects(context) {
  11158. if (this.test.hasEffects(context))
  11159. return true;
  11160. const { brokenFlow, ignore: { breaks, continues } } = context;
  11161. context.ignore.breaks = true;
  11162. context.ignore.continues = true;
  11163. if (this.body.hasEffects(context))
  11164. return true;
  11165. context.ignore.breaks = breaks;
  11166. context.ignore.continues = continues;
  11167. context.brokenFlow = brokenFlow;
  11168. return false;
  11169. }
  11170. include(context, includeChildrenRecursively) {
  11171. this.included = true;
  11172. this.test.include(context, includeChildrenRecursively);
  11173. const { brokenFlow } = context;
  11174. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11175. context.brokenFlow = brokenFlow;
  11176. }
  11177. }
  11178. class YieldExpression extends NodeBase {
  11179. hasEffects(context) {
  11180. var _a;
  11181. if (!this.deoptimized)
  11182. this.applyDeoptimizations();
  11183. return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  11184. }
  11185. render(code, options) {
  11186. if (this.argument) {
  11187. this.argument.render(code, options, { preventASI: true });
  11188. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11189. code.prependLeft(this.start + 5, ' ');
  11190. }
  11191. }
  11192. }
  11193. }
  11194. const nodeConstructors = {
  11195. ArrayExpression,
  11196. ArrayPattern,
  11197. ArrowFunctionExpression,
  11198. AssignmentExpression,
  11199. AssignmentPattern,
  11200. AwaitExpression,
  11201. BinaryExpression,
  11202. BlockStatement,
  11203. BreakStatement,
  11204. CallExpression,
  11205. CatchClause,
  11206. ChainExpression,
  11207. ClassBody,
  11208. ClassDeclaration,
  11209. ClassExpression,
  11210. ConditionalExpression,
  11211. ContinueStatement,
  11212. DoWhileStatement,
  11213. EmptyStatement,
  11214. ExportAllDeclaration,
  11215. ExportDefaultDeclaration,
  11216. ExportNamedDeclaration,
  11217. ExportSpecifier,
  11218. ExpressionStatement,
  11219. ForInStatement,
  11220. ForOfStatement,
  11221. ForStatement,
  11222. FunctionDeclaration,
  11223. FunctionExpression,
  11224. Identifier,
  11225. IfStatement,
  11226. ImportDeclaration,
  11227. ImportDefaultSpecifier,
  11228. ImportExpression,
  11229. ImportNamespaceSpecifier,
  11230. ImportSpecifier,
  11231. LabeledStatement,
  11232. Literal,
  11233. LogicalExpression,
  11234. MemberExpression,
  11235. MetaProperty,
  11236. MethodDefinition,
  11237. NewExpression,
  11238. ObjectExpression,
  11239. ObjectPattern,
  11240. PrivateIdentifier,
  11241. Program,
  11242. Property,
  11243. PropertyDefinition,
  11244. RestElement,
  11245. ReturnStatement,
  11246. SequenceExpression,
  11247. SpreadElement,
  11248. StaticBlock,
  11249. Super,
  11250. SwitchCase,
  11251. SwitchStatement,
  11252. TaggedTemplateExpression,
  11253. TemplateElement,
  11254. TemplateLiteral,
  11255. ThisExpression,
  11256. ThrowStatement,
  11257. TryStatement,
  11258. UnaryExpression,
  11259. UnknownNode,
  11260. UpdateExpression,
  11261. VariableDeclaration,
  11262. VariableDeclarator,
  11263. WhileStatement,
  11264. YieldExpression
  11265. };
  11266. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11267. class ExportShimVariable extends Variable {
  11268. constructor(module) {
  11269. super(MISSING_EXPORT_SHIM_VARIABLE);
  11270. this.module = module;
  11271. }
  11272. include() {
  11273. super.include();
  11274. this.module.needsExportShim = true;
  11275. }
  11276. }
  11277. class NamespaceVariable extends Variable {
  11278. constructor(context) {
  11279. super(context.getModuleName());
  11280. this.memberVariables = null;
  11281. this.mergedNamespaces = [];
  11282. this.referencedEarly = false;
  11283. this.references = [];
  11284. this.context = context;
  11285. this.module = context.module;
  11286. }
  11287. addReference(identifier) {
  11288. this.references.push(identifier);
  11289. this.name = identifier.name;
  11290. }
  11291. getMemberVariables() {
  11292. if (this.memberVariables) {
  11293. return this.memberVariables;
  11294. }
  11295. const memberVariables = Object.create(null);
  11296. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  11297. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  11298. const exportedVariable = this.context.traceExport(name);
  11299. if (exportedVariable) {
  11300. memberVariables[name] = exportedVariable;
  11301. }
  11302. }
  11303. }
  11304. return (this.memberVariables = memberVariables);
  11305. }
  11306. include() {
  11307. this.included = true;
  11308. this.context.includeAllExports();
  11309. }
  11310. prepare(accessedGlobalsByScope) {
  11311. if (this.mergedNamespaces.length > 0) {
  11312. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11313. }
  11314. }
  11315. renderBlock(options) {
  11316. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11317. const memberVariables = this.getMemberVariables();
  11318. const members = Object.entries(memberVariables).map(([name, original]) => {
  11319. if (this.referencedEarly || original.isReassigned) {
  11320. return [
  11321. null,
  11322. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  11323. ];
  11324. }
  11325. return [name, original.getName(getPropertyAccess)];
  11326. });
  11327. members.unshift([null, `__proto__:${_}null`]);
  11328. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11329. if (this.mergedNamespaces.length > 0) {
  11330. const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11331. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
  11332. }
  11333. else {
  11334. // The helper to merge namespaces will also take care of freezing and toStringTag
  11335. if (namespaceToStringTag) {
  11336. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11337. }
  11338. if (freeze) {
  11339. output = `/*#__PURE__*/Object.freeze(${output})`;
  11340. }
  11341. }
  11342. const name = this.getName(getPropertyAccess);
  11343. output = `${cnst} ${name}${_}=${_}${output};`;
  11344. if (format === 'system' && exportNamesByVariable.has(this)) {
  11345. output += `${n}${getSystemExportStatement([this], options)};`;
  11346. }
  11347. return output;
  11348. }
  11349. renderFirst() {
  11350. return this.referencedEarly;
  11351. }
  11352. setMergedNamespaces(mergedNamespaces) {
  11353. this.mergedNamespaces = mergedNamespaces;
  11354. const moduleExecIndex = this.context.getModuleExecIndex();
  11355. for (const identifier of this.references) {
  11356. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  11357. this.referencedEarly = true;
  11358. break;
  11359. }
  11360. }
  11361. }
  11362. }
  11363. NamespaceVariable.prototype.isNamespace = true;
  11364. class SyntheticNamedExportVariable extends Variable {
  11365. constructor(context, name, syntheticNamespace) {
  11366. super(name);
  11367. this.baseVariable = null;
  11368. this.context = context;
  11369. this.module = context.module;
  11370. this.syntheticNamespace = syntheticNamespace;
  11371. }
  11372. getBaseVariable() {
  11373. if (this.baseVariable)
  11374. return this.baseVariable;
  11375. let baseVariable = this.syntheticNamespace;
  11376. while (baseVariable instanceof ExportDefaultVariable ||
  11377. baseVariable instanceof SyntheticNamedExportVariable) {
  11378. if (baseVariable instanceof ExportDefaultVariable) {
  11379. const original = baseVariable.getOriginalVariable();
  11380. if (original === baseVariable)
  11381. break;
  11382. baseVariable = original;
  11383. }
  11384. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11385. baseVariable = baseVariable.syntheticNamespace;
  11386. }
  11387. }
  11388. return (this.baseVariable = baseVariable);
  11389. }
  11390. getBaseVariableName() {
  11391. return this.syntheticNamespace.getBaseVariableName();
  11392. }
  11393. getName(getPropertyAccess) {
  11394. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11395. }
  11396. include() {
  11397. this.included = true;
  11398. this.context.includeVariableInModule(this.syntheticNamespace);
  11399. }
  11400. setRenderNames(baseName, name) {
  11401. super.setRenderNames(baseName, name);
  11402. }
  11403. }
  11404. var BuildPhase;
  11405. (function (BuildPhase) {
  11406. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11407. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11408. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11409. })(BuildPhase || (BuildPhase = {}));
  11410. function getId(m) {
  11411. return m.id;
  11412. }
  11413. function getOriginalLocation(sourcemapChain, location) {
  11414. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11415. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11416. const sourcemap = filteredSourcemapChain.pop();
  11417. const line = sourcemap.mappings[location.line - 1];
  11418. if (line) {
  11419. const filteredLine = line.filter((segment) => segment.length > 1);
  11420. const lastSegment = filteredLine[filteredLine.length - 1];
  11421. for (const segment of filteredLine) {
  11422. if (segment[0] >= location.column || segment === lastSegment) {
  11423. location = {
  11424. column: segment[3],
  11425. line: segment[2] + 1
  11426. };
  11427. continue traceSourcemap;
  11428. }
  11429. }
  11430. }
  11431. throw new Error("Can't resolve original location of error.");
  11432. }
  11433. return location;
  11434. }
  11435. const NOOP = () => { };
  11436. let timers = new Map();
  11437. function getPersistedLabel(label, level) {
  11438. switch (level) {
  11439. case 1:
  11440. return `# ${label}`;
  11441. case 2:
  11442. return `## ${label}`;
  11443. case 3:
  11444. return label;
  11445. default:
  11446. return `${' '.repeat(level - 4)}- ${label}`;
  11447. }
  11448. }
  11449. function timeStartImpl(label, level = 3) {
  11450. label = getPersistedLabel(label, level);
  11451. const startMemory = process$1.memoryUsage().heapUsed;
  11452. const startTime = perf_hooks.performance.now();
  11453. const timer = timers.get(label);
  11454. if (timer === undefined) {
  11455. timers.set(label, {
  11456. memory: 0,
  11457. startMemory,
  11458. startTime,
  11459. time: 0,
  11460. totalMemory: 0
  11461. });
  11462. }
  11463. else {
  11464. timer.startMemory = startMemory;
  11465. timer.startTime = startTime;
  11466. }
  11467. }
  11468. function timeEndImpl(label, level = 3) {
  11469. label = getPersistedLabel(label, level);
  11470. const timer = timers.get(label);
  11471. if (timer !== undefined) {
  11472. const currentMemory = process$1.memoryUsage().heapUsed;
  11473. timer.memory += currentMemory - timer.startMemory;
  11474. timer.time += perf_hooks.performance.now() - timer.startTime;
  11475. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  11476. }
  11477. }
  11478. function getTimings() {
  11479. const newTimings = {};
  11480. for (const [label, { memory, time, totalMemory }] of timers) {
  11481. newTimings[label] = [time, memory, totalMemory];
  11482. }
  11483. return newTimings;
  11484. }
  11485. let timeStart = NOOP;
  11486. let timeEnd = NOOP;
  11487. const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
  11488. function getPluginWithTimers(plugin, index) {
  11489. for (const hook of TIMED_PLUGIN_HOOKS) {
  11490. if (hook in plugin) {
  11491. let timerLabel = `plugin ${index}`;
  11492. if (plugin.name) {
  11493. timerLabel += ` (${plugin.name})`;
  11494. }
  11495. timerLabel += ` - ${hook}`;
  11496. const func = plugin[hook];
  11497. plugin[hook] = function (...args) {
  11498. timeStart(timerLabel, 4);
  11499. const result = func.apply(this, args);
  11500. timeEnd(timerLabel, 4);
  11501. if (result && typeof result.then === 'function') {
  11502. timeStart(`${timerLabel} (async)`, 4);
  11503. return result.then((hookResult) => {
  11504. timeEnd(`${timerLabel} (async)`, 4);
  11505. return hookResult;
  11506. });
  11507. }
  11508. return result;
  11509. };
  11510. }
  11511. }
  11512. return plugin;
  11513. }
  11514. function initialiseTimers(inputOptions) {
  11515. if (inputOptions.perf) {
  11516. timers = new Map();
  11517. timeStart = timeStartImpl;
  11518. timeEnd = timeEndImpl;
  11519. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  11520. }
  11521. else {
  11522. timeStart = NOOP;
  11523. timeEnd = NOOP;
  11524. }
  11525. }
  11526. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  11527. baseModule.isExecuted = true;
  11528. const modules = [baseModule];
  11529. const visitedModules = new Set();
  11530. for (const module of modules) {
  11531. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  11532. if (!(dependency instanceof ExternalModule) &&
  11533. !dependency.isExecuted &&
  11534. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  11535. !visitedModules.has(dependency.id)) {
  11536. dependency.isExecuted = true;
  11537. visitedModules.add(dependency.id);
  11538. modules.push(dependency);
  11539. }
  11540. }
  11541. }
  11542. }
  11543. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  11544. identifier: null,
  11545. localName: MISSING_EXPORT_SHIM_VARIABLE
  11546. };
  11547. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  11548. const searchedModules = searchedNamesAndModules.get(name);
  11549. if (searchedModules) {
  11550. if (searchedModules.has(target)) {
  11551. return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
  11552. }
  11553. searchedModules.add(target);
  11554. }
  11555. else {
  11556. searchedNamesAndModules.set(name, new Set([target]));
  11557. }
  11558. return target.getVariableForExportName(name, {
  11559. importerForSideEffects,
  11560. isExportAllSearch,
  11561. searchedNamesAndModules
  11562. });
  11563. }
  11564. function getAndExtendSideEffectModules(variable, module) {
  11565. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  11566. let currentVariable = variable;
  11567. const referencedVariables = new Set([currentVariable]);
  11568. while (true) {
  11569. const importingModule = currentVariable.module;
  11570. currentVariable =
  11571. currentVariable instanceof ExportDefaultVariable
  11572. ? currentVariable.getDirectOriginalVariable()
  11573. : currentVariable instanceof SyntheticNamedExportVariable
  11574. ? currentVariable.syntheticNamespace
  11575. : null;
  11576. if (!currentVariable || referencedVariables.has(currentVariable)) {
  11577. break;
  11578. }
  11579. referencedVariables.add(currentVariable);
  11580. sideEffectModules.add(importingModule);
  11581. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  11582. if (originalSideEffects) {
  11583. for (const module of originalSideEffects) {
  11584. sideEffectModules.add(module);
  11585. }
  11586. }
  11587. }
  11588. return sideEffectModules;
  11589. }
  11590. class Module {
  11591. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
  11592. this.graph = graph;
  11593. this.id = id;
  11594. this.options = options;
  11595. this.alternativeReexportModules = new Map();
  11596. this.chunkFileNames = new Set();
  11597. this.chunkNames = [];
  11598. this.cycles = new Set();
  11599. this.dependencies = new Set();
  11600. this.dynamicDependencies = new Set();
  11601. this.dynamicImporters = [];
  11602. this.dynamicImports = [];
  11603. this.execIndex = Infinity;
  11604. this.implicitlyLoadedAfter = new Set();
  11605. this.implicitlyLoadedBefore = new Set();
  11606. this.importDescriptions = new Map();
  11607. this.importMetas = [];
  11608. this.importedFromNotTreeshaken = false;
  11609. this.importers = [];
  11610. this.includedDynamicImporters = [];
  11611. this.includedImports = new Set();
  11612. this.isExecuted = false;
  11613. this.isUserDefinedEntryPoint = false;
  11614. this.needsExportShim = false;
  11615. this.sideEffectDependenciesByVariable = new Map();
  11616. this.sources = new Set();
  11617. this.usesTopLevelAwait = false;
  11618. this.allExportNames = null;
  11619. this.ast = null;
  11620. this.exportAllModules = [];
  11621. this.exportAllSources = new Set();
  11622. this.exportNamesByVariable = null;
  11623. this.exportShimVariable = new ExportShimVariable(this);
  11624. this.exports = new Map();
  11625. this.namespaceReexportsByName = new Map();
  11626. this.reexportDescriptions = new Map();
  11627. this.relevantDependencies = null;
  11628. this.syntheticExports = new Map();
  11629. this.syntheticNamespace = null;
  11630. this.transformDependencies = [];
  11631. this.transitiveReexports = null;
  11632. this.excludeFromSourcemap = /\0/.test(id);
  11633. this.context = options.moduleContext(id);
  11634. this.preserveSignature = this.options.preserveEntrySignatures;
  11635. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11636. const module = this;
  11637. const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
  11638. this.info = {
  11639. ast: null,
  11640. code: null,
  11641. get dynamicallyImportedIdResolutions() {
  11642. return dynamicImports
  11643. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  11644. .filter(Boolean);
  11645. },
  11646. get dynamicallyImportedIds() {
  11647. // We cannot use this.dynamicDependencies because this is needed before
  11648. // dynamicDependencies are populated
  11649. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  11650. },
  11651. get dynamicImporters() {
  11652. return dynamicImporters.sort();
  11653. },
  11654. get hasDefaultExport() {
  11655. // This information is only valid after parsing
  11656. if (!module.ast) {
  11657. return null;
  11658. }
  11659. return module.exports.has('default') || reexportDescriptions.has('default');
  11660. },
  11661. get hasModuleSideEffects() {
  11662. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  11663. return this.moduleSideEffects;
  11664. },
  11665. id,
  11666. get implicitlyLoadedAfterOneOf() {
  11667. return Array.from(implicitlyLoadedAfter, getId).sort();
  11668. },
  11669. get implicitlyLoadedBefore() {
  11670. return Array.from(implicitlyLoadedBefore, getId).sort();
  11671. },
  11672. get importedIdResolutions() {
  11673. return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
  11674. },
  11675. get importedIds() {
  11676. // We cannot use this.dependencies because this is needed before
  11677. // dependencies are populated
  11678. return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
  11679. },
  11680. get importers() {
  11681. return importers.sort();
  11682. },
  11683. isEntry,
  11684. isExternal: false,
  11685. get isIncluded() {
  11686. if (graph.phase !== BuildPhase.GENERATE) {
  11687. return null;
  11688. }
  11689. return module.isIncluded();
  11690. },
  11691. meta: { ...meta },
  11692. moduleSideEffects,
  11693. syntheticNamedExports
  11694. };
  11695. // Hide the deprecated key so that it only warns when accessed explicitly
  11696. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  11697. enumerable: false
  11698. });
  11699. }
  11700. basename() {
  11701. const base = require$$0.basename(this.id);
  11702. const ext = require$$0.extname(this.id);
  11703. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  11704. }
  11705. bindReferences() {
  11706. this.ast.bind();
  11707. }
  11708. error(props, pos) {
  11709. this.addLocationToLogProps(props, pos);
  11710. return error(props);
  11711. }
  11712. getAllExportNames() {
  11713. if (this.allExportNames) {
  11714. return this.allExportNames;
  11715. }
  11716. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  11717. for (const module of this.exportAllModules) {
  11718. if (module instanceof ExternalModule) {
  11719. this.allExportNames.add(`*${module.id}`);
  11720. continue;
  11721. }
  11722. for (const name of module.getAllExportNames()) {
  11723. if (name !== 'default')
  11724. this.allExportNames.add(name);
  11725. }
  11726. }
  11727. // We do not count the synthetic namespace as a regular export to hide it
  11728. // from entry signatures and namespace objects
  11729. if (typeof this.info.syntheticNamedExports === 'string') {
  11730. this.allExportNames.delete(this.info.syntheticNamedExports);
  11731. }
  11732. return this.allExportNames;
  11733. }
  11734. getDependenciesToBeIncluded() {
  11735. if (this.relevantDependencies)
  11736. return this.relevantDependencies;
  11737. this.relevantDependencies = new Set();
  11738. const necessaryDependencies = new Set();
  11739. const alwaysCheckedDependencies = new Set();
  11740. const dependencyVariables = new Set(this.includedImports);
  11741. if (this.info.isEntry ||
  11742. this.includedDynamicImporters.length > 0 ||
  11743. this.namespace.included ||
  11744. this.implicitlyLoadedAfter.size > 0) {
  11745. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  11746. const [exportedVariable] = this.getVariableForExportName(exportName);
  11747. if (exportedVariable) {
  11748. dependencyVariables.add(exportedVariable);
  11749. }
  11750. }
  11751. }
  11752. for (let variable of dependencyVariables) {
  11753. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  11754. if (sideEffectDependencies) {
  11755. for (const module of sideEffectDependencies) {
  11756. alwaysCheckedDependencies.add(module);
  11757. }
  11758. }
  11759. if (variable instanceof SyntheticNamedExportVariable) {
  11760. variable = variable.getBaseVariable();
  11761. }
  11762. else if (variable instanceof ExportDefaultVariable) {
  11763. variable = variable.getOriginalVariable();
  11764. }
  11765. necessaryDependencies.add(variable.module);
  11766. }
  11767. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  11768. for (const dependency of this.dependencies) {
  11769. this.relevantDependencies.add(dependency);
  11770. }
  11771. }
  11772. else {
  11773. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  11774. }
  11775. for (const dependency of necessaryDependencies) {
  11776. this.relevantDependencies.add(dependency);
  11777. }
  11778. return this.relevantDependencies;
  11779. }
  11780. getExportNamesByVariable() {
  11781. if (this.exportNamesByVariable) {
  11782. return this.exportNamesByVariable;
  11783. }
  11784. const exportNamesByVariable = new Map();
  11785. for (const exportName of this.getAllExportNames()) {
  11786. let [tracedVariable] = this.getVariableForExportName(exportName);
  11787. if (tracedVariable instanceof ExportDefaultVariable) {
  11788. tracedVariable = tracedVariable.getOriginalVariable();
  11789. }
  11790. if (!tracedVariable ||
  11791. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  11792. continue;
  11793. }
  11794. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  11795. if (existingExportNames) {
  11796. existingExportNames.push(exportName);
  11797. }
  11798. else {
  11799. exportNamesByVariable.set(tracedVariable, [exportName]);
  11800. }
  11801. }
  11802. return (this.exportNamesByVariable = exportNamesByVariable);
  11803. }
  11804. getExports() {
  11805. return Array.from(this.exports.keys());
  11806. }
  11807. getReexports() {
  11808. if (this.transitiveReexports) {
  11809. return this.transitiveReexports;
  11810. }
  11811. // to avoid infinite recursion when using circular `export * from X`
  11812. this.transitiveReexports = [];
  11813. const reexports = new Set(this.reexportDescriptions.keys());
  11814. for (const module of this.exportAllModules) {
  11815. if (module instanceof ExternalModule) {
  11816. reexports.add(`*${module.id}`);
  11817. }
  11818. else {
  11819. for (const name of [...module.getReexports(), ...module.getExports()]) {
  11820. if (name !== 'default')
  11821. reexports.add(name);
  11822. }
  11823. }
  11824. }
  11825. return (this.transitiveReexports = [...reexports]);
  11826. }
  11827. getRenderedExports() {
  11828. // only direct exports are counted here, not reexports at all
  11829. const renderedExports = [];
  11830. const removedExports = [];
  11831. for (const exportName of this.exports.keys()) {
  11832. const [variable] = this.getVariableForExportName(exportName);
  11833. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  11834. }
  11835. return { removedExports, renderedExports };
  11836. }
  11837. getSyntheticNamespace() {
  11838. if (this.syntheticNamespace === null) {
  11839. this.syntheticNamespace = undefined;
  11840. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  11841. ? this.info.syntheticNamedExports
  11842. : 'default', { onlyExplicit: true });
  11843. }
  11844. if (!this.syntheticNamespace) {
  11845. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  11846. }
  11847. return this.syntheticNamespace;
  11848. }
  11849. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  11850. var _a;
  11851. if (name[0] === '*') {
  11852. if (name.length === 1) {
  11853. // export * from './other'
  11854. return [this.namespace];
  11855. }
  11856. // export * from 'external'
  11857. const module = this.graph.modulesById.get(name.slice(1));
  11858. return module.getVariableForExportName('*');
  11859. }
  11860. // export { foo } from './other'
  11861. const reexportDeclaration = this.reexportDescriptions.get(name);
  11862. if (reexportDeclaration) {
  11863. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  11864. if (!variable) {
  11865. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  11866. }
  11867. if (importerForSideEffects) {
  11868. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11869. }
  11870. return [variable];
  11871. }
  11872. const exportDeclaration = this.exports.get(name);
  11873. if (exportDeclaration) {
  11874. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  11875. return [this.exportShimVariable];
  11876. }
  11877. const name = exportDeclaration.localName;
  11878. const variable = this.traceVariable(name, {
  11879. importerForSideEffects,
  11880. searchedNamesAndModules
  11881. });
  11882. if (importerForSideEffects) {
  11883. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  11884. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11885. }
  11886. return [variable];
  11887. }
  11888. if (onlyExplicit) {
  11889. return [null];
  11890. }
  11891. if (name !== 'default') {
  11892. const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  11893. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  11894. if (foundNamespaceReexport[0]) {
  11895. return foundNamespaceReexport;
  11896. }
  11897. }
  11898. if (this.info.syntheticNamedExports) {
  11899. return [
  11900. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  11901. ];
  11902. }
  11903. // we don't want to create shims when we are just
  11904. // probing export * modules for exports
  11905. if (!isExportAllSearch) {
  11906. if (this.options.shimMissingExports) {
  11907. this.shimMissingExport(name);
  11908. return [this.exportShimVariable];
  11909. }
  11910. }
  11911. return [null];
  11912. }
  11913. hasEffects() {
  11914. return (this.info.moduleSideEffects === 'no-treeshake' ||
  11915. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  11916. }
  11917. include() {
  11918. const context = createInclusionContext();
  11919. if (this.ast.shouldBeIncluded(context))
  11920. this.ast.include(context, false);
  11921. }
  11922. includeAllExports(includeNamespaceMembers) {
  11923. if (!this.isExecuted) {
  11924. markModuleAndImpureDependenciesAsExecuted(this);
  11925. this.graph.needsTreeshakingPass = true;
  11926. }
  11927. for (const exportName of this.exports.keys()) {
  11928. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  11929. const variable = this.getVariableForExportName(exportName)[0];
  11930. variable.deoptimizePath(UNKNOWN_PATH);
  11931. if (!variable.included) {
  11932. this.includeVariable(variable);
  11933. }
  11934. }
  11935. }
  11936. for (const name of this.getReexports()) {
  11937. const [variable] = this.getVariableForExportName(name);
  11938. if (variable) {
  11939. variable.deoptimizePath(UNKNOWN_PATH);
  11940. if (!variable.included) {
  11941. this.includeVariable(variable);
  11942. }
  11943. if (variable instanceof ExternalVariable) {
  11944. variable.module.reexported = true;
  11945. }
  11946. }
  11947. }
  11948. if (includeNamespaceMembers) {
  11949. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  11950. }
  11951. }
  11952. includeAllInBundle() {
  11953. this.ast.include(createInclusionContext(), true);
  11954. this.includeAllExports(false);
  11955. }
  11956. isIncluded() {
  11957. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  11958. }
  11959. linkImports() {
  11960. this.addModulesToImportDescriptions(this.importDescriptions);
  11961. this.addModulesToImportDescriptions(this.reexportDescriptions);
  11962. const externalExportAllModules = [];
  11963. for (const source of this.exportAllSources) {
  11964. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  11965. if (module instanceof ExternalModule) {
  11966. externalExportAllModules.push(module);
  11967. continue;
  11968. }
  11969. this.exportAllModules.push(module);
  11970. }
  11971. this.exportAllModules.push(...externalExportAllModules);
  11972. }
  11973. render(options) {
  11974. const magicString = this.magicString.clone();
  11975. this.ast.render(magicString, options);
  11976. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  11977. return magicString;
  11978. }
  11979. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  11980. this.info.code = code;
  11981. this.originalCode = originalCode;
  11982. this.originalSourcemap = originalSourcemap;
  11983. this.sourcemapChain = sourcemapChain;
  11984. if (transformFiles) {
  11985. this.transformFiles = transformFiles;
  11986. }
  11987. this.transformDependencies = transformDependencies;
  11988. this.customTransformCache = customTransformCache;
  11989. this.updateOptions(moduleOptions);
  11990. timeStart('generate ast', 3);
  11991. if (!ast) {
  11992. ast = this.tryParse();
  11993. }
  11994. timeEnd('generate ast', 3);
  11995. this.resolvedIds = resolvedIds || Object.create(null);
  11996. // By default, `id` is the file name. Custom resolvers and loaders
  11997. // can change that, but it makes sense to use it for the source file name
  11998. const fileName = this.id;
  11999. this.magicString = new MagicString(code, {
  12000. filename: (this.excludeFromSourcemap ? null : fileName),
  12001. indentExclusionRanges: []
  12002. });
  12003. timeStart('analyse ast', 3);
  12004. this.astContext = {
  12005. addDynamicImport: this.addDynamicImport.bind(this),
  12006. addExport: this.addExport.bind(this),
  12007. addImport: this.addImport.bind(this),
  12008. addImportMeta: this.addImportMeta.bind(this),
  12009. code,
  12010. deoptimizationTracker: this.graph.deoptimizationTracker,
  12011. error: this.error.bind(this),
  12012. fileName,
  12013. getExports: this.getExports.bind(this),
  12014. getModuleExecIndex: () => this.execIndex,
  12015. getModuleName: this.basename.bind(this),
  12016. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  12017. getReexports: this.getReexports.bind(this),
  12018. importDescriptions: this.importDescriptions,
  12019. includeAllExports: () => this.includeAllExports(true),
  12020. includeDynamicImport: this.includeDynamicImport.bind(this),
  12021. includeVariableInModule: this.includeVariableInModule.bind(this),
  12022. magicString: this.magicString,
  12023. module: this,
  12024. moduleContext: this.context,
  12025. options: this.options,
  12026. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  12027. traceExport: (name) => this.getVariableForExportName(name)[0],
  12028. traceVariable: this.traceVariable.bind(this),
  12029. usesTopLevelAwait: false,
  12030. warn: this.warn.bind(this)
  12031. };
  12032. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  12033. this.namespace = new NamespaceVariable(this.astContext);
  12034. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  12035. this.info.ast = ast;
  12036. timeEnd('analyse ast', 3);
  12037. }
  12038. toJSON() {
  12039. return {
  12040. ast: this.ast.esTreeNode,
  12041. code: this.info.code,
  12042. customTransformCache: this.customTransformCache,
  12043. dependencies: Array.from(this.dependencies, getId),
  12044. id: this.id,
  12045. meta: this.info.meta,
  12046. moduleSideEffects: this.info.moduleSideEffects,
  12047. originalCode: this.originalCode,
  12048. originalSourcemap: this.originalSourcemap,
  12049. resolvedIds: this.resolvedIds,
  12050. sourcemapChain: this.sourcemapChain,
  12051. syntheticNamedExports: this.info.syntheticNamedExports,
  12052. transformDependencies: this.transformDependencies,
  12053. transformFiles: this.transformFiles
  12054. };
  12055. }
  12056. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  12057. const localVariable = this.scope.variables.get(name);
  12058. if (localVariable) {
  12059. return localVariable;
  12060. }
  12061. const importDeclaration = this.importDescriptions.get(name);
  12062. if (importDeclaration) {
  12063. const otherModule = importDeclaration.module;
  12064. if (otherModule instanceof Module && importDeclaration.name === '*') {
  12065. return otherModule.namespace;
  12066. }
  12067. const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  12068. if (!declaration) {
  12069. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  12070. }
  12071. return declaration;
  12072. }
  12073. return null;
  12074. }
  12075. tryParse() {
  12076. try {
  12077. return this.graph.contextParse(this.info.code);
  12078. }
  12079. catch (err) {
  12080. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  12081. if (this.id.endsWith('.json')) {
  12082. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  12083. }
  12084. else if (!this.id.endsWith('.js')) {
  12085. message += ' (Note that you need plugins to import files that are not JavaScript)';
  12086. }
  12087. return this.error({
  12088. code: 'PARSE_ERROR',
  12089. message,
  12090. parserError: err
  12091. }, err.pos);
  12092. }
  12093. }
  12094. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  12095. if (moduleSideEffects != null) {
  12096. this.info.moduleSideEffects = moduleSideEffects;
  12097. }
  12098. if (syntheticNamedExports != null) {
  12099. this.info.syntheticNamedExports = syntheticNamedExports;
  12100. }
  12101. if (meta != null) {
  12102. Object.assign(this.info.meta, meta);
  12103. }
  12104. }
  12105. warn(props, pos) {
  12106. this.addLocationToLogProps(props, pos);
  12107. this.options.onwarn(props);
  12108. }
  12109. addDynamicImport(node) {
  12110. let argument = node.source;
  12111. if (argument instanceof TemplateLiteral) {
  12112. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  12113. argument = argument.quasis[0].value.cooked;
  12114. }
  12115. }
  12116. else if (argument instanceof Literal && typeof argument.value === 'string') {
  12117. argument = argument.value;
  12118. }
  12119. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  12120. }
  12121. addExport(node) {
  12122. if (node instanceof ExportDefaultDeclaration) {
  12123. // export default foo;
  12124. this.exports.set('default', {
  12125. identifier: node.variable.getAssignedVariableName(),
  12126. localName: 'default'
  12127. });
  12128. }
  12129. else if (node instanceof ExportAllDeclaration) {
  12130. const source = node.source.value;
  12131. this.sources.add(source);
  12132. if (node.exported) {
  12133. // export * as name from './other'
  12134. const name = node.exported.name;
  12135. this.reexportDescriptions.set(name, {
  12136. localName: '*',
  12137. module: null,
  12138. source,
  12139. start: node.start
  12140. });
  12141. }
  12142. else {
  12143. // export * from './other'
  12144. this.exportAllSources.add(source);
  12145. }
  12146. }
  12147. else if (node.source instanceof Literal) {
  12148. // export { name } from './other'
  12149. const source = node.source.value;
  12150. this.sources.add(source);
  12151. for (const specifier of node.specifiers) {
  12152. const name = specifier.exported.name;
  12153. this.reexportDescriptions.set(name, {
  12154. localName: specifier.local.name,
  12155. module: null,
  12156. source,
  12157. start: specifier.start
  12158. });
  12159. }
  12160. }
  12161. else if (node.declaration) {
  12162. const declaration = node.declaration;
  12163. if (declaration instanceof VariableDeclaration) {
  12164. // export var { foo, bar } = ...
  12165. // export var foo = 1, bar = 2;
  12166. for (const declarator of declaration.declarations) {
  12167. for (const localName of extractAssignedNames(declarator.id)) {
  12168. this.exports.set(localName, { identifier: null, localName });
  12169. }
  12170. }
  12171. }
  12172. else {
  12173. // export function foo () {}
  12174. const localName = declaration.id.name;
  12175. this.exports.set(localName, { identifier: null, localName });
  12176. }
  12177. }
  12178. else {
  12179. // export { foo, bar, baz }
  12180. for (const specifier of node.specifiers) {
  12181. const localName = specifier.local.name;
  12182. const exportedName = specifier.exported.name;
  12183. this.exports.set(exportedName, { identifier: null, localName });
  12184. }
  12185. }
  12186. }
  12187. addImport(node) {
  12188. const source = node.source.value;
  12189. this.sources.add(source);
  12190. for (const specifier of node.specifiers) {
  12191. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  12192. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  12193. const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
  12194. this.importDescriptions.set(specifier.local.name, {
  12195. module: null,
  12196. name,
  12197. source,
  12198. start: specifier.start
  12199. });
  12200. }
  12201. }
  12202. addImportMeta(node) {
  12203. this.importMetas.push(node);
  12204. }
  12205. addLocationToLogProps(props, pos) {
  12206. props.id = this.id;
  12207. props.pos = pos;
  12208. let code = this.info.code;
  12209. const location = locate(code, pos, { offsetLine: 1 });
  12210. if (location) {
  12211. let { column, line } = location;
  12212. try {
  12213. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  12214. code = this.originalCode;
  12215. }
  12216. catch (err) {
  12217. this.options.onwarn({
  12218. code: 'SOURCEMAP_ERROR',
  12219. id: this.id,
  12220. loc: {
  12221. column,
  12222. file: this.id,
  12223. line
  12224. },
  12225. message: `Error when using sourcemap for reporting an error: ${err.message}`,
  12226. pos
  12227. });
  12228. }
  12229. augmentCodeLocation(props, { column, line }, code, this.id);
  12230. }
  12231. }
  12232. addModulesToImportDescriptions(importDescription) {
  12233. for (const specifier of importDescription.values()) {
  12234. const { id } = this.resolvedIds[specifier.source];
  12235. specifier.module = this.graph.modulesById.get(id);
  12236. }
  12237. }
  12238. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  12239. const handledDependencies = new Set();
  12240. const addSideEffectDependencies = (possibleDependencies) => {
  12241. for (const dependency of possibleDependencies) {
  12242. if (handledDependencies.has(dependency)) {
  12243. continue;
  12244. }
  12245. handledDependencies.add(dependency);
  12246. if (necessaryDependencies.has(dependency)) {
  12247. relevantDependencies.add(dependency);
  12248. continue;
  12249. }
  12250. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  12251. continue;
  12252. }
  12253. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  12254. relevantDependencies.add(dependency);
  12255. continue;
  12256. }
  12257. addSideEffectDependencies(dependency.dependencies);
  12258. }
  12259. };
  12260. addSideEffectDependencies(this.dependencies);
  12261. addSideEffectDependencies(alwaysCheckedDependencies);
  12262. }
  12263. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  12264. let foundSyntheticDeclaration = null;
  12265. const foundInternalDeclarations = new Map();
  12266. const foundExternalDeclarations = new Set();
  12267. for (const module of this.exportAllModules) {
  12268. // Synthetic namespaces should not hide "regular" exports of the same name
  12269. if (module.info.syntheticNamedExports === name) {
  12270. continue;
  12271. }
  12272. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  12273. // We are creating a copy to handle the case where the same binding is
  12274. // imported through different namespace reexports gracefully
  12275. copyNameToModulesMap(searchedNamesAndModules));
  12276. if (module instanceof ExternalModule || indirectExternal) {
  12277. foundExternalDeclarations.add(variable);
  12278. }
  12279. else if (variable instanceof SyntheticNamedExportVariable) {
  12280. if (!foundSyntheticDeclaration) {
  12281. foundSyntheticDeclaration = variable;
  12282. }
  12283. }
  12284. else if (variable) {
  12285. foundInternalDeclarations.set(variable, module);
  12286. }
  12287. }
  12288. if (foundInternalDeclarations.size > 0) {
  12289. const foundDeclarationList = [...foundInternalDeclarations];
  12290. const usedDeclaration = foundDeclarationList[0][0];
  12291. if (foundDeclarationList.length === 1) {
  12292. return [usedDeclaration];
  12293. }
  12294. this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  12295. // TODO we are pretending it was not found while it should behave like "undefined"
  12296. return [null];
  12297. }
  12298. if (foundExternalDeclarations.size > 0) {
  12299. const foundDeclarationList = [...foundExternalDeclarations];
  12300. const usedDeclaration = foundDeclarationList[0];
  12301. if (foundDeclarationList.length > 1) {
  12302. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  12303. }
  12304. return [usedDeclaration, true];
  12305. }
  12306. if (foundSyntheticDeclaration) {
  12307. return [foundSyntheticDeclaration];
  12308. }
  12309. return [null];
  12310. }
  12311. includeAndGetAdditionalMergedNamespaces() {
  12312. const externalNamespaces = new Set();
  12313. const syntheticNamespaces = new Set();
  12314. for (const module of [this, ...this.exportAllModules]) {
  12315. if (module instanceof ExternalModule) {
  12316. const [externalVariable] = module.getVariableForExportName('*');
  12317. externalVariable.include();
  12318. this.includedImports.add(externalVariable);
  12319. externalNamespaces.add(externalVariable);
  12320. }
  12321. else if (module.info.syntheticNamedExports) {
  12322. const syntheticNamespace = module.getSyntheticNamespace();
  12323. syntheticNamespace.include();
  12324. this.includedImports.add(syntheticNamespace);
  12325. syntheticNamespaces.add(syntheticNamespace);
  12326. }
  12327. }
  12328. return [...syntheticNamespaces, ...externalNamespaces];
  12329. }
  12330. includeDynamicImport(node) {
  12331. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  12332. if (resolution instanceof Module) {
  12333. resolution.includedDynamicImporters.push(this);
  12334. resolution.includeAllExports(true);
  12335. }
  12336. }
  12337. includeVariable(variable) {
  12338. if (!variable.included) {
  12339. variable.include();
  12340. this.graph.needsTreeshakingPass = true;
  12341. const variableModule = variable.module;
  12342. if (variableModule instanceof Module) {
  12343. if (!variableModule.isExecuted) {
  12344. markModuleAndImpureDependenciesAsExecuted(variableModule);
  12345. }
  12346. if (variableModule !== this) {
  12347. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  12348. for (const module of sideEffectModules) {
  12349. if (!module.isExecuted) {
  12350. markModuleAndImpureDependenciesAsExecuted(module);
  12351. }
  12352. }
  12353. }
  12354. }
  12355. }
  12356. }
  12357. includeVariableInModule(variable) {
  12358. this.includeVariable(variable);
  12359. const variableModule = variable.module;
  12360. if (variableModule && variableModule !== this) {
  12361. this.includedImports.add(variable);
  12362. }
  12363. }
  12364. shimMissingExport(name) {
  12365. this.options.onwarn({
  12366. code: 'SHIMMED_EXPORT',
  12367. exporter: relativeId(this.id),
  12368. exportName: name,
  12369. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  12370. });
  12371. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  12372. }
  12373. }
  12374. // if there is a cyclic import in the reexport chain, we should not
  12375. // import from the original module but from the cyclic module to not
  12376. // mess up execution order.
  12377. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  12378. if (variable.module instanceof Module && variable.module !== reexporter) {
  12379. const exporterCycles = variable.module.cycles;
  12380. if (exporterCycles.size > 0) {
  12381. const importerCycles = reexporter.cycles;
  12382. for (const cycleSymbol of importerCycles) {
  12383. if (exporterCycles.has(cycleSymbol)) {
  12384. importer.alternativeReexportModules.set(variable, reexporter);
  12385. break;
  12386. }
  12387. }
  12388. }
  12389. }
  12390. }
  12391. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  12392. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  12393. function removeJsExtension(name) {
  12394. return name.endsWith('.js') ? name.slice(0, -3) : name;
  12395. }
  12396. function getCompleteAmdId(options, chunkId) {
  12397. if (options.autoId) {
  12398. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  12399. }
  12400. return options.id || '';
  12401. }
  12402. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  12403. const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  12404. if (!namedExportsMode) {
  12405. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  12406. }
  12407. let exportBlock = '';
  12408. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12409. if (reexports && namedExportsMode) {
  12410. for (const specifier of reexports) {
  12411. if (specifier.reexported !== '*') {
  12412. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12413. if (exportBlock)
  12414. exportBlock += n;
  12415. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  12416. const [left, right] = getDirectReturnFunction([], {
  12417. functionReturn: true,
  12418. lineBreakIndent: null,
  12419. name: null
  12420. });
  12421. exportBlock +=
  12422. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  12423. `${t}enumerable:${_}true,${n}` +
  12424. `${t}get:${_}${left}${importName}${right}${n}});`;
  12425. }
  12426. else {
  12427. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  12428. }
  12429. }
  12430. }
  12431. }
  12432. }
  12433. for (const { exported, local } of exports) {
  12434. const lhs = `exports${getPropertyAccess(exported)}`;
  12435. const rhs = local;
  12436. if (lhs !== rhs) {
  12437. if (exportBlock)
  12438. exportBlock += n;
  12439. exportBlock += `${lhs}${_}=${_}${rhs};`;
  12440. }
  12441. }
  12442. for (const { name, reexports } of dependencies) {
  12443. if (reexports && namedExportsMode) {
  12444. for (const specifier of reexports) {
  12445. if (specifier.reexported === '*') {
  12446. if (exportBlock)
  12447. exportBlock += n;
  12448. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  12449. exportBlock +=
  12450. cnst === 'var' && specifier.needsLiveBinding
  12451. ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  12452. isAsync: false,
  12453. name: null
  12454. })}${copyPropertyIfNecessary});`
  12455. : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
  12456. }
  12457. }
  12458. }
  12459. }
  12460. if (exportBlock) {
  12461. return `${n}${n}${exportBlock}`;
  12462. }
  12463. return '';
  12464. }
  12465. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  12466. if (exports.length > 0) {
  12467. return exports[0].local;
  12468. }
  12469. else {
  12470. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12471. if (reexports) {
  12472. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12473. }
  12474. }
  12475. }
  12476. }
  12477. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  12478. if (imported === 'default') {
  12479. if (!isChunk) {
  12480. const moduleInterop = String(interop(moduleId));
  12481. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  12482. ? defaultVariableName
  12483. : moduleVariableName;
  12484. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  12485. ? `${variableName}${getPropertyAccess('default')}`
  12486. : variableName;
  12487. }
  12488. return depNamedExportsMode
  12489. ? `${moduleVariableName}${getPropertyAccess('default')}`
  12490. : moduleVariableName;
  12491. }
  12492. if (imported === '*') {
  12493. return (isChunk
  12494. ? !depNamedExportsMode
  12495. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  12496. ? namespaceVariableName
  12497. : moduleVariableName;
  12498. }
  12499. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  12500. }
  12501. function getEsModuleValue(getObject) {
  12502. return getObject([['value', 'true']], {
  12503. lineBreakIndent: null
  12504. });
  12505. }
  12506. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  12507. if (hasNamedExports) {
  12508. if (addEsModule) {
  12509. if (addNamespaceToStringTag) {
  12510. return `Object.defineProperties(exports,${_}${getObject([
  12511. ['__esModule', getEsModuleValue(getObject)],
  12512. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  12513. ], {
  12514. lineBreakIndent: null
  12515. })});`;
  12516. }
  12517. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  12518. }
  12519. if (addNamespaceToStringTag) {
  12520. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  12521. }
  12522. }
  12523. return '';
  12524. }
  12525. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  12526. if (needsLiveBinding) {
  12527. const [left, right] = getDirectReturnFunction([], {
  12528. functionReturn: true,
  12529. lineBreakIndent: null,
  12530. name: null
  12531. });
  12532. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  12533. `${t}${t}enumerable:${_}true,${n}` +
  12534. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  12535. }
  12536. return `exports[k]${_}=${_}${name}[k]`;
  12537. };
  12538. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  12539. const { _, cnst, n } = snippets;
  12540. const neededInteropHelpers = new Set();
  12541. const interopStatements = [];
  12542. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  12543. neededInteropHelpers.add(helper);
  12544. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  12545. };
  12546. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12547. if (isChunk) {
  12548. for (const { imported, reexported } of [
  12549. ...(imports || []),
  12550. ...(reexports || [])
  12551. ]) {
  12552. if (imported === '*' && reexported !== '*') {
  12553. if (!namedExportsMode) {
  12554. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  12555. }
  12556. break;
  12557. }
  12558. }
  12559. }
  12560. else {
  12561. const moduleInterop = String(interop(id));
  12562. let hasDefault = false;
  12563. let hasNamespace = false;
  12564. for (const { imported, reexported } of [
  12565. ...(imports || []),
  12566. ...(reexports || [])
  12567. ]) {
  12568. let helper;
  12569. let variableName;
  12570. if (imported === 'default') {
  12571. if (!hasDefault) {
  12572. hasDefault = true;
  12573. if (defaultVariableName !== namespaceVariableName) {
  12574. variableName = defaultVariableName;
  12575. helper = defaultInteropHelpersByInteropType[moduleInterop];
  12576. }
  12577. }
  12578. }
  12579. else if (imported === '*' && reexported !== '*') {
  12580. if (!hasNamespace) {
  12581. hasNamespace = true;
  12582. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  12583. variableName = namespaceVariableName;
  12584. }
  12585. }
  12586. if (helper) {
  12587. addInteropStatement(variableName, helper, name);
  12588. }
  12589. }
  12590. }
  12591. }
  12592. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  12593. }
  12594. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  12595. // The assumption is that this makes sense for all relative ids:
  12596. // https://requirejs.org/docs/api.html#jsfiles
  12597. function removeExtensionFromRelativeAmdId(id) {
  12598. return id[0] === '.' ? removeJsExtension(id) : id;
  12599. }
  12600. const builtins = {
  12601. assert: true,
  12602. buffer: true,
  12603. console: true,
  12604. constants: true,
  12605. domain: true,
  12606. events: true,
  12607. http: true,
  12608. https: true,
  12609. os: true,
  12610. path: true,
  12611. process: true,
  12612. punycode: true,
  12613. querystring: true,
  12614. stream: true,
  12615. string_decoder: true,
  12616. timers: true,
  12617. tty: true,
  12618. url: true,
  12619. util: true,
  12620. vm: true,
  12621. zlib: true
  12622. };
  12623. function warnOnBuiltins(warn, dependencies) {
  12624. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  12625. if (!externalBuiltins.length)
  12626. return;
  12627. warn({
  12628. code: 'MISSING_NODE_BUILTINS',
  12629. 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`,
  12630. modules: externalBuiltins
  12631. });
  12632. }
  12633. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12634. warnOnBuiltins(warn, dependencies);
  12635. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  12636. const args = dependencies.map(m => m.name);
  12637. const { n, getNonArrowFunctionIntro, _ } = snippets;
  12638. if (namedExportsMode && hasExports) {
  12639. args.unshift(`exports`);
  12640. deps.unshift(`'exports'`);
  12641. }
  12642. if (accessedGlobals.has('require')) {
  12643. args.unshift('require');
  12644. deps.unshift(`'require'`);
  12645. }
  12646. if (accessedGlobals.has('module')) {
  12647. args.unshift('module');
  12648. deps.unshift(`'module'`);
  12649. }
  12650. const completeAmdId = getCompleteAmdId(amd, id);
  12651. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12652. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  12653. const useStrict = strict ? `${_}'use strict';` : '';
  12654. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  12655. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12656. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12657. if (namespaceMarkers) {
  12658. namespaceMarkers = n + n + namespaceMarkers;
  12659. }
  12660. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12661. return (magicString
  12662. .indent(t)
  12663. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12664. // cf. https://v8.dev/blog/preparser#pife
  12665. .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
  12666. isAsync: false,
  12667. name: null
  12668. })}{${useStrict}${n}${n}`)
  12669. .append(`${n}${n}}));`));
  12670. }
  12671. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12672. const { _, n } = snippets;
  12673. const useStrict = strict ? `'use strict';${n}${n}` : '';
  12674. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12675. if (namespaceMarkers) {
  12676. namespaceMarkers += n + n;
  12677. }
  12678. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  12679. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12680. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  12681. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  12682. return magicString.append(`${exportBlock}${outro}`);
  12683. }
  12684. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  12685. let importBlock = '';
  12686. let definingVariable = false;
  12687. for (const { id, name, reexports, imports } of dependencies) {
  12688. if (!reexports && !imports) {
  12689. if (importBlock) {
  12690. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  12691. }
  12692. definingVariable = false;
  12693. importBlock += `require('${id}')`;
  12694. }
  12695. else {
  12696. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  12697. definingVariable = true;
  12698. importBlock += `${name}${_}=${_}require('${id}')`;
  12699. }
  12700. }
  12701. if (importBlock) {
  12702. return `${importBlock};${n}${n}`;
  12703. }
  12704. return '';
  12705. }
  12706. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  12707. const { _, n } = snippets;
  12708. const importBlock = getImportBlock(dependencies, _);
  12709. if (importBlock.length > 0)
  12710. intro += importBlock.join(n) + n + n;
  12711. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  12712. if (intro)
  12713. magicString.prepend(intro);
  12714. const exportBlock = getExportBlock(exports, snippets);
  12715. if (exportBlock.length)
  12716. magicString.append(n + n + exportBlock.join(n).trim());
  12717. if (outro)
  12718. magicString.append(outro);
  12719. return magicString.trim();
  12720. }
  12721. function getImportBlock(dependencies, _) {
  12722. const importBlock = [];
  12723. for (const { id, reexports, imports, name } of dependencies) {
  12724. if (!reexports && !imports) {
  12725. importBlock.push(`import${_}'${id}';`);
  12726. continue;
  12727. }
  12728. if (imports) {
  12729. let defaultImport = null;
  12730. let starImport = null;
  12731. const importedNames = [];
  12732. for (const specifier of imports) {
  12733. if (specifier.imported === 'default') {
  12734. defaultImport = specifier;
  12735. }
  12736. else if (specifier.imported === '*') {
  12737. starImport = specifier;
  12738. }
  12739. else {
  12740. importedNames.push(specifier);
  12741. }
  12742. }
  12743. if (starImport) {
  12744. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  12745. }
  12746. if (defaultImport && importedNames.length === 0) {
  12747. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  12748. }
  12749. else if (importedNames.length > 0) {
  12750. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  12751. .map(specifier => {
  12752. if (specifier.imported === specifier.local) {
  12753. return specifier.imported;
  12754. }
  12755. else {
  12756. return `${specifier.imported} as ${specifier.local}`;
  12757. }
  12758. })
  12759. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12760. }
  12761. }
  12762. if (reexports) {
  12763. let starExport = null;
  12764. const namespaceReexports = [];
  12765. const namedReexports = [];
  12766. for (const specifier of reexports) {
  12767. if (specifier.reexported === '*') {
  12768. starExport = specifier;
  12769. }
  12770. else if (specifier.imported === '*') {
  12771. namespaceReexports.push(specifier);
  12772. }
  12773. else {
  12774. namedReexports.push(specifier);
  12775. }
  12776. }
  12777. if (starExport) {
  12778. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  12779. }
  12780. if (namespaceReexports.length > 0) {
  12781. if (!imports ||
  12782. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  12783. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  12784. }
  12785. for (const specifier of namespaceReexports) {
  12786. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  12787. }
  12788. }
  12789. if (namedReexports.length > 0) {
  12790. importBlock.push(`export${_}{${_}${namedReexports
  12791. .map(specifier => {
  12792. if (specifier.imported === specifier.reexported) {
  12793. return specifier.imported;
  12794. }
  12795. else {
  12796. return `${specifier.imported} as ${specifier.reexported}`;
  12797. }
  12798. })
  12799. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12800. }
  12801. }
  12802. }
  12803. return importBlock;
  12804. }
  12805. function getExportBlock(exports, { _, cnst }) {
  12806. const exportBlock = [];
  12807. const exportDeclaration = [];
  12808. for (const specifier of exports) {
  12809. if (specifier.expression) {
  12810. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  12811. }
  12812. exportDeclaration.push(specifier.exported === specifier.local
  12813. ? specifier.local
  12814. : `${specifier.local} as ${specifier.exported}`);
  12815. }
  12816. if (exportDeclaration.length) {
  12817. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  12818. }
  12819. return exportBlock;
  12820. }
  12821. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  12822. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  12823. const parts = name.split('.');
  12824. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12825. parts.pop();
  12826. let propertyPath = root;
  12827. return (parts
  12828. .map(part => {
  12829. propertyPath += getPropertyAccess(part);
  12830. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  12831. })
  12832. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  12833. }
  12834. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  12835. const parts = deepName.split('.');
  12836. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12837. const last = parts.pop();
  12838. let propertyPath = root;
  12839. let deepAssignment = parts
  12840. .map(part => {
  12841. propertyPath += getPropertyAccess(part);
  12842. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12843. })
  12844. .concat(`${propertyPath}${getPropertyAccess(last)}`)
  12845. .join(`,${_}`) + `${_}=${_}${assignment}`;
  12846. if (parts.length > 0) {
  12847. deepAssignment = `(${deepAssignment})`;
  12848. }
  12849. return deepAssignment;
  12850. }
  12851. function trimEmptyImports(dependencies) {
  12852. let i = dependencies.length;
  12853. while (i--) {
  12854. const { imports, reexports } = dependencies[i];
  12855. if (imports || reexports) {
  12856. return dependencies.slice(0, i + 1);
  12857. }
  12858. }
  12859. return [];
  12860. }
  12861. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  12862. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12863. const isNamespaced = name && name.includes('.');
  12864. const useVariableAssignment = !extend && !isNamespaced;
  12865. if (name && useVariableAssignment && !isLegal(name)) {
  12866. return error({
  12867. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  12868. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  12869. });
  12870. }
  12871. warnOnBuiltins(warn, dependencies);
  12872. const external = trimEmptyImports(dependencies);
  12873. const deps = external.map(dep => dep.globalName || 'null');
  12874. const args = external.map(m => m.name);
  12875. if (hasExports && !name) {
  12876. warn({
  12877. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12878. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  12879. });
  12880. }
  12881. if (namedExportsMode && hasExports) {
  12882. if (extend) {
  12883. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12884. args.unshift('exports');
  12885. }
  12886. else {
  12887. deps.unshift('{}');
  12888. args.unshift('exports');
  12889. }
  12890. }
  12891. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12892. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12893. magicString.prepend(`${intro}${interopBlock}`);
  12894. let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
  12895. isAsync: false,
  12896. name: null
  12897. })}{${n}${useStrict}${n}`;
  12898. if (hasExports) {
  12899. if (name && !(extend && namedExportsMode)) {
  12900. wrapperIntro =
  12901. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12902. `${_}=${_}${wrapperIntro}`;
  12903. }
  12904. if (isNamespaced) {
  12905. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  12906. }
  12907. }
  12908. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12909. if (hasExports && !extend && namedExportsMode) {
  12910. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12911. }
  12912. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12913. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  12914. if (namespaceMarkers) {
  12915. namespaceMarkers = n + n + namespaceMarkers;
  12916. }
  12917. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12918. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  12919. }
  12920. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  12921. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12922. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  12923. const registeredName = name ? `'${name}',${_}` : '';
  12924. const wrapperParams = accessedGlobals.has('module')
  12925. ? ['exports', 'module']
  12926. : hasExports
  12927. ? ['exports']
  12928. : [];
  12929. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12930. // cf. https://v8.dev/blog/preparser#pife
  12931. let wrapperStart = `System.register(${registeredName}[` +
  12932. dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
  12933. `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12934. getStarExcludesBlock(starExcludes, t, snippets) +
  12935. getImportBindingsBlock(importBindings, t, snippets) +
  12936. `${n}${t}return${_}{${setters.length
  12937. ? `${n}${t}${t}setters:${_}[${setters
  12938. .map(setter => setter
  12939. ? `${getFunctionIntro(['module'], {
  12940. isAsync: false,
  12941. name: null
  12942. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12943. : systemNullSetters
  12944. ? `null`
  12945. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12946. .join(`,${_}`)}],`
  12947. : ''}${n}`;
  12948. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12949. isAsync: usesTopLevelAwait,
  12950. name: null
  12951. })}{${n}${n}`;
  12952. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12953. magicString.prepend(intro +
  12954. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  12955. getHoistedExportsBlock(exports, t, snippets));
  12956. magicString.append(`${outro}${n}${n}` +
  12957. getSyntheticExportsBlock(exports, t, snippets) +
  12958. getMissingExportsBlock(exports, t, snippets));
  12959. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  12960. }
  12961. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12962. const importBindings = [];
  12963. const setters = [];
  12964. let starExcludes = null;
  12965. for (const { imports, reexports } of dependencies) {
  12966. const setter = [];
  12967. if (imports) {
  12968. for (const specifier of imports) {
  12969. importBindings.push(specifier.local);
  12970. if (specifier.imported === '*') {
  12971. setter.push(`${specifier.local}${_}=${_}module;`);
  12972. }
  12973. else {
  12974. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12975. }
  12976. }
  12977. }
  12978. if (reexports) {
  12979. const reexportedNames = [];
  12980. let hasStarReexport = false;
  12981. for (const { imported, reexported } of reexports) {
  12982. if (reexported === '*') {
  12983. hasStarReexport = true;
  12984. }
  12985. else {
  12986. reexportedNames.push([
  12987. reexported,
  12988. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  12989. ]);
  12990. }
  12991. }
  12992. if (reexportedNames.length > 1 || hasStarReexport) {
  12993. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12994. if (hasStarReexport) {
  12995. if (!starExcludes) {
  12996. starExcludes = getStarExcludes({ dependencies, exports });
  12997. }
  12998. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  12999. }
  13000. else {
  13001. setter.push(`exports(${exportMapping});`);
  13002. }
  13003. }
  13004. else {
  13005. const [key, value] = reexportedNames[0];
  13006. setter.push(`exports('${key}',${_}${value});`);
  13007. }
  13008. }
  13009. setters.push(setter.join(`${n}${t}${t}${t}`));
  13010. }
  13011. return { importBindings, setters, starExcludes };
  13012. }
  13013. const getStarExcludes = ({ dependencies, exports }) => {
  13014. const starExcludes = new Set(exports.map(expt => expt.exported));
  13015. starExcludes.add('default');
  13016. for (const { reexports } of dependencies) {
  13017. if (reexports) {
  13018. for (const reexport of reexports) {
  13019. if (reexport.reexported !== '*')
  13020. starExcludes.add(reexport.reexported);
  13021. }
  13022. }
  13023. }
  13024. return starExcludes;
  13025. };
  13026. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  13027. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
  13028. : '';
  13029. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  13030. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  13031. function getExportsBlock(exports, t, { _, n }) {
  13032. if (exports.length === 0) {
  13033. return '';
  13034. }
  13035. if (exports.length === 1) {
  13036. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  13037. }
  13038. return (`exports({${n}` +
  13039. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  13040. `${n}});${n}${n}`);
  13041. }
  13042. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  13043. .filter(expt => expt.expression)
  13044. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  13045. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  13046. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  13047. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  13048. function globalProp(name, globalVar, getPropertyAccess) {
  13049. if (!name)
  13050. return 'null';
  13051. return `${globalVar}${keypath(name, getPropertyAccess)}`;
  13052. }
  13053. function safeAccess(name, globalVar, { _, getPropertyAccess }) {
  13054. let propertyPath = globalVar;
  13055. return name
  13056. .split('.')
  13057. .map(part => (propertyPath += getPropertyAccess(part)))
  13058. .join(`${_}&&${_}`);
  13059. }
  13060. 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 }) {
  13061. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  13062. const factoryVar = compact ? 'f' : 'factory';
  13063. const globalVar = compact ? 'g' : 'global';
  13064. if (hasExports && !name) {
  13065. return error({
  13066. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  13067. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  13068. });
  13069. }
  13070. warnOnBuiltins(warn, dependencies);
  13071. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  13072. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  13073. const trimmedImports = trimEmptyImports(dependencies);
  13074. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
  13075. const factoryParams = trimmedImports.map(m => m.name);
  13076. if (namedExportsMode && (hasExports || noConflict)) {
  13077. amdDeps.unshift(`'exports'`);
  13078. cjsDeps.unshift(`exports`);
  13079. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  13080. factoryParams.unshift('exports');
  13081. }
  13082. const completeAmdId = getCompleteAmdId(amd, id);
  13083. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  13084. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  13085. const define = amd.define;
  13086. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  13087. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  13088. let iifeExport;
  13089. if (noConflict) {
  13090. const noConflictExportsVar = compact ? 'e' : 'exports';
  13091. let factory;
  13092. if (!namedExportsMode && hasExports) {
  13093. factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  13094. }
  13095. else {
  13096. const module = globalDeps.shift();
  13097. factory =
  13098. `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
  13099. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  13100. }
  13101. iifeExport =
  13102. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  13103. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
  13104. `${t}${t}${factory}${n}` +
  13105. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
  13106. isAsync: false,
  13107. name: null
  13108. })}{${_}` +
  13109. `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
  13110. `${t}})()`;
  13111. }
  13112. else {
  13113. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  13114. if (!namedExportsMode && hasExports) {
  13115. iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
  13116. }
  13117. }
  13118. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  13119. const wrapperParams = [factoryVar];
  13120. if (iifeNeedsGlobal) {
  13121. wrapperParams.unshift(globalVar);
  13122. }
  13123. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  13124. const iifeStart = iifeNeedsGlobal
  13125. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  13126. : '';
  13127. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  13128. const cjsIntro = iifeNeedsGlobal
  13129. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  13130. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  13131. : '';
  13132. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
  13133. cjsIntro +
  13134. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  13135. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  13136. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13137. // cf. https://v8.dev/blog/preparser#pife
  13138. `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
  13139. isAsync: false,
  13140. name: null
  13141. })}{${useStrict}${n}`;
  13142. const wrapperOutro = n + n + '}));';
  13143. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13144. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13145. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  13146. if (namespaceMarkers) {
  13147. namespaceMarkers = n + n + namespaceMarkers;
  13148. }
  13149. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  13150. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  13151. }
  13152. const finalisers = { amd, cjs, es, iife, system, umd };
  13153. class Source {
  13154. constructor(filename, content) {
  13155. this.isOriginal = true;
  13156. this.filename = filename;
  13157. this.content = content;
  13158. }
  13159. traceSegment(line, column, name) {
  13160. return { column, line, name, source: this };
  13161. }
  13162. }
  13163. class Link {
  13164. constructor(map, sources) {
  13165. this.sources = sources;
  13166. this.names = map.names;
  13167. this.mappings = map.mappings;
  13168. }
  13169. traceMappings() {
  13170. const sources = [];
  13171. const sourceIndexMap = new Map();
  13172. const sourcesContent = [];
  13173. const names = [];
  13174. const nameIndexMap = new Map();
  13175. const mappings = [];
  13176. for (const line of this.mappings) {
  13177. const tracedLine = [];
  13178. for (const segment of line) {
  13179. if (segment.length === 1)
  13180. continue;
  13181. const source = this.sources[segment[1]];
  13182. if (!source)
  13183. continue;
  13184. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  13185. if (traced) {
  13186. const { column, line, name, source: { content, filename } } = traced;
  13187. let sourceIndex = sourceIndexMap.get(filename);
  13188. if (sourceIndex === undefined) {
  13189. sourceIndex = sources.length;
  13190. sources.push(filename);
  13191. sourceIndexMap.set(filename, sourceIndex);
  13192. sourcesContent[sourceIndex] = content;
  13193. }
  13194. else if (sourcesContent[sourceIndex] == null) {
  13195. sourcesContent[sourceIndex] = content;
  13196. }
  13197. else if (content != null && sourcesContent[sourceIndex] !== content) {
  13198. return error({
  13199. message: `Multiple conflicting contents for sourcemap source ${filename}`
  13200. });
  13201. }
  13202. const tracedSegment = [segment[0], sourceIndex, line, column];
  13203. if (name) {
  13204. let nameIndex = nameIndexMap.get(name);
  13205. if (nameIndex === undefined) {
  13206. nameIndex = names.length;
  13207. names.push(name);
  13208. nameIndexMap.set(name, nameIndex);
  13209. }
  13210. tracedSegment[4] = nameIndex;
  13211. }
  13212. tracedLine.push(tracedSegment);
  13213. }
  13214. }
  13215. mappings.push(tracedLine);
  13216. }
  13217. return { mappings, names, sources, sourcesContent };
  13218. }
  13219. traceSegment(line, column, name) {
  13220. const segments = this.mappings[line];
  13221. if (!segments)
  13222. return null;
  13223. // binary search through segments for the given column
  13224. let searchStart = 0;
  13225. let searchEnd = segments.length - 1;
  13226. while (searchStart <= searchEnd) {
  13227. const m = (searchStart + searchEnd) >> 1;
  13228. const segment = segments[m];
  13229. // If a sourcemap does not have sufficient resolution to contain a
  13230. // necessary mapping, e.g. because it only contains line information, we
  13231. // use the best approximation we could find
  13232. if (segment[0] === column || searchStart === searchEnd) {
  13233. if (segment.length == 1)
  13234. return null;
  13235. const source = this.sources[segment[1]];
  13236. if (!source)
  13237. return null;
  13238. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  13239. }
  13240. if (segment[0] > column) {
  13241. searchEnd = m - 1;
  13242. }
  13243. else {
  13244. searchStart = m + 1;
  13245. }
  13246. }
  13247. return null;
  13248. }
  13249. }
  13250. function getLinkMap(warn) {
  13251. return function linkMap(source, map) {
  13252. if (map.mappings) {
  13253. return new Link(map, [source]);
  13254. }
  13255. warn({
  13256. code: 'SOURCEMAP_BROKEN',
  13257. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  13258. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  13259. 'documentation for help',
  13260. plugin: map.plugin,
  13261. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  13262. });
  13263. return new Link({
  13264. mappings: [],
  13265. names: []
  13266. }, [source]);
  13267. };
  13268. }
  13269. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  13270. let source;
  13271. if (!originalSourcemap) {
  13272. source = new Source(id, originalCode);
  13273. }
  13274. else {
  13275. const sources = originalSourcemap.sources;
  13276. const sourcesContent = originalSourcemap.sourcesContent || [];
  13277. const directory = require$$0.dirname(id) || '.';
  13278. const sourceRoot = originalSourcemap.sourceRoot || '.';
  13279. const baseSources = sources.map((source, i) => new Source(require$$0.resolve(directory, sourceRoot, source), sourcesContent[i]));
  13280. source = new Link(originalSourcemap, baseSources);
  13281. }
  13282. return sourcemapChain.reduce(linkMap, source);
  13283. }
  13284. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  13285. const linkMap = getLinkMap(warn);
  13286. const moduleSources = modules
  13287. .filter(module => !module.excludeFromSourcemap)
  13288. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  13289. const link = new Link(map, moduleSources);
  13290. const source = bundleSourcemapChain.reduce(linkMap, link);
  13291. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  13292. if (file) {
  13293. const directory = require$$0.dirname(file);
  13294. sources = sources.map((source) => require$$0.relative(directory, source));
  13295. file = require$$0.basename(file);
  13296. }
  13297. sourcesContent = (excludeContent ? null : sourcesContent);
  13298. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  13299. }
  13300. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  13301. if (!sourcemapChain.length) {
  13302. return originalSourcemap;
  13303. }
  13304. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  13305. const map = source.traceMappings();
  13306. return { version: 3, ...map };
  13307. }
  13308. const createHash = () => crypto.createHash('sha256');
  13309. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  13310. amd: deconflictImportsOther,
  13311. cjs: deconflictImportsOther,
  13312. es: deconflictImportsEsmOrSystem,
  13313. iife: deconflictImportsOther,
  13314. system: deconflictImportsEsmOrSystem,
  13315. umd: deconflictImportsOther
  13316. };
  13317. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  13318. const reversedModules = modules.slice().reverse();
  13319. for (const module of reversedModules) {
  13320. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  13321. }
  13322. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  13323. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  13324. for (const module of reversedModules) {
  13325. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13326. }
  13327. }
  13328. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  13329. // This is needed for namespace reexports
  13330. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  13331. if (preserveModules || dependency instanceof ExternalModule) {
  13332. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  13333. }
  13334. }
  13335. for (const variable of imports) {
  13336. const module = variable.module;
  13337. const name = variable.name;
  13338. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  13339. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  13340. }
  13341. else if (module instanceof ExternalModule && name === 'default') {
  13342. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  13343. ? module.suggestedVariableName + '__default'
  13344. : module.suggestedVariableName, usedNames));
  13345. }
  13346. else {
  13347. variable.setRenderNames(null, getSafeName(name, usedNames));
  13348. }
  13349. }
  13350. for (const variable of syntheticExports) {
  13351. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13352. }
  13353. }
  13354. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  13355. for (const chunkOrExternalModule of dependencies) {
  13356. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  13357. }
  13358. for (const externalModuleOrChunk of deconflictedNamespace) {
  13359. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  13360. }
  13361. for (const externalModule of deconflictedDefault) {
  13362. if (deconflictedNamespace.has(externalModule) &&
  13363. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  13364. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  13365. }
  13366. else {
  13367. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  13368. }
  13369. }
  13370. for (const variable of imports) {
  13371. const module = variable.module;
  13372. if (module instanceof ExternalModule) {
  13373. const name = variable.name;
  13374. if (name === 'default') {
  13375. const moduleInterop = String(interop(module.id));
  13376. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13377. ? module.defaultVariableName
  13378. : module.variableName;
  13379. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  13380. variable.setRenderNames(variableName, 'default');
  13381. }
  13382. else {
  13383. variable.setRenderNames(null, variableName);
  13384. }
  13385. }
  13386. else if (name === '*') {
  13387. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  13388. ? module.namespaceVariableName
  13389. : module.variableName);
  13390. }
  13391. else {
  13392. // if the second parameter is `null`, it uses its "name" for the property name
  13393. variable.setRenderNames(module.variableName, null);
  13394. }
  13395. }
  13396. else {
  13397. const chunk = chunkByModule.get(module);
  13398. if (preserveModules && variable.isNamespace) {
  13399. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  13400. }
  13401. else if (chunk.exportMode === 'default') {
  13402. variable.setRenderNames(null, chunk.variableName);
  13403. }
  13404. else {
  13405. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  13406. }
  13407. }
  13408. }
  13409. }
  13410. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  13411. for (const module of modules) {
  13412. for (const variable of module.scope.variables.values()) {
  13413. if (variable.included &&
  13414. // this will only happen for exports in some formats
  13415. !(variable.renderBaseName ||
  13416. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  13417. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13418. }
  13419. }
  13420. if (includedNamespaces.has(module)) {
  13421. const namespace = module.namespace;
  13422. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  13423. }
  13424. }
  13425. }
  13426. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  13427. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  13428. const backSlashRegEx = /\\/g;
  13429. function escapeId(id) {
  13430. if (!id.match(needsEscapeRegEx))
  13431. return id;
  13432. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  13433. }
  13434. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  13435. let nameIndex = 0;
  13436. for (const variable of exports) {
  13437. let [exportName] = variable.name;
  13438. if (exportsByName.has(exportName)) {
  13439. do {
  13440. exportName = toBase64(++nameIndex);
  13441. // skip past leading number identifiers
  13442. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  13443. nameIndex += 9 * 64 ** (exportName.length - 1);
  13444. exportName = toBase64(nameIndex);
  13445. }
  13446. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  13447. }
  13448. exportsByName.set(exportName, variable);
  13449. exportNamesByVariable.set(variable, [exportName]);
  13450. }
  13451. }
  13452. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  13453. for (const variable of exports) {
  13454. let nameIndex = 0;
  13455. let exportName = variable.name;
  13456. while (exportsByName.has(exportName)) {
  13457. exportName = variable.name + '$' + ++nameIndex;
  13458. }
  13459. exportsByName.set(exportName, variable);
  13460. exportNamesByVariable.set(variable, [exportName]);
  13461. }
  13462. }
  13463. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  13464. const exportKeys = chunk.getExportNames();
  13465. if (exportMode === 'default') {
  13466. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13467. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13468. }
  13469. }
  13470. else if (exportMode === 'none' && exportKeys.length) {
  13471. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13472. }
  13473. if (exportMode === 'auto') {
  13474. if (exportKeys.length === 0) {
  13475. exportMode = 'none';
  13476. }
  13477. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13478. if (format === 'cjs' && unsetOptions.has('exports')) {
  13479. warn(errPreferNamedExports(facadeModuleId));
  13480. }
  13481. exportMode = 'default';
  13482. }
  13483. else {
  13484. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  13485. warn(errMixedExport(facadeModuleId, name));
  13486. }
  13487. exportMode = 'named';
  13488. }
  13489. }
  13490. return exportMode;
  13491. }
  13492. function guessIndentString(code) {
  13493. const lines = code.split('\n');
  13494. const tabbed = lines.filter(line => /^\t+/.test(line));
  13495. const spaced = lines.filter(line => /^ {2,}/.test(line));
  13496. if (tabbed.length === 0 && spaced.length === 0) {
  13497. return null;
  13498. }
  13499. // More lines tabbed than spaced? Assume tabs, and
  13500. // default to tabs in the case of a tie (or nothing
  13501. // to go on)
  13502. if (tabbed.length >= spaced.length) {
  13503. return '\t';
  13504. }
  13505. // Otherwise, we need to guess the multiple
  13506. const min = spaced.reduce((previous, current) => {
  13507. const numSpaces = /^ +/.exec(current)[0].length;
  13508. return Math.min(numSpaces, previous);
  13509. }, Infinity);
  13510. return new Array(min + 1).join(' ');
  13511. }
  13512. function getIndentString(modules, options) {
  13513. if (options.indent !== true)
  13514. return options.indent;
  13515. for (const module of modules) {
  13516. const indent = guessIndentString(module.originalCode);
  13517. if (indent !== null)
  13518. return indent;
  13519. }
  13520. return '\t';
  13521. }
  13522. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  13523. const staticDependencyBlocks = [];
  13524. const handledDependencies = new Set();
  13525. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  13526. const module = orderedModules[modulePos];
  13527. if (!handledDependencies.has(module)) {
  13528. const staticDependencies = [];
  13529. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  13530. staticDependencyBlocks.unshift(staticDependencies);
  13531. }
  13532. }
  13533. const dependencies = new Set();
  13534. for (const block of staticDependencyBlocks) {
  13535. for (const dependency of block) {
  13536. dependencies.add(dependency);
  13537. }
  13538. }
  13539. return dependencies;
  13540. }
  13541. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  13542. const dependencies = module.getDependenciesToBeIncluded();
  13543. for (const dependency of dependencies) {
  13544. if (dependency instanceof ExternalModule) {
  13545. staticDependencies.push(dependency);
  13546. continue;
  13547. }
  13548. const dependencyChunk = chunkByModule.get(dependency);
  13549. if (dependencyChunk !== chunk) {
  13550. staticDependencies.push(dependencyChunk);
  13551. continue;
  13552. }
  13553. if (!handledModules.has(dependency)) {
  13554. handledModules.add(dependency);
  13555. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  13556. }
  13557. }
  13558. }
  13559. function decodedSourcemap(map) {
  13560. if (!map)
  13561. return null;
  13562. if (typeof map === 'string') {
  13563. map = JSON.parse(map);
  13564. }
  13565. if (map.mappings === '') {
  13566. return {
  13567. mappings: [],
  13568. names: [],
  13569. sources: [],
  13570. version: 3
  13571. };
  13572. }
  13573. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  13574. return { ...map, mappings };
  13575. }
  13576. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  13577. const renderChunkReducer = (code, result, plugin) => {
  13578. if (result == null)
  13579. return code;
  13580. if (typeof result === 'string')
  13581. result = {
  13582. code: result,
  13583. map: undefined
  13584. };
  13585. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  13586. if (result.map !== null) {
  13587. const map = decodedSourcemap(result.map);
  13588. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  13589. }
  13590. return result.code;
  13591. };
  13592. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  13593. }
  13594. function renderNamePattern(pattern, patternName, replacements) {
  13595. if (isPathFragment(pattern))
  13596. 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.`));
  13597. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  13598. if (!replacements.hasOwnProperty(type)) {
  13599. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  13600. }
  13601. const replacement = replacements[type]();
  13602. if (isPathFragment(replacement))
  13603. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  13604. return replacement;
  13605. });
  13606. }
  13607. function makeUnique(name, existingNames) {
  13608. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  13609. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  13610. return name;
  13611. const ext = require$$0.extname(name);
  13612. name = name.substring(0, name.length - ext.length);
  13613. let uniqueName, uniqueIndex = 1;
  13614. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  13615. ;
  13616. return uniqueName;
  13617. }
  13618. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  13619. function getGlobalName(module, globals, hasExports, warn) {
  13620. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  13621. if (globalName) {
  13622. return globalName;
  13623. }
  13624. if (hasExports) {
  13625. warn({
  13626. code: 'MISSING_GLOBAL_NAME',
  13627. guess: module.variableName,
  13628. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  13629. source: module.id
  13630. });
  13631. return module.variableName;
  13632. }
  13633. }
  13634. class Chunk {
  13635. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  13636. this.orderedModules = orderedModules;
  13637. this.inputOptions = inputOptions;
  13638. this.outputOptions = outputOptions;
  13639. this.unsetOptions = unsetOptions;
  13640. this.pluginDriver = pluginDriver;
  13641. this.modulesById = modulesById;
  13642. this.chunkByModule = chunkByModule;
  13643. this.facadeChunkByModule = facadeChunkByModule;
  13644. this.includedNamespaces = includedNamespaces;
  13645. this.manualChunkAlias = manualChunkAlias;
  13646. this.entryModules = [];
  13647. this.exportMode = 'named';
  13648. this.facadeModule = null;
  13649. this.id = null;
  13650. this.namespaceVariableName = '';
  13651. this.needsExportsShim = false;
  13652. this.variableName = '';
  13653. this.accessedGlobalsByScope = new Map();
  13654. this.dependencies = new Set();
  13655. this.dynamicDependencies = new Set();
  13656. this.dynamicEntryModules = [];
  13657. this.dynamicName = null;
  13658. this.exportNamesByVariable = new Map();
  13659. this.exports = new Set();
  13660. this.exportsByName = new Map();
  13661. this.fileName = null;
  13662. this.implicitEntryModules = [];
  13663. this.implicitlyLoadedBefore = new Set();
  13664. this.imports = new Set();
  13665. this.includedReexportsByModule = new Map();
  13666. this.indentString = undefined;
  13667. // This may only be updated in the constructor
  13668. this.isEmpty = true;
  13669. this.name = null;
  13670. this.renderedDependencies = null;
  13671. this.renderedExports = null;
  13672. this.renderedHash = undefined;
  13673. this.renderedModuleSources = new Map();
  13674. this.renderedModules = Object.create(null);
  13675. this.renderedSource = null;
  13676. this.sortedExportNames = null;
  13677. this.strictFacade = false;
  13678. this.usedModules = undefined;
  13679. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  13680. const chunkModules = new Set(orderedModules);
  13681. for (const module of orderedModules) {
  13682. if (module.namespace.included) {
  13683. includedNamespaces.add(module);
  13684. }
  13685. if (this.isEmpty && module.isIncluded()) {
  13686. this.isEmpty = false;
  13687. }
  13688. if (module.info.isEntry || outputOptions.preserveModules) {
  13689. this.entryModules.push(module);
  13690. }
  13691. for (const importer of module.includedDynamicImporters) {
  13692. if (!chunkModules.has(importer)) {
  13693. this.dynamicEntryModules.push(module);
  13694. // Modules with synthetic exports need an artificial namespace for dynamic imports
  13695. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  13696. includedNamespaces.add(module);
  13697. this.exports.add(module.namespace);
  13698. }
  13699. }
  13700. }
  13701. if (module.implicitlyLoadedAfter.size > 0) {
  13702. this.implicitEntryModules.push(module);
  13703. }
  13704. }
  13705. this.suggestedVariableName = makeLegal(this.generateVariableName());
  13706. }
  13707. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  13708. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  13709. chunk.assignFacadeName(facadeName, facadedModule);
  13710. if (!facadeChunkByModule.has(facadedModule)) {
  13711. facadeChunkByModule.set(facadedModule, chunk);
  13712. }
  13713. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  13714. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  13715. }
  13716. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  13717. facadedModule.info.moduleSideEffects &&
  13718. facadedModule.hasEffects()) {
  13719. chunk.dependencies.add(chunkByModule.get(facadedModule));
  13720. }
  13721. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  13722. chunk.facadeModule = facadedModule;
  13723. chunk.strictFacade = true;
  13724. return chunk;
  13725. }
  13726. canModuleBeFacade(module, exposedVariables) {
  13727. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  13728. for (const exposedVariable of this.exports) {
  13729. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  13730. if (moduleExportNamesByVariable.size === 0 &&
  13731. module.isUserDefinedEntryPoint &&
  13732. module.preserveSignature === 'strict' &&
  13733. this.unsetOptions.has('preserveEntrySignatures')) {
  13734. this.inputOptions.onwarn({
  13735. code: 'EMPTY_FACADE',
  13736. id: module.id,
  13737. 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.`,
  13738. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  13739. });
  13740. }
  13741. return false;
  13742. }
  13743. }
  13744. for (const exposedVariable of exposedVariables) {
  13745. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  13746. return false;
  13747. }
  13748. }
  13749. return true;
  13750. }
  13751. generateExports() {
  13752. this.sortedExportNames = null;
  13753. const remainingExports = new Set(this.exports);
  13754. if (this.facadeModule !== null &&
  13755. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  13756. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  13757. for (const [variable, exportNames] of exportNamesByVariable) {
  13758. this.exportNamesByVariable.set(variable, [...exportNames]);
  13759. for (const exportName of exportNames) {
  13760. this.exportsByName.set(exportName, variable);
  13761. }
  13762. remainingExports.delete(variable);
  13763. }
  13764. }
  13765. if (this.outputOptions.minifyInternalExports) {
  13766. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13767. }
  13768. else {
  13769. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13770. }
  13771. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  13772. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  13773. }
  13774. generateFacades() {
  13775. var _a;
  13776. const facades = [];
  13777. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  13778. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  13779. for (const module of entryModules) {
  13780. if (module.preserveSignature) {
  13781. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  13782. exposedVariables.add(exportedVariable);
  13783. }
  13784. }
  13785. }
  13786. for (const module of entryModules) {
  13787. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  13788. // mapping must run after Set 'name' dedupe
  13789. name => ({
  13790. name
  13791. }));
  13792. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  13793. requiredFacades.push({});
  13794. }
  13795. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  13796. if (requiredFacades.length === 0) {
  13797. requiredFacades.push({});
  13798. }
  13799. if (!this.facadeModule) {
  13800. const needsStrictFacade = module.preserveSignature === 'strict' ||
  13801. (module.preserveSignature === 'exports-only' &&
  13802. module.getExportNamesByVariable().size !== 0);
  13803. if (!needsStrictFacade ||
  13804. this.outputOptions.preserveModules ||
  13805. this.canModuleBeFacade(module, exposedVariables)) {
  13806. this.facadeModule = module;
  13807. this.facadeChunkByModule.set(module, this);
  13808. if (module.preserveSignature) {
  13809. this.strictFacade = needsStrictFacade;
  13810. }
  13811. this.assignFacadeName(requiredFacades.shift(), module);
  13812. }
  13813. }
  13814. for (const facadeName of requiredFacades) {
  13815. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  13816. }
  13817. }
  13818. for (const module of this.dynamicEntryModules) {
  13819. if (module.info.syntheticNamedExports)
  13820. continue;
  13821. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  13822. this.facadeModule = module;
  13823. this.facadeChunkByModule.set(module, this);
  13824. this.strictFacade = true;
  13825. this.dynamicName = getChunkNameFromModule(module);
  13826. }
  13827. else if (this.facadeModule === module &&
  13828. !this.strictFacade &&
  13829. this.canModuleBeFacade(module, exposedVariables)) {
  13830. this.strictFacade = true;
  13831. }
  13832. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  13833. this.includedNamespaces.add(module);
  13834. this.exports.add(module.namespace);
  13835. }
  13836. }
  13837. if (!this.outputOptions.preserveModules) {
  13838. this.addNecessaryImportsForFacades();
  13839. }
  13840. return facades;
  13841. }
  13842. generateId(addons, options, existingNames, includeHash) {
  13843. if (this.fileName !== null) {
  13844. return this.fileName;
  13845. }
  13846. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  13847. ? [options.entryFileNames, 'output.entryFileNames']
  13848. : [options.chunkFileNames, 'output.chunkFileNames'];
  13849. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  13850. format: () => options.format,
  13851. hash: () => includeHash
  13852. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  13853. : '[hash]',
  13854. name: () => this.getChunkName()
  13855. }), existingNames);
  13856. }
  13857. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  13858. const [{ id }] = this.orderedModules;
  13859. const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
  13860. let path;
  13861. const patternOpt = unsetOptions.has('entryFileNames')
  13862. ? '[name][assetExtname].js'
  13863. : options.entryFileNames;
  13864. const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
  13865. if (isAbsolute(sanitizedId)) {
  13866. const currentDir = require$$0.dirname(sanitizedId);
  13867. const extension = require$$0.extname(sanitizedId);
  13868. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13869. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13870. ext: () => extension.substring(1),
  13871. extname: () => extension,
  13872. format: () => options.format,
  13873. name: () => this.getChunkName()
  13874. });
  13875. const currentPath = `${currentDir}/${fileName}`;
  13876. const { preserveModulesRoot } = options;
  13877. if (preserveModulesRoot && require$$0.resolve(currentPath).startsWith(preserveModulesRoot)) {
  13878. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  13879. }
  13880. else {
  13881. path = relative(preserveModulesRelativeDir, currentPath);
  13882. }
  13883. }
  13884. else {
  13885. const extension = require$$0.extname(sanitizedId);
  13886. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13887. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13888. ext: () => extension.substring(1),
  13889. extname: () => extension,
  13890. format: () => options.format,
  13891. name: () => getAliasName(sanitizedId)
  13892. });
  13893. path = `_virtual/${fileName}`;
  13894. }
  13895. return makeUnique(normalize(path), existingNames);
  13896. }
  13897. getChunkInfo() {
  13898. const facadeModule = this.facadeModule;
  13899. const getChunkName = this.getChunkName.bind(this);
  13900. return {
  13901. exports: this.getExportNames(),
  13902. facadeModuleId: facadeModule && facadeModule.id,
  13903. isDynamicEntry: this.dynamicEntryModules.length > 0,
  13904. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  13905. isImplicitEntry: this.implicitEntryModules.length > 0,
  13906. modules: this.renderedModules,
  13907. get name() {
  13908. return getChunkName();
  13909. },
  13910. type: 'chunk'
  13911. };
  13912. }
  13913. getChunkInfoWithFileNames() {
  13914. return Object.assign(this.getChunkInfo(), {
  13915. code: undefined,
  13916. dynamicImports: Array.from(this.dynamicDependencies, getId),
  13917. fileName: this.id,
  13918. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  13919. importedBindings: this.getImportedBindingsPerDependency(),
  13920. imports: Array.from(this.dependencies, getId),
  13921. map: undefined,
  13922. referencedFiles: this.getReferencedFiles()
  13923. });
  13924. }
  13925. getChunkName() {
  13926. var _a;
  13927. return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  13928. }
  13929. getExportNames() {
  13930. var _a;
  13931. return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
  13932. }
  13933. getRenderedHash() {
  13934. if (this.renderedHash)
  13935. return this.renderedHash;
  13936. const hash = createHash();
  13937. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  13938. if (pluginHash) {
  13939. augmentation += pluginHash;
  13940. }
  13941. return augmentation;
  13942. });
  13943. hash.update(hashAugmentation);
  13944. hash.update(this.renderedSource.toString());
  13945. hash.update(this.getExportNames()
  13946. .map(exportName => {
  13947. const variable = this.exportsByName.get(exportName);
  13948. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  13949. })
  13950. .join(','));
  13951. return (this.renderedHash = hash.digest('hex'));
  13952. }
  13953. getVariableExportName(variable) {
  13954. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  13955. return '*';
  13956. }
  13957. return this.exportNamesByVariable.get(variable)[0];
  13958. }
  13959. link() {
  13960. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  13961. for (const module of this.orderedModules) {
  13962. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  13963. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  13964. this.setUpChunkImportsAndExportsForModule(module);
  13965. }
  13966. }
  13967. // prerender allows chunk hashes and names to be generated before finalizing
  13968. preRender(options, inputBase, snippets) {
  13969. const { _, getPropertyAccess, n } = snippets;
  13970. const magicString = new Bundle$1({ separator: `${n}${n}` });
  13971. this.usedModules = [];
  13972. this.indentString = getIndentString(this.orderedModules, options);
  13973. const renderOptions = {
  13974. dynamicImportFunction: options.dynamicImportFunction,
  13975. exportNamesByVariable: this.exportNamesByVariable,
  13976. format: options.format,
  13977. freeze: options.freeze,
  13978. indent: this.indentString,
  13979. namespaceToStringTag: options.namespaceToStringTag,
  13980. outputPluginDriver: this.pluginDriver,
  13981. snippets
  13982. };
  13983. // for static and dynamic entry points, inline the execution list to avoid loading latency
  13984. if (options.hoistTransitiveImports &&
  13985. !this.outputOptions.preserveModules &&
  13986. this.facadeModule !== null) {
  13987. for (const dep of this.dependencies) {
  13988. if (dep instanceof Chunk)
  13989. this.inlineChunkDependencies(dep);
  13990. }
  13991. }
  13992. this.prepareModulesForRendering(snippets);
  13993. this.setIdentifierRenderResolutions(options);
  13994. let hoistedSource = '';
  13995. const renderedModules = this.renderedModules;
  13996. for (const module of this.orderedModules) {
  13997. let renderedLength = 0;
  13998. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  13999. const source = module.render(renderOptions).trim();
  14000. renderedLength = source.length();
  14001. if (renderedLength) {
  14002. if (options.compact && source.lastLine().includes('//'))
  14003. source.append('\n');
  14004. this.renderedModuleSources.set(module, source);
  14005. magicString.addSource(source);
  14006. this.usedModules.push(module);
  14007. }
  14008. const namespace = module.namespace;
  14009. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14010. const rendered = namespace.renderBlock(renderOptions);
  14011. if (namespace.renderFirst())
  14012. hoistedSource += n + rendered;
  14013. else
  14014. magicString.addSource(new MagicString(rendered));
  14015. }
  14016. }
  14017. const { renderedExports, removedExports } = module.getRenderedExports();
  14018. const { renderedModuleSources } = this;
  14019. renderedModules[module.id] = {
  14020. get code() {
  14021. var _a, _b;
  14022. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  14023. },
  14024. originalLength: module.originalCode.length,
  14025. removedExports,
  14026. renderedExports,
  14027. renderedLength
  14028. };
  14029. }
  14030. if (hoistedSource)
  14031. magicString.prepend(hoistedSource + n + n);
  14032. if (this.needsExportsShim) {
  14033. magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  14034. }
  14035. if (options.compact) {
  14036. this.renderedSource = magicString;
  14037. }
  14038. else {
  14039. this.renderedSource = magicString.trim();
  14040. }
  14041. this.renderedHash = undefined;
  14042. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  14043. const chunkName = this.getChunkName();
  14044. this.inputOptions.onwarn({
  14045. chunkName,
  14046. code: 'EMPTY_BUNDLE',
  14047. message: `Generated an empty chunk: "${chunkName}"`
  14048. });
  14049. }
  14050. this.setExternalRenderPaths(options, inputBase);
  14051. this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
  14052. this.renderedExports =
  14053. this.exportMode === 'none'
  14054. ? []
  14055. : this.getChunkExportDeclarations(options.format, getPropertyAccess);
  14056. }
  14057. async render(options, addons, outputChunk, snippets) {
  14058. timeStart('render format', 2);
  14059. const format = options.format;
  14060. const finalise = finalisers[format];
  14061. if (options.dynamicImportFunction && format !== 'es') {
  14062. this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
  14063. }
  14064. // populate ids in the rendered declarations only here
  14065. // as chunk ids known only after prerender
  14066. for (const dependency of this.dependencies) {
  14067. const renderedDependency = this.renderedDependencies.get(dependency);
  14068. if (dependency instanceof ExternalModule) {
  14069. const originalId = dependency.renderPath;
  14070. renderedDependency.id = escapeId(dependency.renormalizeRenderPath
  14071. ? getImportPath(this.id, originalId, false, false)
  14072. : originalId);
  14073. }
  14074. else {
  14075. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  14076. renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
  14077. }
  14078. }
  14079. this.finaliseDynamicImports(options, snippets);
  14080. this.finaliseImportMetas(format, snippets);
  14081. const hasExports = this.renderedExports.length !== 0 ||
  14082. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  14083. let topLevelAwaitModule = null;
  14084. const accessedGlobals = new Set();
  14085. for (const module of this.orderedModules) {
  14086. if (module.usesTopLevelAwait) {
  14087. topLevelAwaitModule = module.id;
  14088. }
  14089. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  14090. if (accessedGlobalVariables) {
  14091. for (const name of accessedGlobalVariables) {
  14092. accessedGlobals.add(name);
  14093. }
  14094. }
  14095. }
  14096. if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
  14097. return error({
  14098. code: 'INVALID_TLA_FORMAT',
  14099. id: topLevelAwaitModule,
  14100. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  14101. });
  14102. }
  14103. /* istanbul ignore next */
  14104. if (!this.id) {
  14105. throw new Error('Internal Error: expecting chunk id');
  14106. }
  14107. const magicString = finalise(this.renderedSource, {
  14108. accessedGlobals,
  14109. dependencies: [...this.renderedDependencies.values()],
  14110. exports: this.renderedExports,
  14111. hasExports,
  14112. id: this.id,
  14113. indent: this.indentString,
  14114. intro: addons.intro,
  14115. isEntryFacade: this.outputOptions.preserveModules ||
  14116. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  14117. isModuleFacade: this.facadeModule !== null,
  14118. namedExportsMode: this.exportMode !== 'default',
  14119. outro: addons.outro,
  14120. snippets,
  14121. usesTopLevelAwait: topLevelAwaitModule !== null,
  14122. warn: this.inputOptions.onwarn
  14123. }, options);
  14124. if (addons.banner)
  14125. magicString.prepend(addons.banner);
  14126. if (addons.footer)
  14127. magicString.append(addons.footer);
  14128. const prevCode = magicString.toString();
  14129. timeEnd('render format', 2);
  14130. let map = null;
  14131. const chunkSourcemapChain = [];
  14132. let code = await renderChunk({
  14133. code: prevCode,
  14134. options,
  14135. outputPluginDriver: this.pluginDriver,
  14136. renderChunk: outputChunk,
  14137. sourcemapChain: chunkSourcemapChain
  14138. });
  14139. if (options.sourcemap) {
  14140. timeStart('sourcemap', 2);
  14141. let file;
  14142. if (options.file)
  14143. file = require$$0.resolve(options.sourcemapFile || options.file);
  14144. else if (options.dir)
  14145. file = require$$0.resolve(options.dir, this.id);
  14146. else
  14147. file = require$$0.resolve(this.id);
  14148. const decodedMap = magicString.generateDecodedMap({});
  14149. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  14150. map.sources = map.sources
  14151. .map(sourcePath => {
  14152. const { sourcemapPathTransform } = options;
  14153. if (sourcemapPathTransform) {
  14154. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  14155. if (typeof newSourcePath !== 'string') {
  14156. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  14157. }
  14158. return newSourcePath;
  14159. }
  14160. return sourcePath;
  14161. })
  14162. .map(normalize);
  14163. timeEnd('sourcemap', 2);
  14164. }
  14165. if (!options.compact && code[code.length - 1] !== '\n')
  14166. code += '\n';
  14167. return { code, map };
  14168. }
  14169. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  14170. for (const module of moduleDependencies) {
  14171. if (module instanceof Module) {
  14172. const chunk = this.chunkByModule.get(module);
  14173. if (chunk && chunk !== this) {
  14174. chunkDependencies.add(chunk);
  14175. }
  14176. }
  14177. else {
  14178. chunkDependencies.add(module);
  14179. }
  14180. }
  14181. }
  14182. addNecessaryImportsForFacades() {
  14183. for (const [module, variables] of this.includedReexportsByModule) {
  14184. if (this.includedNamespaces.has(module)) {
  14185. for (const variable of variables) {
  14186. this.imports.add(variable);
  14187. }
  14188. }
  14189. }
  14190. }
  14191. assignFacadeName({ fileName, name }, facadedModule) {
  14192. if (fileName) {
  14193. this.fileName = fileName;
  14194. }
  14195. else {
  14196. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  14197. }
  14198. }
  14199. checkCircularDependencyImport(variable, importingModule) {
  14200. const variableModule = variable.module;
  14201. if (variableModule instanceof Module) {
  14202. const exportChunk = this.chunkByModule.get(variableModule);
  14203. let alternativeReexportModule;
  14204. do {
  14205. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  14206. if (alternativeReexportModule) {
  14207. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  14208. if (exportingChunk && exportingChunk !== exportChunk) {
  14209. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  14210. }
  14211. importingModule = alternativeReexportModule;
  14212. }
  14213. } while (alternativeReexportModule);
  14214. }
  14215. }
  14216. computeContentHashWithDependencies(addons, options, existingNames) {
  14217. const hash = createHash();
  14218. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
  14219. hash.update(options.format);
  14220. const dependenciesForHashing = new Set([this]);
  14221. for (const current of dependenciesForHashing) {
  14222. if (current instanceof ExternalModule) {
  14223. hash.update(`:${current.renderPath}`);
  14224. }
  14225. else {
  14226. hash.update(current.getRenderedHash());
  14227. hash.update(current.generateId(addons, options, existingNames, false));
  14228. }
  14229. if (current instanceof ExternalModule)
  14230. continue;
  14231. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  14232. dependenciesForHashing.add(dependency);
  14233. }
  14234. }
  14235. return hash.digest('hex').substr(0, 8);
  14236. }
  14237. ensureReexportsAreAvailableForModule(module) {
  14238. const includedReexports = [];
  14239. const map = module.getExportNamesByVariable();
  14240. for (const exportedVariable of map.keys()) {
  14241. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  14242. const importedVariable = isSynthetic
  14243. ? exportedVariable.getBaseVariable()
  14244. : exportedVariable;
  14245. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  14246. this.checkCircularDependencyImport(importedVariable, module);
  14247. const exportingModule = importedVariable.module;
  14248. if (exportingModule instanceof Module) {
  14249. const chunk = this.chunkByModule.get(exportingModule);
  14250. if (chunk && chunk !== this) {
  14251. chunk.exports.add(importedVariable);
  14252. includedReexports.push(importedVariable);
  14253. if (isSynthetic) {
  14254. this.imports.add(importedVariable);
  14255. }
  14256. }
  14257. }
  14258. }
  14259. }
  14260. if (includedReexports.length) {
  14261. this.includedReexportsByModule.set(module, includedReexports);
  14262. }
  14263. }
  14264. finaliseDynamicImports(options, snippets) {
  14265. const stripKnownJsExtensions = options.format === 'amd';
  14266. for (const [module, code] of this.renderedModuleSources) {
  14267. for (const { node, resolution } of module.dynamicImports) {
  14268. const chunk = this.chunkByModule.get(resolution);
  14269. const facadeChunk = this.facadeChunkByModule.get(resolution);
  14270. if (!resolution || !node.included || chunk === this) {
  14271. continue;
  14272. }
  14273. const renderedResolution = resolution instanceof Module
  14274. ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
  14275. : resolution instanceof ExternalModule
  14276. ? `'${escapeId(resolution.renormalizeRenderPath
  14277. ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
  14278. : resolution.renderPath)}'`
  14279. : resolution;
  14280. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  14281. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  14282. chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
  14283. }
  14284. }
  14285. }
  14286. finaliseImportMetas(format, snippets) {
  14287. for (const [module, code] of this.renderedModuleSources) {
  14288. for (const importMeta of module.importMetas) {
  14289. importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
  14290. }
  14291. }
  14292. }
  14293. generateVariableName() {
  14294. if (this.manualChunkAlias) {
  14295. return this.manualChunkAlias;
  14296. }
  14297. const moduleForNaming = this.entryModules[0] ||
  14298. this.implicitEntryModules[0] ||
  14299. this.dynamicEntryModules[0] ||
  14300. this.orderedModules[this.orderedModules.length - 1];
  14301. if (moduleForNaming) {
  14302. return getChunkNameFromModule(moduleForNaming);
  14303. }
  14304. return 'chunk';
  14305. }
  14306. getChunkDependencyDeclarations(options, getPropertyAccess) {
  14307. const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
  14308. const reexportSpecifiers = this.getReexportSpecifiers();
  14309. const dependencyDeclaration = new Map();
  14310. for (const dep of this.dependencies) {
  14311. const imports = importSpecifiers.get(dep) || null;
  14312. const reexports = reexportSpecifiers.get(dep) || null;
  14313. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  14314. dependencyDeclaration.set(dep, {
  14315. defaultVariableName: dep.defaultVariableName,
  14316. globalName: (dep instanceof ExternalModule &&
  14317. (options.format === 'umd' || options.format === 'iife') &&
  14318. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  14319. id: undefined,
  14320. imports,
  14321. isChunk: dep instanceof Chunk,
  14322. name: dep.variableName,
  14323. namedExportsMode,
  14324. namespaceVariableName: dep.namespaceVariableName,
  14325. reexports
  14326. });
  14327. }
  14328. return dependencyDeclaration;
  14329. }
  14330. getChunkExportDeclarations(format, getPropertyAccess) {
  14331. const exports = [];
  14332. for (const exportName of this.getExportNames()) {
  14333. if (exportName[0] === '*')
  14334. continue;
  14335. const variable = this.exportsByName.get(exportName);
  14336. if (!(variable instanceof SyntheticNamedExportVariable)) {
  14337. const module = variable.module;
  14338. if (module && this.chunkByModule.get(module) !== this)
  14339. continue;
  14340. }
  14341. let expression = null;
  14342. let hoisted = false;
  14343. let local = variable.getName(getPropertyAccess);
  14344. if (variable instanceof LocalVariable) {
  14345. for (const declaration of variable.declarations) {
  14346. if (declaration.parent instanceof FunctionDeclaration ||
  14347. (declaration instanceof ExportDefaultDeclaration &&
  14348. declaration.declaration instanceof FunctionDeclaration)) {
  14349. hoisted = true;
  14350. break;
  14351. }
  14352. }
  14353. }
  14354. else if (variable instanceof SyntheticNamedExportVariable) {
  14355. expression = local;
  14356. if (format === 'es') {
  14357. local = variable.renderName;
  14358. }
  14359. }
  14360. exports.push({
  14361. exported: exportName,
  14362. expression,
  14363. hoisted,
  14364. local
  14365. });
  14366. }
  14367. return exports;
  14368. }
  14369. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  14370. const dependencies = new Set();
  14371. const deconflictedDefault = new Set();
  14372. const deconflictedNamespace = new Set();
  14373. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  14374. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  14375. const module = variable.module;
  14376. if (module instanceof ExternalModule) {
  14377. dependencies.add(module);
  14378. if (addNonNamespacesAndInteropHelpers) {
  14379. if (variable.name === 'default') {
  14380. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  14381. deconflictedDefault.add(module);
  14382. }
  14383. }
  14384. else if (variable.name === '*') {
  14385. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  14386. deconflictedNamespace.add(module);
  14387. }
  14388. }
  14389. }
  14390. }
  14391. else {
  14392. const chunk = this.chunkByModule.get(module);
  14393. if (chunk !== this) {
  14394. dependencies.add(chunk);
  14395. if (addNonNamespacesAndInteropHelpers &&
  14396. chunk.exportMode === 'default' &&
  14397. variable.isNamespace) {
  14398. deconflictedNamespace.add(chunk);
  14399. }
  14400. }
  14401. }
  14402. }
  14403. }
  14404. if (addDependenciesWithoutBindings) {
  14405. for (const dependency of this.dependencies) {
  14406. dependencies.add(dependency);
  14407. }
  14408. }
  14409. return { deconflictedDefault, deconflictedNamespace, dependencies };
  14410. }
  14411. getFallbackChunkName() {
  14412. if (this.manualChunkAlias) {
  14413. return this.manualChunkAlias;
  14414. }
  14415. if (this.dynamicName) {
  14416. return this.dynamicName;
  14417. }
  14418. if (this.fileName) {
  14419. return getAliasName(this.fileName);
  14420. }
  14421. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  14422. }
  14423. getImportSpecifiers(getPropertyAccess) {
  14424. const { interop } = this.outputOptions;
  14425. const importsByDependency = new Map();
  14426. for (const variable of this.imports) {
  14427. const module = variable.module;
  14428. let dependency;
  14429. let imported;
  14430. if (module instanceof ExternalModule) {
  14431. dependency = module;
  14432. imported = variable.name;
  14433. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14434. return error(errUnexpectedNamedImport(module.id, imported, false));
  14435. }
  14436. }
  14437. else {
  14438. dependency = this.chunkByModule.get(module);
  14439. imported = dependency.getVariableExportName(variable);
  14440. }
  14441. getOrCreate(importsByDependency, dependency, () => []).push({
  14442. imported,
  14443. local: variable.getName(getPropertyAccess)
  14444. });
  14445. }
  14446. return importsByDependency;
  14447. }
  14448. getImportedBindingsPerDependency() {
  14449. const importSpecifiers = {};
  14450. for (const [dependency, declaration] of this.renderedDependencies) {
  14451. const specifiers = new Set();
  14452. if (declaration.imports) {
  14453. for (const { imported } of declaration.imports) {
  14454. specifiers.add(imported);
  14455. }
  14456. }
  14457. if (declaration.reexports) {
  14458. for (const { imported } of declaration.reexports) {
  14459. specifiers.add(imported);
  14460. }
  14461. }
  14462. importSpecifiers[dependency.id] = [...specifiers];
  14463. }
  14464. return importSpecifiers;
  14465. }
  14466. getReexportSpecifiers() {
  14467. const { externalLiveBindings, interop } = this.outputOptions;
  14468. const reexportSpecifiers = new Map();
  14469. for (let exportName of this.getExportNames()) {
  14470. let dependency;
  14471. let imported;
  14472. let needsLiveBinding = false;
  14473. if (exportName[0] === '*') {
  14474. const id = exportName.substring(1);
  14475. if (interop(id) === 'defaultOnly') {
  14476. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  14477. }
  14478. needsLiveBinding = externalLiveBindings;
  14479. dependency = this.modulesById.get(id);
  14480. imported = exportName = '*';
  14481. }
  14482. else {
  14483. const variable = this.exportsByName.get(exportName);
  14484. if (variable instanceof SyntheticNamedExportVariable)
  14485. continue;
  14486. const module = variable.module;
  14487. if (module instanceof Module) {
  14488. dependency = this.chunkByModule.get(module);
  14489. if (dependency === this)
  14490. continue;
  14491. imported = dependency.getVariableExportName(variable);
  14492. needsLiveBinding = variable.isReassigned;
  14493. }
  14494. else {
  14495. dependency = module;
  14496. imported = variable.name;
  14497. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14498. return error(errUnexpectedNamedImport(module.id, imported, true));
  14499. }
  14500. needsLiveBinding =
  14501. externalLiveBindings &&
  14502. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  14503. }
  14504. }
  14505. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  14506. imported,
  14507. needsLiveBinding,
  14508. reexported: exportName
  14509. });
  14510. }
  14511. return reexportSpecifiers;
  14512. }
  14513. getReferencedFiles() {
  14514. const referencedFiles = [];
  14515. for (const module of this.orderedModules) {
  14516. for (const meta of module.importMetas) {
  14517. const fileName = meta.getReferencedFileName(this.pluginDriver);
  14518. if (fileName) {
  14519. referencedFiles.push(fileName);
  14520. }
  14521. }
  14522. }
  14523. return referencedFiles;
  14524. }
  14525. inlineChunkDependencies(chunk) {
  14526. for (const dep of chunk.dependencies) {
  14527. if (this.dependencies.has(dep))
  14528. continue;
  14529. this.dependencies.add(dep);
  14530. if (dep instanceof Chunk) {
  14531. this.inlineChunkDependencies(dep);
  14532. }
  14533. }
  14534. }
  14535. prepareModulesForRendering(snippets) {
  14536. var _a;
  14537. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  14538. for (const module of this.orderedModules) {
  14539. for (const { node, resolution } of module.dynamicImports) {
  14540. if (node.included) {
  14541. if (resolution instanceof Module) {
  14542. const chunk = this.chunkByModule.get(resolution);
  14543. if (chunk === this) {
  14544. node.setInternalResolution(resolution.namespace);
  14545. }
  14546. else {
  14547. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14548. }
  14549. }
  14550. else {
  14551. node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14552. }
  14553. }
  14554. }
  14555. for (const importMeta of module.importMetas) {
  14556. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  14557. }
  14558. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14559. module.namespace.prepare(accessedGlobalsByScope);
  14560. }
  14561. }
  14562. }
  14563. setExternalRenderPaths(options, inputBase) {
  14564. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  14565. if (dependency instanceof ExternalModule) {
  14566. dependency.setRenderPath(options, inputBase);
  14567. }
  14568. }
  14569. }
  14570. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  14571. const syntheticExports = new Set();
  14572. for (const exportName of this.getExportNames()) {
  14573. const exportVariable = this.exportsByName.get(exportName);
  14574. if (format !== 'es' &&
  14575. format !== 'system' &&
  14576. exportVariable.isReassigned &&
  14577. !exportVariable.isId) {
  14578. exportVariable.setRenderNames('exports', exportName);
  14579. }
  14580. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  14581. syntheticExports.add(exportVariable);
  14582. }
  14583. else {
  14584. exportVariable.setRenderNames(null, null);
  14585. }
  14586. }
  14587. for (const module of this.orderedModules) {
  14588. if (module.needsExportShim) {
  14589. this.needsExportsShim = true;
  14590. break;
  14591. }
  14592. }
  14593. const usedNames = new Set(['Object', 'Promise']);
  14594. if (this.needsExportsShim) {
  14595. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  14596. }
  14597. if (namespaceToStringTag) {
  14598. usedNames.add('Symbol');
  14599. }
  14600. switch (format) {
  14601. case 'system':
  14602. usedNames.add('module').add('exports');
  14603. break;
  14604. case 'es':
  14605. break;
  14606. case 'cjs':
  14607. usedNames.add('module').add('require').add('__filename').add('__dirname');
  14608. // fallthrough
  14609. default:
  14610. usedNames.add('exports');
  14611. for (const helper of HELPER_NAMES) {
  14612. usedNames.add(helper);
  14613. }
  14614. }
  14615. 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);
  14616. }
  14617. setUpChunkImportsAndExportsForModule(module) {
  14618. const moduleImports = new Set(module.includedImports);
  14619. // when we are not preserving modules, we need to make all namespace variables available for
  14620. // rendering the namespace object
  14621. if (!this.outputOptions.preserveModules) {
  14622. if (this.includedNamespaces.has(module)) {
  14623. const memberVariables = module.namespace.getMemberVariables();
  14624. for (const variable of Object.values(memberVariables)) {
  14625. moduleImports.add(variable);
  14626. }
  14627. }
  14628. }
  14629. for (let variable of moduleImports) {
  14630. if (variable instanceof ExportDefaultVariable) {
  14631. variable = variable.getOriginalVariable();
  14632. }
  14633. if (variable instanceof SyntheticNamedExportVariable) {
  14634. variable = variable.getBaseVariable();
  14635. }
  14636. const chunk = this.chunkByModule.get(variable.module);
  14637. if (chunk !== this) {
  14638. this.imports.add(variable);
  14639. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  14640. variable.module instanceof Module) {
  14641. chunk.exports.add(variable);
  14642. this.checkCircularDependencyImport(variable, module);
  14643. }
  14644. }
  14645. }
  14646. if (this.includedNamespaces.has(module) ||
  14647. (module.info.isEntry && module.preserveSignature !== false) ||
  14648. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  14649. this.ensureReexportsAreAvailableForModule(module);
  14650. }
  14651. for (const { node, resolution } of module.dynamicImports) {
  14652. if (node.included &&
  14653. resolution instanceof Module &&
  14654. this.chunkByModule.get(resolution) === this &&
  14655. !this.includedNamespaces.has(resolution)) {
  14656. this.includedNamespaces.add(resolution);
  14657. this.ensureReexportsAreAvailableForModule(resolution);
  14658. }
  14659. }
  14660. }
  14661. }
  14662. function getChunkNameFromModule(module) {
  14663. var _a, _b, _c, _d;
  14664. 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));
  14665. }
  14666. const QUERY_HASH_REGEX = /[?#]/;
  14667. function generateAssetFileName(name, source, outputOptions, bundle) {
  14668. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  14669. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  14670. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  14671. : outputOptions.assetFileNames, 'output.assetFileNames', {
  14672. ext: () => require$$0.extname(emittedName).substring(1),
  14673. extname: () => require$$0.extname(emittedName),
  14674. hash() {
  14675. return createHash()
  14676. .update(emittedName)
  14677. .update(':')
  14678. .update(source)
  14679. .digest('hex')
  14680. .substring(0, 8);
  14681. },
  14682. name: () => emittedName.substring(0, emittedName.length - require$$0.extname(emittedName).length)
  14683. }), bundle);
  14684. }
  14685. function reserveFileNameInBundle(fileName, bundle, warn) {
  14686. if (fileName in bundle) {
  14687. warn(errFileNameConflict(fileName));
  14688. }
  14689. bundle[fileName] = FILE_PLACEHOLDER;
  14690. }
  14691. const FILE_PLACEHOLDER = {
  14692. type: 'placeholder'
  14693. };
  14694. function hasValidType(emittedFile) {
  14695. return Boolean(emittedFile &&
  14696. (emittedFile.type === 'asset' ||
  14697. emittedFile.type === 'chunk'));
  14698. }
  14699. function hasValidName(emittedFile) {
  14700. const validatedName = emittedFile.fileName || emittedFile.name;
  14701. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  14702. }
  14703. function getValidSource(source, emittedFile, fileReferenceId) {
  14704. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  14705. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  14706. 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.`));
  14707. }
  14708. return source;
  14709. }
  14710. function getAssetFileName(file, referenceId) {
  14711. if (typeof file.fileName !== 'string') {
  14712. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  14713. }
  14714. return file.fileName;
  14715. }
  14716. function getChunkFileName(file, facadeChunkByModule) {
  14717. var _a;
  14718. 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));
  14719. if (!fileName)
  14720. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  14721. return fileName;
  14722. }
  14723. class FileEmitter {
  14724. constructor(graph, options, baseFileEmitter) {
  14725. this.graph = graph;
  14726. this.options = options;
  14727. this.bundle = null;
  14728. this.facadeChunkByModule = null;
  14729. this.outputOptions = null;
  14730. this.assertAssetsFinalized = () => {
  14731. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  14732. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  14733. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  14734. }
  14735. };
  14736. this.emitFile = (emittedFile) => {
  14737. if (!hasValidType(emittedFile)) {
  14738. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  14739. }
  14740. if (!hasValidName(emittedFile)) {
  14741. 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}".`));
  14742. }
  14743. if (emittedFile.type === 'chunk') {
  14744. return this.emitChunk(emittedFile);
  14745. }
  14746. return this.emitAsset(emittedFile);
  14747. };
  14748. this.getFileName = (fileReferenceId) => {
  14749. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  14750. if (!emittedFile)
  14751. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  14752. if (emittedFile.type === 'chunk') {
  14753. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  14754. }
  14755. return getAssetFileName(emittedFile, fileReferenceId);
  14756. };
  14757. this.setAssetSource = (referenceId, requestedSource) => {
  14758. const consumedFile = this.filesByReferenceId.get(referenceId);
  14759. if (!consumedFile)
  14760. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  14761. if (consumedFile.type !== 'asset') {
  14762. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  14763. }
  14764. if (consumedFile.source !== undefined) {
  14765. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  14766. }
  14767. const source = getValidSource(requestedSource, consumedFile, referenceId);
  14768. if (this.bundle) {
  14769. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  14770. }
  14771. else {
  14772. consumedFile.source = source;
  14773. }
  14774. };
  14775. this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
  14776. this.outputOptions = outputOptions;
  14777. this.bundle = outputBundle;
  14778. this.facadeChunkByModule = facadeChunkByModule;
  14779. for (const emittedFile of this.filesByReferenceId.values()) {
  14780. if (emittedFile.fileName) {
  14781. reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
  14782. }
  14783. }
  14784. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  14785. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  14786. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
  14787. }
  14788. }
  14789. };
  14790. this.filesByReferenceId = baseFileEmitter
  14791. ? new Map(baseFileEmitter.filesByReferenceId)
  14792. : new Map();
  14793. }
  14794. assignReferenceId(file, idBase) {
  14795. let referenceId;
  14796. do {
  14797. referenceId = createHash()
  14798. .update(referenceId || idBase)
  14799. .digest('hex')
  14800. .substring(0, 8);
  14801. } while (this.filesByReferenceId.has(referenceId));
  14802. this.filesByReferenceId.set(referenceId, file);
  14803. return referenceId;
  14804. }
  14805. emitAsset(emittedAsset) {
  14806. const source = typeof emittedAsset.source !== 'undefined'
  14807. ? getValidSource(emittedAsset.source, emittedAsset, null)
  14808. : undefined;
  14809. const consumedAsset = {
  14810. fileName: emittedAsset.fileName,
  14811. name: emittedAsset.name,
  14812. source,
  14813. type: 'asset'
  14814. };
  14815. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  14816. if (this.bundle) {
  14817. if (emittedAsset.fileName) {
  14818. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  14819. }
  14820. if (source !== undefined) {
  14821. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  14822. }
  14823. }
  14824. return referenceId;
  14825. }
  14826. emitChunk(emittedChunk) {
  14827. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  14828. return error(errInvalidRollupPhaseForChunkEmission());
  14829. }
  14830. if (typeof emittedChunk.id !== 'string') {
  14831. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  14832. }
  14833. const consumedChunk = {
  14834. fileName: emittedChunk.fileName,
  14835. module: null,
  14836. name: emittedChunk.name || emittedChunk.id,
  14837. type: 'chunk'
  14838. };
  14839. this.graph.moduleLoader
  14840. .emitChunk(emittedChunk)
  14841. .then(module => (consumedChunk.module = module))
  14842. .catch(() => {
  14843. // Avoid unhandled Promise rejection as the error will be thrown later
  14844. // once module loading has finished
  14845. });
  14846. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  14847. }
  14848. finalizeAsset(consumedFile, source, referenceId, bundle) {
  14849. const fileName = consumedFile.fileName ||
  14850. findExistingAssetFileNameWithSource(bundle, source) ||
  14851. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  14852. // We must not modify the original assets to avoid interaction between outputs
  14853. const assetWithFileName = { ...consumedFile, fileName, source };
  14854. this.filesByReferenceId.set(referenceId, assetWithFileName);
  14855. const { options } = this;
  14856. bundle[fileName] = {
  14857. fileName,
  14858. get isAsset() {
  14859. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  14860. return true;
  14861. },
  14862. name: consumedFile.name,
  14863. source,
  14864. type: 'asset'
  14865. };
  14866. }
  14867. }
  14868. function findExistingAssetFileNameWithSource(bundle, source) {
  14869. for (const [fileName, outputFile] of Object.entries(bundle)) {
  14870. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  14871. return fileName;
  14872. }
  14873. return null;
  14874. }
  14875. function areSourcesEqual(sourceA, sourceB) {
  14876. if (typeof sourceA === 'string') {
  14877. return sourceA === sourceB;
  14878. }
  14879. if (typeof sourceB === 'string') {
  14880. return false;
  14881. }
  14882. if ('equals' in sourceA) {
  14883. return sourceA.equals(sourceB);
  14884. }
  14885. if (sourceA.length !== sourceB.length) {
  14886. return false;
  14887. }
  14888. for (let index = 0; index < sourceA.length; index++) {
  14889. if (sourceA[index] !== sourceB[index]) {
  14890. return false;
  14891. }
  14892. }
  14893. return true;
  14894. }
  14895. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  14896. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  14897. async function createAddons(options, outputPluginDriver) {
  14898. try {
  14899. let [banner, footer, intro, outro] = await Promise.all([
  14900. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  14901. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  14902. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  14903. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  14904. ]);
  14905. if (intro)
  14906. intro += '\n\n';
  14907. if (outro)
  14908. outro = `\n\n${outro}`;
  14909. if (banner.length)
  14910. banner += '\n';
  14911. if (footer.length)
  14912. footer = '\n' + footer;
  14913. return { banner, footer, intro, outro };
  14914. }
  14915. catch (err) {
  14916. return error({
  14917. code: 'ADDON_ERROR',
  14918. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  14919. \tError Message: ${err.message}`
  14920. });
  14921. }
  14922. }
  14923. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  14924. const chunkDefinitions = [];
  14925. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  14926. const manualChunkModulesByAlias = Object.create(null);
  14927. for (const [entry, alias] of manualChunkAliasByEntry) {
  14928. const chunkModules = (manualChunkModulesByAlias[alias] =
  14929. manualChunkModulesByAlias[alias] || []);
  14930. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  14931. }
  14932. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  14933. chunkDefinitions.push({ alias, modules });
  14934. }
  14935. const assignedEntryPointsByModule = new Map();
  14936. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  14937. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  14938. const staticEntries = new Set(entryModules);
  14939. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  14940. const modulesToHandle = new Set([entry]);
  14941. for (const module of modulesToHandle) {
  14942. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  14943. if (dynamicDependentEntryPoints &&
  14944. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  14945. continue;
  14946. }
  14947. else {
  14948. assignedEntryPoints.add(entry);
  14949. }
  14950. for (const dependency of module.getDependenciesToBeIncluded()) {
  14951. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14952. modulesToHandle.add(dependency);
  14953. }
  14954. }
  14955. }
  14956. }
  14957. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  14958. const entriesToCheck = new Set(entryPoints);
  14959. for (const entry of entriesToCheck) {
  14960. if (!containedIn.has(entry)) {
  14961. if (staticEntries.has(entry))
  14962. return false;
  14963. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  14964. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  14965. entriesToCheck.add(dependentEntry);
  14966. }
  14967. }
  14968. }
  14969. return true;
  14970. }
  14971. for (const entry of entryModules) {
  14972. if (!modulesInManualChunks.has(entry)) {
  14973. assignEntryToStaticDependencies(entry, null);
  14974. }
  14975. }
  14976. for (const entry of dynamicEntryModules) {
  14977. if (!modulesInManualChunks.has(entry)) {
  14978. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  14979. }
  14980. }
  14981. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  14982. return chunkDefinitions;
  14983. }
  14984. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  14985. const modulesToHandle = new Set([entry]);
  14986. for (const module of modulesToHandle) {
  14987. modulesInManualChunks.add(module);
  14988. manualChunkModules.push(module);
  14989. for (const dependency of module.dependencies) {
  14990. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14991. modulesToHandle.add(dependency);
  14992. }
  14993. }
  14994. }
  14995. }
  14996. function analyzeModuleGraph(entryModules) {
  14997. const dynamicEntryModules = new Set();
  14998. const dependentEntryPointsByModule = new Map();
  14999. const entriesToHandle = new Set(entryModules);
  15000. for (const currentEntry of entriesToHandle) {
  15001. const modulesToHandle = new Set([currentEntry]);
  15002. for (const module of modulesToHandle) {
  15003. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  15004. for (const dependency of module.getDependenciesToBeIncluded()) {
  15005. if (!(dependency instanceof ExternalModule)) {
  15006. modulesToHandle.add(dependency);
  15007. }
  15008. }
  15009. for (const { resolution } of module.dynamicImports) {
  15010. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  15011. dynamicEntryModules.add(resolution);
  15012. entriesToHandle.add(resolution);
  15013. }
  15014. }
  15015. for (const dependency of module.implicitlyLoadedBefore) {
  15016. dynamicEntryModules.add(dependency);
  15017. entriesToHandle.add(dependency);
  15018. }
  15019. }
  15020. }
  15021. return { dependentEntryPointsByModule, dynamicEntryModules };
  15022. }
  15023. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  15024. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  15025. for (const dynamicEntry of dynamicEntryModules) {
  15026. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  15027. for (const importer of [
  15028. ...dynamicEntry.includedDynamicImporters,
  15029. ...dynamicEntry.implicitlyLoadedAfter
  15030. ]) {
  15031. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  15032. dynamicDependentEntryPoints.add(entryPoint);
  15033. }
  15034. }
  15035. }
  15036. return dynamicallyDependentEntryPointsByDynamicEntry;
  15037. }
  15038. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  15039. const chunkModules = Object.create(null);
  15040. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  15041. let chunkSignature = '';
  15042. for (const entry of allEntryPoints) {
  15043. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  15044. }
  15045. const chunk = chunkModules[chunkSignature];
  15046. if (chunk) {
  15047. chunk.push(module);
  15048. }
  15049. else {
  15050. chunkModules[chunkSignature] = [module];
  15051. }
  15052. }
  15053. return Object.values(chunkModules).map(modules => ({
  15054. alias: null,
  15055. modules
  15056. }));
  15057. }
  15058. // ported from https://github.com/substack/node-commondir
  15059. function commondir(files) {
  15060. if (files.length === 0)
  15061. return '/';
  15062. if (files.length === 1)
  15063. return require$$0.dirname(files[0]);
  15064. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  15065. const pathSegements = file.split(/\/+|\\+/);
  15066. let i;
  15067. for (i = 0; commonSegments[i] === pathSegements[i] &&
  15068. i < Math.min(commonSegments.length, pathSegements.length); i++)
  15069. ;
  15070. return commonSegments.slice(0, i);
  15071. }, files[0].split(/\/+|\\+/));
  15072. // Windows correctly handles paths with forward-slashes
  15073. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  15074. }
  15075. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  15076. function sortByExecutionOrder(units) {
  15077. units.sort(compareExecIndex);
  15078. }
  15079. function analyseModuleExecution(entryModules) {
  15080. let nextExecIndex = 0;
  15081. const cyclePaths = [];
  15082. const analysedModules = new Set();
  15083. const dynamicImports = new Set();
  15084. const parents = new Map();
  15085. const orderedModules = [];
  15086. const analyseModule = (module) => {
  15087. if (module instanceof Module) {
  15088. for (const dependency of module.dependencies) {
  15089. if (parents.has(dependency)) {
  15090. if (!analysedModules.has(dependency)) {
  15091. cyclePaths.push(getCyclePath(dependency, module, parents));
  15092. }
  15093. continue;
  15094. }
  15095. parents.set(dependency, module);
  15096. analyseModule(dependency);
  15097. }
  15098. for (const dependency of module.implicitlyLoadedBefore) {
  15099. dynamicImports.add(dependency);
  15100. }
  15101. for (const { resolution } of module.dynamicImports) {
  15102. if (resolution instanceof Module) {
  15103. dynamicImports.add(resolution);
  15104. }
  15105. }
  15106. orderedModules.push(module);
  15107. }
  15108. module.execIndex = nextExecIndex++;
  15109. analysedModules.add(module);
  15110. };
  15111. for (const curEntry of entryModules) {
  15112. if (!parents.has(curEntry)) {
  15113. parents.set(curEntry, null);
  15114. analyseModule(curEntry);
  15115. }
  15116. }
  15117. for (const curEntry of dynamicImports) {
  15118. if (!parents.has(curEntry)) {
  15119. parents.set(curEntry, null);
  15120. analyseModule(curEntry);
  15121. }
  15122. }
  15123. return { cyclePaths, orderedModules };
  15124. }
  15125. function getCyclePath(module, parent, parents) {
  15126. const cycleSymbol = Symbol(module.id);
  15127. const path = [relativeId(module.id)];
  15128. let nextModule = parent;
  15129. module.cycles.add(cycleSymbol);
  15130. while (nextModule !== module) {
  15131. nextModule.cycles.add(cycleSymbol);
  15132. path.push(relativeId(nextModule.id));
  15133. nextModule = parents.get(nextModule);
  15134. }
  15135. path.push(path[0]);
  15136. path.reverse();
  15137. return path;
  15138. }
  15139. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  15140. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  15141. const cnst = constBindings ? 'const' : 'var';
  15142. const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
  15143. const getFunctionIntro = arrowFunctions
  15144. ? (params, { isAsync, name }) => {
  15145. const singleParam = params.length === 1;
  15146. const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
  15147. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
  15148. }
  15149. : getNonArrowFunctionIntro;
  15150. const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
  15151. `${getFunctionIntro(params, {
  15152. isAsync: false,
  15153. name
  15154. })}${arrowFunctions
  15155. ? lineBreakIndent
  15156. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  15157. : ''
  15158. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  15159. arrowFunctions
  15160. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  15161. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  15162. ];
  15163. const isValidPropName = reservedNamesAsProps
  15164. ? (name) => validPropName.test(name)
  15165. : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
  15166. return {
  15167. _,
  15168. cnst,
  15169. getDirectReturnFunction,
  15170. getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  15171. const [left, right] = getDirectReturnFunction(params, {
  15172. functionReturn: true,
  15173. lineBreakIndent: null,
  15174. name: null
  15175. });
  15176. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  15177. },
  15178. getFunctionIntro,
  15179. getNonArrowFunctionIntro,
  15180. getObject(fields, { lineBreakIndent }) {
  15181. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  15182. return `{${fields
  15183. .map(([key, value]) => {
  15184. if (key === null)
  15185. return `${prefix}${value}`;
  15186. const needsQuotes = !isValidPropName(key);
  15187. return key === value && objectShorthand && !needsQuotes
  15188. ? prefix + key
  15189. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  15190. })
  15191. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  15192. },
  15193. getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  15194. n,
  15195. s
  15196. };
  15197. }
  15198. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  15199. const validPropName = /^(?!\d)[\w$]+$/;
  15200. class Bundle {
  15201. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  15202. this.outputOptions = outputOptions;
  15203. this.unsetOptions = unsetOptions;
  15204. this.inputOptions = inputOptions;
  15205. this.pluginDriver = pluginDriver;
  15206. this.graph = graph;
  15207. this.facadeChunkByModule = new Map();
  15208. this.includedNamespaces = new Set();
  15209. }
  15210. async generate(isWrite) {
  15211. timeStart('GENERATE', 1);
  15212. const outputBundle = Object.create(null);
  15213. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  15214. try {
  15215. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  15216. timeStart('generate chunks', 2);
  15217. const chunks = await this.generateChunks();
  15218. if (chunks.length > 1) {
  15219. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  15220. }
  15221. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  15222. timeEnd('generate chunks', 2);
  15223. timeStart('render modules', 2);
  15224. // We need to create addons before prerender because at the moment, there
  15225. // can be no async code between prerender and render due to internal state
  15226. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  15227. const snippets = getGenerateCodeSnippets(this.outputOptions);
  15228. this.prerenderChunks(chunks, inputBase, snippets);
  15229. timeEnd('render modules', 2);
  15230. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
  15231. }
  15232. catch (err) {
  15233. await this.pluginDriver.hookParallel('renderError', [err]);
  15234. throw err;
  15235. }
  15236. await this.pluginDriver.hookSeq('generateBundle', [
  15237. this.outputOptions,
  15238. outputBundle,
  15239. isWrite
  15240. ]);
  15241. this.finaliseAssets(outputBundle);
  15242. timeEnd('GENERATE', 1);
  15243. return outputBundle;
  15244. }
  15245. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
  15246. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  15247. for (const chunk of chunks) {
  15248. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  15249. }
  15250. await Promise.all(chunks.map(async (chunk) => {
  15251. const outputChunk = outputBundle[chunk.id];
  15252. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
  15253. }));
  15254. }
  15255. async addManualChunks(manualChunks) {
  15256. const manualChunkAliasByEntry = new Map();
  15257. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  15258. alias,
  15259. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  15260. })));
  15261. for (const { alias, entries } of chunkEntries) {
  15262. for (const entry of entries) {
  15263. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  15264. }
  15265. }
  15266. return manualChunkAliasByEntry;
  15267. }
  15268. assignChunkIds(chunks, inputBase, addons, bundle) {
  15269. const entryChunks = [];
  15270. const otherChunks = [];
  15271. for (const chunk of chunks) {
  15272. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  15273. ? entryChunks
  15274. : otherChunks).push(chunk);
  15275. }
  15276. // make sure entry chunk names take precedence with regard to deconflicting
  15277. const chunksForNaming = entryChunks.concat(otherChunks);
  15278. for (const chunk of chunksForNaming) {
  15279. if (this.outputOptions.file) {
  15280. chunk.id = require$$0.basename(this.outputOptions.file);
  15281. }
  15282. else if (this.outputOptions.preserveModules) {
  15283. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  15284. }
  15285. else {
  15286. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  15287. }
  15288. bundle[chunk.id] = FILE_PLACEHOLDER;
  15289. }
  15290. }
  15291. assignManualChunks(getManualChunk) {
  15292. const manualChunkAliasesWithEntry = [];
  15293. const manualChunksApi = {
  15294. getModuleIds: () => this.graph.modulesById.keys(),
  15295. getModuleInfo: this.graph.getModuleInfo
  15296. };
  15297. for (const module of this.graph.modulesById.values()) {
  15298. if (module instanceof Module) {
  15299. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  15300. if (typeof manualChunkAlias === 'string') {
  15301. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  15302. }
  15303. }
  15304. }
  15305. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  15306. const manualChunkAliasByEntry = new Map();
  15307. for (const [alias, module] of manualChunkAliasesWithEntry) {
  15308. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  15309. }
  15310. return manualChunkAliasByEntry;
  15311. }
  15312. finaliseAssets(outputBundle) {
  15313. for (const file of Object.values(outputBundle)) {
  15314. if (!file.type) {
  15315. 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);
  15316. file.type = 'asset';
  15317. }
  15318. if (this.outputOptions.validate && 'code' in file) {
  15319. try {
  15320. this.graph.contextParse(file.code, {
  15321. allowHashBang: true,
  15322. ecmaVersion: 'latest'
  15323. });
  15324. }
  15325. catch (err) {
  15326. this.inputOptions.onwarn(errChunkInvalid(file, err));
  15327. }
  15328. }
  15329. }
  15330. this.pluginDriver.finaliseAssets();
  15331. }
  15332. async generateChunks() {
  15333. const { manualChunks } = this.outputOptions;
  15334. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  15335. ? await this.addManualChunks(manualChunks)
  15336. : this.assignManualChunks(manualChunks);
  15337. const chunks = [];
  15338. const chunkByModule = new Map();
  15339. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  15340. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  15341. : this.outputOptions.preserveModules
  15342. ? getIncludedModules(this.graph.modulesById).map(module => ({
  15343. alias: null,
  15344. modules: [module]
  15345. }))
  15346. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  15347. sortByExecutionOrder(modules);
  15348. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  15349. chunks.push(chunk);
  15350. for (const module of modules) {
  15351. chunkByModule.set(module, chunk);
  15352. }
  15353. }
  15354. for (const chunk of chunks) {
  15355. chunk.link();
  15356. }
  15357. const facades = [];
  15358. for (const chunk of chunks) {
  15359. facades.push(...chunk.generateFacades());
  15360. }
  15361. return [...chunks, ...facades];
  15362. }
  15363. prerenderChunks(chunks, inputBase, snippets) {
  15364. for (const chunk of chunks) {
  15365. chunk.generateExports();
  15366. }
  15367. for (const chunk of chunks) {
  15368. chunk.preRender(this.outputOptions, inputBase, snippets);
  15369. }
  15370. }
  15371. }
  15372. function getAbsoluteEntryModulePaths(chunks) {
  15373. const absoluteEntryModulePaths = [];
  15374. for (const chunk of chunks) {
  15375. for (const entryModule of chunk.entryModules) {
  15376. if (isAbsolute(entryModule.id)) {
  15377. absoluteEntryModulePaths.push(entryModule.id);
  15378. }
  15379. }
  15380. }
  15381. return absoluteEntryModulePaths;
  15382. }
  15383. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  15384. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  15385. return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  15386. if (typeof outputOptions.file === 'string')
  15387. 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'));
  15388. if (outputOptions.sourcemapFile)
  15389. return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
  15390. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  15391. 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'));
  15392. }
  15393. function getIncludedModules(modulesById) {
  15394. return [...modulesById.values()].filter((module) => module instanceof Module &&
  15395. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  15396. }
  15397. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  15398. const existingAlias = manualChunkAliasByEntry.get(module);
  15399. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  15400. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  15401. }
  15402. manualChunkAliasByEntry.set(module, alias);
  15403. }
  15404. // This file was generated. Do not modify manually!
  15405. 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];
  15406. // This file was generated. Do not modify manually!
  15407. 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];
  15408. // This file was generated. Do not modify manually!
  15409. 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";
  15410. // This file was generated. Do not modify manually!
  15411. 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";
  15412. // These are a run-length and offset encoded representation of the
  15413. // Reserved word lists for various dialects of the language
  15414. var reservedWords = {
  15415. 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",
  15416. 5: "class enum extends super const export import",
  15417. 6: "enum",
  15418. strict: "implements interface let package private protected public static yield",
  15419. strictBind: "eval arguments"
  15420. };
  15421. // And the keywords
  15422. 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";
  15423. var keywords$1 = {
  15424. 5: ecma5AndLessKeywords,
  15425. "5module": ecma5AndLessKeywords + " export import",
  15426. 6: ecma5AndLessKeywords + " const class extends export import super"
  15427. };
  15428. var keywordRelationalOperator = /^in(stanceof)?$/;
  15429. // ## Character categories
  15430. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  15431. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  15432. // This has a complexity linear to the value of the code. The
  15433. // assumption is that looking up astral identifier characters is
  15434. // rare.
  15435. function isInAstralSet(code, set) {
  15436. var pos = 0x10000;
  15437. for (var i = 0; i < set.length; i += 2) {
  15438. pos += set[i];
  15439. if (pos > code) { return false }
  15440. pos += set[i + 1];
  15441. if (pos >= code) { return true }
  15442. }
  15443. }
  15444. // Test whether a given character code starts an identifier.
  15445. function isIdentifierStart(code, astral) {
  15446. if (code < 65) { return code === 36 }
  15447. if (code < 91) { return true }
  15448. if (code < 97) { return code === 95 }
  15449. if (code < 123) { return true }
  15450. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  15451. if (astral === false) { return false }
  15452. return isInAstralSet(code, astralIdentifierStartCodes)
  15453. }
  15454. // Test whether a given character is part of an identifier.
  15455. function isIdentifierChar(code, astral) {
  15456. if (code < 48) { return code === 36 }
  15457. if (code < 58) { return true }
  15458. if (code < 65) { return false }
  15459. if (code < 91) { return true }
  15460. if (code < 97) { return code === 95 }
  15461. if (code < 123) { return true }
  15462. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  15463. if (astral === false) { return false }
  15464. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  15465. }
  15466. // ## Token types
  15467. // The assignment of fine-grained, information-carrying type objects
  15468. // allows the tokenizer to store the information it has about a
  15469. // token in a way that is very cheap for the parser to look up.
  15470. // All token type variables start with an underscore, to make them
  15471. // easy to recognize.
  15472. // The `beforeExpr` property is used to disambiguate between regular
  15473. // expressions and divisions. It is set on all token types that can
  15474. // be followed by an expression (thus, a slash after them would be a
  15475. // regular expression).
  15476. //
  15477. // The `startsExpr` property is used to check if the token ends a
  15478. // `yield` expression. It is set on all token types that either can
  15479. // directly start an expression (like a quotation mark) or can
  15480. // continue an expression (like the body of a string).
  15481. //
  15482. // `isLoop` marks a keyword as starting a loop, which is important
  15483. // to know when parsing a label, in order to allow or disallow
  15484. // continue jumps to that label.
  15485. var TokenType = function TokenType(label, conf) {
  15486. if ( conf === void 0 ) conf = {};
  15487. this.label = label;
  15488. this.keyword = conf.keyword;
  15489. this.beforeExpr = !!conf.beforeExpr;
  15490. this.startsExpr = !!conf.startsExpr;
  15491. this.isLoop = !!conf.isLoop;
  15492. this.isAssign = !!conf.isAssign;
  15493. this.prefix = !!conf.prefix;
  15494. this.postfix = !!conf.postfix;
  15495. this.binop = conf.binop || null;
  15496. this.updateContext = null;
  15497. };
  15498. function binop(name, prec) {
  15499. return new TokenType(name, {beforeExpr: true, binop: prec})
  15500. }
  15501. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  15502. // Map keyword names to token types.
  15503. var keywords = {};
  15504. // Succinct definitions of keyword token types
  15505. function kw(name, options) {
  15506. if ( options === void 0 ) options = {};
  15507. options.keyword = name;
  15508. return keywords[name] = new TokenType(name, options)
  15509. }
  15510. var types$1 = {
  15511. num: new TokenType("num", startsExpr),
  15512. regexp: new TokenType("regexp", startsExpr),
  15513. string: new TokenType("string", startsExpr),
  15514. name: new TokenType("name", startsExpr),
  15515. privateId: new TokenType("privateId", startsExpr),
  15516. eof: new TokenType("eof"),
  15517. // Punctuation token types.
  15518. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  15519. bracketR: new TokenType("]"),
  15520. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  15521. braceR: new TokenType("}"),
  15522. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  15523. parenR: new TokenType(")"),
  15524. comma: new TokenType(",", beforeExpr),
  15525. semi: new TokenType(";", beforeExpr),
  15526. colon: new TokenType(":", beforeExpr),
  15527. dot: new TokenType("."),
  15528. question: new TokenType("?", beforeExpr),
  15529. questionDot: new TokenType("?."),
  15530. arrow: new TokenType("=>", beforeExpr),
  15531. template: new TokenType("template"),
  15532. invalidTemplate: new TokenType("invalidTemplate"),
  15533. ellipsis: new TokenType("...", beforeExpr),
  15534. backQuote: new TokenType("`", startsExpr),
  15535. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  15536. // Operators. These carry several kinds of properties to help the
  15537. // parser use them properly (the presence of these properties is
  15538. // what categorizes them as operators).
  15539. //
  15540. // `binop`, when present, specifies that this operator is a binary
  15541. // operator, and will refer to its precedence.
  15542. //
  15543. // `prefix` and `postfix` mark the operator as a prefix or postfix
  15544. // unary operator.
  15545. //
  15546. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  15547. // binary operators with a very low precedence, that should result
  15548. // in AssignmentExpression nodes.
  15549. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  15550. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  15551. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  15552. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  15553. logicalOR: binop("||", 1),
  15554. logicalAND: binop("&&", 2),
  15555. bitwiseOR: binop("|", 3),
  15556. bitwiseXOR: binop("^", 4),
  15557. bitwiseAND: binop("&", 5),
  15558. equality: binop("==/!=/===/!==", 6),
  15559. relational: binop("</>/<=/>=", 7),
  15560. bitShift: binop("<</>>/>>>", 8),
  15561. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  15562. modulo: binop("%", 10),
  15563. star: binop("*", 10),
  15564. slash: binop("/", 10),
  15565. starstar: new TokenType("**", {beforeExpr: true}),
  15566. coalesce: binop("??", 1),
  15567. // Keyword token types.
  15568. _break: kw("break"),
  15569. _case: kw("case", beforeExpr),
  15570. _catch: kw("catch"),
  15571. _continue: kw("continue"),
  15572. _debugger: kw("debugger"),
  15573. _default: kw("default", beforeExpr),
  15574. _do: kw("do", {isLoop: true, beforeExpr: true}),
  15575. _else: kw("else", beforeExpr),
  15576. _finally: kw("finally"),
  15577. _for: kw("for", {isLoop: true}),
  15578. _function: kw("function", startsExpr),
  15579. _if: kw("if"),
  15580. _return: kw("return", beforeExpr),
  15581. _switch: kw("switch"),
  15582. _throw: kw("throw", beforeExpr),
  15583. _try: kw("try"),
  15584. _var: kw("var"),
  15585. _const: kw("const"),
  15586. _while: kw("while", {isLoop: true}),
  15587. _with: kw("with"),
  15588. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  15589. _this: kw("this", startsExpr),
  15590. _super: kw("super", startsExpr),
  15591. _class: kw("class", startsExpr),
  15592. _extends: kw("extends", beforeExpr),
  15593. _export: kw("export"),
  15594. _import: kw("import", startsExpr),
  15595. _null: kw("null", startsExpr),
  15596. _true: kw("true", startsExpr),
  15597. _false: kw("false", startsExpr),
  15598. _in: kw("in", {beforeExpr: true, binop: 7}),
  15599. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  15600. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  15601. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  15602. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  15603. };
  15604. // Matches a whole line break (where CRLF is considered a single
  15605. // line break). Used to count lines.
  15606. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  15607. var lineBreakG = new RegExp(lineBreak.source, "g");
  15608. function isNewLine(code) {
  15609. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15610. }
  15611. function nextLineBreak(code, from, end) {
  15612. if ( end === void 0 ) end = code.length;
  15613. for (var i = from; i < end; i++) {
  15614. var next = code.charCodeAt(i);
  15615. if (isNewLine(next))
  15616. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15617. }
  15618. return -1
  15619. }
  15620. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15621. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15622. var ref = Object.prototype;
  15623. var hasOwnProperty = ref.hasOwnProperty;
  15624. var toString = ref.toString;
  15625. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15626. hasOwnProperty.call(obj, propName)
  15627. ); });
  15628. var isArray = Array.isArray || (function (obj) { return (
  15629. toString.call(obj) === "[object Array]"
  15630. ); });
  15631. function wordsRegexp(words) {
  15632. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15633. }
  15634. function codePointToString(code) {
  15635. // UTF-16 Decoding
  15636. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15637. code -= 0x10000;
  15638. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15639. }
  15640. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15641. // These are used when `options.locations` is on, for the
  15642. // `startLoc` and `endLoc` properties.
  15643. var Position = function Position(line, col) {
  15644. this.line = line;
  15645. this.column = col;
  15646. };
  15647. Position.prototype.offset = function offset (n) {
  15648. return new Position(this.line, this.column + n)
  15649. };
  15650. var SourceLocation = function SourceLocation(p, start, end) {
  15651. this.start = start;
  15652. this.end = end;
  15653. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15654. };
  15655. // The `getLineInfo` function is mostly useful when the
  15656. // `locations` option is off (for performance reasons) and you
  15657. // want to find the line/column position for a given character
  15658. // offset. `input` should be the code string that the offset refers
  15659. // into.
  15660. function getLineInfo(input, offset) {
  15661. for (var line = 1, cur = 0;;) {
  15662. var nextBreak = nextLineBreak(input, cur, offset);
  15663. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15664. ++line;
  15665. cur = nextBreak;
  15666. }
  15667. }
  15668. // A second argument must be given to configure the parser process.
  15669. // These options are recognized (only `ecmaVersion` is required):
  15670. var defaultOptions = {
  15671. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15672. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15673. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  15674. // latest version the library supports). This influences support
  15675. // for strict mode, the set of reserved words, and support for
  15676. // new syntax features.
  15677. ecmaVersion: null,
  15678. // `sourceType` indicates the mode the code should be parsed in.
  15679. // Can be either `"script"` or `"module"`. This influences global
  15680. // strict mode and parsing of `import` and `export` declarations.
  15681. sourceType: "script",
  15682. // `onInsertedSemicolon` can be a callback that will be called
  15683. // when a semicolon is automatically inserted. It will be passed
  15684. // the position of the comma as an offset, and if `locations` is
  15685. // enabled, it is given the location as a `{line, column}` object
  15686. // as second argument.
  15687. onInsertedSemicolon: null,
  15688. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15689. // trailing commas.
  15690. onTrailingComma: null,
  15691. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15692. // Set `allowReserved` to a boolean value to explicitly turn this on
  15693. // an off. When this option has the value "never", reserved words
  15694. // and keywords can also not be used as property names.
  15695. allowReserved: null,
  15696. // When enabled, a return at the top level is not considered an
  15697. // error.
  15698. allowReturnOutsideFunction: false,
  15699. // When enabled, import/export statements are not constrained to
  15700. // appearing at the top of the program, and an import.meta expression
  15701. // in a script isn't considered an error.
  15702. allowImportExportEverywhere: false,
  15703. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15704. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15705. // but they are still not allowed in non-async functions.
  15706. allowAwaitOutsideFunction: null,
  15707. // When enabled, super identifiers are not constrained to
  15708. // appearing in methods and do not raise an error when they appear elsewhere.
  15709. allowSuperOutsideMethod: null,
  15710. // When enabled, hashbang directive in the beginning of file
  15711. // is allowed and treated as a line comment.
  15712. allowHashBang: false,
  15713. // When `locations` is on, `loc` properties holding objects with
  15714. // `start` and `end` properties in `{line, column}` form (with
  15715. // line being 1-based and column 0-based) will be attached to the
  15716. // nodes.
  15717. locations: false,
  15718. // A function can be passed as `onToken` option, which will
  15719. // cause Acorn to call that function with object in the same
  15720. // format as tokens returned from `tokenizer().getToken()`. Note
  15721. // that you are not allowed to call the parser from the
  15722. // callback—that will corrupt its internal state.
  15723. onToken: null,
  15724. // A function can be passed as `onComment` option, which will
  15725. // cause Acorn to call that function with `(block, text, start,
  15726. // end)` parameters whenever a comment is skipped. `block` is a
  15727. // boolean indicating whether this is a block (`/* */`) comment,
  15728. // `text` is the content of the comment, and `start` and `end` are
  15729. // character offsets that denote the start and end of the comment.
  15730. // When the `locations` option is on, two more parameters are
  15731. // passed, the full `{line, column}` locations of the start and
  15732. // end of the comments. Note that you are not allowed to call the
  15733. // parser from the callback—that will corrupt its internal state.
  15734. onComment: null,
  15735. // Nodes have their start and end characters offsets recorded in
  15736. // `start` and `end` properties (directly on the node, rather than
  15737. // the `loc` object, which holds line/column data. To also add a
  15738. // [semi-standardized][range] `range` property holding a `[start,
  15739. // end]` array with the same numbers, set the `ranges` option to
  15740. // `true`.
  15741. //
  15742. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15743. ranges: false,
  15744. // It is possible to parse multiple files into a single AST by
  15745. // passing the tree produced by parsing the first file as
  15746. // `program` option in subsequent parses. This will add the
  15747. // toplevel forms of the parsed file to the `Program` (top) node
  15748. // of an existing parse tree.
  15749. program: null,
  15750. // When `locations` is on, you can pass this to record the source
  15751. // file in every node's `loc` object.
  15752. sourceFile: null,
  15753. // This value, if given, is stored in every node, whether
  15754. // `locations` is on or off.
  15755. directSourceFile: null,
  15756. // When enabled, parenthesized expressions are represented by
  15757. // (non-standard) ParenthesizedExpression nodes
  15758. preserveParens: false
  15759. };
  15760. // Interpret and default an options object
  15761. var warnedAboutEcmaVersion = false;
  15762. function getOptions(opts) {
  15763. var options = {};
  15764. for (var opt in defaultOptions)
  15765. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15766. if (options.ecmaVersion === "latest") {
  15767. options.ecmaVersion = 1e8;
  15768. } else if (options.ecmaVersion == null) {
  15769. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15770. warnedAboutEcmaVersion = true;
  15771. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15772. }
  15773. options.ecmaVersion = 11;
  15774. } else if (options.ecmaVersion >= 2015) {
  15775. options.ecmaVersion -= 2009;
  15776. }
  15777. if (options.allowReserved == null)
  15778. { options.allowReserved = options.ecmaVersion < 5; }
  15779. if (isArray(options.onToken)) {
  15780. var tokens = options.onToken;
  15781. options.onToken = function (token) { return tokens.push(token); };
  15782. }
  15783. if (isArray(options.onComment))
  15784. { options.onComment = pushComment(options, options.onComment); }
  15785. return options
  15786. }
  15787. function pushComment(options, array) {
  15788. return function(block, text, start, end, startLoc, endLoc) {
  15789. var comment = {
  15790. type: block ? "Block" : "Line",
  15791. value: text,
  15792. start: start,
  15793. end: end
  15794. };
  15795. if (options.locations)
  15796. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15797. if (options.ranges)
  15798. { comment.range = [start, end]; }
  15799. array.push(comment);
  15800. }
  15801. }
  15802. // Each scope gets a bitset that may contain these flags
  15803. var
  15804. SCOPE_TOP = 1,
  15805. SCOPE_FUNCTION = 2,
  15806. SCOPE_ASYNC = 4,
  15807. SCOPE_GENERATOR = 8,
  15808. SCOPE_ARROW = 16,
  15809. SCOPE_SIMPLE_CATCH = 32,
  15810. SCOPE_SUPER = 64,
  15811. SCOPE_DIRECT_SUPER = 128,
  15812. SCOPE_CLASS_STATIC_BLOCK = 256,
  15813. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15814. function functionFlags(async, generator) {
  15815. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15816. }
  15817. // Used in checkLVal* and declareName to determine the type of a binding
  15818. var
  15819. BIND_NONE = 0, // Not a binding
  15820. BIND_VAR = 1, // Var-style binding
  15821. BIND_LEXICAL = 2, // Let- or const-style binding
  15822. BIND_FUNCTION = 3, // Function declaration
  15823. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15824. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15825. var Parser = function Parser(options, input, startPos) {
  15826. this.options = options = getOptions(options);
  15827. this.sourceFile = options.sourceFile;
  15828. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15829. var reserved = "";
  15830. if (options.allowReserved !== true) {
  15831. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15832. if (options.sourceType === "module") { reserved += " await"; }
  15833. }
  15834. this.reservedWords = wordsRegexp(reserved);
  15835. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15836. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15837. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15838. this.input = String(input);
  15839. // Used to signal to callers of `readWord1` whether the word
  15840. // contained any escape sequences. This is needed because words with
  15841. // escape sequences must not be interpreted as keywords.
  15842. this.containsEsc = false;
  15843. // Set up token state
  15844. // The current position of the tokenizer in the input.
  15845. if (startPos) {
  15846. this.pos = startPos;
  15847. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15848. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15849. } else {
  15850. this.pos = this.lineStart = 0;
  15851. this.curLine = 1;
  15852. }
  15853. // Properties of the current token:
  15854. // Its type
  15855. this.type = types$1.eof;
  15856. // For tokens that include more information than their type, the value
  15857. this.value = null;
  15858. // Its start and end offset
  15859. this.start = this.end = this.pos;
  15860. // And, if locations are used, the {line, column} object
  15861. // corresponding to those offsets
  15862. this.startLoc = this.endLoc = this.curPosition();
  15863. // Position information for the previous token
  15864. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15865. this.lastTokStart = this.lastTokEnd = this.pos;
  15866. // The context stack is used to superficially track syntactic
  15867. // context to predict whether a regular expression is allowed in a
  15868. // given position.
  15869. this.context = this.initialContext();
  15870. this.exprAllowed = true;
  15871. // Figure out if it's a module code.
  15872. this.inModule = options.sourceType === "module";
  15873. this.strict = this.inModule || this.strictDirective(this.pos);
  15874. // Used to signify the start of a potential arrow function
  15875. this.potentialArrowAt = -1;
  15876. this.potentialArrowInForAwait = false;
  15877. // Positions to delayed-check that yield/await does not exist in default parameters.
  15878. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15879. // Labels in scope.
  15880. this.labels = [];
  15881. // Thus-far undefined exports.
  15882. this.undefinedExports = Object.create(null);
  15883. // If enabled, skip leading hashbang line.
  15884. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15885. { this.skipLineComment(2); }
  15886. // Scope tracking for duplicate variable names (see scope.js)
  15887. this.scopeStack = [];
  15888. this.enterScope(SCOPE_TOP);
  15889. // For RegExp validation
  15890. this.regexpState = null;
  15891. // The stack of private names.
  15892. // Each element has two properties: 'declared' and 'used'.
  15893. // When it exited from the outermost class definition, all used private names must be declared.
  15894. this.privateNameStack = [];
  15895. };
  15896. 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 } };
  15897. Parser.prototype.parse = function parse () {
  15898. var node = this.options.program || this.startNode();
  15899. this.nextToken();
  15900. return this.parseTopLevel(node)
  15901. };
  15902. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15903. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15904. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15905. prototypeAccessors.canAwait.get = function () {
  15906. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15907. var scope = this.scopeStack[i];
  15908. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15909. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15910. }
  15911. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15912. };
  15913. prototypeAccessors.allowSuper.get = function () {
  15914. var ref = this.currentThisScope();
  15915. var flags = ref.flags;
  15916. var inClassFieldInit = ref.inClassFieldInit;
  15917. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15918. };
  15919. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15920. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15921. prototypeAccessors.allowNewDotTarget.get = function () {
  15922. var ref = this.currentThisScope();
  15923. var flags = ref.flags;
  15924. var inClassFieldInit = ref.inClassFieldInit;
  15925. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15926. };
  15927. prototypeAccessors.inClassStaticBlock.get = function () {
  15928. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15929. };
  15930. Parser.extend = function extend () {
  15931. var plugins = [], len = arguments.length;
  15932. while ( len-- ) plugins[ len ] = arguments[ len ];
  15933. var cls = this;
  15934. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15935. return cls
  15936. };
  15937. Parser.parse = function parse (input, options) {
  15938. return new this(options, input).parse()
  15939. };
  15940. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15941. var parser = new this(options, input, pos);
  15942. parser.nextToken();
  15943. return parser.parseExpression()
  15944. };
  15945. Parser.tokenizer = function tokenizer (input, options) {
  15946. return new this(options, input)
  15947. };
  15948. Object.defineProperties( Parser.prototype, prototypeAccessors );
  15949. var pp$9 = Parser.prototype;
  15950. // ## Parser utilities
  15951. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15952. pp$9.strictDirective = function(start) {
  15953. if (this.options.ecmaVersion < 5) { return false }
  15954. for (;;) {
  15955. // Try to find string literal.
  15956. skipWhiteSpace.lastIndex = start;
  15957. start += skipWhiteSpace.exec(this.input)[0].length;
  15958. var match = literal.exec(this.input.slice(start));
  15959. if (!match) { return false }
  15960. if ((match[1] || match[2]) === "use strict") {
  15961. skipWhiteSpace.lastIndex = start + match[0].length;
  15962. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15963. var next = this.input.charAt(end);
  15964. return next === ";" || next === "}" ||
  15965. (lineBreak.test(spaceAfter[0]) &&
  15966. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15967. }
  15968. start += match[0].length;
  15969. // Skip semicolon, if any.
  15970. skipWhiteSpace.lastIndex = start;
  15971. start += skipWhiteSpace.exec(this.input)[0].length;
  15972. if (this.input[start] === ";")
  15973. { start++; }
  15974. }
  15975. };
  15976. // Predicate that tests whether the next token is of the given
  15977. // type, and if yes, consumes it as a side effect.
  15978. pp$9.eat = function(type) {
  15979. if (this.type === type) {
  15980. this.next();
  15981. return true
  15982. } else {
  15983. return false
  15984. }
  15985. };
  15986. // Tests whether parsed token is a contextual keyword.
  15987. pp$9.isContextual = function(name) {
  15988. return this.type === types$1.name && this.value === name && !this.containsEsc
  15989. };
  15990. // Consumes contextual keyword if possible.
  15991. pp$9.eatContextual = function(name) {
  15992. if (!this.isContextual(name)) { return false }
  15993. this.next();
  15994. return true
  15995. };
  15996. // Asserts that following token is given contextual keyword.
  15997. pp$9.expectContextual = function(name) {
  15998. if (!this.eatContextual(name)) { this.unexpected(); }
  15999. };
  16000. // Test whether a semicolon can be inserted at the current position.
  16001. pp$9.canInsertSemicolon = function() {
  16002. return this.type === types$1.eof ||
  16003. this.type === types$1.braceR ||
  16004. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  16005. };
  16006. pp$9.insertSemicolon = function() {
  16007. if (this.canInsertSemicolon()) {
  16008. if (this.options.onInsertedSemicolon)
  16009. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  16010. return true
  16011. }
  16012. };
  16013. // Consume a semicolon, or, failing that, see if we are allowed to
  16014. // pretend that there is a semicolon at this position.
  16015. pp$9.semicolon = function() {
  16016. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  16017. };
  16018. pp$9.afterTrailingComma = function(tokType, notNext) {
  16019. if (this.type === tokType) {
  16020. if (this.options.onTrailingComma)
  16021. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  16022. if (!notNext)
  16023. { this.next(); }
  16024. return true
  16025. }
  16026. };
  16027. // Expect a token of a given type. If found, consume it, otherwise,
  16028. // raise an unexpected token error.
  16029. pp$9.expect = function(type) {
  16030. this.eat(type) || this.unexpected();
  16031. };
  16032. // Raise an unexpected token error.
  16033. pp$9.unexpected = function(pos) {
  16034. this.raise(pos != null ? pos : this.start, "Unexpected token");
  16035. };
  16036. var DestructuringErrors = function DestructuringErrors() {
  16037. this.shorthandAssign =
  16038. this.trailingComma =
  16039. this.parenthesizedAssign =
  16040. this.parenthesizedBind =
  16041. this.doubleProto =
  16042. -1;
  16043. };
  16044. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  16045. if (!refDestructuringErrors) { return }
  16046. if (refDestructuringErrors.trailingComma > -1)
  16047. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  16048. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  16049. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  16050. };
  16051. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  16052. if (!refDestructuringErrors) { return false }
  16053. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  16054. var doubleProto = refDestructuringErrors.doubleProto;
  16055. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  16056. if (shorthandAssign >= 0)
  16057. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  16058. if (doubleProto >= 0)
  16059. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  16060. };
  16061. pp$9.checkYieldAwaitInDefaultParams = function() {
  16062. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  16063. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  16064. if (this.awaitPos)
  16065. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  16066. };
  16067. pp$9.isSimpleAssignTarget = function(expr) {
  16068. if (expr.type === "ParenthesizedExpression")
  16069. { return this.isSimpleAssignTarget(expr.expression) }
  16070. return expr.type === "Identifier" || expr.type === "MemberExpression"
  16071. };
  16072. var pp$8 = Parser.prototype;
  16073. // ### Statement parsing
  16074. // Parse a program. Initializes the parser, reads any number of
  16075. // statements, and wraps them in a Program node. Optionally takes a
  16076. // `program` argument. If present, the statements will be appended
  16077. // to its body instead of creating a new node.
  16078. pp$8.parseTopLevel = function(node) {
  16079. var exports = Object.create(null);
  16080. if (!node.body) { node.body = []; }
  16081. while (this.type !== types$1.eof) {
  16082. var stmt = this.parseStatement(null, true, exports);
  16083. node.body.push(stmt);
  16084. }
  16085. if (this.inModule)
  16086. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  16087. {
  16088. var name = list[i];
  16089. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  16090. } }
  16091. this.adaptDirectivePrologue(node.body);
  16092. this.next();
  16093. node.sourceType = this.options.sourceType;
  16094. return this.finishNode(node, "Program")
  16095. };
  16096. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  16097. pp$8.isLet = function(context) {
  16098. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  16099. skipWhiteSpace.lastIndex = this.pos;
  16100. var skip = skipWhiteSpace.exec(this.input);
  16101. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  16102. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  16103. // Statement) is allowed here. If context is not empty then only a Statement
  16104. // is allowed. However, `let [` is an explicit negative lookahead for
  16105. // ExpressionStatement, so special-case it first.
  16106. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  16107. if (context) { return false }
  16108. if (nextCh === 123) { return true } // '{'
  16109. if (isIdentifierStart(nextCh, true)) {
  16110. var pos = next + 1;
  16111. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  16112. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  16113. var ident = this.input.slice(next, pos);
  16114. if (!keywordRelationalOperator.test(ident)) { return true }
  16115. }
  16116. return false
  16117. };
  16118. // check 'async [no LineTerminator here] function'
  16119. // - 'async /*foo*/ function' is OK.
  16120. // - 'async /*\n*/ function' is invalid.
  16121. pp$8.isAsyncFunction = function() {
  16122. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  16123. { return false }
  16124. skipWhiteSpace.lastIndex = this.pos;
  16125. var skip = skipWhiteSpace.exec(this.input);
  16126. var next = this.pos + skip[0].length, after;
  16127. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  16128. this.input.slice(next, next + 8) === "function" &&
  16129. (next + 8 === this.input.length ||
  16130. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  16131. };
  16132. // Parse a single statement.
  16133. //
  16134. // If expecting a statement and finding a slash operator, parse a
  16135. // regular expression literal. This is to handle cases like
  16136. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  16137. // does not help.
  16138. pp$8.parseStatement = function(context, topLevel, exports) {
  16139. var starttype = this.type, node = this.startNode(), kind;
  16140. if (this.isLet(context)) {
  16141. starttype = types$1._var;
  16142. kind = "let";
  16143. }
  16144. // Most types of statements are recognized by the keyword they
  16145. // start with. Many are trivial to parse, some require a bit of
  16146. // complexity.
  16147. switch (starttype) {
  16148. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  16149. case types$1._debugger: return this.parseDebuggerStatement(node)
  16150. case types$1._do: return this.parseDoStatement(node)
  16151. case types$1._for: return this.parseForStatement(node)
  16152. case types$1._function:
  16153. // Function as sole body of either an if statement or a labeled statement
  16154. // works, but not when it is part of a labeled statement that is the sole
  16155. // body of an if statement.
  16156. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  16157. return this.parseFunctionStatement(node, false, !context)
  16158. case types$1._class:
  16159. if (context) { this.unexpected(); }
  16160. return this.parseClass(node, true)
  16161. case types$1._if: return this.parseIfStatement(node)
  16162. case types$1._return: return this.parseReturnStatement(node)
  16163. case types$1._switch: return this.parseSwitchStatement(node)
  16164. case types$1._throw: return this.parseThrowStatement(node)
  16165. case types$1._try: return this.parseTryStatement(node)
  16166. case types$1._const: case types$1._var:
  16167. kind = kind || this.value;
  16168. if (context && kind !== "var") { this.unexpected(); }
  16169. return this.parseVarStatement(node, kind)
  16170. case types$1._while: return this.parseWhileStatement(node)
  16171. case types$1._with: return this.parseWithStatement(node)
  16172. case types$1.braceL: return this.parseBlock(true, node)
  16173. case types$1.semi: return this.parseEmptyStatement(node)
  16174. case types$1._export:
  16175. case types$1._import:
  16176. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  16177. skipWhiteSpace.lastIndex = this.pos;
  16178. var skip = skipWhiteSpace.exec(this.input);
  16179. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  16180. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  16181. { return this.parseExpressionStatement(node, this.parseExpression()) }
  16182. }
  16183. if (!this.options.allowImportExportEverywhere) {
  16184. if (!topLevel)
  16185. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  16186. if (!this.inModule)
  16187. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  16188. }
  16189. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  16190. // If the statement does not start with a statement keyword or a
  16191. // brace, it's an ExpressionStatement or LabeledStatement. We
  16192. // simply start parsing an expression, and afterwards, if the
  16193. // next token is a colon and the expression was a simple
  16194. // Identifier node, we switch to interpreting it as a label.
  16195. default:
  16196. if (this.isAsyncFunction()) {
  16197. if (context) { this.unexpected(); }
  16198. this.next();
  16199. return this.parseFunctionStatement(node, true, !context)
  16200. }
  16201. var maybeName = this.value, expr = this.parseExpression();
  16202. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  16203. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  16204. else { return this.parseExpressionStatement(node, expr) }
  16205. }
  16206. };
  16207. pp$8.parseBreakContinueStatement = function(node, keyword) {
  16208. var isBreak = keyword === "break";
  16209. this.next();
  16210. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  16211. else if (this.type !== types$1.name) { this.unexpected(); }
  16212. else {
  16213. node.label = this.parseIdent();
  16214. this.semicolon();
  16215. }
  16216. // Verify that there is an actual destination to break or
  16217. // continue to.
  16218. var i = 0;
  16219. for (; i < this.labels.length; ++i) {
  16220. var lab = this.labels[i];
  16221. if (node.label == null || lab.name === node.label.name) {
  16222. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  16223. if (node.label && isBreak) { break }
  16224. }
  16225. }
  16226. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  16227. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  16228. };
  16229. pp$8.parseDebuggerStatement = function(node) {
  16230. this.next();
  16231. this.semicolon();
  16232. return this.finishNode(node, "DebuggerStatement")
  16233. };
  16234. pp$8.parseDoStatement = function(node) {
  16235. this.next();
  16236. this.labels.push(loopLabel);
  16237. node.body = this.parseStatement("do");
  16238. this.labels.pop();
  16239. this.expect(types$1._while);
  16240. node.test = this.parseParenExpression();
  16241. if (this.options.ecmaVersion >= 6)
  16242. { this.eat(types$1.semi); }
  16243. else
  16244. { this.semicolon(); }
  16245. return this.finishNode(node, "DoWhileStatement")
  16246. };
  16247. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  16248. // loop is non-trivial. Basically, we have to parse the init `var`
  16249. // statement or expression, disallowing the `in` operator (see
  16250. // the second parameter to `parseExpression`), and then check
  16251. // whether the next token is `in` or `of`. When there is no init
  16252. // part (semicolon immediately after the opening parenthesis), it
  16253. // is a regular `for` loop.
  16254. pp$8.parseForStatement = function(node) {
  16255. this.next();
  16256. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  16257. this.labels.push(loopLabel);
  16258. this.enterScope(0);
  16259. this.expect(types$1.parenL);
  16260. if (this.type === types$1.semi) {
  16261. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16262. return this.parseFor(node, null)
  16263. }
  16264. var isLet = this.isLet();
  16265. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  16266. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  16267. this.next();
  16268. this.parseVar(init$1, true, kind);
  16269. this.finishNode(init$1, "VariableDeclaration");
  16270. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  16271. if (this.options.ecmaVersion >= 9) {
  16272. if (this.type === types$1._in) {
  16273. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16274. } else { node.await = awaitAt > -1; }
  16275. }
  16276. return this.parseForIn(node, init$1)
  16277. }
  16278. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16279. return this.parseFor(node, init$1)
  16280. }
  16281. var startsWithLet = this.isContextual("let"), isForOf = false;
  16282. var refDestructuringErrors = new DestructuringErrors;
  16283. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  16284. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  16285. if (this.options.ecmaVersion >= 9) {
  16286. if (this.type === types$1._in) {
  16287. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16288. } else { node.await = awaitAt > -1; }
  16289. }
  16290. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  16291. this.toAssignable(init, false, refDestructuringErrors);
  16292. this.checkLValPattern(init);
  16293. return this.parseForIn(node, init)
  16294. } else {
  16295. this.checkExpressionErrors(refDestructuringErrors, true);
  16296. }
  16297. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16298. return this.parseFor(node, init)
  16299. };
  16300. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  16301. this.next();
  16302. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  16303. };
  16304. pp$8.parseIfStatement = function(node) {
  16305. this.next();
  16306. node.test = this.parseParenExpression();
  16307. // allow function declarations in branches, but only in non-strict mode
  16308. node.consequent = this.parseStatement("if");
  16309. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  16310. return this.finishNode(node, "IfStatement")
  16311. };
  16312. pp$8.parseReturnStatement = function(node) {
  16313. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  16314. { this.raise(this.start, "'return' outside of function"); }
  16315. this.next();
  16316. // In `return` (and `break`/`continue`), the keywords with
  16317. // optional arguments, we eagerly look for a semicolon or the
  16318. // possibility to insert one.
  16319. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  16320. else { node.argument = this.parseExpression(); this.semicolon(); }
  16321. return this.finishNode(node, "ReturnStatement")
  16322. };
  16323. pp$8.parseSwitchStatement = function(node) {
  16324. this.next();
  16325. node.discriminant = this.parseParenExpression();
  16326. node.cases = [];
  16327. this.expect(types$1.braceL);
  16328. this.labels.push(switchLabel);
  16329. this.enterScope(0);
  16330. // Statements under must be grouped (by label) in SwitchCase
  16331. // nodes. `cur` is used to keep the node that we are currently
  16332. // adding statements to.
  16333. var cur;
  16334. for (var sawDefault = false; this.type !== types$1.braceR;) {
  16335. if (this.type === types$1._case || this.type === types$1._default) {
  16336. var isCase = this.type === types$1._case;
  16337. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16338. node.cases.push(cur = this.startNode());
  16339. cur.consequent = [];
  16340. this.next();
  16341. if (isCase) {
  16342. cur.test = this.parseExpression();
  16343. } else {
  16344. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  16345. sawDefault = true;
  16346. cur.test = null;
  16347. }
  16348. this.expect(types$1.colon);
  16349. } else {
  16350. if (!cur) { this.unexpected(); }
  16351. cur.consequent.push(this.parseStatement(null));
  16352. }
  16353. }
  16354. this.exitScope();
  16355. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16356. this.next(); // Closing brace
  16357. this.labels.pop();
  16358. return this.finishNode(node, "SwitchStatement")
  16359. };
  16360. pp$8.parseThrowStatement = function(node) {
  16361. this.next();
  16362. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  16363. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  16364. node.argument = this.parseExpression();
  16365. this.semicolon();
  16366. return this.finishNode(node, "ThrowStatement")
  16367. };
  16368. // Reused empty array added for node fields that are always empty.
  16369. var empty$1 = [];
  16370. pp$8.parseTryStatement = function(node) {
  16371. this.next();
  16372. node.block = this.parseBlock();
  16373. node.handler = null;
  16374. if (this.type === types$1._catch) {
  16375. var clause = this.startNode();
  16376. this.next();
  16377. if (this.eat(types$1.parenL)) {
  16378. clause.param = this.parseBindingAtom();
  16379. var simple = clause.param.type === "Identifier";
  16380. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  16381. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  16382. this.expect(types$1.parenR);
  16383. } else {
  16384. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  16385. clause.param = null;
  16386. this.enterScope(0);
  16387. }
  16388. clause.body = this.parseBlock(false);
  16389. this.exitScope();
  16390. node.handler = this.finishNode(clause, "CatchClause");
  16391. }
  16392. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  16393. if (!node.handler && !node.finalizer)
  16394. { this.raise(node.start, "Missing catch or finally clause"); }
  16395. return this.finishNode(node, "TryStatement")
  16396. };
  16397. pp$8.parseVarStatement = function(node, kind) {
  16398. this.next();
  16399. this.parseVar(node, false, kind);
  16400. this.semicolon();
  16401. return this.finishNode(node, "VariableDeclaration")
  16402. };
  16403. pp$8.parseWhileStatement = function(node) {
  16404. this.next();
  16405. node.test = this.parseParenExpression();
  16406. this.labels.push(loopLabel);
  16407. node.body = this.parseStatement("while");
  16408. this.labels.pop();
  16409. return this.finishNode(node, "WhileStatement")
  16410. };
  16411. pp$8.parseWithStatement = function(node) {
  16412. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  16413. this.next();
  16414. node.object = this.parseParenExpression();
  16415. node.body = this.parseStatement("with");
  16416. return this.finishNode(node, "WithStatement")
  16417. };
  16418. pp$8.parseEmptyStatement = function(node) {
  16419. this.next();
  16420. return this.finishNode(node, "EmptyStatement")
  16421. };
  16422. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  16423. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  16424. {
  16425. var label = list[i$1];
  16426. if (label.name === maybeName)
  16427. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  16428. } }
  16429. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  16430. for (var i = this.labels.length - 1; i >= 0; i--) {
  16431. var label$1 = this.labels[i];
  16432. if (label$1.statementStart === node.start) {
  16433. // Update information about previous labels on this node
  16434. label$1.statementStart = this.start;
  16435. label$1.kind = kind;
  16436. } else { break }
  16437. }
  16438. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  16439. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  16440. this.labels.pop();
  16441. node.label = expr;
  16442. return this.finishNode(node, "LabeledStatement")
  16443. };
  16444. pp$8.parseExpressionStatement = function(node, expr) {
  16445. node.expression = expr;
  16446. this.semicolon();
  16447. return this.finishNode(node, "ExpressionStatement")
  16448. };
  16449. // Parse a semicolon-enclosed block of statements, handling `"use
  16450. // strict"` declarations when `allowStrict` is true (used for
  16451. // function bodies).
  16452. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  16453. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  16454. if ( node === void 0 ) node = this.startNode();
  16455. node.body = [];
  16456. this.expect(types$1.braceL);
  16457. if (createNewLexicalScope) { this.enterScope(0); }
  16458. while (this.type !== types$1.braceR) {
  16459. var stmt = this.parseStatement(null);
  16460. node.body.push(stmt);
  16461. }
  16462. if (exitStrict) { this.strict = false; }
  16463. this.next();
  16464. if (createNewLexicalScope) { this.exitScope(); }
  16465. return this.finishNode(node, "BlockStatement")
  16466. };
  16467. // Parse a regular `for` loop. The disambiguation code in
  16468. // `parseStatement` will already have parsed the init statement or
  16469. // expression.
  16470. pp$8.parseFor = function(node, init) {
  16471. node.init = init;
  16472. this.expect(types$1.semi);
  16473. node.test = this.type === types$1.semi ? null : this.parseExpression();
  16474. this.expect(types$1.semi);
  16475. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  16476. this.expect(types$1.parenR);
  16477. node.body = this.parseStatement("for");
  16478. this.exitScope();
  16479. this.labels.pop();
  16480. return this.finishNode(node, "ForStatement")
  16481. };
  16482. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  16483. // same from parser's perspective.
  16484. pp$8.parseForIn = function(node, init) {
  16485. var isForIn = this.type === types$1._in;
  16486. this.next();
  16487. if (
  16488. init.type === "VariableDeclaration" &&
  16489. init.declarations[0].init != null &&
  16490. (
  16491. !isForIn ||
  16492. this.options.ecmaVersion < 8 ||
  16493. this.strict ||
  16494. init.kind !== "var" ||
  16495. init.declarations[0].id.type !== "Identifier"
  16496. )
  16497. ) {
  16498. this.raise(
  16499. init.start,
  16500. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  16501. );
  16502. }
  16503. node.left = init;
  16504. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  16505. this.expect(types$1.parenR);
  16506. node.body = this.parseStatement("for");
  16507. this.exitScope();
  16508. this.labels.pop();
  16509. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  16510. };
  16511. // Parse a list of variable declarations.
  16512. pp$8.parseVar = function(node, isFor, kind) {
  16513. node.declarations = [];
  16514. node.kind = kind;
  16515. for (;;) {
  16516. var decl = this.startNode();
  16517. this.parseVarId(decl, kind);
  16518. if (this.eat(types$1.eq)) {
  16519. decl.init = this.parseMaybeAssign(isFor);
  16520. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  16521. this.unexpected();
  16522. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  16523. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  16524. } else {
  16525. decl.init = null;
  16526. }
  16527. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  16528. if (!this.eat(types$1.comma)) { break }
  16529. }
  16530. return node
  16531. };
  16532. pp$8.parseVarId = function(decl, kind) {
  16533. decl.id = this.parseBindingAtom();
  16534. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  16535. };
  16536. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  16537. // Parse a function declaration or literal (depending on the
  16538. // `statement & FUNC_STATEMENT`).
  16539. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  16540. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  16541. this.initFunction(node);
  16542. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  16543. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  16544. { this.unexpected(); }
  16545. node.generator = this.eat(types$1.star);
  16546. }
  16547. if (this.options.ecmaVersion >= 8)
  16548. { node.async = !!isAsync; }
  16549. if (statement & FUNC_STATEMENT) {
  16550. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  16551. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  16552. // If it is a regular function declaration in sloppy mode, then it is
  16553. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  16554. // mode depends on properties of the current scope (see
  16555. // treatFunctionsAsVar).
  16556. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  16557. }
  16558. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  16559. this.yieldPos = 0;
  16560. this.awaitPos = 0;
  16561. this.awaitIdentPos = 0;
  16562. this.enterScope(functionFlags(node.async, node.generator));
  16563. if (!(statement & FUNC_STATEMENT))
  16564. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  16565. this.parseFunctionParams(node);
  16566. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  16567. this.yieldPos = oldYieldPos;
  16568. this.awaitPos = oldAwaitPos;
  16569. this.awaitIdentPos = oldAwaitIdentPos;
  16570. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  16571. };
  16572. pp$8.parseFunctionParams = function(node) {
  16573. this.expect(types$1.parenL);
  16574. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  16575. this.checkYieldAwaitInDefaultParams();
  16576. };
  16577. // Parse a class declaration or literal (depending on the
  16578. // `isStatement` parameter).
  16579. pp$8.parseClass = function(node, isStatement) {
  16580. this.next();
  16581. // ecma-262 14.6 Class Definitions
  16582. // A class definition is always strict mode code.
  16583. var oldStrict = this.strict;
  16584. this.strict = true;
  16585. this.parseClassId(node, isStatement);
  16586. this.parseClassSuper(node);
  16587. var privateNameMap = this.enterClassBody();
  16588. var classBody = this.startNode();
  16589. var hadConstructor = false;
  16590. classBody.body = [];
  16591. this.expect(types$1.braceL);
  16592. while (this.type !== types$1.braceR) {
  16593. var element = this.parseClassElement(node.superClass !== null);
  16594. if (element) {
  16595. classBody.body.push(element);
  16596. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  16597. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  16598. hadConstructor = true;
  16599. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  16600. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  16601. }
  16602. }
  16603. }
  16604. this.strict = oldStrict;
  16605. this.next();
  16606. node.body = this.finishNode(classBody, "ClassBody");
  16607. this.exitClassBody();
  16608. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16609. };
  16610. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16611. if (this.eat(types$1.semi)) { return null }
  16612. var ecmaVersion = this.options.ecmaVersion;
  16613. var node = this.startNode();
  16614. var keyName = "";
  16615. var isGenerator = false;
  16616. var isAsync = false;
  16617. var kind = "method";
  16618. var isStatic = false;
  16619. if (this.eatContextual("static")) {
  16620. // Parse static init block
  16621. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16622. this.parseClassStaticBlock(node);
  16623. return node
  16624. }
  16625. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16626. isStatic = true;
  16627. } else {
  16628. keyName = "static";
  16629. }
  16630. }
  16631. node.static = isStatic;
  16632. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16633. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16634. isAsync = true;
  16635. } else {
  16636. keyName = "async";
  16637. }
  16638. }
  16639. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16640. isGenerator = true;
  16641. }
  16642. if (!keyName && !isAsync && !isGenerator) {
  16643. var lastValue = this.value;
  16644. if (this.eatContextual("get") || this.eatContextual("set")) {
  16645. if (this.isClassElementNameStart()) {
  16646. kind = lastValue;
  16647. } else {
  16648. keyName = lastValue;
  16649. }
  16650. }
  16651. }
  16652. // Parse element name
  16653. if (keyName) {
  16654. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16655. // The last token is any of those. Make it the element name.
  16656. node.computed = false;
  16657. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16658. node.key.name = keyName;
  16659. this.finishNode(node.key, "Identifier");
  16660. } else {
  16661. this.parseClassElementName(node);
  16662. }
  16663. // Parse element value
  16664. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16665. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16666. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16667. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16668. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16669. node.kind = isConstructor ? "constructor" : kind;
  16670. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16671. } else {
  16672. this.parseClassField(node);
  16673. }
  16674. return node
  16675. };
  16676. pp$8.isClassElementNameStart = function() {
  16677. return (
  16678. this.type === types$1.name ||
  16679. this.type === types$1.privateId ||
  16680. this.type === types$1.num ||
  16681. this.type === types$1.string ||
  16682. this.type === types$1.bracketL ||
  16683. this.type.keyword
  16684. )
  16685. };
  16686. pp$8.parseClassElementName = function(element) {
  16687. if (this.type === types$1.privateId) {
  16688. if (this.value === "constructor") {
  16689. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16690. }
  16691. element.computed = false;
  16692. element.key = this.parsePrivateIdent();
  16693. } else {
  16694. this.parsePropertyName(element);
  16695. }
  16696. };
  16697. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16698. // Check key and flags
  16699. var key = method.key;
  16700. if (method.kind === "constructor") {
  16701. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16702. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16703. } else if (method.static && checkKeyName(method, "prototype")) {
  16704. this.raise(key.start, "Classes may not have a static property named prototype");
  16705. }
  16706. // Parse value
  16707. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16708. // Check value
  16709. if (method.kind === "get" && value.params.length !== 0)
  16710. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16711. if (method.kind === "set" && value.params.length !== 1)
  16712. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16713. if (method.kind === "set" && value.params[0].type === "RestElement")
  16714. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16715. return this.finishNode(method, "MethodDefinition")
  16716. };
  16717. pp$8.parseClassField = function(field) {
  16718. if (checkKeyName(field, "constructor")) {
  16719. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16720. } else if (field.static && checkKeyName(field, "prototype")) {
  16721. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16722. }
  16723. if (this.eat(types$1.eq)) {
  16724. // To raise SyntaxError if 'arguments' exists in the initializer.
  16725. var scope = this.currentThisScope();
  16726. var inClassFieldInit = scope.inClassFieldInit;
  16727. scope.inClassFieldInit = true;
  16728. field.value = this.parseMaybeAssign();
  16729. scope.inClassFieldInit = inClassFieldInit;
  16730. } else {
  16731. field.value = null;
  16732. }
  16733. this.semicolon();
  16734. return this.finishNode(field, "PropertyDefinition")
  16735. };
  16736. pp$8.parseClassStaticBlock = function(node) {
  16737. node.body = [];
  16738. var oldLabels = this.labels;
  16739. this.labels = [];
  16740. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16741. while (this.type !== types$1.braceR) {
  16742. var stmt = this.parseStatement(null);
  16743. node.body.push(stmt);
  16744. }
  16745. this.next();
  16746. this.exitScope();
  16747. this.labels = oldLabels;
  16748. return this.finishNode(node, "StaticBlock")
  16749. };
  16750. pp$8.parseClassId = function(node, isStatement) {
  16751. if (this.type === types$1.name) {
  16752. node.id = this.parseIdent();
  16753. if (isStatement)
  16754. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16755. } else {
  16756. if (isStatement === true)
  16757. { this.unexpected(); }
  16758. node.id = null;
  16759. }
  16760. };
  16761. pp$8.parseClassSuper = function(node) {
  16762. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  16763. };
  16764. pp$8.enterClassBody = function() {
  16765. var element = {declared: Object.create(null), used: []};
  16766. this.privateNameStack.push(element);
  16767. return element.declared
  16768. };
  16769. pp$8.exitClassBody = function() {
  16770. var ref = this.privateNameStack.pop();
  16771. var declared = ref.declared;
  16772. var used = ref.used;
  16773. var len = this.privateNameStack.length;
  16774. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16775. for (var i = 0; i < used.length; ++i) {
  16776. var id = used[i];
  16777. if (!hasOwn(declared, id.name)) {
  16778. if (parent) {
  16779. parent.used.push(id);
  16780. } else {
  16781. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16782. }
  16783. }
  16784. }
  16785. };
  16786. function isPrivateNameConflicted(privateNameMap, element) {
  16787. var name = element.key.name;
  16788. var curr = privateNameMap[name];
  16789. var next = "true";
  16790. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16791. next = (element.static ? "s" : "i") + element.kind;
  16792. }
  16793. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16794. if (
  16795. curr === "iget" && next === "iset" ||
  16796. curr === "iset" && next === "iget" ||
  16797. curr === "sget" && next === "sset" ||
  16798. curr === "sset" && next === "sget"
  16799. ) {
  16800. privateNameMap[name] = "true";
  16801. return false
  16802. } else if (!curr) {
  16803. privateNameMap[name] = next;
  16804. return false
  16805. } else {
  16806. return true
  16807. }
  16808. }
  16809. function checkKeyName(node, name) {
  16810. var computed = node.computed;
  16811. var key = node.key;
  16812. return !computed && (
  16813. key.type === "Identifier" && key.name === name ||
  16814. key.type === "Literal" && key.value === name
  16815. )
  16816. }
  16817. // Parses module export declaration.
  16818. pp$8.parseExport = function(node, exports) {
  16819. this.next();
  16820. // export * from '...'
  16821. if (this.eat(types$1.star)) {
  16822. if (this.options.ecmaVersion >= 11) {
  16823. if (this.eatContextual("as")) {
  16824. node.exported = this.parseModuleExportName();
  16825. this.checkExport(exports, node.exported, this.lastTokStart);
  16826. } else {
  16827. node.exported = null;
  16828. }
  16829. }
  16830. this.expectContextual("from");
  16831. if (this.type !== types$1.string) { this.unexpected(); }
  16832. node.source = this.parseExprAtom();
  16833. this.semicolon();
  16834. return this.finishNode(node, "ExportAllDeclaration")
  16835. }
  16836. if (this.eat(types$1._default)) { // export default ...
  16837. this.checkExport(exports, "default", this.lastTokStart);
  16838. var isAsync;
  16839. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16840. var fNode = this.startNode();
  16841. this.next();
  16842. if (isAsync) { this.next(); }
  16843. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16844. } else if (this.type === types$1._class) {
  16845. var cNode = this.startNode();
  16846. node.declaration = this.parseClass(cNode, "nullableID");
  16847. } else {
  16848. node.declaration = this.parseMaybeAssign();
  16849. this.semicolon();
  16850. }
  16851. return this.finishNode(node, "ExportDefaultDeclaration")
  16852. }
  16853. // export var|const|let|function|class ...
  16854. if (this.shouldParseExportStatement()) {
  16855. node.declaration = this.parseStatement(null);
  16856. if (node.declaration.type === "VariableDeclaration")
  16857. { this.checkVariableExport(exports, node.declaration.declarations); }
  16858. else
  16859. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16860. node.specifiers = [];
  16861. node.source = null;
  16862. } else { // export { x, y as z } [from '...']
  16863. node.declaration = null;
  16864. node.specifiers = this.parseExportSpecifiers(exports);
  16865. if (this.eatContextual("from")) {
  16866. if (this.type !== types$1.string) { this.unexpected(); }
  16867. node.source = this.parseExprAtom();
  16868. } else {
  16869. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16870. // check for keywords used as local names
  16871. var spec = list[i];
  16872. this.checkUnreserved(spec.local);
  16873. // check if export is defined
  16874. this.checkLocalExport(spec.local);
  16875. if (spec.local.type === "Literal") {
  16876. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16877. }
  16878. }
  16879. node.source = null;
  16880. }
  16881. this.semicolon();
  16882. }
  16883. return this.finishNode(node, "ExportNamedDeclaration")
  16884. };
  16885. pp$8.checkExport = function(exports, name, pos) {
  16886. if (!exports) { return }
  16887. if (typeof name !== "string")
  16888. { name = name.type === "Identifier" ? name.name : name.value; }
  16889. if (hasOwn(exports, name))
  16890. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16891. exports[name] = true;
  16892. };
  16893. pp$8.checkPatternExport = function(exports, pat) {
  16894. var type = pat.type;
  16895. if (type === "Identifier")
  16896. { this.checkExport(exports, pat, pat.start); }
  16897. else if (type === "ObjectPattern")
  16898. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16899. {
  16900. var prop = list[i];
  16901. this.checkPatternExport(exports, prop);
  16902. } }
  16903. else if (type === "ArrayPattern")
  16904. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16905. var elt = list$1[i$1];
  16906. if (elt) { this.checkPatternExport(exports, elt); }
  16907. } }
  16908. else if (type === "Property")
  16909. { this.checkPatternExport(exports, pat.value); }
  16910. else if (type === "AssignmentPattern")
  16911. { this.checkPatternExport(exports, pat.left); }
  16912. else if (type === "RestElement")
  16913. { this.checkPatternExport(exports, pat.argument); }
  16914. else if (type === "ParenthesizedExpression")
  16915. { this.checkPatternExport(exports, pat.expression); }
  16916. };
  16917. pp$8.checkVariableExport = function(exports, decls) {
  16918. if (!exports) { return }
  16919. for (var i = 0, list = decls; i < list.length; i += 1)
  16920. {
  16921. var decl = list[i];
  16922. this.checkPatternExport(exports, decl.id);
  16923. }
  16924. };
  16925. pp$8.shouldParseExportStatement = function() {
  16926. return this.type.keyword === "var" ||
  16927. this.type.keyword === "const" ||
  16928. this.type.keyword === "class" ||
  16929. this.type.keyword === "function" ||
  16930. this.isLet() ||
  16931. this.isAsyncFunction()
  16932. };
  16933. // Parses a comma-separated list of module exports.
  16934. pp$8.parseExportSpecifiers = function(exports) {
  16935. var nodes = [], first = true;
  16936. // export { x, y as z } [from '...']
  16937. this.expect(types$1.braceL);
  16938. while (!this.eat(types$1.braceR)) {
  16939. if (!first) {
  16940. this.expect(types$1.comma);
  16941. if (this.afterTrailingComma(types$1.braceR)) { break }
  16942. } else { first = false; }
  16943. var node = this.startNode();
  16944. node.local = this.parseModuleExportName();
  16945. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16946. this.checkExport(
  16947. exports,
  16948. node.exported,
  16949. node.exported.start
  16950. );
  16951. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16952. }
  16953. return nodes
  16954. };
  16955. // Parses import declaration.
  16956. pp$8.parseImport = function(node) {
  16957. this.next();
  16958. // import '...'
  16959. if (this.type === types$1.string) {
  16960. node.specifiers = empty$1;
  16961. node.source = this.parseExprAtom();
  16962. } else {
  16963. node.specifiers = this.parseImportSpecifiers();
  16964. this.expectContextual("from");
  16965. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16966. }
  16967. this.semicolon();
  16968. return this.finishNode(node, "ImportDeclaration")
  16969. };
  16970. // Parses a comma-separated list of module imports.
  16971. pp$8.parseImportSpecifiers = function() {
  16972. var nodes = [], first = true;
  16973. if (this.type === types$1.name) {
  16974. // import defaultObj, { x, y as z } from '...'
  16975. var node = this.startNode();
  16976. node.local = this.parseIdent();
  16977. this.checkLValSimple(node.local, BIND_LEXICAL);
  16978. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16979. if (!this.eat(types$1.comma)) { return nodes }
  16980. }
  16981. if (this.type === types$1.star) {
  16982. var node$1 = this.startNode();
  16983. this.next();
  16984. this.expectContextual("as");
  16985. node$1.local = this.parseIdent();
  16986. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16987. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16988. return nodes
  16989. }
  16990. this.expect(types$1.braceL);
  16991. while (!this.eat(types$1.braceR)) {
  16992. if (!first) {
  16993. this.expect(types$1.comma);
  16994. if (this.afterTrailingComma(types$1.braceR)) { break }
  16995. } else { first = false; }
  16996. var node$2 = this.startNode();
  16997. node$2.imported = this.parseModuleExportName();
  16998. if (this.eatContextual("as")) {
  16999. node$2.local = this.parseIdent();
  17000. } else {
  17001. this.checkUnreserved(node$2.imported);
  17002. node$2.local = node$2.imported;
  17003. }
  17004. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  17005. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  17006. }
  17007. return nodes
  17008. };
  17009. pp$8.parseModuleExportName = function() {
  17010. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  17011. var stringLiteral = this.parseLiteral(this.value);
  17012. if (loneSurrogate.test(stringLiteral.value)) {
  17013. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  17014. }
  17015. return stringLiteral
  17016. }
  17017. return this.parseIdent(true)
  17018. };
  17019. // Set `ExpressionStatement#directive` property for directive prologues.
  17020. pp$8.adaptDirectivePrologue = function(statements) {
  17021. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  17022. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  17023. }
  17024. };
  17025. pp$8.isDirectiveCandidate = function(statement) {
  17026. return (
  17027. statement.type === "ExpressionStatement" &&
  17028. statement.expression.type === "Literal" &&
  17029. typeof statement.expression.value === "string" &&
  17030. // Reject parenthesized strings.
  17031. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  17032. )
  17033. };
  17034. var pp$7 = Parser.prototype;
  17035. // Convert existing expression atom to assignable pattern
  17036. // if possible.
  17037. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  17038. if (this.options.ecmaVersion >= 6 && node) {
  17039. switch (node.type) {
  17040. case "Identifier":
  17041. if (this.inAsync && node.name === "await")
  17042. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  17043. break
  17044. case "ObjectPattern":
  17045. case "ArrayPattern":
  17046. case "AssignmentPattern":
  17047. case "RestElement":
  17048. break
  17049. case "ObjectExpression":
  17050. node.type = "ObjectPattern";
  17051. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  17052. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  17053. var prop = list[i];
  17054. this.toAssignable(prop, isBinding);
  17055. // Early error:
  17056. // AssignmentRestProperty[Yield, Await] :
  17057. // `...` DestructuringAssignmentTarget[Yield, Await]
  17058. //
  17059. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  17060. if (
  17061. prop.type === "RestElement" &&
  17062. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  17063. ) {
  17064. this.raise(prop.argument.start, "Unexpected token");
  17065. }
  17066. }
  17067. break
  17068. case "Property":
  17069. // AssignmentProperty has type === "Property"
  17070. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  17071. this.toAssignable(node.value, isBinding);
  17072. break
  17073. case "ArrayExpression":
  17074. node.type = "ArrayPattern";
  17075. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  17076. this.toAssignableList(node.elements, isBinding);
  17077. break
  17078. case "SpreadElement":
  17079. node.type = "RestElement";
  17080. this.toAssignable(node.argument, isBinding);
  17081. if (node.argument.type === "AssignmentPattern")
  17082. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  17083. break
  17084. case "AssignmentExpression":
  17085. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  17086. node.type = "AssignmentPattern";
  17087. delete node.operator;
  17088. this.toAssignable(node.left, isBinding);
  17089. break
  17090. case "ParenthesizedExpression":
  17091. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  17092. break
  17093. case "ChainExpression":
  17094. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  17095. break
  17096. case "MemberExpression":
  17097. if (!isBinding) { break }
  17098. default:
  17099. this.raise(node.start, "Assigning to rvalue");
  17100. }
  17101. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  17102. return node
  17103. };
  17104. // Convert list of expression atoms to binding list.
  17105. pp$7.toAssignableList = function(exprList, isBinding) {
  17106. var end = exprList.length;
  17107. for (var i = 0; i < end; i++) {
  17108. var elt = exprList[i];
  17109. if (elt) { this.toAssignable(elt, isBinding); }
  17110. }
  17111. if (end) {
  17112. var last = exprList[end - 1];
  17113. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  17114. { this.unexpected(last.argument.start); }
  17115. }
  17116. return exprList
  17117. };
  17118. // Parses spread element.
  17119. pp$7.parseSpread = function(refDestructuringErrors) {
  17120. var node = this.startNode();
  17121. this.next();
  17122. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17123. return this.finishNode(node, "SpreadElement")
  17124. };
  17125. pp$7.parseRestBinding = function() {
  17126. var node = this.startNode();
  17127. this.next();
  17128. // RestElement inside of a function parameter must be an identifier
  17129. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  17130. { this.unexpected(); }
  17131. node.argument = this.parseBindingAtom();
  17132. return this.finishNode(node, "RestElement")
  17133. };
  17134. // Parses lvalue (assignable) atom.
  17135. pp$7.parseBindingAtom = function() {
  17136. if (this.options.ecmaVersion >= 6) {
  17137. switch (this.type) {
  17138. case types$1.bracketL:
  17139. var node = this.startNode();
  17140. this.next();
  17141. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  17142. return this.finishNode(node, "ArrayPattern")
  17143. case types$1.braceL:
  17144. return this.parseObj(true)
  17145. }
  17146. }
  17147. return this.parseIdent()
  17148. };
  17149. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  17150. var elts = [], first = true;
  17151. while (!this.eat(close)) {
  17152. if (first) { first = false; }
  17153. else { this.expect(types$1.comma); }
  17154. if (allowEmpty && this.type === types$1.comma) {
  17155. elts.push(null);
  17156. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  17157. break
  17158. } else if (this.type === types$1.ellipsis) {
  17159. var rest = this.parseRestBinding();
  17160. this.parseBindingListItem(rest);
  17161. elts.push(rest);
  17162. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17163. this.expect(close);
  17164. break
  17165. } else {
  17166. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  17167. this.parseBindingListItem(elem);
  17168. elts.push(elem);
  17169. }
  17170. }
  17171. return elts
  17172. };
  17173. pp$7.parseBindingListItem = function(param) {
  17174. return param
  17175. };
  17176. // Parses assignment pattern around given atom if possible.
  17177. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  17178. left = left || this.parseBindingAtom();
  17179. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  17180. var node = this.startNodeAt(startPos, startLoc);
  17181. node.left = left;
  17182. node.right = this.parseMaybeAssign();
  17183. return this.finishNode(node, "AssignmentPattern")
  17184. };
  17185. // The following three functions all verify that a node is an lvalue —
  17186. // something that can be bound, or assigned to. In order to do so, they perform
  17187. // a variety of checks:
  17188. //
  17189. // - Check that none of the bound/assigned-to identifiers are reserved words.
  17190. // - Record name declarations for bindings in the appropriate scope.
  17191. // - Check duplicate argument names, if checkClashes is set.
  17192. //
  17193. // If a complex binding pattern is encountered (e.g., object and array
  17194. // destructuring), the entire pattern is recursively checked.
  17195. //
  17196. // There are three versions of checkLVal*() appropriate for different
  17197. // circumstances:
  17198. //
  17199. // - checkLValSimple() shall be used if the syntactic construct supports
  17200. // nothing other than identifiers and member expressions. Parenthesized
  17201. // expressions are also correctly handled. This is generally appropriate for
  17202. // constructs for which the spec says
  17203. //
  17204. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  17205. // > simple.
  17206. //
  17207. // It is also appropriate for checking if an identifier is valid and not
  17208. // defined elsewhere, like import declarations or function/class identifiers.
  17209. //
  17210. // Examples where this is used include:
  17211. // a += …;
  17212. // import a from '…';
  17213. // where a is the node to be checked.
  17214. //
  17215. // - checkLValPattern() shall be used if the syntactic construct supports
  17216. // anything checkLValSimple() supports, as well as object and array
  17217. // destructuring patterns. This is generally appropriate for constructs for
  17218. // which the spec says
  17219. //
  17220. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  17221. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  17222. // > simple.
  17223. //
  17224. // Examples where this is used include:
  17225. // (a = …);
  17226. // const a = …;
  17227. // try { … } catch (a) { … }
  17228. // where a is the node to be checked.
  17229. //
  17230. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  17231. // anything checkLValPattern() supports, as well as default assignment
  17232. // patterns, rest elements, and other constructs that may appear within an
  17233. // object or array destructuring pattern.
  17234. //
  17235. // As a special case, function parameters also use checkLValInnerPattern(),
  17236. // as they also support defaults and rest constructs.
  17237. //
  17238. // These functions deliberately support both assignment and binding constructs,
  17239. // as the logic for both is exceedingly similar. If the node is the target of
  17240. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  17241. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  17242. // BIND_LEXICAL.
  17243. //
  17244. // If the function is called with a non-BIND_NONE bindingType, then
  17245. // additionally a checkClashes object may be specified to allow checking for
  17246. // duplicate argument names. checkClashes is ignored if the provided construct
  17247. // is an assignment (i.e., bindingType is BIND_NONE).
  17248. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  17249. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17250. var isBind = bindingType !== BIND_NONE;
  17251. switch (expr.type) {
  17252. case "Identifier":
  17253. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  17254. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  17255. if (isBind) {
  17256. if (bindingType === BIND_LEXICAL && expr.name === "let")
  17257. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  17258. if (checkClashes) {
  17259. if (hasOwn(checkClashes, expr.name))
  17260. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  17261. checkClashes[expr.name] = true;
  17262. }
  17263. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  17264. }
  17265. break
  17266. case "ChainExpression":
  17267. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  17268. break
  17269. case "MemberExpression":
  17270. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  17271. break
  17272. case "ParenthesizedExpression":
  17273. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  17274. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  17275. default:
  17276. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  17277. }
  17278. };
  17279. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  17280. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17281. switch (expr.type) {
  17282. case "ObjectPattern":
  17283. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  17284. var prop = list[i];
  17285. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  17286. }
  17287. break
  17288. case "ArrayPattern":
  17289. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  17290. var elem = list$1[i$1];
  17291. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  17292. }
  17293. break
  17294. default:
  17295. this.checkLValSimple(expr, bindingType, checkClashes);
  17296. }
  17297. };
  17298. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  17299. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17300. switch (expr.type) {
  17301. case "Property":
  17302. // AssignmentProperty has type === "Property"
  17303. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  17304. break
  17305. case "AssignmentPattern":
  17306. this.checkLValPattern(expr.left, bindingType, checkClashes);
  17307. break
  17308. case "RestElement":
  17309. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  17310. break
  17311. default:
  17312. this.checkLValPattern(expr, bindingType, checkClashes);
  17313. }
  17314. };
  17315. // The algorithm used to determine whether a regexp can appear at a
  17316. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  17317. this.token = token;
  17318. this.isExpr = !!isExpr;
  17319. this.preserveSpace = !!preserveSpace;
  17320. this.override = override;
  17321. this.generator = !!generator;
  17322. };
  17323. var types = {
  17324. b_stat: new TokContext("{", false),
  17325. b_expr: new TokContext("{", true),
  17326. b_tmpl: new TokContext("${", false),
  17327. p_stat: new TokContext("(", false),
  17328. p_expr: new TokContext("(", true),
  17329. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  17330. f_stat: new TokContext("function", false),
  17331. f_expr: new TokContext("function", true),
  17332. f_expr_gen: new TokContext("function", true, false, null, true),
  17333. f_gen: new TokContext("function", false, false, null, true)
  17334. };
  17335. var pp$6 = Parser.prototype;
  17336. pp$6.initialContext = function() {
  17337. return [types.b_stat]
  17338. };
  17339. pp$6.curContext = function() {
  17340. return this.context[this.context.length - 1]
  17341. };
  17342. pp$6.braceIsBlock = function(prevType) {
  17343. var parent = this.curContext();
  17344. if (parent === types.f_expr || parent === types.f_stat)
  17345. { return true }
  17346. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  17347. { return !parent.isExpr }
  17348. // The check for `tt.name && exprAllowed` detects whether we are
  17349. // after a `yield` or `of` construct. See the `updateContext` for
  17350. // `tt.name`.
  17351. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  17352. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  17353. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  17354. { return true }
  17355. if (prevType === types$1.braceL)
  17356. { return parent === types.b_stat }
  17357. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  17358. { return false }
  17359. return !this.exprAllowed
  17360. };
  17361. pp$6.inGeneratorContext = function() {
  17362. for (var i = this.context.length - 1; i >= 1; i--) {
  17363. var context = this.context[i];
  17364. if (context.token === "function")
  17365. { return context.generator }
  17366. }
  17367. return false
  17368. };
  17369. pp$6.updateContext = function(prevType) {
  17370. var update, type = this.type;
  17371. if (type.keyword && prevType === types$1.dot)
  17372. { this.exprAllowed = false; }
  17373. else if (update = type.updateContext)
  17374. { update.call(this, prevType); }
  17375. else
  17376. { this.exprAllowed = type.beforeExpr; }
  17377. };
  17378. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  17379. pp$6.overrideContext = function(tokenCtx) {
  17380. if (this.curContext() !== tokenCtx) {
  17381. this.context[this.context.length - 1] = tokenCtx;
  17382. }
  17383. };
  17384. // Token-specific context update code
  17385. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  17386. if (this.context.length === 1) {
  17387. this.exprAllowed = true;
  17388. return
  17389. }
  17390. var out = this.context.pop();
  17391. if (out === types.b_stat && this.curContext().token === "function") {
  17392. out = this.context.pop();
  17393. }
  17394. this.exprAllowed = !out.isExpr;
  17395. };
  17396. types$1.braceL.updateContext = function(prevType) {
  17397. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  17398. this.exprAllowed = true;
  17399. };
  17400. types$1.dollarBraceL.updateContext = function() {
  17401. this.context.push(types.b_tmpl);
  17402. this.exprAllowed = true;
  17403. };
  17404. types$1.parenL.updateContext = function(prevType) {
  17405. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  17406. this.context.push(statementParens ? types.p_stat : types.p_expr);
  17407. this.exprAllowed = true;
  17408. };
  17409. types$1.incDec.updateContext = function() {
  17410. // tokExprAllowed stays unchanged
  17411. };
  17412. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  17413. if (prevType.beforeExpr && prevType !== types$1._else &&
  17414. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  17415. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  17416. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  17417. { this.context.push(types.f_expr); }
  17418. else
  17419. { this.context.push(types.f_stat); }
  17420. this.exprAllowed = false;
  17421. };
  17422. types$1.backQuote.updateContext = function() {
  17423. if (this.curContext() === types.q_tmpl)
  17424. { this.context.pop(); }
  17425. else
  17426. { this.context.push(types.q_tmpl); }
  17427. this.exprAllowed = false;
  17428. };
  17429. types$1.star.updateContext = function(prevType) {
  17430. if (prevType === types$1._function) {
  17431. var index = this.context.length - 1;
  17432. if (this.context[index] === types.f_expr)
  17433. { this.context[index] = types.f_expr_gen; }
  17434. else
  17435. { this.context[index] = types.f_gen; }
  17436. }
  17437. this.exprAllowed = true;
  17438. };
  17439. types$1.name.updateContext = function(prevType) {
  17440. var allowed = false;
  17441. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  17442. if (this.value === "of" && !this.exprAllowed ||
  17443. this.value === "yield" && this.inGeneratorContext())
  17444. { allowed = true; }
  17445. }
  17446. this.exprAllowed = allowed;
  17447. };
  17448. // A recursive descent parser operates by defining functions for all
  17449. var pp$5 = Parser.prototype;
  17450. // Check if property name clashes with already added.
  17451. // Object/class getters and setters are not allowed to clash —
  17452. // either with each other or with an init property — and in
  17453. // strict mode, init properties are also not allowed to be repeated.
  17454. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  17455. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  17456. { return }
  17457. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  17458. { return }
  17459. var key = prop.key;
  17460. var name;
  17461. switch (key.type) {
  17462. case "Identifier": name = key.name; break
  17463. case "Literal": name = String(key.value); break
  17464. default: return
  17465. }
  17466. var kind = prop.kind;
  17467. if (this.options.ecmaVersion >= 6) {
  17468. if (name === "__proto__" && kind === "init") {
  17469. if (propHash.proto) {
  17470. if (refDestructuringErrors) {
  17471. if (refDestructuringErrors.doubleProto < 0) {
  17472. refDestructuringErrors.doubleProto = key.start;
  17473. }
  17474. } else {
  17475. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  17476. }
  17477. }
  17478. propHash.proto = true;
  17479. }
  17480. return
  17481. }
  17482. name = "$" + name;
  17483. var other = propHash[name];
  17484. if (other) {
  17485. var redefinition;
  17486. if (kind === "init") {
  17487. redefinition = this.strict && other.init || other.get || other.set;
  17488. } else {
  17489. redefinition = other.init || other[kind];
  17490. }
  17491. if (redefinition)
  17492. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  17493. } else {
  17494. other = propHash[name] = {
  17495. init: false,
  17496. get: false,
  17497. set: false
  17498. };
  17499. }
  17500. other[kind] = true;
  17501. };
  17502. // ### Expression parsing
  17503. // These nest, from the most general expression type at the top to
  17504. // 'atomic', nondivisible expression types at the bottom. Most of
  17505. // the functions will simply let the function(s) below them parse,
  17506. // and, *if* the syntactic construct they handle is present, wrap
  17507. // the AST node that the inner parser gave them in another node.
  17508. // Parse a full expression. The optional arguments are used to
  17509. // forbid the `in` operator (in for loops initalization expressions)
  17510. // and provide reference for storing '=' operator inside shorthand
  17511. // property assignment in contexts where both object expression
  17512. // and object pattern might appear (so it's possible to raise
  17513. // delayed syntax error at correct position).
  17514. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  17515. var startPos = this.start, startLoc = this.startLoc;
  17516. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  17517. if (this.type === types$1.comma) {
  17518. var node = this.startNodeAt(startPos, startLoc);
  17519. node.expressions = [expr];
  17520. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  17521. return this.finishNode(node, "SequenceExpression")
  17522. }
  17523. return expr
  17524. };
  17525. // Parse an assignment expression. This includes applications of
  17526. // operators like `+=`.
  17527. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  17528. if (this.isContextual("yield")) {
  17529. if (this.inGenerator) { return this.parseYield(forInit) }
  17530. // The tokenizer will assume an expression is allowed after
  17531. // `yield`, but this isn't that kind of yield
  17532. else { this.exprAllowed = false; }
  17533. }
  17534. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  17535. if (refDestructuringErrors) {
  17536. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  17537. oldTrailingComma = refDestructuringErrors.trailingComma;
  17538. oldDoubleProto = refDestructuringErrors.doubleProto;
  17539. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  17540. } else {
  17541. refDestructuringErrors = new DestructuringErrors;
  17542. ownDestructuringErrors = true;
  17543. }
  17544. var startPos = this.start, startLoc = this.startLoc;
  17545. if (this.type === types$1.parenL || this.type === types$1.name) {
  17546. this.potentialArrowAt = this.start;
  17547. this.potentialArrowInForAwait = forInit === "await";
  17548. }
  17549. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  17550. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  17551. if (this.type.isAssign) {
  17552. var node = this.startNodeAt(startPos, startLoc);
  17553. node.operator = this.value;
  17554. if (this.type === types$1.eq)
  17555. { left = this.toAssignable(left, false, refDestructuringErrors); }
  17556. if (!ownDestructuringErrors) {
  17557. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  17558. }
  17559. if (refDestructuringErrors.shorthandAssign >= left.start)
  17560. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  17561. if (this.type === types$1.eq)
  17562. { this.checkLValPattern(left); }
  17563. else
  17564. { this.checkLValSimple(left); }
  17565. node.left = left;
  17566. this.next();
  17567. node.right = this.parseMaybeAssign(forInit);
  17568. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  17569. return this.finishNode(node, "AssignmentExpression")
  17570. } else {
  17571. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  17572. }
  17573. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  17574. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  17575. return left
  17576. };
  17577. // Parse a ternary conditional (`?:`) operator.
  17578. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  17579. var startPos = this.start, startLoc = this.startLoc;
  17580. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  17581. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17582. if (this.eat(types$1.question)) {
  17583. var node = this.startNodeAt(startPos, startLoc);
  17584. node.test = expr;
  17585. node.consequent = this.parseMaybeAssign();
  17586. this.expect(types$1.colon);
  17587. node.alternate = this.parseMaybeAssign(forInit);
  17588. return this.finishNode(node, "ConditionalExpression")
  17589. }
  17590. return expr
  17591. };
  17592. // Start the precedence parser.
  17593. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  17594. var startPos = this.start, startLoc = this.startLoc;
  17595. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  17596. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17597. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  17598. };
  17599. // Parse binary operators with the operator precedence parsing
  17600. // algorithm. `left` is the left-hand side of the operator.
  17601. // `minPrec` provides context that allows the function to stop and
  17602. // defer further parser to one of its callers when it encounters an
  17603. // operator that has a lower precedence than the set it is parsing.
  17604. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  17605. var prec = this.type.binop;
  17606. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17607. if (prec > minPrec) {
  17608. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17609. var coalesce = this.type === types$1.coalesce;
  17610. if (coalesce) {
  17611. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17612. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17613. prec = types$1.logicalAND.binop;
  17614. }
  17615. var op = this.value;
  17616. this.next();
  17617. var startPos = this.start, startLoc = this.startLoc;
  17618. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17619. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17620. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17621. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17622. }
  17623. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17624. }
  17625. }
  17626. return left
  17627. };
  17628. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17629. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17630. var node = this.startNodeAt(startPos, startLoc);
  17631. node.left = left;
  17632. node.operator = op;
  17633. node.right = right;
  17634. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17635. };
  17636. // Parse unary operators, both prefix and postfix.
  17637. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17638. var startPos = this.start, startLoc = this.startLoc, expr;
  17639. if (this.isContextual("await") && this.canAwait) {
  17640. expr = this.parseAwait(forInit);
  17641. sawUnary = true;
  17642. } else if (this.type.prefix) {
  17643. var node = this.startNode(), update = this.type === types$1.incDec;
  17644. node.operator = this.value;
  17645. node.prefix = true;
  17646. this.next();
  17647. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17648. this.checkExpressionErrors(refDestructuringErrors, true);
  17649. if (update) { this.checkLValSimple(node.argument); }
  17650. else if (this.strict && node.operator === "delete" &&
  17651. node.argument.type === "Identifier")
  17652. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17653. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17654. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17655. else { sawUnary = true; }
  17656. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17657. } else if (!sawUnary && this.type === types$1.privateId) {
  17658. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17659. expr = this.parsePrivateIdent();
  17660. // only could be private fields in 'in', such as #x in obj
  17661. if (this.type !== types$1._in) { this.unexpected(); }
  17662. } else {
  17663. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17664. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17665. while (this.type.postfix && !this.canInsertSemicolon()) {
  17666. var node$1 = this.startNodeAt(startPos, startLoc);
  17667. node$1.operator = this.value;
  17668. node$1.prefix = false;
  17669. node$1.argument = expr;
  17670. this.checkLValSimple(expr);
  17671. this.next();
  17672. expr = this.finishNode(node$1, "UpdateExpression");
  17673. }
  17674. }
  17675. if (!incDec && this.eat(types$1.starstar)) {
  17676. if (sawUnary)
  17677. { this.unexpected(this.lastTokStart); }
  17678. else
  17679. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17680. } else {
  17681. return expr
  17682. }
  17683. };
  17684. function isPrivateFieldAccess(node) {
  17685. return (
  17686. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17687. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17688. )
  17689. }
  17690. // Parse call, dot, and `[]`-subscript expressions.
  17691. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17692. var startPos = this.start, startLoc = this.startLoc;
  17693. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17694. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17695. { return expr }
  17696. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17697. if (refDestructuringErrors && result.type === "MemberExpression") {
  17698. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17699. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17700. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17701. }
  17702. return result
  17703. };
  17704. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17705. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17706. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17707. this.potentialArrowAt === base.start;
  17708. var optionalChained = false;
  17709. while (true) {
  17710. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17711. if (element.optional) { optionalChained = true; }
  17712. if (element === base || element.type === "ArrowFunctionExpression") {
  17713. if (optionalChained) {
  17714. var chainNode = this.startNodeAt(startPos, startLoc);
  17715. chainNode.expression = element;
  17716. element = this.finishNode(chainNode, "ChainExpression");
  17717. }
  17718. return element
  17719. }
  17720. base = element;
  17721. }
  17722. };
  17723. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17724. var optionalSupported = this.options.ecmaVersion >= 11;
  17725. var optional = optionalSupported && this.eat(types$1.questionDot);
  17726. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17727. var computed = this.eat(types$1.bracketL);
  17728. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17729. var node = this.startNodeAt(startPos, startLoc);
  17730. node.object = base;
  17731. if (computed) {
  17732. node.property = this.parseExpression();
  17733. this.expect(types$1.bracketR);
  17734. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17735. node.property = this.parsePrivateIdent();
  17736. } else {
  17737. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17738. }
  17739. node.computed = !!computed;
  17740. if (optionalSupported) {
  17741. node.optional = optional;
  17742. }
  17743. base = this.finishNode(node, "MemberExpression");
  17744. } else if (!noCalls && this.eat(types$1.parenL)) {
  17745. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17746. this.yieldPos = 0;
  17747. this.awaitPos = 0;
  17748. this.awaitIdentPos = 0;
  17749. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17750. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17751. this.checkPatternErrors(refDestructuringErrors, false);
  17752. this.checkYieldAwaitInDefaultParams();
  17753. if (this.awaitIdentPos > 0)
  17754. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17755. this.yieldPos = oldYieldPos;
  17756. this.awaitPos = oldAwaitPos;
  17757. this.awaitIdentPos = oldAwaitIdentPos;
  17758. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17759. }
  17760. this.checkExpressionErrors(refDestructuringErrors, true);
  17761. this.yieldPos = oldYieldPos || this.yieldPos;
  17762. this.awaitPos = oldAwaitPos || this.awaitPos;
  17763. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17764. var node$1 = this.startNodeAt(startPos, startLoc);
  17765. node$1.callee = base;
  17766. node$1.arguments = exprList;
  17767. if (optionalSupported) {
  17768. node$1.optional = optional;
  17769. }
  17770. base = this.finishNode(node$1, "CallExpression");
  17771. } else if (this.type === types$1.backQuote) {
  17772. if (optional || optionalChained) {
  17773. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17774. }
  17775. var node$2 = this.startNodeAt(startPos, startLoc);
  17776. node$2.tag = base;
  17777. node$2.quasi = this.parseTemplate({isTagged: true});
  17778. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17779. }
  17780. return base
  17781. };
  17782. // Parse an atomic expression — either a single token that is an
  17783. // expression, an expression started by a keyword like `function` or
  17784. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17785. // or `{}`.
  17786. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17787. // If a division operator appears in an expression position, the
  17788. // tokenizer got confused, and we force it to read a regexp instead.
  17789. if (this.type === types$1.slash) { this.readRegexp(); }
  17790. var node, canBeArrow = this.potentialArrowAt === this.start;
  17791. switch (this.type) {
  17792. case types$1._super:
  17793. if (!this.allowSuper)
  17794. { this.raise(this.start, "'super' keyword outside a method"); }
  17795. node = this.startNode();
  17796. this.next();
  17797. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17798. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17799. // The `super` keyword can appear at below:
  17800. // SuperProperty:
  17801. // super [ Expression ]
  17802. // super . IdentifierName
  17803. // SuperCall:
  17804. // super ( Arguments )
  17805. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17806. { this.unexpected(); }
  17807. return this.finishNode(node, "Super")
  17808. case types$1._this:
  17809. node = this.startNode();
  17810. this.next();
  17811. return this.finishNode(node, "ThisExpression")
  17812. case types$1.name:
  17813. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17814. var id = this.parseIdent(false);
  17815. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17816. this.overrideContext(types.f_expr);
  17817. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17818. }
  17819. if (canBeArrow && !this.canInsertSemicolon()) {
  17820. if (this.eat(types$1.arrow))
  17821. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17822. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17823. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17824. id = this.parseIdent(false);
  17825. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17826. { this.unexpected(); }
  17827. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17828. }
  17829. }
  17830. return id
  17831. case types$1.regexp:
  17832. var value = this.value;
  17833. node = this.parseLiteral(value.value);
  17834. node.regex = {pattern: value.pattern, flags: value.flags};
  17835. return node
  17836. case types$1.num: case types$1.string:
  17837. return this.parseLiteral(this.value)
  17838. case types$1._null: case types$1._true: case types$1._false:
  17839. node = this.startNode();
  17840. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17841. node.raw = this.type.keyword;
  17842. this.next();
  17843. return this.finishNode(node, "Literal")
  17844. case types$1.parenL:
  17845. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17846. if (refDestructuringErrors) {
  17847. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17848. { refDestructuringErrors.parenthesizedAssign = start; }
  17849. if (refDestructuringErrors.parenthesizedBind < 0)
  17850. { refDestructuringErrors.parenthesizedBind = start; }
  17851. }
  17852. return expr
  17853. case types$1.bracketL:
  17854. node = this.startNode();
  17855. this.next();
  17856. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17857. return this.finishNode(node, "ArrayExpression")
  17858. case types$1.braceL:
  17859. this.overrideContext(types.b_expr);
  17860. return this.parseObj(false, refDestructuringErrors)
  17861. case types$1._function:
  17862. node = this.startNode();
  17863. this.next();
  17864. return this.parseFunction(node, 0)
  17865. case types$1._class:
  17866. return this.parseClass(this.startNode(), false)
  17867. case types$1._new:
  17868. return this.parseNew()
  17869. case types$1.backQuote:
  17870. return this.parseTemplate()
  17871. case types$1._import:
  17872. if (this.options.ecmaVersion >= 11) {
  17873. return this.parseExprImport()
  17874. } else {
  17875. return this.unexpected()
  17876. }
  17877. default:
  17878. this.unexpected();
  17879. }
  17880. };
  17881. pp$5.parseExprImport = function() {
  17882. var node = this.startNode();
  17883. // Consume `import` as an identifier for `import.meta`.
  17884. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17885. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17886. var meta = this.parseIdent(true);
  17887. switch (this.type) {
  17888. case types$1.parenL:
  17889. return this.parseDynamicImport(node)
  17890. case types$1.dot:
  17891. node.meta = meta;
  17892. return this.parseImportMeta(node)
  17893. default:
  17894. this.unexpected();
  17895. }
  17896. };
  17897. pp$5.parseDynamicImport = function(node) {
  17898. this.next(); // skip `(`
  17899. // Parse node.source.
  17900. node.source = this.parseMaybeAssign();
  17901. // Verify ending.
  17902. if (!this.eat(types$1.parenR)) {
  17903. var errorPos = this.start;
  17904. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17905. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17906. } else {
  17907. this.unexpected(errorPos);
  17908. }
  17909. }
  17910. return this.finishNode(node, "ImportExpression")
  17911. };
  17912. pp$5.parseImportMeta = function(node) {
  17913. this.next(); // skip `.`
  17914. var containsEsc = this.containsEsc;
  17915. node.property = this.parseIdent(true);
  17916. if (node.property.name !== "meta")
  17917. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17918. if (containsEsc)
  17919. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17920. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17921. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17922. return this.finishNode(node, "MetaProperty")
  17923. };
  17924. pp$5.parseLiteral = function(value) {
  17925. var node = this.startNode();
  17926. node.value = value;
  17927. node.raw = this.input.slice(this.start, this.end);
  17928. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17929. this.next();
  17930. return this.finishNode(node, "Literal")
  17931. };
  17932. pp$5.parseParenExpression = function() {
  17933. this.expect(types$1.parenL);
  17934. var val = this.parseExpression();
  17935. this.expect(types$1.parenR);
  17936. return val
  17937. };
  17938. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17939. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17940. if (this.options.ecmaVersion >= 6) {
  17941. this.next();
  17942. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17943. var exprList = [], first = true, lastIsComma = false;
  17944. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17945. this.yieldPos = 0;
  17946. this.awaitPos = 0;
  17947. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17948. while (this.type !== types$1.parenR) {
  17949. first ? first = false : this.expect(types$1.comma);
  17950. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17951. lastIsComma = true;
  17952. break
  17953. } else if (this.type === types$1.ellipsis) {
  17954. spreadStart = this.start;
  17955. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17956. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17957. break
  17958. } else {
  17959. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17960. }
  17961. }
  17962. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17963. this.expect(types$1.parenR);
  17964. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17965. this.checkPatternErrors(refDestructuringErrors, false);
  17966. this.checkYieldAwaitInDefaultParams();
  17967. this.yieldPos = oldYieldPos;
  17968. this.awaitPos = oldAwaitPos;
  17969. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17970. }
  17971. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17972. if (spreadStart) { this.unexpected(spreadStart); }
  17973. this.checkExpressionErrors(refDestructuringErrors, true);
  17974. this.yieldPos = oldYieldPos || this.yieldPos;
  17975. this.awaitPos = oldAwaitPos || this.awaitPos;
  17976. if (exprList.length > 1) {
  17977. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17978. val.expressions = exprList;
  17979. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17980. } else {
  17981. val = exprList[0];
  17982. }
  17983. } else {
  17984. val = this.parseParenExpression();
  17985. }
  17986. if (this.options.preserveParens) {
  17987. var par = this.startNodeAt(startPos, startLoc);
  17988. par.expression = val;
  17989. return this.finishNode(par, "ParenthesizedExpression")
  17990. } else {
  17991. return val
  17992. }
  17993. };
  17994. pp$5.parseParenItem = function(item) {
  17995. return item
  17996. };
  17997. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17998. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17999. };
  18000. // New's precedence is slightly tricky. It must allow its argument to
  18001. // be a `[]` or dot subscript expression, but not a call — at least,
  18002. // not without wrapping it in parentheses. Thus, it uses the noCalls
  18003. // argument to parseSubscripts to prevent it from consuming the
  18004. // argument list.
  18005. var empty = [];
  18006. pp$5.parseNew = function() {
  18007. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  18008. var node = this.startNode();
  18009. var meta = this.parseIdent(true);
  18010. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  18011. node.meta = meta;
  18012. var containsEsc = this.containsEsc;
  18013. node.property = this.parseIdent(true);
  18014. if (node.property.name !== "target")
  18015. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  18016. if (containsEsc)
  18017. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  18018. if (!this.allowNewDotTarget)
  18019. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  18020. return this.finishNode(node, "MetaProperty")
  18021. }
  18022. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  18023. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  18024. if (isImport && node.callee.type === "ImportExpression") {
  18025. this.raise(startPos, "Cannot use new with import()");
  18026. }
  18027. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  18028. else { node.arguments = empty; }
  18029. return this.finishNode(node, "NewExpression")
  18030. };
  18031. // Parse template expression.
  18032. pp$5.parseTemplateElement = function(ref) {
  18033. var isTagged = ref.isTagged;
  18034. var elem = this.startNode();
  18035. if (this.type === types$1.invalidTemplate) {
  18036. if (!isTagged) {
  18037. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  18038. }
  18039. elem.value = {
  18040. raw: this.value,
  18041. cooked: null
  18042. };
  18043. } else {
  18044. elem.value = {
  18045. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  18046. cooked: this.value
  18047. };
  18048. }
  18049. this.next();
  18050. elem.tail = this.type === types$1.backQuote;
  18051. return this.finishNode(elem, "TemplateElement")
  18052. };
  18053. pp$5.parseTemplate = function(ref) {
  18054. if ( ref === void 0 ) ref = {};
  18055. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  18056. var node = this.startNode();
  18057. this.next();
  18058. node.expressions = [];
  18059. var curElt = this.parseTemplateElement({isTagged: isTagged});
  18060. node.quasis = [curElt];
  18061. while (!curElt.tail) {
  18062. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  18063. this.expect(types$1.dollarBraceL);
  18064. node.expressions.push(this.parseExpression());
  18065. this.expect(types$1.braceR);
  18066. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  18067. }
  18068. this.next();
  18069. return this.finishNode(node, "TemplateLiteral")
  18070. };
  18071. pp$5.isAsyncProp = function(prop) {
  18072. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  18073. (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)) &&
  18074. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  18075. };
  18076. // Parse an object literal or binding pattern.
  18077. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  18078. var node = this.startNode(), first = true, propHash = {};
  18079. node.properties = [];
  18080. this.next();
  18081. while (!this.eat(types$1.braceR)) {
  18082. if (!first) {
  18083. this.expect(types$1.comma);
  18084. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  18085. } else { first = false; }
  18086. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  18087. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  18088. node.properties.push(prop);
  18089. }
  18090. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  18091. };
  18092. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  18093. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  18094. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  18095. if (isPattern) {
  18096. prop.argument = this.parseIdent(false);
  18097. if (this.type === types$1.comma) {
  18098. this.raise(this.start, "Comma is not permitted after the rest element");
  18099. }
  18100. return this.finishNode(prop, "RestElement")
  18101. }
  18102. // To disallow parenthesized identifier via `this.toAssignable()`.
  18103. if (this.type === types$1.parenL && refDestructuringErrors) {
  18104. if (refDestructuringErrors.parenthesizedAssign < 0) {
  18105. refDestructuringErrors.parenthesizedAssign = this.start;
  18106. }
  18107. if (refDestructuringErrors.parenthesizedBind < 0) {
  18108. refDestructuringErrors.parenthesizedBind = this.start;
  18109. }
  18110. }
  18111. // Parse argument.
  18112. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  18113. // To disallow trailing comma via `this.toAssignable()`.
  18114. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  18115. refDestructuringErrors.trailingComma = this.start;
  18116. }
  18117. // Finish
  18118. return this.finishNode(prop, "SpreadElement")
  18119. }
  18120. if (this.options.ecmaVersion >= 6) {
  18121. prop.method = false;
  18122. prop.shorthand = false;
  18123. if (isPattern || refDestructuringErrors) {
  18124. startPos = this.start;
  18125. startLoc = this.startLoc;
  18126. }
  18127. if (!isPattern)
  18128. { isGenerator = this.eat(types$1.star); }
  18129. }
  18130. var containsEsc = this.containsEsc;
  18131. this.parsePropertyName(prop);
  18132. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  18133. isAsync = true;
  18134. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  18135. this.parsePropertyName(prop, refDestructuringErrors);
  18136. } else {
  18137. isAsync = false;
  18138. }
  18139. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  18140. return this.finishNode(prop, "Property")
  18141. };
  18142. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  18143. if ((isGenerator || isAsync) && this.type === types$1.colon)
  18144. { this.unexpected(); }
  18145. if (this.eat(types$1.colon)) {
  18146. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  18147. prop.kind = "init";
  18148. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  18149. if (isPattern) { this.unexpected(); }
  18150. prop.kind = "init";
  18151. prop.method = true;
  18152. prop.value = this.parseMethod(isGenerator, isAsync);
  18153. } else if (!isPattern && !containsEsc &&
  18154. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  18155. (prop.key.name === "get" || prop.key.name === "set") &&
  18156. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  18157. if (isGenerator || isAsync) { this.unexpected(); }
  18158. prop.kind = prop.key.name;
  18159. this.parsePropertyName(prop);
  18160. prop.value = this.parseMethod(false);
  18161. var paramCount = prop.kind === "get" ? 0 : 1;
  18162. if (prop.value.params.length !== paramCount) {
  18163. var start = prop.value.start;
  18164. if (prop.kind === "get")
  18165. { this.raiseRecoverable(start, "getter should have no params"); }
  18166. else
  18167. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  18168. } else {
  18169. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  18170. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  18171. }
  18172. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  18173. if (isGenerator || isAsync) { this.unexpected(); }
  18174. this.checkUnreserved(prop.key);
  18175. if (prop.key.name === "await" && !this.awaitIdentPos)
  18176. { this.awaitIdentPos = startPos; }
  18177. prop.kind = "init";
  18178. if (isPattern) {
  18179. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18180. } else if (this.type === types$1.eq && refDestructuringErrors) {
  18181. if (refDestructuringErrors.shorthandAssign < 0)
  18182. { refDestructuringErrors.shorthandAssign = this.start; }
  18183. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18184. } else {
  18185. prop.value = this.copyNode(prop.key);
  18186. }
  18187. prop.shorthand = true;
  18188. } else { this.unexpected(); }
  18189. };
  18190. pp$5.parsePropertyName = function(prop) {
  18191. if (this.options.ecmaVersion >= 6) {
  18192. if (this.eat(types$1.bracketL)) {
  18193. prop.computed = true;
  18194. prop.key = this.parseMaybeAssign();
  18195. this.expect(types$1.bracketR);
  18196. return prop.key
  18197. } else {
  18198. prop.computed = false;
  18199. }
  18200. }
  18201. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  18202. };
  18203. // Initialize empty function node.
  18204. pp$5.initFunction = function(node) {
  18205. node.id = null;
  18206. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  18207. if (this.options.ecmaVersion >= 8) { node.async = false; }
  18208. };
  18209. // Parse object or class method.
  18210. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  18211. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18212. this.initFunction(node);
  18213. if (this.options.ecmaVersion >= 6)
  18214. { node.generator = isGenerator; }
  18215. if (this.options.ecmaVersion >= 8)
  18216. { node.async = !!isAsync; }
  18217. this.yieldPos = 0;
  18218. this.awaitPos = 0;
  18219. this.awaitIdentPos = 0;
  18220. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  18221. this.expect(types$1.parenL);
  18222. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18223. this.checkYieldAwaitInDefaultParams();
  18224. this.parseFunctionBody(node, false, true, false);
  18225. this.yieldPos = oldYieldPos;
  18226. this.awaitPos = oldAwaitPos;
  18227. this.awaitIdentPos = oldAwaitIdentPos;
  18228. return this.finishNode(node, "FunctionExpression")
  18229. };
  18230. // Parse arrow function expression with given parameters.
  18231. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  18232. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18233. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  18234. this.initFunction(node);
  18235. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  18236. this.yieldPos = 0;
  18237. this.awaitPos = 0;
  18238. this.awaitIdentPos = 0;
  18239. node.params = this.toAssignableList(params, true);
  18240. this.parseFunctionBody(node, true, false, forInit);
  18241. this.yieldPos = oldYieldPos;
  18242. this.awaitPos = oldAwaitPos;
  18243. this.awaitIdentPos = oldAwaitIdentPos;
  18244. return this.finishNode(node, "ArrowFunctionExpression")
  18245. };
  18246. // Parse function body and check parameters.
  18247. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  18248. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  18249. var oldStrict = this.strict, useStrict = false;
  18250. if (isExpression) {
  18251. node.body = this.parseMaybeAssign(forInit);
  18252. node.expression = true;
  18253. this.checkParams(node, false);
  18254. } else {
  18255. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  18256. if (!oldStrict || nonSimple) {
  18257. useStrict = this.strictDirective(this.end);
  18258. // If this is a strict mode function, verify that argument names
  18259. // are not repeated, and it does not try to bind the words `eval`
  18260. // or `arguments`.
  18261. if (useStrict && nonSimple)
  18262. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  18263. }
  18264. // Start a new scope with regard to labels and the `inFunction`
  18265. // flag (restore them to their old value afterwards).
  18266. var oldLabels = this.labels;
  18267. this.labels = [];
  18268. if (useStrict) { this.strict = true; }
  18269. // Add the params to varDeclaredNames to ensure that an error is thrown
  18270. // if a let/const declaration in the function clashes with one of the params.
  18271. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  18272. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  18273. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  18274. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  18275. node.expression = false;
  18276. this.adaptDirectivePrologue(node.body.body);
  18277. this.labels = oldLabels;
  18278. }
  18279. this.exitScope();
  18280. };
  18281. pp$5.isSimpleParamList = function(params) {
  18282. for (var i = 0, list = params; i < list.length; i += 1)
  18283. {
  18284. var param = list[i];
  18285. if (param.type !== "Identifier") { return false
  18286. } }
  18287. return true
  18288. };
  18289. // Checks function params for various disallowed patterns such as using "eval"
  18290. // or "arguments" and duplicate parameters.
  18291. pp$5.checkParams = function(node, allowDuplicates) {
  18292. var nameHash = Object.create(null);
  18293. for (var i = 0, list = node.params; i < list.length; i += 1)
  18294. {
  18295. var param = list[i];
  18296. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  18297. }
  18298. };
  18299. // Parses a comma-separated list of expressions, and returns them as
  18300. // an array. `close` is the token type that ends the list, and
  18301. // `allowEmpty` can be turned on to allow subsequent commas with
  18302. // nothing in between them to be parsed as `null` (which is needed
  18303. // for array literals).
  18304. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  18305. var elts = [], first = true;
  18306. while (!this.eat(close)) {
  18307. if (!first) {
  18308. this.expect(types$1.comma);
  18309. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  18310. } else { first = false; }
  18311. var elt = (void 0);
  18312. if (allowEmpty && this.type === types$1.comma)
  18313. { elt = null; }
  18314. else if (this.type === types$1.ellipsis) {
  18315. elt = this.parseSpread(refDestructuringErrors);
  18316. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  18317. { refDestructuringErrors.trailingComma = this.start; }
  18318. } else {
  18319. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  18320. }
  18321. elts.push(elt);
  18322. }
  18323. return elts
  18324. };
  18325. pp$5.checkUnreserved = function(ref) {
  18326. var start = ref.start;
  18327. var end = ref.end;
  18328. var name = ref.name;
  18329. if (this.inGenerator && name === "yield")
  18330. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  18331. if (this.inAsync && name === "await")
  18332. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  18333. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  18334. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  18335. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  18336. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  18337. if (this.keywords.test(name))
  18338. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  18339. if (this.options.ecmaVersion < 6 &&
  18340. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  18341. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  18342. if (re.test(name)) {
  18343. if (!this.inAsync && name === "await")
  18344. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  18345. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  18346. }
  18347. };
  18348. // Parse the next token as an identifier. If `liberal` is true (used
  18349. // when parsing properties), it will also convert keywords into
  18350. // identifiers.
  18351. pp$5.parseIdent = function(liberal, isBinding) {
  18352. var node = this.startNode();
  18353. if (this.type === types$1.name) {
  18354. node.name = this.value;
  18355. } else if (this.type.keyword) {
  18356. node.name = this.type.keyword;
  18357. // To fix https://github.com/acornjs/acorn/issues/575
  18358. // `class` and `function` keywords push new context into this.context.
  18359. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  18360. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  18361. if ((node.name === "class" || node.name === "function") &&
  18362. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  18363. this.context.pop();
  18364. }
  18365. } else {
  18366. this.unexpected();
  18367. }
  18368. this.next(!!liberal);
  18369. this.finishNode(node, "Identifier");
  18370. if (!liberal) {
  18371. this.checkUnreserved(node);
  18372. if (node.name === "await" && !this.awaitIdentPos)
  18373. { this.awaitIdentPos = node.start; }
  18374. }
  18375. return node
  18376. };
  18377. pp$5.parsePrivateIdent = function() {
  18378. var node = this.startNode();
  18379. if (this.type === types$1.privateId) {
  18380. node.name = this.value;
  18381. } else {
  18382. this.unexpected();
  18383. }
  18384. this.next();
  18385. this.finishNode(node, "PrivateIdentifier");
  18386. // For validating existence
  18387. if (this.privateNameStack.length === 0) {
  18388. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  18389. } else {
  18390. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  18391. }
  18392. return node
  18393. };
  18394. // Parses yield expression inside generator.
  18395. pp$5.parseYield = function(forInit) {
  18396. if (!this.yieldPos) { this.yieldPos = this.start; }
  18397. var node = this.startNode();
  18398. this.next();
  18399. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  18400. node.delegate = false;
  18401. node.argument = null;
  18402. } else {
  18403. node.delegate = this.eat(types$1.star);
  18404. node.argument = this.parseMaybeAssign(forInit);
  18405. }
  18406. return this.finishNode(node, "YieldExpression")
  18407. };
  18408. pp$5.parseAwait = function(forInit) {
  18409. if (!this.awaitPos) { this.awaitPos = this.start; }
  18410. var node = this.startNode();
  18411. this.next();
  18412. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  18413. return this.finishNode(node, "AwaitExpression")
  18414. };
  18415. var pp$4 = Parser.prototype;
  18416. // This function is used to raise exceptions on parse errors. It
  18417. // takes an offset integer (into the current `input`) to indicate
  18418. // the location of the error, attaches the position to the end
  18419. // of the error message, and then raises a `SyntaxError` with that
  18420. // message.
  18421. pp$4.raise = function(pos, message) {
  18422. var loc = getLineInfo(this.input, pos);
  18423. message += " (" + loc.line + ":" + loc.column + ")";
  18424. var err = new SyntaxError(message);
  18425. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  18426. throw err
  18427. };
  18428. pp$4.raiseRecoverable = pp$4.raise;
  18429. pp$4.curPosition = function() {
  18430. if (this.options.locations) {
  18431. return new Position(this.curLine, this.pos - this.lineStart)
  18432. }
  18433. };
  18434. var pp$3 = Parser.prototype;
  18435. var Scope = function Scope(flags) {
  18436. this.flags = flags;
  18437. // A list of var-declared names in the current lexical scope
  18438. this.var = [];
  18439. // A list of lexically-declared names in the current lexical scope
  18440. this.lexical = [];
  18441. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  18442. this.functions = [];
  18443. // A switch to disallow the identifier reference 'arguments'
  18444. this.inClassFieldInit = false;
  18445. };
  18446. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  18447. pp$3.enterScope = function(flags) {
  18448. this.scopeStack.push(new Scope(flags));
  18449. };
  18450. pp$3.exitScope = function() {
  18451. this.scopeStack.pop();
  18452. };
  18453. // The spec says:
  18454. // > At the top level of a function, or script, function declarations are
  18455. // > treated like var declarations rather than like lexical declarations.
  18456. pp$3.treatFunctionsAsVarInScope = function(scope) {
  18457. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  18458. };
  18459. pp$3.declareName = function(name, bindingType, pos) {
  18460. var redeclared = false;
  18461. if (bindingType === BIND_LEXICAL) {
  18462. var scope = this.currentScope();
  18463. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  18464. scope.lexical.push(name);
  18465. if (this.inModule && (scope.flags & SCOPE_TOP))
  18466. { delete this.undefinedExports[name]; }
  18467. } else if (bindingType === BIND_SIMPLE_CATCH) {
  18468. var scope$1 = this.currentScope();
  18469. scope$1.lexical.push(name);
  18470. } else if (bindingType === BIND_FUNCTION) {
  18471. var scope$2 = this.currentScope();
  18472. if (this.treatFunctionsAsVar)
  18473. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  18474. else
  18475. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  18476. scope$2.functions.push(name);
  18477. } else {
  18478. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  18479. var scope$3 = this.scopeStack[i];
  18480. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  18481. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  18482. redeclared = true;
  18483. break
  18484. }
  18485. scope$3.var.push(name);
  18486. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  18487. { delete this.undefinedExports[name]; }
  18488. if (scope$3.flags & SCOPE_VAR) { break }
  18489. }
  18490. }
  18491. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  18492. };
  18493. pp$3.checkLocalExport = function(id) {
  18494. // scope.functions must be empty as Module code is always strict.
  18495. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  18496. this.scopeStack[0].var.indexOf(id.name) === -1) {
  18497. this.undefinedExports[id.name] = id;
  18498. }
  18499. };
  18500. pp$3.currentScope = function() {
  18501. return this.scopeStack[this.scopeStack.length - 1]
  18502. };
  18503. pp$3.currentVarScope = function() {
  18504. for (var i = this.scopeStack.length - 1;; i--) {
  18505. var scope = this.scopeStack[i];
  18506. if (scope.flags & SCOPE_VAR) { return scope }
  18507. }
  18508. };
  18509. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  18510. pp$3.currentThisScope = function() {
  18511. for (var i = this.scopeStack.length - 1;; i--) {
  18512. var scope = this.scopeStack[i];
  18513. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  18514. }
  18515. };
  18516. var Node = function Node(parser, pos, loc) {
  18517. this.type = "";
  18518. this.start = pos;
  18519. this.end = 0;
  18520. if (parser.options.locations)
  18521. { this.loc = new SourceLocation(parser, loc); }
  18522. if (parser.options.directSourceFile)
  18523. { this.sourceFile = parser.options.directSourceFile; }
  18524. if (parser.options.ranges)
  18525. { this.range = [pos, 0]; }
  18526. };
  18527. // Start an AST node, attaching a start offset.
  18528. var pp$2 = Parser.prototype;
  18529. pp$2.startNode = function() {
  18530. return new Node(this, this.start, this.startLoc)
  18531. };
  18532. pp$2.startNodeAt = function(pos, loc) {
  18533. return new Node(this, pos, loc)
  18534. };
  18535. // Finish an AST node, adding `type` and `end` properties.
  18536. function finishNodeAt(node, type, pos, loc) {
  18537. node.type = type;
  18538. node.end = pos;
  18539. if (this.options.locations)
  18540. { node.loc.end = loc; }
  18541. if (this.options.ranges)
  18542. { node.range[1] = pos; }
  18543. return node
  18544. }
  18545. pp$2.finishNode = function(node, type) {
  18546. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  18547. };
  18548. // Finish node at given position
  18549. pp$2.finishNodeAt = function(node, type, pos, loc) {
  18550. return finishNodeAt.call(this, node, type, pos, loc)
  18551. };
  18552. pp$2.copyNode = function(node) {
  18553. var newNode = new Node(this, node.start, this.startLoc);
  18554. for (var prop in node) { newNode[prop] = node[prop]; }
  18555. return newNode
  18556. };
  18557. // This file contains Unicode properties extracted from the ECMAScript
  18558. // specification. The lists are extracted like so:
  18559. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  18560. // #table-binary-unicode-properties
  18561. 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";
  18562. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  18563. var ecma11BinaryProperties = ecma10BinaryProperties;
  18564. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  18565. var ecma13BinaryProperties = ecma12BinaryProperties;
  18566. var unicodeBinaryProperties = {
  18567. 9: ecma9BinaryProperties,
  18568. 10: ecma10BinaryProperties,
  18569. 11: ecma11BinaryProperties,
  18570. 12: ecma12BinaryProperties,
  18571. 13: ecma13BinaryProperties
  18572. };
  18573. // #table-unicode-general-category-values
  18574. 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";
  18575. // #table-unicode-script-values
  18576. 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";
  18577. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  18578. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  18579. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  18580. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  18581. var unicodeScriptValues = {
  18582. 9: ecma9ScriptValues,
  18583. 10: ecma10ScriptValues,
  18584. 11: ecma11ScriptValues,
  18585. 12: ecma12ScriptValues,
  18586. 13: ecma13ScriptValues
  18587. };
  18588. var data = {};
  18589. function buildUnicodeData(ecmaVersion) {
  18590. var d = data[ecmaVersion] = {
  18591. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  18592. nonBinary: {
  18593. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  18594. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  18595. }
  18596. };
  18597. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  18598. d.nonBinary.gc = d.nonBinary.General_Category;
  18599. d.nonBinary.sc = d.nonBinary.Script;
  18600. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  18601. }
  18602. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  18603. var ecmaVersion = list[i];
  18604. buildUnicodeData(ecmaVersion);
  18605. }
  18606. var pp$1 = Parser.prototype;
  18607. var RegExpValidationState = function RegExpValidationState(parser) {
  18608. this.parser = parser;
  18609. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  18610. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  18611. this.source = "";
  18612. this.flags = "";
  18613. this.start = 0;
  18614. this.switchU = false;
  18615. this.switchN = false;
  18616. this.pos = 0;
  18617. this.lastIntValue = 0;
  18618. this.lastStringValue = "";
  18619. this.lastAssertionIsQuantifiable = false;
  18620. this.numCapturingParens = 0;
  18621. this.maxBackReference = 0;
  18622. this.groupNames = [];
  18623. this.backReferenceNames = [];
  18624. };
  18625. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18626. var unicode = flags.indexOf("u") !== -1;
  18627. this.start = start | 0;
  18628. this.source = pattern + "";
  18629. this.flags = flags;
  18630. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18631. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18632. };
  18633. RegExpValidationState.prototype.raise = function raise (message) {
  18634. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18635. };
  18636. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18637. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18638. RegExpValidationState.prototype.at = function at (i, forceU) {
  18639. if ( forceU === void 0 ) forceU = false;
  18640. var s = this.source;
  18641. var l = s.length;
  18642. if (i >= l) {
  18643. return -1
  18644. }
  18645. var c = s.charCodeAt(i);
  18646. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18647. return c
  18648. }
  18649. var next = s.charCodeAt(i + 1);
  18650. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18651. };
  18652. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18653. if ( forceU === void 0 ) forceU = false;
  18654. var s = this.source;
  18655. var l = s.length;
  18656. if (i >= l) {
  18657. return l
  18658. }
  18659. var c = s.charCodeAt(i), next;
  18660. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18661. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18662. return i + 1
  18663. }
  18664. return i + 2
  18665. };
  18666. RegExpValidationState.prototype.current = function current (forceU) {
  18667. if ( forceU === void 0 ) forceU = false;
  18668. return this.at(this.pos, forceU)
  18669. };
  18670. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18671. if ( forceU === void 0 ) forceU = false;
  18672. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18673. };
  18674. RegExpValidationState.prototype.advance = function advance (forceU) {
  18675. if ( forceU === void 0 ) forceU = false;
  18676. this.pos = this.nextIndex(this.pos, forceU);
  18677. };
  18678. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18679. if ( forceU === void 0 ) forceU = false;
  18680. if (this.current(forceU) === ch) {
  18681. this.advance(forceU);
  18682. return true
  18683. }
  18684. return false
  18685. };
  18686. /**
  18687. * Validate the flags part of a given RegExpLiteral.
  18688. *
  18689. * @param {RegExpValidationState} state The state to validate RegExp.
  18690. * @returns {void}
  18691. */
  18692. pp$1.validateRegExpFlags = function(state) {
  18693. var validFlags = state.validFlags;
  18694. var flags = state.flags;
  18695. for (var i = 0; i < flags.length; i++) {
  18696. var flag = flags.charAt(i);
  18697. if (validFlags.indexOf(flag) === -1) {
  18698. this.raise(state.start, "Invalid regular expression flag");
  18699. }
  18700. if (flags.indexOf(flag, i + 1) > -1) {
  18701. this.raise(state.start, "Duplicate regular expression flag");
  18702. }
  18703. }
  18704. };
  18705. /**
  18706. * Validate the pattern part of a given RegExpLiteral.
  18707. *
  18708. * @param {RegExpValidationState} state The state to validate RegExp.
  18709. * @returns {void}
  18710. */
  18711. pp$1.validateRegExpPattern = function(state) {
  18712. this.regexp_pattern(state);
  18713. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18714. // parsing contains a |GroupName|, reparse with the goal symbol
  18715. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18716. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18717. // were not matched by the parse, or if any Early Error conditions exist.
  18718. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18719. state.switchN = true;
  18720. this.regexp_pattern(state);
  18721. }
  18722. };
  18723. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18724. pp$1.regexp_pattern = function(state) {
  18725. state.pos = 0;
  18726. state.lastIntValue = 0;
  18727. state.lastStringValue = "";
  18728. state.lastAssertionIsQuantifiable = false;
  18729. state.numCapturingParens = 0;
  18730. state.maxBackReference = 0;
  18731. state.groupNames.length = 0;
  18732. state.backReferenceNames.length = 0;
  18733. this.regexp_disjunction(state);
  18734. if (state.pos !== state.source.length) {
  18735. // Make the same messages as V8.
  18736. if (state.eat(0x29 /* ) */)) {
  18737. state.raise("Unmatched ')'");
  18738. }
  18739. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18740. state.raise("Lone quantifier brackets");
  18741. }
  18742. }
  18743. if (state.maxBackReference > state.numCapturingParens) {
  18744. state.raise("Invalid escape");
  18745. }
  18746. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18747. var name = list[i];
  18748. if (state.groupNames.indexOf(name) === -1) {
  18749. state.raise("Invalid named capture referenced");
  18750. }
  18751. }
  18752. };
  18753. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18754. pp$1.regexp_disjunction = function(state) {
  18755. this.regexp_alternative(state);
  18756. while (state.eat(0x7C /* | */)) {
  18757. this.regexp_alternative(state);
  18758. }
  18759. // Make the same message as V8.
  18760. if (this.regexp_eatQuantifier(state, true)) {
  18761. state.raise("Nothing to repeat");
  18762. }
  18763. if (state.eat(0x7B /* { */)) {
  18764. state.raise("Lone quantifier brackets");
  18765. }
  18766. };
  18767. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18768. pp$1.regexp_alternative = function(state) {
  18769. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18770. { }
  18771. };
  18772. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18773. pp$1.regexp_eatTerm = function(state) {
  18774. if (this.regexp_eatAssertion(state)) {
  18775. // Handle `QuantifiableAssertion Quantifier` alternative.
  18776. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18777. // is a QuantifiableAssertion.
  18778. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18779. // Make the same message as V8.
  18780. if (state.switchU) {
  18781. state.raise("Invalid quantifier");
  18782. }
  18783. }
  18784. return true
  18785. }
  18786. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18787. this.regexp_eatQuantifier(state);
  18788. return true
  18789. }
  18790. return false
  18791. };
  18792. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18793. pp$1.regexp_eatAssertion = function(state) {
  18794. var start = state.pos;
  18795. state.lastAssertionIsQuantifiable = false;
  18796. // ^, $
  18797. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18798. return true
  18799. }
  18800. // \b \B
  18801. if (state.eat(0x5C /* \ */)) {
  18802. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18803. return true
  18804. }
  18805. state.pos = start;
  18806. }
  18807. // Lookahead / Lookbehind
  18808. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18809. var lookbehind = false;
  18810. if (this.options.ecmaVersion >= 9) {
  18811. lookbehind = state.eat(0x3C /* < */);
  18812. }
  18813. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18814. this.regexp_disjunction(state);
  18815. if (!state.eat(0x29 /* ) */)) {
  18816. state.raise("Unterminated group");
  18817. }
  18818. state.lastAssertionIsQuantifiable = !lookbehind;
  18819. return true
  18820. }
  18821. }
  18822. state.pos = start;
  18823. return false
  18824. };
  18825. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18826. pp$1.regexp_eatQuantifier = function(state, noError) {
  18827. if ( noError === void 0 ) noError = false;
  18828. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18829. state.eat(0x3F /* ? */);
  18830. return true
  18831. }
  18832. return false
  18833. };
  18834. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18835. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18836. return (
  18837. state.eat(0x2A /* * */) ||
  18838. state.eat(0x2B /* + */) ||
  18839. state.eat(0x3F /* ? */) ||
  18840. this.regexp_eatBracedQuantifier(state, noError)
  18841. )
  18842. };
  18843. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18844. var start = state.pos;
  18845. if (state.eat(0x7B /* { */)) {
  18846. var min = 0, max = -1;
  18847. if (this.regexp_eatDecimalDigits(state)) {
  18848. min = state.lastIntValue;
  18849. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18850. max = state.lastIntValue;
  18851. }
  18852. if (state.eat(0x7D /* } */)) {
  18853. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18854. if (max !== -1 && max < min && !noError) {
  18855. state.raise("numbers out of order in {} quantifier");
  18856. }
  18857. return true
  18858. }
  18859. }
  18860. if (state.switchU && !noError) {
  18861. state.raise("Incomplete quantifier");
  18862. }
  18863. state.pos = start;
  18864. }
  18865. return false
  18866. };
  18867. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18868. pp$1.regexp_eatAtom = function(state) {
  18869. return (
  18870. this.regexp_eatPatternCharacters(state) ||
  18871. state.eat(0x2E /* . */) ||
  18872. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18873. this.regexp_eatCharacterClass(state) ||
  18874. this.regexp_eatUncapturingGroup(state) ||
  18875. this.regexp_eatCapturingGroup(state)
  18876. )
  18877. };
  18878. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18879. var start = state.pos;
  18880. if (state.eat(0x5C /* \ */)) {
  18881. if (this.regexp_eatAtomEscape(state)) {
  18882. return true
  18883. }
  18884. state.pos = start;
  18885. }
  18886. return false
  18887. };
  18888. pp$1.regexp_eatUncapturingGroup = function(state) {
  18889. var start = state.pos;
  18890. if (state.eat(0x28 /* ( */)) {
  18891. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18892. this.regexp_disjunction(state);
  18893. if (state.eat(0x29 /* ) */)) {
  18894. return true
  18895. }
  18896. state.raise("Unterminated group");
  18897. }
  18898. state.pos = start;
  18899. }
  18900. return false
  18901. };
  18902. pp$1.regexp_eatCapturingGroup = function(state) {
  18903. if (state.eat(0x28 /* ( */)) {
  18904. if (this.options.ecmaVersion >= 9) {
  18905. this.regexp_groupSpecifier(state);
  18906. } else if (state.current() === 0x3F /* ? */) {
  18907. state.raise("Invalid group");
  18908. }
  18909. this.regexp_disjunction(state);
  18910. if (state.eat(0x29 /* ) */)) {
  18911. state.numCapturingParens += 1;
  18912. return true
  18913. }
  18914. state.raise("Unterminated group");
  18915. }
  18916. return false
  18917. };
  18918. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18919. pp$1.regexp_eatExtendedAtom = function(state) {
  18920. return (
  18921. state.eat(0x2E /* . */) ||
  18922. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18923. this.regexp_eatCharacterClass(state) ||
  18924. this.regexp_eatUncapturingGroup(state) ||
  18925. this.regexp_eatCapturingGroup(state) ||
  18926. this.regexp_eatInvalidBracedQuantifier(state) ||
  18927. this.regexp_eatExtendedPatternCharacter(state)
  18928. )
  18929. };
  18930. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18931. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18932. if (this.regexp_eatBracedQuantifier(state, true)) {
  18933. state.raise("Nothing to repeat");
  18934. }
  18935. return false
  18936. };
  18937. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18938. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18939. var ch = state.current();
  18940. if (isSyntaxCharacter(ch)) {
  18941. state.lastIntValue = ch;
  18942. state.advance();
  18943. return true
  18944. }
  18945. return false
  18946. };
  18947. function isSyntaxCharacter(ch) {
  18948. return (
  18949. ch === 0x24 /* $ */ ||
  18950. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18951. ch === 0x2E /* . */ ||
  18952. ch === 0x3F /* ? */ ||
  18953. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18954. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18955. )
  18956. }
  18957. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18958. // But eat eager.
  18959. pp$1.regexp_eatPatternCharacters = function(state) {
  18960. var start = state.pos;
  18961. var ch = 0;
  18962. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18963. state.advance();
  18964. }
  18965. return state.pos !== start
  18966. };
  18967. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18968. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18969. var ch = state.current();
  18970. if (
  18971. ch !== -1 &&
  18972. ch !== 0x24 /* $ */ &&
  18973. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18974. ch !== 0x2E /* . */ &&
  18975. ch !== 0x3F /* ? */ &&
  18976. ch !== 0x5B /* [ */ &&
  18977. ch !== 0x5E /* ^ */ &&
  18978. ch !== 0x7C /* | */
  18979. ) {
  18980. state.advance();
  18981. return true
  18982. }
  18983. return false
  18984. };
  18985. // GroupSpecifier ::
  18986. // [empty]
  18987. // `?` GroupName
  18988. pp$1.regexp_groupSpecifier = function(state) {
  18989. if (state.eat(0x3F /* ? */)) {
  18990. if (this.regexp_eatGroupName(state)) {
  18991. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18992. state.raise("Duplicate capture group name");
  18993. }
  18994. state.groupNames.push(state.lastStringValue);
  18995. return
  18996. }
  18997. state.raise("Invalid group");
  18998. }
  18999. };
  19000. // GroupName ::
  19001. // `<` RegExpIdentifierName `>`
  19002. // Note: this updates `state.lastStringValue` property with the eaten name.
  19003. pp$1.regexp_eatGroupName = function(state) {
  19004. state.lastStringValue = "";
  19005. if (state.eat(0x3C /* < */)) {
  19006. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  19007. return true
  19008. }
  19009. state.raise("Invalid capture group name");
  19010. }
  19011. return false
  19012. };
  19013. // RegExpIdentifierName ::
  19014. // RegExpIdentifierStart
  19015. // RegExpIdentifierName RegExpIdentifierPart
  19016. // Note: this updates `state.lastStringValue` property with the eaten name.
  19017. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  19018. state.lastStringValue = "";
  19019. if (this.regexp_eatRegExpIdentifierStart(state)) {
  19020. state.lastStringValue += codePointToString(state.lastIntValue);
  19021. while (this.regexp_eatRegExpIdentifierPart(state)) {
  19022. state.lastStringValue += codePointToString(state.lastIntValue);
  19023. }
  19024. return true
  19025. }
  19026. return false
  19027. };
  19028. // RegExpIdentifierStart ::
  19029. // UnicodeIDStart
  19030. // `$`
  19031. // `_`
  19032. // `\` RegExpUnicodeEscapeSequence[+U]
  19033. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  19034. var start = state.pos;
  19035. var forceU = this.options.ecmaVersion >= 11;
  19036. var ch = state.current(forceU);
  19037. state.advance(forceU);
  19038. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  19039. ch = state.lastIntValue;
  19040. }
  19041. if (isRegExpIdentifierStart(ch)) {
  19042. state.lastIntValue = ch;
  19043. return true
  19044. }
  19045. state.pos = start;
  19046. return false
  19047. };
  19048. function isRegExpIdentifierStart(ch) {
  19049. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  19050. }
  19051. // RegExpIdentifierPart ::
  19052. // UnicodeIDContinue
  19053. // `$`
  19054. // `_`
  19055. // `\` RegExpUnicodeEscapeSequence[+U]
  19056. // <ZWNJ>
  19057. // <ZWJ>
  19058. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  19059. var start = state.pos;
  19060. var forceU = this.options.ecmaVersion >= 11;
  19061. var ch = state.current(forceU);
  19062. state.advance(forceU);
  19063. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  19064. ch = state.lastIntValue;
  19065. }
  19066. if (isRegExpIdentifierPart(ch)) {
  19067. state.lastIntValue = ch;
  19068. return true
  19069. }
  19070. state.pos = start;
  19071. return false
  19072. };
  19073. function isRegExpIdentifierPart(ch) {
  19074. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  19075. }
  19076. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  19077. pp$1.regexp_eatAtomEscape = function(state) {
  19078. if (
  19079. this.regexp_eatBackReference(state) ||
  19080. this.regexp_eatCharacterClassEscape(state) ||
  19081. this.regexp_eatCharacterEscape(state) ||
  19082. (state.switchN && this.regexp_eatKGroupName(state))
  19083. ) {
  19084. return true
  19085. }
  19086. if (state.switchU) {
  19087. // Make the same message as V8.
  19088. if (state.current() === 0x63 /* c */) {
  19089. state.raise("Invalid unicode escape");
  19090. }
  19091. state.raise("Invalid escape");
  19092. }
  19093. return false
  19094. };
  19095. pp$1.regexp_eatBackReference = function(state) {
  19096. var start = state.pos;
  19097. if (this.regexp_eatDecimalEscape(state)) {
  19098. var n = state.lastIntValue;
  19099. if (state.switchU) {
  19100. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  19101. if (n > state.maxBackReference) {
  19102. state.maxBackReference = n;
  19103. }
  19104. return true
  19105. }
  19106. if (n <= state.numCapturingParens) {
  19107. return true
  19108. }
  19109. state.pos = start;
  19110. }
  19111. return false
  19112. };
  19113. pp$1.regexp_eatKGroupName = function(state) {
  19114. if (state.eat(0x6B /* k */)) {
  19115. if (this.regexp_eatGroupName(state)) {
  19116. state.backReferenceNames.push(state.lastStringValue);
  19117. return true
  19118. }
  19119. state.raise("Invalid named reference");
  19120. }
  19121. return false
  19122. };
  19123. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  19124. pp$1.regexp_eatCharacterEscape = function(state) {
  19125. return (
  19126. this.regexp_eatControlEscape(state) ||
  19127. this.regexp_eatCControlLetter(state) ||
  19128. this.regexp_eatZero(state) ||
  19129. this.regexp_eatHexEscapeSequence(state) ||
  19130. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  19131. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  19132. this.regexp_eatIdentityEscape(state)
  19133. )
  19134. };
  19135. pp$1.regexp_eatCControlLetter = function(state) {
  19136. var start = state.pos;
  19137. if (state.eat(0x63 /* c */)) {
  19138. if (this.regexp_eatControlLetter(state)) {
  19139. return true
  19140. }
  19141. state.pos = start;
  19142. }
  19143. return false
  19144. };
  19145. pp$1.regexp_eatZero = function(state) {
  19146. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  19147. state.lastIntValue = 0;
  19148. state.advance();
  19149. return true
  19150. }
  19151. return false
  19152. };
  19153. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  19154. pp$1.regexp_eatControlEscape = function(state) {
  19155. var ch = state.current();
  19156. if (ch === 0x74 /* t */) {
  19157. state.lastIntValue = 0x09; /* \t */
  19158. state.advance();
  19159. return true
  19160. }
  19161. if (ch === 0x6E /* n */) {
  19162. state.lastIntValue = 0x0A; /* \n */
  19163. state.advance();
  19164. return true
  19165. }
  19166. if (ch === 0x76 /* v */) {
  19167. state.lastIntValue = 0x0B; /* \v */
  19168. state.advance();
  19169. return true
  19170. }
  19171. if (ch === 0x66 /* f */) {
  19172. state.lastIntValue = 0x0C; /* \f */
  19173. state.advance();
  19174. return true
  19175. }
  19176. if (ch === 0x72 /* r */) {
  19177. state.lastIntValue = 0x0D; /* \r */
  19178. state.advance();
  19179. return true
  19180. }
  19181. return false
  19182. };
  19183. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  19184. pp$1.regexp_eatControlLetter = function(state) {
  19185. var ch = state.current();
  19186. if (isControlLetter(ch)) {
  19187. state.lastIntValue = ch % 0x20;
  19188. state.advance();
  19189. return true
  19190. }
  19191. return false
  19192. };
  19193. function isControlLetter(ch) {
  19194. return (
  19195. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  19196. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  19197. )
  19198. }
  19199. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  19200. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  19201. if ( forceU === void 0 ) forceU = false;
  19202. var start = state.pos;
  19203. var switchU = forceU || state.switchU;
  19204. if (state.eat(0x75 /* u */)) {
  19205. if (this.regexp_eatFixedHexDigits(state, 4)) {
  19206. var lead = state.lastIntValue;
  19207. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  19208. var leadSurrogateEnd = state.pos;
  19209. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  19210. var trail = state.lastIntValue;
  19211. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  19212. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  19213. return true
  19214. }
  19215. }
  19216. state.pos = leadSurrogateEnd;
  19217. state.lastIntValue = lead;
  19218. }
  19219. return true
  19220. }
  19221. if (
  19222. switchU &&
  19223. state.eat(0x7B /* { */) &&
  19224. this.regexp_eatHexDigits(state) &&
  19225. state.eat(0x7D /* } */) &&
  19226. isValidUnicode(state.lastIntValue)
  19227. ) {
  19228. return true
  19229. }
  19230. if (switchU) {
  19231. state.raise("Invalid unicode escape");
  19232. }
  19233. state.pos = start;
  19234. }
  19235. return false
  19236. };
  19237. function isValidUnicode(ch) {
  19238. return ch >= 0 && ch <= 0x10FFFF
  19239. }
  19240. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  19241. pp$1.regexp_eatIdentityEscape = function(state) {
  19242. if (state.switchU) {
  19243. if (this.regexp_eatSyntaxCharacter(state)) {
  19244. return true
  19245. }
  19246. if (state.eat(0x2F /* / */)) {
  19247. state.lastIntValue = 0x2F; /* / */
  19248. return true
  19249. }
  19250. return false
  19251. }
  19252. var ch = state.current();
  19253. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  19254. state.lastIntValue = ch;
  19255. state.advance();
  19256. return true
  19257. }
  19258. return false
  19259. };
  19260. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  19261. pp$1.regexp_eatDecimalEscape = function(state) {
  19262. state.lastIntValue = 0;
  19263. var ch = state.current();
  19264. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  19265. do {
  19266. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19267. state.advance();
  19268. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  19269. return true
  19270. }
  19271. return false
  19272. };
  19273. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  19274. pp$1.regexp_eatCharacterClassEscape = function(state) {
  19275. var ch = state.current();
  19276. if (isCharacterClassEscape(ch)) {
  19277. state.lastIntValue = -1;
  19278. state.advance();
  19279. return true
  19280. }
  19281. if (
  19282. state.switchU &&
  19283. this.options.ecmaVersion >= 9 &&
  19284. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  19285. ) {
  19286. state.lastIntValue = -1;
  19287. state.advance();
  19288. if (
  19289. state.eat(0x7B /* { */) &&
  19290. this.regexp_eatUnicodePropertyValueExpression(state) &&
  19291. state.eat(0x7D /* } */)
  19292. ) {
  19293. return true
  19294. }
  19295. state.raise("Invalid property name");
  19296. }
  19297. return false
  19298. };
  19299. function isCharacterClassEscape(ch) {
  19300. return (
  19301. ch === 0x64 /* d */ ||
  19302. ch === 0x44 /* D */ ||
  19303. ch === 0x73 /* s */ ||
  19304. ch === 0x53 /* S */ ||
  19305. ch === 0x77 /* w */ ||
  19306. ch === 0x57 /* W */
  19307. )
  19308. }
  19309. // UnicodePropertyValueExpression ::
  19310. // UnicodePropertyName `=` UnicodePropertyValue
  19311. // LoneUnicodePropertyNameOrValue
  19312. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  19313. var start = state.pos;
  19314. // UnicodePropertyName `=` UnicodePropertyValue
  19315. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  19316. var name = state.lastStringValue;
  19317. if (this.regexp_eatUnicodePropertyValue(state)) {
  19318. var value = state.lastStringValue;
  19319. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  19320. return true
  19321. }
  19322. }
  19323. state.pos = start;
  19324. // LoneUnicodePropertyNameOrValue
  19325. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  19326. var nameOrValue = state.lastStringValue;
  19327. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  19328. return true
  19329. }
  19330. return false
  19331. };
  19332. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  19333. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  19334. { state.raise("Invalid property name"); }
  19335. if (!state.unicodeProperties.nonBinary[name].test(value))
  19336. { state.raise("Invalid property value"); }
  19337. };
  19338. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  19339. if (!state.unicodeProperties.binary.test(nameOrValue))
  19340. { state.raise("Invalid property name"); }
  19341. };
  19342. // UnicodePropertyName ::
  19343. // UnicodePropertyNameCharacters
  19344. pp$1.regexp_eatUnicodePropertyName = function(state) {
  19345. var ch = 0;
  19346. state.lastStringValue = "";
  19347. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  19348. state.lastStringValue += codePointToString(ch);
  19349. state.advance();
  19350. }
  19351. return state.lastStringValue !== ""
  19352. };
  19353. function isUnicodePropertyNameCharacter(ch) {
  19354. return isControlLetter(ch) || ch === 0x5F /* _ */
  19355. }
  19356. // UnicodePropertyValue ::
  19357. // UnicodePropertyValueCharacters
  19358. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  19359. var ch = 0;
  19360. state.lastStringValue = "";
  19361. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  19362. state.lastStringValue += codePointToString(ch);
  19363. state.advance();
  19364. }
  19365. return state.lastStringValue !== ""
  19366. };
  19367. function isUnicodePropertyValueCharacter(ch) {
  19368. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  19369. }
  19370. // LoneUnicodePropertyNameOrValue ::
  19371. // UnicodePropertyValueCharacters
  19372. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  19373. return this.regexp_eatUnicodePropertyValue(state)
  19374. };
  19375. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  19376. pp$1.regexp_eatCharacterClass = function(state) {
  19377. if (state.eat(0x5B /* [ */)) {
  19378. state.eat(0x5E /* ^ */);
  19379. this.regexp_classRanges(state);
  19380. if (state.eat(0x5D /* ] */)) {
  19381. return true
  19382. }
  19383. // Unreachable since it threw "unterminated regular expression" error before.
  19384. state.raise("Unterminated character class");
  19385. }
  19386. return false
  19387. };
  19388. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  19389. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  19390. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  19391. pp$1.regexp_classRanges = function(state) {
  19392. while (this.regexp_eatClassAtom(state)) {
  19393. var left = state.lastIntValue;
  19394. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  19395. var right = state.lastIntValue;
  19396. if (state.switchU && (left === -1 || right === -1)) {
  19397. state.raise("Invalid character class");
  19398. }
  19399. if (left !== -1 && right !== -1 && left > right) {
  19400. state.raise("Range out of order in character class");
  19401. }
  19402. }
  19403. }
  19404. };
  19405. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  19406. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  19407. pp$1.regexp_eatClassAtom = function(state) {
  19408. var start = state.pos;
  19409. if (state.eat(0x5C /* \ */)) {
  19410. if (this.regexp_eatClassEscape(state)) {
  19411. return true
  19412. }
  19413. if (state.switchU) {
  19414. // Make the same message as V8.
  19415. var ch$1 = state.current();
  19416. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  19417. state.raise("Invalid class escape");
  19418. }
  19419. state.raise("Invalid escape");
  19420. }
  19421. state.pos = start;
  19422. }
  19423. var ch = state.current();
  19424. if (ch !== 0x5D /* ] */) {
  19425. state.lastIntValue = ch;
  19426. state.advance();
  19427. return true
  19428. }
  19429. return false
  19430. };
  19431. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  19432. pp$1.regexp_eatClassEscape = function(state) {
  19433. var start = state.pos;
  19434. if (state.eat(0x62 /* b */)) {
  19435. state.lastIntValue = 0x08; /* <BS> */
  19436. return true
  19437. }
  19438. if (state.switchU && state.eat(0x2D /* - */)) {
  19439. state.lastIntValue = 0x2D; /* - */
  19440. return true
  19441. }
  19442. if (!state.switchU && state.eat(0x63 /* c */)) {
  19443. if (this.regexp_eatClassControlLetter(state)) {
  19444. return true
  19445. }
  19446. state.pos = start;
  19447. }
  19448. return (
  19449. this.regexp_eatCharacterClassEscape(state) ||
  19450. this.regexp_eatCharacterEscape(state)
  19451. )
  19452. };
  19453. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  19454. pp$1.regexp_eatClassControlLetter = function(state) {
  19455. var ch = state.current();
  19456. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  19457. state.lastIntValue = ch % 0x20;
  19458. state.advance();
  19459. return true
  19460. }
  19461. return false
  19462. };
  19463. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19464. pp$1.regexp_eatHexEscapeSequence = function(state) {
  19465. var start = state.pos;
  19466. if (state.eat(0x78 /* x */)) {
  19467. if (this.regexp_eatFixedHexDigits(state, 2)) {
  19468. return true
  19469. }
  19470. if (state.switchU) {
  19471. state.raise("Invalid escape");
  19472. }
  19473. state.pos = start;
  19474. }
  19475. return false
  19476. };
  19477. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  19478. pp$1.regexp_eatDecimalDigits = function(state) {
  19479. var start = state.pos;
  19480. var ch = 0;
  19481. state.lastIntValue = 0;
  19482. while (isDecimalDigit(ch = state.current())) {
  19483. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19484. state.advance();
  19485. }
  19486. return state.pos !== start
  19487. };
  19488. function isDecimalDigit(ch) {
  19489. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  19490. }
  19491. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  19492. pp$1.regexp_eatHexDigits = function(state) {
  19493. var start = state.pos;
  19494. var ch = 0;
  19495. state.lastIntValue = 0;
  19496. while (isHexDigit(ch = state.current())) {
  19497. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19498. state.advance();
  19499. }
  19500. return state.pos !== start
  19501. };
  19502. function isHexDigit(ch) {
  19503. return (
  19504. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  19505. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  19506. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  19507. )
  19508. }
  19509. function hexToInt(ch) {
  19510. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  19511. return 10 + (ch - 0x41 /* A */)
  19512. }
  19513. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  19514. return 10 + (ch - 0x61 /* a */)
  19515. }
  19516. return ch - 0x30 /* 0 */
  19517. }
  19518. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  19519. // Allows only 0-377(octal) i.e. 0-255(decimal).
  19520. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  19521. if (this.regexp_eatOctalDigit(state)) {
  19522. var n1 = state.lastIntValue;
  19523. if (this.regexp_eatOctalDigit(state)) {
  19524. var n2 = state.lastIntValue;
  19525. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  19526. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  19527. } else {
  19528. state.lastIntValue = n1 * 8 + n2;
  19529. }
  19530. } else {
  19531. state.lastIntValue = n1;
  19532. }
  19533. return true
  19534. }
  19535. return false
  19536. };
  19537. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  19538. pp$1.regexp_eatOctalDigit = function(state) {
  19539. var ch = state.current();
  19540. if (isOctalDigit(ch)) {
  19541. state.lastIntValue = ch - 0x30; /* 0 */
  19542. state.advance();
  19543. return true
  19544. }
  19545. state.lastIntValue = 0;
  19546. return false
  19547. };
  19548. function isOctalDigit(ch) {
  19549. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  19550. }
  19551. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  19552. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  19553. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19554. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  19555. var start = state.pos;
  19556. state.lastIntValue = 0;
  19557. for (var i = 0; i < length; ++i) {
  19558. var ch = state.current();
  19559. if (!isHexDigit(ch)) {
  19560. state.pos = start;
  19561. return false
  19562. }
  19563. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19564. state.advance();
  19565. }
  19566. return true
  19567. };
  19568. // Object type used to represent tokens. Note that normally, tokens
  19569. // simply exist as properties on the parser object. This is only
  19570. // used for the onToken callback and the external tokenizer.
  19571. var Token = function Token(p) {
  19572. this.type = p.type;
  19573. this.value = p.value;
  19574. this.start = p.start;
  19575. this.end = p.end;
  19576. if (p.options.locations)
  19577. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  19578. if (p.options.ranges)
  19579. { this.range = [p.start, p.end]; }
  19580. };
  19581. // ## Tokenizer
  19582. var pp = Parser.prototype;
  19583. // Move to the next token
  19584. pp.next = function(ignoreEscapeSequenceInKeyword) {
  19585. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  19586. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  19587. if (this.options.onToken)
  19588. { this.options.onToken(new Token(this)); }
  19589. this.lastTokEnd = this.end;
  19590. this.lastTokStart = this.start;
  19591. this.lastTokEndLoc = this.endLoc;
  19592. this.lastTokStartLoc = this.startLoc;
  19593. this.nextToken();
  19594. };
  19595. pp.getToken = function() {
  19596. this.next();
  19597. return new Token(this)
  19598. };
  19599. // If we're in an ES6 environment, make parsers iterable
  19600. if (typeof Symbol !== "undefined")
  19601. { pp[Symbol.iterator] = function() {
  19602. var this$1$1 = this;
  19603. return {
  19604. next: function () {
  19605. var token = this$1$1.getToken();
  19606. return {
  19607. done: token.type === types$1.eof,
  19608. value: token
  19609. }
  19610. }
  19611. }
  19612. }; }
  19613. // Toggle strict mode. Re-reads the next number or string to please
  19614. // pedantic tests (`"use strict"; 010;` should fail).
  19615. // Read a single token, updating the parser object's token-related
  19616. // properties.
  19617. pp.nextToken = function() {
  19618. var curContext = this.curContext();
  19619. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19620. this.start = this.pos;
  19621. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19622. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19623. if (curContext.override) { return curContext.override(this) }
  19624. else { this.readToken(this.fullCharCodeAtPos()); }
  19625. };
  19626. pp.readToken = function(code) {
  19627. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19628. // identifiers, so '\' also dispatches to that.
  19629. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19630. { return this.readWord() }
  19631. return this.getTokenFromCode(code)
  19632. };
  19633. pp.fullCharCodeAtPos = function() {
  19634. var code = this.input.charCodeAt(this.pos);
  19635. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19636. var next = this.input.charCodeAt(this.pos + 1);
  19637. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19638. };
  19639. pp.skipBlockComment = function() {
  19640. var startLoc = this.options.onComment && this.curPosition();
  19641. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19642. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19643. this.pos = end + 2;
  19644. if (this.options.locations) {
  19645. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19646. ++this.curLine;
  19647. pos = this.lineStart = nextBreak;
  19648. }
  19649. }
  19650. if (this.options.onComment)
  19651. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19652. startLoc, this.curPosition()); }
  19653. };
  19654. pp.skipLineComment = function(startSkip) {
  19655. var start = this.pos;
  19656. var startLoc = this.options.onComment && this.curPosition();
  19657. var ch = this.input.charCodeAt(this.pos += startSkip);
  19658. while (this.pos < this.input.length && !isNewLine(ch)) {
  19659. ch = this.input.charCodeAt(++this.pos);
  19660. }
  19661. if (this.options.onComment)
  19662. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19663. startLoc, this.curPosition()); }
  19664. };
  19665. // Called at the start of the parse and after every token. Skips
  19666. // whitespace and comments, and.
  19667. pp.skipSpace = function() {
  19668. loop: while (this.pos < this.input.length) {
  19669. var ch = this.input.charCodeAt(this.pos);
  19670. switch (ch) {
  19671. case 32: case 160: // ' '
  19672. ++this.pos;
  19673. break
  19674. case 13:
  19675. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19676. ++this.pos;
  19677. }
  19678. case 10: case 8232: case 8233:
  19679. ++this.pos;
  19680. if (this.options.locations) {
  19681. ++this.curLine;
  19682. this.lineStart = this.pos;
  19683. }
  19684. break
  19685. case 47: // '/'
  19686. switch (this.input.charCodeAt(this.pos + 1)) {
  19687. case 42: // '*'
  19688. this.skipBlockComment();
  19689. break
  19690. case 47:
  19691. this.skipLineComment(2);
  19692. break
  19693. default:
  19694. break loop
  19695. }
  19696. break
  19697. default:
  19698. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19699. ++this.pos;
  19700. } else {
  19701. break loop
  19702. }
  19703. }
  19704. }
  19705. };
  19706. // Called at the end of every token. Sets `end`, `val`, and
  19707. // maintains `context` and `exprAllowed`, and skips the space after
  19708. // the token, so that the next one's `start` will point at the
  19709. // right position.
  19710. pp.finishToken = function(type, val) {
  19711. this.end = this.pos;
  19712. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19713. var prevType = this.type;
  19714. this.type = type;
  19715. this.value = val;
  19716. this.updateContext(prevType);
  19717. };
  19718. // ### Token reading
  19719. // This is the function that is called to fetch the next token. It
  19720. // is somewhat obscure, because it works in character codes rather
  19721. // than characters, and because operator parsing has been inlined
  19722. // into it.
  19723. //
  19724. // All in the name of speed.
  19725. //
  19726. pp.readToken_dot = function() {
  19727. var next = this.input.charCodeAt(this.pos + 1);
  19728. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19729. var next2 = this.input.charCodeAt(this.pos + 2);
  19730. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19731. this.pos += 3;
  19732. return this.finishToken(types$1.ellipsis)
  19733. } else {
  19734. ++this.pos;
  19735. return this.finishToken(types$1.dot)
  19736. }
  19737. };
  19738. pp.readToken_slash = function() { // '/'
  19739. var next = this.input.charCodeAt(this.pos + 1);
  19740. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19741. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19742. return this.finishOp(types$1.slash, 1)
  19743. };
  19744. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19745. var next = this.input.charCodeAt(this.pos + 1);
  19746. var size = 1;
  19747. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19748. // exponentiation operator ** and **=
  19749. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19750. ++size;
  19751. tokentype = types$1.starstar;
  19752. next = this.input.charCodeAt(this.pos + 2);
  19753. }
  19754. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19755. return this.finishOp(tokentype, size)
  19756. };
  19757. pp.readToken_pipe_amp = function(code) { // '|&'
  19758. var next = this.input.charCodeAt(this.pos + 1);
  19759. if (next === code) {
  19760. if (this.options.ecmaVersion >= 12) {
  19761. var next2 = this.input.charCodeAt(this.pos + 2);
  19762. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19763. }
  19764. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19765. }
  19766. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19767. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19768. };
  19769. pp.readToken_caret = function() { // '^'
  19770. var next = this.input.charCodeAt(this.pos + 1);
  19771. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19772. return this.finishOp(types$1.bitwiseXOR, 1)
  19773. };
  19774. pp.readToken_plus_min = function(code) { // '+-'
  19775. var next = this.input.charCodeAt(this.pos + 1);
  19776. if (next === code) {
  19777. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19778. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19779. // A `-->` line comment
  19780. this.skipLineComment(3);
  19781. this.skipSpace();
  19782. return this.nextToken()
  19783. }
  19784. return this.finishOp(types$1.incDec, 2)
  19785. }
  19786. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19787. return this.finishOp(types$1.plusMin, 1)
  19788. };
  19789. pp.readToken_lt_gt = function(code) { // '<>'
  19790. var next = this.input.charCodeAt(this.pos + 1);
  19791. var size = 1;
  19792. if (next === code) {
  19793. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19794. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19795. return this.finishOp(types$1.bitShift, size)
  19796. }
  19797. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19798. this.input.charCodeAt(this.pos + 3) === 45) {
  19799. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19800. this.skipLineComment(4);
  19801. this.skipSpace();
  19802. return this.nextToken()
  19803. }
  19804. if (next === 61) { size = 2; }
  19805. return this.finishOp(types$1.relational, size)
  19806. };
  19807. pp.readToken_eq_excl = function(code) { // '=!'
  19808. var next = this.input.charCodeAt(this.pos + 1);
  19809. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19810. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19811. this.pos += 2;
  19812. return this.finishToken(types$1.arrow)
  19813. }
  19814. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19815. };
  19816. pp.readToken_question = function() { // '?'
  19817. var ecmaVersion = this.options.ecmaVersion;
  19818. if (ecmaVersion >= 11) {
  19819. var next = this.input.charCodeAt(this.pos + 1);
  19820. if (next === 46) {
  19821. var next2 = this.input.charCodeAt(this.pos + 2);
  19822. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19823. }
  19824. if (next === 63) {
  19825. if (ecmaVersion >= 12) {
  19826. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19827. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19828. }
  19829. return this.finishOp(types$1.coalesce, 2)
  19830. }
  19831. }
  19832. return this.finishOp(types$1.question, 1)
  19833. };
  19834. pp.readToken_numberSign = function() { // '#'
  19835. var ecmaVersion = this.options.ecmaVersion;
  19836. var code = 35; // '#'
  19837. if (ecmaVersion >= 13) {
  19838. ++this.pos;
  19839. code = this.fullCharCodeAtPos();
  19840. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19841. return this.finishToken(types$1.privateId, this.readWord1())
  19842. }
  19843. }
  19844. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19845. };
  19846. pp.getTokenFromCode = function(code) {
  19847. switch (code) {
  19848. // The interpretation of a dot depends on whether it is followed
  19849. // by a digit or another two dots.
  19850. case 46: // '.'
  19851. return this.readToken_dot()
  19852. // Punctuation tokens.
  19853. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19854. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19855. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19856. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19857. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19858. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19859. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19860. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19861. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19862. case 96: // '`'
  19863. if (this.options.ecmaVersion < 6) { break }
  19864. ++this.pos;
  19865. return this.finishToken(types$1.backQuote)
  19866. case 48: // '0'
  19867. var next = this.input.charCodeAt(this.pos + 1);
  19868. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19869. if (this.options.ecmaVersion >= 6) {
  19870. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19871. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19872. }
  19873. // Anything else beginning with a digit is an integer, octal
  19874. // number, or float.
  19875. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19876. return this.readNumber(false)
  19877. // Quotes produce strings.
  19878. case 34: case 39: // '"', "'"
  19879. return this.readString(code)
  19880. // Operators are parsed inline in tiny state machines. '=' (61) is
  19881. // often referred to. `finishOp` simply skips the amount of
  19882. // characters it is given as second argument, and returns a token
  19883. // of the type given by its first argument.
  19884. case 47: // '/'
  19885. return this.readToken_slash()
  19886. case 37: case 42: // '%*'
  19887. return this.readToken_mult_modulo_exp(code)
  19888. case 124: case 38: // '|&'
  19889. return this.readToken_pipe_amp(code)
  19890. case 94: // '^'
  19891. return this.readToken_caret()
  19892. case 43: case 45: // '+-'
  19893. return this.readToken_plus_min(code)
  19894. case 60: case 62: // '<>'
  19895. return this.readToken_lt_gt(code)
  19896. case 61: case 33: // '=!'
  19897. return this.readToken_eq_excl(code)
  19898. case 63: // '?'
  19899. return this.readToken_question()
  19900. case 126: // '~'
  19901. return this.finishOp(types$1.prefix, 1)
  19902. case 35: // '#'
  19903. return this.readToken_numberSign()
  19904. }
  19905. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19906. };
  19907. pp.finishOp = function(type, size) {
  19908. var str = this.input.slice(this.pos, this.pos + size);
  19909. this.pos += size;
  19910. return this.finishToken(type, str)
  19911. };
  19912. pp.readRegexp = function() {
  19913. var escaped, inClass, start = this.pos;
  19914. for (;;) {
  19915. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19916. var ch = this.input.charAt(this.pos);
  19917. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19918. if (!escaped) {
  19919. if (ch === "[") { inClass = true; }
  19920. else if (ch === "]" && inClass) { inClass = false; }
  19921. else if (ch === "/" && !inClass) { break }
  19922. escaped = ch === "\\";
  19923. } else { escaped = false; }
  19924. ++this.pos;
  19925. }
  19926. var pattern = this.input.slice(start, this.pos);
  19927. ++this.pos;
  19928. var flagsStart = this.pos;
  19929. var flags = this.readWord1();
  19930. if (this.containsEsc) { this.unexpected(flagsStart); }
  19931. // Validate pattern
  19932. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19933. state.reset(start, pattern, flags);
  19934. this.validateRegExpFlags(state);
  19935. this.validateRegExpPattern(state);
  19936. // Create Literal#value property value.
  19937. var value = null;
  19938. try {
  19939. value = new RegExp(pattern, flags);
  19940. } catch (e) {
  19941. // ESTree requires null if it failed to instantiate RegExp object.
  19942. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19943. }
  19944. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19945. };
  19946. // Read an integer in the given radix. Return null if zero digits
  19947. // were read, the integer value otherwise. When `len` is given, this
  19948. // will return `null` unless the integer has exactly `len` digits.
  19949. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19950. // `len` is used for character escape sequences. In that case, disallow separators.
  19951. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19952. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19953. // and isn't fraction part nor exponent part. In that case, if the first digit
  19954. // is zero then disallow separators.
  19955. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19956. var start = this.pos, total = 0, lastCode = 0;
  19957. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19958. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19959. if (allowSeparators && code === 95) {
  19960. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19961. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19962. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19963. lastCode = code;
  19964. continue
  19965. }
  19966. if (code >= 97) { val = code - 97 + 10; } // a
  19967. else if (code >= 65) { val = code - 65 + 10; } // A
  19968. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19969. else { val = Infinity; }
  19970. if (val >= radix) { break }
  19971. lastCode = code;
  19972. total = total * radix + val;
  19973. }
  19974. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19975. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19976. return total
  19977. };
  19978. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19979. if (isLegacyOctalNumericLiteral) {
  19980. return parseInt(str, 8)
  19981. }
  19982. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19983. return parseFloat(str.replace(/_/g, ""))
  19984. }
  19985. function stringToBigInt(str) {
  19986. if (typeof BigInt !== "function") {
  19987. return null
  19988. }
  19989. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19990. return BigInt(str.replace(/_/g, ""))
  19991. }
  19992. pp.readRadixNumber = function(radix) {
  19993. var start = this.pos;
  19994. this.pos += 2; // 0x
  19995. var val = this.readInt(radix);
  19996. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19997. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19998. val = stringToBigInt(this.input.slice(start, this.pos));
  19999. ++this.pos;
  20000. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  20001. return this.finishToken(types$1.num, val)
  20002. };
  20003. // Read an integer, octal integer, or floating-point number.
  20004. pp.readNumber = function(startsWithDot) {
  20005. var start = this.pos;
  20006. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  20007. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  20008. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  20009. var next = this.input.charCodeAt(this.pos);
  20010. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  20011. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  20012. ++this.pos;
  20013. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  20014. return this.finishToken(types$1.num, val$1)
  20015. }
  20016. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  20017. if (next === 46 && !octal) { // '.'
  20018. ++this.pos;
  20019. this.readInt(10);
  20020. next = this.input.charCodeAt(this.pos);
  20021. }
  20022. if ((next === 69 || next === 101) && !octal) { // 'eE'
  20023. next = this.input.charCodeAt(++this.pos);
  20024. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  20025. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  20026. }
  20027. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  20028. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  20029. return this.finishToken(types$1.num, val)
  20030. };
  20031. // Read a string value, interpreting backslash-escapes.
  20032. pp.readCodePoint = function() {
  20033. var ch = this.input.charCodeAt(this.pos), code;
  20034. if (ch === 123) { // '{'
  20035. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  20036. var codePos = ++this.pos;
  20037. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  20038. ++this.pos;
  20039. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  20040. } else {
  20041. code = this.readHexChar(4);
  20042. }
  20043. return code
  20044. };
  20045. pp.readString = function(quote) {
  20046. var out = "", chunkStart = ++this.pos;
  20047. for (;;) {
  20048. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  20049. var ch = this.input.charCodeAt(this.pos);
  20050. if (ch === quote) { break }
  20051. if (ch === 92) { // '\'
  20052. out += this.input.slice(chunkStart, this.pos);
  20053. out += this.readEscapedChar(false);
  20054. chunkStart = this.pos;
  20055. } else if (ch === 0x2028 || ch === 0x2029) {
  20056. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  20057. ++this.pos;
  20058. if (this.options.locations) {
  20059. this.curLine++;
  20060. this.lineStart = this.pos;
  20061. }
  20062. } else {
  20063. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  20064. ++this.pos;
  20065. }
  20066. }
  20067. out += this.input.slice(chunkStart, this.pos++);
  20068. return this.finishToken(types$1.string, out)
  20069. };
  20070. // Reads template string tokens.
  20071. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  20072. pp.tryReadTemplateToken = function() {
  20073. this.inTemplateElement = true;
  20074. try {
  20075. this.readTmplToken();
  20076. } catch (err) {
  20077. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  20078. this.readInvalidTemplateToken();
  20079. } else {
  20080. throw err
  20081. }
  20082. }
  20083. this.inTemplateElement = false;
  20084. };
  20085. pp.invalidStringToken = function(position, message) {
  20086. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  20087. throw INVALID_TEMPLATE_ESCAPE_ERROR
  20088. } else {
  20089. this.raise(position, message);
  20090. }
  20091. };
  20092. pp.readTmplToken = function() {
  20093. var out = "", chunkStart = this.pos;
  20094. for (;;) {
  20095. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  20096. var ch = this.input.charCodeAt(this.pos);
  20097. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  20098. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  20099. if (ch === 36) {
  20100. this.pos += 2;
  20101. return this.finishToken(types$1.dollarBraceL)
  20102. } else {
  20103. ++this.pos;
  20104. return this.finishToken(types$1.backQuote)
  20105. }
  20106. }
  20107. out += this.input.slice(chunkStart, this.pos);
  20108. return this.finishToken(types$1.template, out)
  20109. }
  20110. if (ch === 92) { // '\'
  20111. out += this.input.slice(chunkStart, this.pos);
  20112. out += this.readEscapedChar(true);
  20113. chunkStart = this.pos;
  20114. } else if (isNewLine(ch)) {
  20115. out += this.input.slice(chunkStart, this.pos);
  20116. ++this.pos;
  20117. switch (ch) {
  20118. case 13:
  20119. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  20120. case 10:
  20121. out += "\n";
  20122. break
  20123. default:
  20124. out += String.fromCharCode(ch);
  20125. break
  20126. }
  20127. if (this.options.locations) {
  20128. ++this.curLine;
  20129. this.lineStart = this.pos;
  20130. }
  20131. chunkStart = this.pos;
  20132. } else {
  20133. ++this.pos;
  20134. }
  20135. }
  20136. };
  20137. // Reads a template token to search for the end, without validating any escape sequences
  20138. pp.readInvalidTemplateToken = function() {
  20139. for (; this.pos < this.input.length; this.pos++) {
  20140. switch (this.input[this.pos]) {
  20141. case "\\":
  20142. ++this.pos;
  20143. break
  20144. case "$":
  20145. if (this.input[this.pos + 1] !== "{") {
  20146. break
  20147. }
  20148. // falls through
  20149. case "`":
  20150. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  20151. // no default
  20152. }
  20153. }
  20154. this.raise(this.start, "Unterminated template");
  20155. };
  20156. // Used to read escaped characters
  20157. pp.readEscapedChar = function(inTemplate) {
  20158. var ch = this.input.charCodeAt(++this.pos);
  20159. ++this.pos;
  20160. switch (ch) {
  20161. case 110: return "\n" // 'n' -> '\n'
  20162. case 114: return "\r" // 'r' -> '\r'
  20163. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  20164. case 117: return codePointToString(this.readCodePoint()) // 'u'
  20165. case 116: return "\t" // 't' -> '\t'
  20166. case 98: return "\b" // 'b' -> '\b'
  20167. case 118: return "\u000b" // 'v' -> '\u000b'
  20168. case 102: return "\f" // 'f' -> '\f'
  20169. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  20170. case 10: // ' \n'
  20171. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  20172. return ""
  20173. case 56:
  20174. case 57:
  20175. if (this.strict) {
  20176. this.invalidStringToken(
  20177. this.pos - 1,
  20178. "Invalid escape sequence"
  20179. );
  20180. }
  20181. if (inTemplate) {
  20182. var codePos = this.pos - 1;
  20183. this.invalidStringToken(
  20184. codePos,
  20185. "Invalid escape sequence in template string"
  20186. );
  20187. return null
  20188. }
  20189. default:
  20190. if (ch >= 48 && ch <= 55) {
  20191. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  20192. var octal = parseInt(octalStr, 8);
  20193. if (octal > 255) {
  20194. octalStr = octalStr.slice(0, -1);
  20195. octal = parseInt(octalStr, 8);
  20196. }
  20197. this.pos += octalStr.length - 1;
  20198. ch = this.input.charCodeAt(this.pos);
  20199. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  20200. this.invalidStringToken(
  20201. this.pos - 1 - octalStr.length,
  20202. inTemplate
  20203. ? "Octal literal in template string"
  20204. : "Octal literal in strict mode"
  20205. );
  20206. }
  20207. return String.fromCharCode(octal)
  20208. }
  20209. if (isNewLine(ch)) {
  20210. // Unicode new line characters after \ get removed from output in both
  20211. // template literals and strings
  20212. return ""
  20213. }
  20214. return String.fromCharCode(ch)
  20215. }
  20216. };
  20217. // Used to read character escape sequences ('\x', '\u', '\U').
  20218. pp.readHexChar = function(len) {
  20219. var codePos = this.pos;
  20220. var n = this.readInt(16, len);
  20221. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  20222. return n
  20223. };
  20224. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  20225. // to whether the word contained a '\u' escape.
  20226. //
  20227. // Incrementally adds only escaped chars, adding other chunks as-is
  20228. // as a micro-optimization.
  20229. pp.readWord1 = function() {
  20230. this.containsEsc = false;
  20231. var word = "", first = true, chunkStart = this.pos;
  20232. var astral = this.options.ecmaVersion >= 6;
  20233. while (this.pos < this.input.length) {
  20234. var ch = this.fullCharCodeAtPos();
  20235. if (isIdentifierChar(ch, astral)) {
  20236. this.pos += ch <= 0xffff ? 1 : 2;
  20237. } else if (ch === 92) { // "\"
  20238. this.containsEsc = true;
  20239. word += this.input.slice(chunkStart, this.pos);
  20240. var escStart = this.pos;
  20241. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  20242. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  20243. ++this.pos;
  20244. var esc = this.readCodePoint();
  20245. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  20246. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  20247. word += codePointToString(esc);
  20248. chunkStart = this.pos;
  20249. } else {
  20250. break
  20251. }
  20252. first = false;
  20253. }
  20254. return word + this.input.slice(chunkStart, this.pos)
  20255. };
  20256. // Read an identifier or keyword token. Will check for reserved
  20257. // words when necessary.
  20258. pp.readWord = function() {
  20259. var word = this.readWord1();
  20260. var type = types$1.name;
  20261. if (this.keywords.test(word)) {
  20262. type = keywords[word];
  20263. }
  20264. return this.finishToken(type, word)
  20265. };
  20266. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  20267. var version = "8.7.1";
  20268. Parser.acorn = {
  20269. Parser: Parser,
  20270. version: version,
  20271. defaultOptions: defaultOptions,
  20272. Position: Position,
  20273. SourceLocation: SourceLocation,
  20274. getLineInfo: getLineInfo,
  20275. Node: Node,
  20276. TokenType: TokenType,
  20277. tokTypes: types$1,
  20278. keywordTypes: keywords,
  20279. TokContext: TokContext,
  20280. tokContexts: types,
  20281. isIdentifierChar: isIdentifierChar,
  20282. isIdentifierStart: isIdentifierStart,
  20283. Token: Token,
  20284. isNewLine: isNewLine,
  20285. lineBreak: lineBreak,
  20286. lineBreakG: lineBreakG,
  20287. nonASCIIwhitespace: nonASCIIwhitespace
  20288. };
  20289. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20290. let skipped = null;
  20291. let replaceContext = null;
  20292. if (skip) {
  20293. skipped = new Set();
  20294. for (const skippedCall of skip) {
  20295. if (source === skippedCall.source && importer === skippedCall.importer) {
  20296. skipped.add(skippedCall.plugin);
  20297. }
  20298. }
  20299. replaceContext = (pluginContext, plugin) => ({
  20300. ...pluginContext,
  20301. resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
  20302. return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20303. }
  20304. });
  20305. }
  20306. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
  20307. }
  20308. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20309. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
  20310. if (pluginResult != null)
  20311. return pluginResult;
  20312. // external modules (non-entry modules that start with neither '.' or '/')
  20313. // are skipped at this stage.
  20314. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  20315. return null;
  20316. // `resolve` processes paths from right to left, prepending them until an
  20317. // absolute path is created. Absolute importees therefore shortcircuit the
  20318. // resolve call and require no special handing on our part.
  20319. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20320. return addJsExtensionIfNecessary(importer ? require$$0.resolve(require$$0.dirname(importer), source) : require$$0.resolve(source), preserveSymlinks);
  20321. }
  20322. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20323. var _a, _b;
  20324. 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)));
  20325. }
  20326. async function findFile(file, preserveSymlinks) {
  20327. try {
  20328. const stats = await require$$0$1.promises.lstat(file);
  20329. if (!preserveSymlinks && stats.isSymbolicLink())
  20330. return await findFile(await require$$0$1.promises.realpath(file), preserveSymlinks);
  20331. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20332. // check case
  20333. const name = require$$0.basename(file);
  20334. const files = await require$$0$1.promises.readdir(require$$0.dirname(file));
  20335. if (files.includes(name))
  20336. return file;
  20337. }
  20338. }
  20339. catch (_a) {
  20340. // suppress
  20341. }
  20342. }
  20343. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20344. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20345. function throwPluginError(err, plugin, { hook, id } = {}) {
  20346. if (typeof err === 'string')
  20347. err = { message: err };
  20348. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  20349. err.pluginCode = err.code;
  20350. }
  20351. err.code = Errors.PLUGIN_ERROR;
  20352. err.plugin = plugin;
  20353. if (hook) {
  20354. err.hook = hook;
  20355. }
  20356. if (id) {
  20357. err.id = id;
  20358. }
  20359. return error(err);
  20360. }
  20361. const deprecatedHooks = [
  20362. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  20363. ];
  20364. function warnDeprecatedHooks(plugins, options) {
  20365. for (const { active, deprecated, replacement } of deprecatedHooks) {
  20366. for (const plugin of plugins) {
  20367. if (deprecated in plugin) {
  20368. warnDeprecation({
  20369. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  20370. plugin: plugin.name
  20371. }, active, options);
  20372. }
  20373. }
  20374. }
  20375. }
  20376. function createPluginCache(cache) {
  20377. return {
  20378. delete(id) {
  20379. return delete cache[id];
  20380. },
  20381. get(id) {
  20382. const item = cache[id];
  20383. if (!item)
  20384. return undefined;
  20385. item[0] = 0;
  20386. return item[1];
  20387. },
  20388. has(id) {
  20389. const item = cache[id];
  20390. if (!item)
  20391. return false;
  20392. item[0] = 0;
  20393. return true;
  20394. },
  20395. set(id, value) {
  20396. cache[id] = [0, value];
  20397. }
  20398. };
  20399. }
  20400. function getTrackedPluginCache(pluginCache, onUse) {
  20401. return {
  20402. delete(id) {
  20403. onUse();
  20404. return pluginCache.delete(id);
  20405. },
  20406. get(id) {
  20407. onUse();
  20408. return pluginCache.get(id);
  20409. },
  20410. has(id) {
  20411. onUse();
  20412. return pluginCache.has(id);
  20413. },
  20414. set(id, value) {
  20415. onUse();
  20416. return pluginCache.set(id, value);
  20417. }
  20418. };
  20419. }
  20420. const NO_CACHE = {
  20421. delete() {
  20422. return false;
  20423. },
  20424. get() {
  20425. return undefined;
  20426. },
  20427. has() {
  20428. return false;
  20429. },
  20430. set() { }
  20431. };
  20432. function uncacheablePluginError(pluginName) {
  20433. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20434. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20435. return error({
  20436. code: 'ANONYMOUS_PLUGIN_CACHE',
  20437. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  20438. });
  20439. }
  20440. return error({
  20441. code: 'DUPLICATE_PLUGIN_NAME',
  20442. 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).`
  20443. });
  20444. }
  20445. function getCacheForUncacheablePlugin(pluginName) {
  20446. return {
  20447. delete() {
  20448. return uncacheablePluginError(pluginName);
  20449. },
  20450. get() {
  20451. return uncacheablePluginError(pluginName);
  20452. },
  20453. has() {
  20454. return uncacheablePluginError(pluginName);
  20455. },
  20456. set() {
  20457. return uncacheablePluginError(pluginName);
  20458. }
  20459. };
  20460. }
  20461. async function transform(source, module, pluginDriver, warn) {
  20462. const id = module.id;
  20463. const sourcemapChain = [];
  20464. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20465. const originalCode = source.code;
  20466. let ast = source.ast;
  20467. const transformDependencies = [];
  20468. const emittedFiles = [];
  20469. let customTransformCache = false;
  20470. const useCustomTransformCache = () => (customTransformCache = true);
  20471. let pluginName = '';
  20472. const curSource = source.code;
  20473. function transformReducer(previousCode, result, plugin) {
  20474. let code;
  20475. let map;
  20476. if (typeof result === 'string') {
  20477. code = result;
  20478. }
  20479. else if (result && typeof result === 'object') {
  20480. module.updateOptions(result);
  20481. if (result.code == null) {
  20482. if (result.map || result.ast) {
  20483. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  20484. }
  20485. return previousCode;
  20486. }
  20487. ({ code, map, ast } = result);
  20488. }
  20489. else {
  20490. return previousCode;
  20491. }
  20492. // strict null check allows 'null' maps to not be pushed to the chain,
  20493. // while 'undefined' gets the missing map warning
  20494. if (map !== null) {
  20495. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20496. missing: true,
  20497. plugin: plugin.name
  20498. });
  20499. }
  20500. return code;
  20501. }
  20502. let code;
  20503. try {
  20504. code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  20505. pluginName = plugin.name;
  20506. return {
  20507. ...pluginContext,
  20508. addWatchFile(id) {
  20509. transformDependencies.push(id);
  20510. pluginContext.addWatchFile(id);
  20511. },
  20512. cache: customTransformCache
  20513. ? pluginContext.cache
  20514. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20515. emitAsset(name, source) {
  20516. emittedFiles.push({ name, source, type: 'asset' });
  20517. return pluginContext.emitAsset(name, source);
  20518. },
  20519. emitChunk(id, options) {
  20520. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  20521. return pluginContext.emitChunk(id, options);
  20522. },
  20523. emitFile(emittedFile) {
  20524. emittedFiles.push(emittedFile);
  20525. return pluginDriver.emitFile(emittedFile);
  20526. },
  20527. error(err, pos) {
  20528. if (typeof err === 'string')
  20529. err = { message: err };
  20530. if (pos)
  20531. augmentCodeLocation(err, pos, curSource, id);
  20532. err.id = id;
  20533. err.hook = 'transform';
  20534. return pluginContext.error(err);
  20535. },
  20536. getCombinedSourcemap() {
  20537. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  20538. if (!combinedMap) {
  20539. const magicString = new MagicString(originalCode);
  20540. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20541. }
  20542. if (originalSourcemap !== combinedMap) {
  20543. originalSourcemap = combinedMap;
  20544. sourcemapChain.length = 0;
  20545. }
  20546. return new SourceMap({
  20547. ...combinedMap,
  20548. file: null,
  20549. sourcesContent: combinedMap.sourcesContent
  20550. });
  20551. },
  20552. setAssetSource() {
  20553. return this.error({
  20554. code: 'INVALID_SETASSETSOURCE',
  20555. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  20556. });
  20557. },
  20558. warn(warning, pos) {
  20559. if (typeof warning === 'string')
  20560. warning = { message: warning };
  20561. if (pos)
  20562. augmentCodeLocation(warning, pos, curSource, id);
  20563. warning.id = id;
  20564. warning.hook = 'transform';
  20565. pluginContext.warn(warning);
  20566. }
  20567. };
  20568. });
  20569. }
  20570. catch (err) {
  20571. throwPluginError(err, pluginName, { hook: 'transform', id });
  20572. }
  20573. if (!customTransformCache) {
  20574. // files emitted by a transform hook need to be emitted again if the hook is skipped
  20575. if (emittedFiles.length)
  20576. module.transformFiles = emittedFiles;
  20577. }
  20578. return {
  20579. ast,
  20580. code,
  20581. customTransformCache,
  20582. originalCode,
  20583. originalSourcemap,
  20584. sourcemapChain,
  20585. transformDependencies
  20586. };
  20587. }
  20588. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20589. class ModuleLoader {
  20590. constructor(graph, modulesById, options, pluginDriver) {
  20591. this.graph = graph;
  20592. this.modulesById = modulesById;
  20593. this.options = options;
  20594. this.pluginDriver = pluginDriver;
  20595. this.implicitEntryModules = new Set();
  20596. this.indexedEntryModules = [];
  20597. this.latestLoadModulesPromise = Promise.resolve();
  20598. this.moduleLoadPromises = new Map();
  20599. this.modulesWithLoadedDependencies = new Set();
  20600. this.nextChunkNamePriority = 0;
  20601. this.nextEntryModuleIndex = 0;
  20602. this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
  20603. return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20604. ? false
  20605. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
  20606. };
  20607. this.hasModuleSideEffects = options.treeshake
  20608. ? options.treeshake.moduleSideEffects
  20609. : () => true;
  20610. }
  20611. async addAdditionalModules(unresolvedModules) {
  20612. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  20613. await this.awaitLoadModulesPromise();
  20614. return result;
  20615. }
  20616. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20617. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20618. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20619. const firstChunkNamePriority = this.nextChunkNamePriority;
  20620. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20621. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20622. for (let index = 0; index < entryModules.length; index++) {
  20623. const entryModule = entryModules[index];
  20624. entryModule.isUserDefinedEntryPoint =
  20625. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20626. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20627. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20628. if (!existingIndexedModule) {
  20629. this.indexedEntryModules.push({
  20630. index: firstEntryModuleIndex + index,
  20631. module: entryModule
  20632. });
  20633. }
  20634. else {
  20635. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20636. }
  20637. }
  20638. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20639. return entryModules;
  20640. }));
  20641. await this.awaitLoadModulesPromise();
  20642. return {
  20643. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20644. implicitEntryModules: [...this.implicitEntryModules],
  20645. newEntryModules
  20646. };
  20647. }
  20648. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20649. const unresolvedModule = {
  20650. fileName: fileName || null,
  20651. id,
  20652. importer,
  20653. name: name || null
  20654. };
  20655. const module = implicitlyLoadedAfterOneOf
  20656. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20657. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20658. if (preserveSignature != null) {
  20659. module.preserveSignature = preserveSignature;
  20660. }
  20661. return module;
  20662. }
  20663. async preloadModule(resolvedId) {
  20664. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20665. return module.info;
  20666. }
  20667. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20668. const chunkNamePriority = this.nextChunkNamePriority++;
  20669. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20670. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20671. if (!entryModule.info.isEntry) {
  20672. this.implicitEntryModules.add(entryModule);
  20673. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20674. for (const module of implicitlyLoadedAfterModules) {
  20675. entryModule.implicitlyLoadedAfter.add(module);
  20676. }
  20677. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20678. dependant.implicitlyLoadedBefore.add(entryModule);
  20679. }
  20680. }
  20681. return entryModule;
  20682. }));
  20683. }
  20684. async addModuleSource(id, importer, module) {
  20685. timeStart('load modules', 3);
  20686. let source;
  20687. try {
  20688. source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await require$$0$1.promises.readFile(id, 'utf8')); });
  20689. }
  20690. catch (err) {
  20691. timeEnd('load modules', 3);
  20692. let msg = `Could not load ${id}`;
  20693. if (importer)
  20694. msg += ` (imported by ${relativeId(importer)})`;
  20695. msg += `: ${err.message}`;
  20696. err.message = msg;
  20697. throw err;
  20698. }
  20699. timeEnd('load modules', 3);
  20700. const sourceDescription = typeof source === 'string'
  20701. ? { code: source }
  20702. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20703. ? source
  20704. : error(errBadLoader(id));
  20705. const cachedModule = this.graph.cachedModules.get(id);
  20706. if (cachedModule &&
  20707. !cachedModule.customTransformCache &&
  20708. cachedModule.originalCode === sourceDescription.code &&
  20709. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20710. {
  20711. ast: cachedModule.ast,
  20712. code: cachedModule.code,
  20713. id: cachedModule.id,
  20714. meta: cachedModule.meta,
  20715. moduleSideEffects: cachedModule.moduleSideEffects,
  20716. resolvedSources: cachedModule.resolvedIds,
  20717. syntheticNamedExports: cachedModule.syntheticNamedExports
  20718. }
  20719. ]))) {
  20720. if (cachedModule.transformFiles) {
  20721. for (const emittedFile of cachedModule.transformFiles)
  20722. this.pluginDriver.emitFile(emittedFile);
  20723. }
  20724. module.setSource(cachedModule);
  20725. }
  20726. else {
  20727. module.updateOptions(sourceDescription);
  20728. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  20729. }
  20730. }
  20731. async awaitLoadModulesPromise() {
  20732. let startingPromise;
  20733. do {
  20734. startingPromise = this.latestLoadModulesPromise;
  20735. await startingPromise;
  20736. } while (startingPromise !== this.latestLoadModulesPromise);
  20737. }
  20738. extendLoadModulesPromise(loadNewModulesPromise) {
  20739. this.latestLoadModulesPromise = Promise.all([
  20740. loadNewModulesPromise,
  20741. this.latestLoadModulesPromise
  20742. ]);
  20743. this.latestLoadModulesPromise.catch(() => {
  20744. /* Avoid unhandled Promise rejections */
  20745. });
  20746. return loadNewModulesPromise;
  20747. }
  20748. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20749. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20750. if (resolvedId === null)
  20751. return null;
  20752. if (typeof resolvedId === 'string') {
  20753. dynamicImport.resolution = resolvedId;
  20754. return null;
  20755. }
  20756. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20757. })));
  20758. for (const dependency of dependencies) {
  20759. if (dependency) {
  20760. module.dynamicDependencies.add(dependency);
  20761. dependency.dynamicImporters.push(module.id);
  20762. }
  20763. }
  20764. }
  20765. // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
  20766. // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
  20767. // Otherwise it returns immediately.
  20768. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20769. const existingModule = this.modulesById.get(id);
  20770. if (existingModule instanceof Module) {
  20771. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20772. return existingModule;
  20773. }
  20774. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  20775. this.modulesById.set(id, module);
  20776. this.graph.watchFiles[id] = true;
  20777. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20778. this.getResolveStaticDependencyPromises(module),
  20779. this.getResolveDynamicImportPromises(module),
  20780. loadAndResolveDependenciesPromise
  20781. ]);
  20782. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20783. loadAndResolveDependenciesPromise.catch(() => {
  20784. /* avoid unhandled promise rejections */
  20785. });
  20786. this.moduleLoadPromises.set(module, loadPromise);
  20787. const resolveDependencyPromises = await loadPromise;
  20788. if (!isPreload) {
  20789. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20790. }
  20791. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20792. await loadAndResolveDependenciesPromise;
  20793. }
  20794. return module;
  20795. }
  20796. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20797. if (this.modulesWithLoadedDependencies.has(module)) {
  20798. return;
  20799. }
  20800. this.modulesWithLoadedDependencies.add(module);
  20801. await Promise.all([
  20802. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20803. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20804. ]);
  20805. module.linkImports();
  20806. // To handle errors when resolving dependencies or in moduleParsed
  20807. await loadAndResolveDependenciesPromise;
  20808. }
  20809. fetchResolvedDependency(source, importer, resolvedId) {
  20810. if (resolvedId.external) {
  20811. const { external, id, moduleSideEffects, meta } = resolvedId;
  20812. if (!this.modulesById.has(id)) {
  20813. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  20814. }
  20815. const externalModule = this.modulesById.get(id);
  20816. if (!(externalModule instanceof ExternalModule)) {
  20817. return error(errInternalIdCannotBeExternal(source, importer));
  20818. }
  20819. return Promise.resolve(externalModule);
  20820. }
  20821. return this.fetchModule(resolvedId, importer, false, false);
  20822. }
  20823. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20824. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20825. module.dependencies.add(dependency);
  20826. dependency.importers.push(module.id);
  20827. }
  20828. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20829. for (const dependency of module.dependencies) {
  20830. if (dependency instanceof Module) {
  20831. dependency.importedFromNotTreeshaken = true;
  20832. }
  20833. }
  20834. }
  20835. }
  20836. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20837. const { makeAbsoluteExternalsRelative } = this.options;
  20838. if (resolveIdResult) {
  20839. if (typeof resolveIdResult === 'object') {
  20840. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20841. return {
  20842. ...resolveIdResult,
  20843. external: external &&
  20844. (external === 'relative' ||
  20845. !isAbsolute(resolveIdResult.id) ||
  20846. (external === true &&
  20847. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20848. 'absolute')
  20849. };
  20850. }
  20851. const external = this.options.external(resolveIdResult, importer, true);
  20852. return {
  20853. external: external &&
  20854. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20855. 'absolute'),
  20856. id: external && makeAbsoluteExternalsRelative
  20857. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20858. : resolveIdResult
  20859. };
  20860. }
  20861. const id = makeAbsoluteExternalsRelative
  20862. ? normalizeRelativeExternalId(source, importer)
  20863. : source;
  20864. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20865. return null;
  20866. }
  20867. return {
  20868. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20869. id
  20870. };
  20871. }
  20872. getResolveDynamicImportPromises(module) {
  20873. return module.dynamicImports.map(async (dynamicImport) => {
  20874. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  20875. ? dynamicImport.argument
  20876. : dynamicImport.argument.esTreeNode, module.id);
  20877. if (resolvedId && typeof resolvedId === 'object') {
  20878. dynamicImport.id = resolvedId.id;
  20879. }
  20880. return [dynamicImport, resolvedId];
  20881. });
  20882. }
  20883. getResolveStaticDependencyPromises(module) {
  20884. return Array.from(module.sources, async (source) => [
  20885. source,
  20886. (module.resolvedIds[source] =
  20887. module.resolvedIds[source] ||
  20888. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
  20889. ]);
  20890. }
  20891. getResolvedIdWithDefaults(resolvedId) {
  20892. var _a, _b;
  20893. if (!resolvedId) {
  20894. return null;
  20895. }
  20896. const external = resolvedId.external || false;
  20897. return {
  20898. external,
  20899. id: resolvedId.id,
  20900. meta: resolvedId.meta || {},
  20901. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  20902. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  20903. };
  20904. }
  20905. async handleExistingModule(module, isEntry, isPreload) {
  20906. const loadPromise = this.moduleLoadPromises.get(module);
  20907. if (isPreload) {
  20908. return isPreload === RESOLVE_DEPENDENCIES
  20909. ? waitForDependencyResolution(loadPromise)
  20910. : loadPromise;
  20911. }
  20912. if (isEntry) {
  20913. module.info.isEntry = true;
  20914. this.implicitEntryModules.delete(module);
  20915. for (const dependant of module.implicitlyLoadedAfter) {
  20916. dependant.implicitlyLoadedBefore.delete(module);
  20917. }
  20918. module.implicitlyLoadedAfter.clear();
  20919. }
  20920. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20921. }
  20922. handleResolveId(resolvedId, source, importer) {
  20923. if (resolvedId === null) {
  20924. if (isRelative(source)) {
  20925. return error(errUnresolvedImport(source, importer));
  20926. }
  20927. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  20928. return {
  20929. external: true,
  20930. id: source,
  20931. meta: {},
  20932. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20933. syntheticNamedExports: false
  20934. };
  20935. }
  20936. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20937. this.options.onwarn(errExternalSyntheticExports(source, importer));
  20938. }
  20939. return resolvedId;
  20940. }
  20941. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  20942. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
  20943. if (resolveIdResult == null) {
  20944. return error(implicitlyLoadedBefore === null
  20945. ? errUnresolvedEntry(unresolvedId)
  20946. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20947. }
  20948. if (resolveIdResult === false ||
  20949. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  20950. return error(implicitlyLoadedBefore === null
  20951. ? errEntryCannotBeExternal(unresolvedId)
  20952. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20953. }
  20954. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20955. ? resolveIdResult
  20956. : { id: resolveIdResult }), undefined, isEntry, false);
  20957. }
  20958. async resolveDynamicImport(module, specifier, importer) {
  20959. var _a;
  20960. var _b;
  20961. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20962. specifier,
  20963. importer
  20964. ]);
  20965. if (typeof specifier !== 'string') {
  20966. if (typeof resolution === 'string') {
  20967. return resolution;
  20968. }
  20969. if (!resolution) {
  20970. return null;
  20971. }
  20972. return {
  20973. external: false,
  20974. moduleSideEffects: true,
  20975. ...resolution
  20976. };
  20977. }
  20978. if (resolution == null) {
  20979. 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)));
  20980. }
  20981. return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  20982. }
  20983. }
  20984. function normalizeRelativeExternalId(source, importer) {
  20985. return isRelative(source)
  20986. ? importer
  20987. ? require$$0.resolve(importer, '..', source)
  20988. : require$$0.resolve(source)
  20989. : source;
  20990. }
  20991. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20992. var _a;
  20993. if (fileName !== null) {
  20994. module.chunkFileNames.add(fileName);
  20995. }
  20996. else if (name !== null) {
  20997. // Always keep chunkNames sorted by priority
  20998. let namePosition = 0;
  20999. while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
  21000. namePosition++;
  21001. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  21002. }
  21003. }
  21004. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  21005. return (makeAbsoluteExternalsRelative === true ||
  21006. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  21007. !isAbsolute(id));
  21008. }
  21009. async function waitForDependencyResolution(loadPromise) {
  21010. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  21011. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  21012. }
  21013. class GlobalScope extends Scope$1 {
  21014. constructor() {
  21015. super();
  21016. this.parent = null;
  21017. this.variables.set('undefined', new UndefinedVariable());
  21018. }
  21019. findVariable(name) {
  21020. let variable = this.variables.get(name);
  21021. if (!variable) {
  21022. variable = new GlobalVariable(name);
  21023. this.variables.set(name, variable);
  21024. }
  21025. return variable;
  21026. }
  21027. }
  21028. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  21029. let deprecationWarningShown = false;
  21030. return ((...args) => {
  21031. if (!deprecationWarningShown) {
  21032. deprecationWarningShown = true;
  21033. warnDeprecation({
  21034. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  21035. plugin: pluginName
  21036. }, activeDeprecation, options);
  21037. }
  21038. return handler(...args);
  21039. });
  21040. }
  21041. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  21042. let cacheable = true;
  21043. if (typeof plugin.cacheKey !== 'string') {
  21044. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  21045. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  21046. existingPluginNames.has(plugin.name)) {
  21047. cacheable = false;
  21048. }
  21049. else {
  21050. existingPluginNames.add(plugin.name);
  21051. }
  21052. }
  21053. let cacheInstance;
  21054. if (!pluginCache) {
  21055. cacheInstance = NO_CACHE;
  21056. }
  21057. else if (cacheable) {
  21058. const cacheKey = plugin.cacheKey || plugin.name;
  21059. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  21060. }
  21061. else {
  21062. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  21063. }
  21064. const context = {
  21065. addWatchFile(id) {
  21066. if (graph.phase >= BuildPhase.GENERATE) {
  21067. return this.error(errInvalidRollupPhaseForAddWatchFile());
  21068. }
  21069. graph.watchFiles[id] = true;
  21070. },
  21071. cache: cacheInstance,
  21072. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  21073. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  21074. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  21075. error(err) {
  21076. return throwPluginError(err, plugin.name);
  21077. },
  21078. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  21079. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  21080. getFileName: fileEmitter.getFileName,
  21081. getModuleIds: () => graph.modulesById.keys(),
  21082. getModuleInfo: graph.getModuleInfo,
  21083. getWatchFiles: () => Object.keys(graph.watchFiles),
  21084. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  21085. load(resolvedId) {
  21086. return graph.moduleLoader.preloadModule(resolvedId);
  21087. },
  21088. meta: {
  21089. rollupVersion: version$1,
  21090. watchMode: graph.watchMode
  21091. },
  21092. get moduleIds() {
  21093. function* wrappedModuleIds() {
  21094. // We are wrapping this in a generator to only show the message once we are actually iterating
  21095. warnDeprecation({
  21096. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  21097. plugin: plugin.name
  21098. }, false, options);
  21099. yield* moduleIds;
  21100. }
  21101. const moduleIds = graph.modulesById.keys();
  21102. return wrappedModuleIds();
  21103. },
  21104. parse: graph.contextParse.bind(graph),
  21105. resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
  21106. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
  21107. },
  21108. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  21109. .resolveId(source, importer, BLANK, undefined)
  21110. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  21111. setAssetSource: fileEmitter.setAssetSource,
  21112. warn(warning) {
  21113. if (typeof warning === 'string')
  21114. warning = { message: warning };
  21115. if (warning.code)
  21116. warning.pluginCode = warning.code;
  21117. warning.code = 'PLUGIN_WARNING';
  21118. warning.plugin = plugin.name;
  21119. options.onwarn(warning);
  21120. }
  21121. };
  21122. return context;
  21123. }
  21124. const inputHookNames = {
  21125. buildEnd: 1,
  21126. buildStart: 1,
  21127. closeBundle: 1,
  21128. closeWatcher: 1,
  21129. load: 1,
  21130. moduleParsed: 1,
  21131. options: 1,
  21132. resolveDynamicImport: 1,
  21133. resolveId: 1,
  21134. shouldTransformCachedModule: 1,
  21135. transform: 1,
  21136. watchChange: 1
  21137. };
  21138. const inputHooks = Object.keys(inputHookNames);
  21139. function throwInvalidHookError(hookName, pluginName) {
  21140. return error({
  21141. code: 'INVALID_PLUGIN_HOOK',
  21142. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  21143. });
  21144. }
  21145. class PluginDriver {
  21146. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21147. this.graph = graph;
  21148. this.options = options;
  21149. this.unfulfilledActions = new Set();
  21150. warnDeprecatedHooks(userPlugins, options);
  21151. this.pluginCache = pluginCache;
  21152. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21153. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21154. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21155. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  21156. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21157. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  21158. const existingPluginNames = new Set();
  21159. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21160. plugin,
  21161. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21162. ]));
  21163. if (basePluginDriver) {
  21164. for (const plugin of userPlugins) {
  21165. for (const hook of inputHooks) {
  21166. if (hook in plugin) {
  21167. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  21168. }
  21169. }
  21170. }
  21171. }
  21172. }
  21173. createOutputPluginDriver(plugins) {
  21174. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21175. }
  21176. getUnfulfilledHookActions() {
  21177. return this.unfulfilledActions;
  21178. }
  21179. // chains, first non-null result stops and returns
  21180. hookFirst(hookName, args, replaceContext, skipped) {
  21181. let promise = Promise.resolve(undefined);
  21182. for (const plugin of this.plugins) {
  21183. if (skipped && skipped.has(plugin))
  21184. continue;
  21185. promise = promise.then(result => {
  21186. if (result != null)
  21187. return result;
  21188. return this.runHook(hookName, args, plugin, false, replaceContext);
  21189. });
  21190. }
  21191. return promise;
  21192. }
  21193. // chains synchronously, first non-null result stops and returns
  21194. hookFirstSync(hookName, args, replaceContext) {
  21195. for (const plugin of this.plugins) {
  21196. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21197. if (result != null)
  21198. return result;
  21199. }
  21200. return null;
  21201. }
  21202. // parallel, ignores returns
  21203. hookParallel(hookName, args, replaceContext) {
  21204. const promises = [];
  21205. for (const plugin of this.plugins) {
  21206. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  21207. if (!hookPromise)
  21208. continue;
  21209. promises.push(hookPromise);
  21210. }
  21211. return Promise.all(promises).then(() => { });
  21212. }
  21213. // chains, reduces returned value, handling the reduced value as the first hook argument
  21214. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  21215. let promise = Promise.resolve(arg0);
  21216. for (const plugin of this.plugins) {
  21217. promise = promise.then(arg0 => {
  21218. const args = [arg0, ...rest];
  21219. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  21220. if (!hookPromise)
  21221. return arg0;
  21222. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
  21223. });
  21224. }
  21225. return promise;
  21226. }
  21227. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21228. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  21229. for (const plugin of this.plugins) {
  21230. const args = [arg0, ...rest];
  21231. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21232. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  21233. }
  21234. return arg0;
  21235. }
  21236. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21237. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  21238. let promise = Promise.resolve(initialValue);
  21239. for (const plugin of this.plugins) {
  21240. promise = promise.then(value => {
  21241. const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
  21242. if (!hookPromise)
  21243. return value;
  21244. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
  21245. });
  21246. }
  21247. return promise;
  21248. }
  21249. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21250. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  21251. let acc = initialValue;
  21252. for (const plugin of this.plugins) {
  21253. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21254. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  21255. }
  21256. return acc;
  21257. }
  21258. // chains, ignores returns
  21259. hookSeq(hookName, args, replaceContext) {
  21260. let promise = Promise.resolve();
  21261. for (const plugin of this.plugins) {
  21262. promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
  21263. }
  21264. return promise;
  21265. }
  21266. runHook(hookName, args, plugin, permitValues, hookContext) {
  21267. const hook = plugin[hookName];
  21268. if (!hook)
  21269. return undefined;
  21270. let context = this.pluginContexts.get(plugin);
  21271. if (hookContext) {
  21272. context = hookContext(context, plugin);
  21273. }
  21274. let action = null;
  21275. return Promise.resolve()
  21276. .then(() => {
  21277. // permit values allows values to be returned instead of a functional hook
  21278. if (typeof hook !== 'function') {
  21279. if (permitValues)
  21280. return hook;
  21281. return throwInvalidHookError(hookName, plugin.name);
  21282. }
  21283. // eslint-disable-next-line @typescript-eslint/ban-types
  21284. const hookResult = hook.apply(context, args);
  21285. if (!hookResult || !hookResult.then) {
  21286. // short circuit for non-thenables and non-Promises
  21287. return hookResult;
  21288. }
  21289. // Track pending hook actions to properly error out when
  21290. // unfulfilled promises cause rollup to abruptly and confusingly
  21291. // exit with a successful 0 return code but without producing any
  21292. // output, errors or warnings.
  21293. action = [plugin.name, hookName, args];
  21294. this.unfulfilledActions.add(action);
  21295. // Although it would be more elegant to just return hookResult here
  21296. // and put the .then() handler just above the .catch() handler below,
  21297. // doing so would subtly change the defacto async event dispatch order
  21298. // which at least one test and some plugins in the wild may depend on.
  21299. return Promise.resolve(hookResult).then(result => {
  21300. // action was fulfilled
  21301. this.unfulfilledActions.delete(action);
  21302. return result;
  21303. });
  21304. })
  21305. .catch(err => {
  21306. if (action !== null) {
  21307. // action considered to be fulfilled since error being handled
  21308. this.unfulfilledActions.delete(action);
  21309. }
  21310. return throwPluginError(err, plugin.name, { hook: hookName });
  21311. });
  21312. }
  21313. /**
  21314. * Run a sync plugin hook and return the result.
  21315. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21316. * @param args Arguments passed to the plugin hook.
  21317. * @param plugin The acutal plugin
  21318. * @param hookContext When passed, the plugin context can be overridden.
  21319. */
  21320. runHookSync(hookName, args, plugin, hookContext) {
  21321. const hook = plugin[hookName];
  21322. if (!hook)
  21323. return undefined;
  21324. let context = this.pluginContexts.get(plugin);
  21325. if (hookContext) {
  21326. context = hookContext(context, plugin);
  21327. }
  21328. try {
  21329. // permit values allows values to be returned instead of a functional hook
  21330. if (typeof hook !== 'function') {
  21331. return throwInvalidHookError(hookName, plugin.name);
  21332. }
  21333. // eslint-disable-next-line @typescript-eslint/ban-types
  21334. return hook.apply(context, args);
  21335. }
  21336. catch (err) {
  21337. return throwPluginError(err, plugin.name, { hook: hookName });
  21338. }
  21339. }
  21340. }
  21341. class Queue {
  21342. constructor(maxParallel) {
  21343. this.maxParallel = maxParallel;
  21344. this.queue = [];
  21345. this.workerCount = 0;
  21346. }
  21347. run(task) {
  21348. return new Promise((resolve, reject) => {
  21349. this.queue.push({ reject, resolve, task });
  21350. this.work();
  21351. });
  21352. }
  21353. async work() {
  21354. if (this.workerCount >= this.maxParallel)
  21355. return;
  21356. this.workerCount++;
  21357. let entry;
  21358. while ((entry = this.queue.shift())) {
  21359. const { reject, resolve, task } = entry;
  21360. try {
  21361. const result = await task();
  21362. resolve(result);
  21363. }
  21364. catch (err) {
  21365. reject(err);
  21366. }
  21367. }
  21368. this.workerCount--;
  21369. }
  21370. }
  21371. function normalizeEntryModules(entryModules) {
  21372. if (Array.isArray(entryModules)) {
  21373. return entryModules.map(id => ({
  21374. fileName: null,
  21375. id,
  21376. implicitlyLoadedAfter: [],
  21377. importer: undefined,
  21378. name: null
  21379. }));
  21380. }
  21381. return Object.entries(entryModules).map(([name, id]) => ({
  21382. fileName: null,
  21383. id,
  21384. implicitlyLoadedAfter: [],
  21385. importer: undefined,
  21386. name
  21387. }));
  21388. }
  21389. class Graph {
  21390. constructor(options, watcher) {
  21391. var _a, _b;
  21392. this.options = options;
  21393. this.cachedModules = new Map();
  21394. this.deoptimizationTracker = new PathTracker();
  21395. this.entryModules = [];
  21396. this.modulesById = new Map();
  21397. this.needsTreeshakingPass = false;
  21398. this.phase = BuildPhase.LOAD_AND_PARSE;
  21399. this.scope = new GlobalScope();
  21400. this.watchFiles = Object.create(null);
  21401. this.watchMode = false;
  21402. this.externalModules = [];
  21403. this.implicitEntryModules = [];
  21404. this.modules = [];
  21405. this.getModuleInfo = (moduleId) => {
  21406. const foundModule = this.modulesById.get(moduleId);
  21407. if (!foundModule)
  21408. return null;
  21409. return foundModule.info;
  21410. };
  21411. if (options.cache !== false) {
  21412. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  21413. for (const module of options.cache.modules)
  21414. this.cachedModules.set(module.id, module);
  21415. }
  21416. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  21417. // increment access counter
  21418. for (const name in this.pluginCache) {
  21419. const cache = this.pluginCache[name];
  21420. for (const value of Object.values(cache))
  21421. value[0]++;
  21422. }
  21423. }
  21424. if (watcher) {
  21425. this.watchMode = true;
  21426. const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
  21427. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21428. watcher.onCurrentAwaited('change', handleChange);
  21429. watcher.onCurrentAwaited('close', handleClose);
  21430. }
  21431. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21432. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  21433. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21434. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21435. }
  21436. async build() {
  21437. timeStart('generate module graph', 2);
  21438. await this.generateModuleGraph();
  21439. timeEnd('generate module graph', 2);
  21440. timeStart('sort modules', 2);
  21441. this.phase = BuildPhase.ANALYSE;
  21442. this.sortModules();
  21443. timeEnd('sort modules', 2);
  21444. timeStart('mark included statements', 2);
  21445. this.includeStatements();
  21446. timeEnd('mark included statements', 2);
  21447. this.phase = BuildPhase.GENERATE;
  21448. }
  21449. contextParse(code, options = {}) {
  21450. const onCommentOrig = options.onComment;
  21451. const comments = [];
  21452. if (onCommentOrig && typeof onCommentOrig == 'function') {
  21453. options.onComment = (block, text, start, end, ...args) => {
  21454. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  21455. return onCommentOrig.call(options, block, text, start, end, ...args);
  21456. };
  21457. }
  21458. else {
  21459. options.onComment = comments;
  21460. }
  21461. const ast = this.acornParser.parse(code, {
  21462. ...this.options.acorn,
  21463. ...options
  21464. });
  21465. if (typeof onCommentOrig == 'object') {
  21466. onCommentOrig.push(...comments);
  21467. }
  21468. options.onComment = onCommentOrig;
  21469. addAnnotations(comments, ast, code);
  21470. return ast;
  21471. }
  21472. getCache() {
  21473. // handle plugin cache eviction
  21474. for (const name in this.pluginCache) {
  21475. const cache = this.pluginCache[name];
  21476. let allDeleted = true;
  21477. for (const [key, value] of Object.entries(cache)) {
  21478. if (value[0] >= this.options.experimentalCacheExpiry)
  21479. delete cache[key];
  21480. else
  21481. allDeleted = false;
  21482. }
  21483. if (allDeleted)
  21484. delete this.pluginCache[name];
  21485. }
  21486. return {
  21487. modules: this.modules.map(module => module.toJSON()),
  21488. plugins: this.pluginCache
  21489. };
  21490. }
  21491. async generateModuleGraph() {
  21492. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21493. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21494. if (this.entryModules.length === 0) {
  21495. throw new Error('You must supply options.input to rollup');
  21496. }
  21497. for (const module of this.modulesById.values()) {
  21498. if (module instanceof Module) {
  21499. this.modules.push(module);
  21500. }
  21501. else {
  21502. this.externalModules.push(module);
  21503. }
  21504. }
  21505. }
  21506. includeStatements() {
  21507. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21508. markModuleAndImpureDependenciesAsExecuted(module);
  21509. }
  21510. if (this.options.treeshake) {
  21511. let treeshakingPass = 1;
  21512. do {
  21513. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21514. this.needsTreeshakingPass = false;
  21515. for (const module of this.modules) {
  21516. if (module.isExecuted) {
  21517. if (module.info.moduleSideEffects === 'no-treeshake') {
  21518. module.includeAllInBundle();
  21519. }
  21520. else {
  21521. module.include();
  21522. }
  21523. }
  21524. }
  21525. if (treeshakingPass === 1) {
  21526. // We only include exports after the first pass to avoid issues with
  21527. // the TDZ detection logic
  21528. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21529. if (module.preserveSignature !== false) {
  21530. module.includeAllExports(false);
  21531. this.needsTreeshakingPass = true;
  21532. }
  21533. }
  21534. }
  21535. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21536. } while (this.needsTreeshakingPass);
  21537. }
  21538. else {
  21539. for (const module of this.modules)
  21540. module.includeAllInBundle();
  21541. }
  21542. for (const externalModule of this.externalModules)
  21543. externalModule.warnUnusedImports();
  21544. for (const module of this.implicitEntryModules) {
  21545. for (const dependant of module.implicitlyLoadedAfter) {
  21546. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21547. error(errImplicitDependantIsNotIncluded(dependant));
  21548. }
  21549. }
  21550. }
  21551. }
  21552. sortModules() {
  21553. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21554. for (const cyclePath of cyclePaths) {
  21555. this.options.onwarn({
  21556. code: 'CIRCULAR_DEPENDENCY',
  21557. cycle: cyclePath,
  21558. importer: cyclePath[0],
  21559. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  21560. });
  21561. }
  21562. this.modules = orderedModules;
  21563. for (const module of this.modules) {
  21564. module.bindReferences();
  21565. }
  21566. this.warnForMissingExports();
  21567. }
  21568. warnForMissingExports() {
  21569. for (const module of this.modules) {
  21570. for (const importDescription of module.importDescriptions.values()) {
  21571. if (importDescription.name !== '*' &&
  21572. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21573. module.warn({
  21574. code: 'NON_EXISTENT_EXPORT',
  21575. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  21576. name: importDescription.name,
  21577. source: importDescription.module.id
  21578. }, importDescription.start);
  21579. }
  21580. }
  21581. }
  21582. }
  21583. }
  21584. function formatAction([pluginName, hookName, args]) {
  21585. const action = `(${pluginName}) ${hookName}`;
  21586. const s = JSON.stringify;
  21587. switch (hookName) {
  21588. case 'resolveId':
  21589. return `${action} ${s(args[0])} ${s(args[1])}`;
  21590. case 'load':
  21591. return `${action} ${s(args[0])}`;
  21592. case 'transform':
  21593. return `${action} ${s(args[1])}`;
  21594. case 'shouldTransformCachedModule':
  21595. return `${action} ${s(args[0].id)}`;
  21596. case 'moduleParsed':
  21597. return `${action} ${s(args[0].id)}`;
  21598. }
  21599. return action;
  21600. }
  21601. // We do not directly listen on process to avoid max listeners warnings for
  21602. // complicated build processes
  21603. const beforeExitEvent = 'beforeExit';
  21604. const beforeExitEmitter = new require$$0$2.EventEmitter();
  21605. beforeExitEmitter.setMaxListeners(0);
  21606. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  21607. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21608. let handleEmptyEventLoop;
  21609. const emptyEventLoopPromise = new Promise((_, reject) => {
  21610. handleEmptyEventLoop = () => {
  21611. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21612. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21613. [...unfulfilledActions].map(formatAction).join('\n')));
  21614. };
  21615. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  21616. });
  21617. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  21618. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  21619. return result;
  21620. }
  21621. function normalizeInputOptions(config) {
  21622. var _a, _b, _c;
  21623. // These are options that may trigger special warnings or behaviour later
  21624. // if the user did not select an explicit value
  21625. const unsetOptions = new Set();
  21626. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  21627. const onwarn = getOnwarn(config);
  21628. const strictDeprecations = config.strictDeprecations || false;
  21629. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  21630. const options = {
  21631. acorn: getAcorn(config),
  21632. acornInjectPlugins: getAcornInjectPlugins(config),
  21633. cache: getCache(config),
  21634. context,
  21635. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  21636. external: getIdMatcher(config.external),
  21637. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  21638. input: getInput(config),
  21639. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  21640. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  21641. maxParallelFileOps,
  21642. maxParallelFileReads: maxParallelFileOps,
  21643. moduleContext: getModuleContext(config, context),
  21644. onwarn,
  21645. perf: config.perf || false,
  21646. plugins: ensureArray$1(config.plugins),
  21647. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  21648. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  21649. preserveSymlinks: config.preserveSymlinks || false,
  21650. shimMissingExports: config.shimMissingExports || false,
  21651. strictDeprecations,
  21652. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  21653. };
  21654. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  21655. return { options, unsetOptions };
  21656. }
  21657. const getOnwarn = (config) => {
  21658. const { onwarn } = config;
  21659. return onwarn
  21660. ? warning => {
  21661. warning.toString = () => {
  21662. let str = '';
  21663. if (warning.plugin)
  21664. str += `(${warning.plugin} plugin) `;
  21665. if (warning.loc)
  21666. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  21667. str += warning.message;
  21668. return str;
  21669. };
  21670. onwarn(warning, defaultOnWarn);
  21671. }
  21672. : defaultOnWarn;
  21673. };
  21674. const getAcorn = (config) => ({
  21675. allowAwaitOutsideFunction: true,
  21676. ecmaVersion: 'latest',
  21677. preserveParens: false,
  21678. sourceType: 'module',
  21679. ...config.acorn
  21680. });
  21681. const getAcornInjectPlugins = (config) => ensureArray$1(config.acornInjectPlugins);
  21682. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  21683. const getIdMatcher = (option) => {
  21684. if (option === true) {
  21685. return () => true;
  21686. }
  21687. if (typeof option === 'function') {
  21688. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  21689. }
  21690. if (option) {
  21691. const ids = new Set();
  21692. const matchers = [];
  21693. for (const value of ensureArray$1(option)) {
  21694. if (value instanceof RegExp) {
  21695. matchers.push(value);
  21696. }
  21697. else {
  21698. ids.add(value);
  21699. }
  21700. }
  21701. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21702. }
  21703. return () => false;
  21704. };
  21705. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  21706. const configInlineDynamicImports = config.inlineDynamicImports;
  21707. if (configInlineDynamicImports) {
  21708. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  21709. }
  21710. return configInlineDynamicImports;
  21711. };
  21712. const getInput = (config) => {
  21713. const configInput = config.input;
  21714. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21715. };
  21716. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  21717. const configManualChunks = config.manualChunks;
  21718. if (configManualChunks) {
  21719. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  21720. }
  21721. return configManualChunks;
  21722. };
  21723. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  21724. var _a;
  21725. const maxParallelFileReads = config.maxParallelFileReads;
  21726. if (typeof maxParallelFileReads === 'number') {
  21727. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
  21728. }
  21729. const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
  21730. if (typeof maxParallelFileOps === 'number') {
  21731. if (maxParallelFileOps <= 0)
  21732. return Infinity;
  21733. return maxParallelFileOps;
  21734. }
  21735. return 20;
  21736. };
  21737. const getModuleContext = (config, context) => {
  21738. const configModuleContext = config.moduleContext;
  21739. if (typeof configModuleContext === 'function') {
  21740. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  21741. }
  21742. if (configModuleContext) {
  21743. const contextByModuleId = Object.create(null);
  21744. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21745. contextByModuleId[require$$0.resolve(key)] = moduleContext;
  21746. }
  21747. return id => contextByModuleId[id] || context;
  21748. }
  21749. return () => context;
  21750. };
  21751. const getPreserveEntrySignatures = (config, unsetOptions) => {
  21752. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  21753. if (configPreserveEntrySignatures == null) {
  21754. unsetOptions.add('preserveEntrySignatures');
  21755. }
  21756. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  21757. };
  21758. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  21759. const configPreserveModules = config.preserveModules;
  21760. if (configPreserveModules) {
  21761. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  21762. }
  21763. return configPreserveModules;
  21764. };
  21765. const getTreeshake = (config, warn, strictDeprecations) => {
  21766. const configTreeshake = config.treeshake;
  21767. if (configTreeshake === false) {
  21768. return false;
  21769. }
  21770. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
  21771. if (typeof configWithPreset.pureExternalModules !== 'undefined') {
  21772. 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);
  21773. }
  21774. return {
  21775. annotations: configWithPreset.annotations !== false,
  21776. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21777. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  21778. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  21779. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  21780. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21781. ? 'always'
  21782. : configWithPreset.propertyReadSideEffects !== false,
  21783. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21784. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21785. };
  21786. };
  21787. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  21788. if (typeof moduleSideEffectsOption === 'boolean') {
  21789. return () => moduleSideEffectsOption;
  21790. }
  21791. if (moduleSideEffectsOption === 'no-external') {
  21792. return (_id, external) => !external;
  21793. }
  21794. if (typeof moduleSideEffectsOption === 'function') {
  21795. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  21796. }
  21797. if (Array.isArray(moduleSideEffectsOption)) {
  21798. const ids = new Set(moduleSideEffectsOption);
  21799. return id => ids.has(id);
  21800. }
  21801. if (moduleSideEffectsOption) {
  21802. error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
  21803. }
  21804. const isPureExternalModule = getIdMatcher(pureExternalModules);
  21805. return (id, external) => !(external && isPureExternalModule(id));
  21806. };
  21807. // https://datatracker.ietf.org/doc/html/rfc2396
  21808. // eslint-disable-next-line no-control-regex
  21809. const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
  21810. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21811. function sanitizeFileName(name) {
  21812. const match = DRIVE_LETTER_REGEX.exec(name);
  21813. const driveLetter = match ? match[0] : '';
  21814. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21815. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21816. return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21817. }
  21818. function isValidUrl(url) {
  21819. try {
  21820. new URL(url);
  21821. }
  21822. catch (_) {
  21823. return false;
  21824. }
  21825. return true;
  21826. }
  21827. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21828. var _a, _b, _c, _d, _e, _f, _g;
  21829. // These are options that may trigger special warnings or behaviour later
  21830. // if the user did not select an explicit value
  21831. const unsetOptions = new Set(unsetInputOptions);
  21832. const compact = config.compact || false;
  21833. const format = getFormat(config);
  21834. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21835. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21836. const file = getFile(config, preserveModules, inputOptions);
  21837. const preferConst = getPreferConst(config, inputOptions);
  21838. const generatedCode = getGeneratedCode(config, preferConst);
  21839. const outputOptions = {
  21840. amd: getAmd(config),
  21841. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  21842. banner: getAddon(config, 'banner'),
  21843. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  21844. compact,
  21845. dir: getDir(config, file),
  21846. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  21847. entryFileNames: getEntryFileNames(config, unsetOptions),
  21848. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  21849. exports: getExports(config, unsetOptions),
  21850. extend: config.extend || false,
  21851. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  21852. file,
  21853. footer: getAddon(config, 'footer'),
  21854. format,
  21855. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  21856. generatedCode,
  21857. globals: config.globals || {},
  21858. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  21859. indent: getIndent(config, compact),
  21860. inlineDynamicImports,
  21861. interop: getInterop(config, inputOptions),
  21862. intro: getAddon(config, 'intro'),
  21863. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  21864. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21865. name: config.name,
  21866. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  21867. noConflict: config.noConflict || false,
  21868. outro: getAddon(config, 'outro'),
  21869. paths: config.paths || {},
  21870. plugins: ensureArray$1(config.plugins),
  21871. preferConst,
  21872. preserveModules,
  21873. preserveModulesRoot: getPreserveModulesRoot(config),
  21874. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21875. ? config.sanitizeFileName
  21876. : config.sanitizeFileName === false
  21877. ? id => id
  21878. : sanitizeFileName,
  21879. sourcemap: config.sourcemap || false,
  21880. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21881. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21882. sourcemapFile: config.sourcemapFile,
  21883. sourcemapPathTransform: config.sourcemapPathTransform,
  21884. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  21885. systemNullSetters: config.systemNullSetters || false,
  21886. validate: config.validate || false
  21887. };
  21888. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  21889. return { options: outputOptions, unsetOptions };
  21890. }
  21891. const getFile = (config, preserveModules, inputOptions) => {
  21892. const { file } = config;
  21893. if (typeof file === 'string') {
  21894. if (preserveModules) {
  21895. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21896. }
  21897. if (!Array.isArray(inputOptions.input))
  21898. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21899. }
  21900. return file;
  21901. };
  21902. const getFormat = (config) => {
  21903. const configFormat = config.format;
  21904. switch (configFormat) {
  21905. case undefined:
  21906. case 'es':
  21907. case 'esm':
  21908. case 'module':
  21909. return 'es';
  21910. case 'cjs':
  21911. case 'commonjs':
  21912. return 'cjs';
  21913. case 'system':
  21914. case 'systemjs':
  21915. return 'system';
  21916. case 'amd':
  21917. case 'iife':
  21918. case 'umd':
  21919. return configFormat;
  21920. default:
  21921. return error({
  21922. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  21923. url: `https://rollupjs.org/guide/en/#outputformat`
  21924. });
  21925. }
  21926. };
  21927. const getInlineDynamicImports = (config, inputOptions) => {
  21928. var _a;
  21929. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  21930. const { input } = inputOptions;
  21931. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21932. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21933. }
  21934. return inlineDynamicImports;
  21935. };
  21936. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21937. var _a;
  21938. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  21939. if (preserveModules) {
  21940. if (inlineDynamicImports) {
  21941. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
  21942. }
  21943. if (inputOptions.preserveEntrySignatures === false) {
  21944. return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
  21945. }
  21946. }
  21947. return preserveModules;
  21948. };
  21949. const getPreferConst = (config, inputOptions) => {
  21950. const configPreferConst = config.preferConst;
  21951. if (configPreferConst != null) {
  21952. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
  21953. }
  21954. return !!configPreferConst;
  21955. };
  21956. const getPreserveModulesRoot = (config) => {
  21957. const { preserveModulesRoot } = config;
  21958. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21959. return undefined;
  21960. }
  21961. return require$$0.resolve(preserveModulesRoot);
  21962. };
  21963. const getAmd = (config) => {
  21964. const mergedOption = {
  21965. autoId: false,
  21966. basePath: '',
  21967. define: 'define',
  21968. ...config.amd
  21969. };
  21970. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  21971. return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  21972. }
  21973. if (mergedOption.basePath && !mergedOption.autoId) {
  21974. return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
  21975. }
  21976. let normalized;
  21977. if (mergedOption.autoId) {
  21978. normalized = {
  21979. autoId: true,
  21980. basePath: mergedOption.basePath,
  21981. define: mergedOption.define
  21982. };
  21983. }
  21984. else {
  21985. normalized = {
  21986. autoId: false,
  21987. define: mergedOption.define,
  21988. id: mergedOption.id
  21989. };
  21990. }
  21991. return normalized;
  21992. };
  21993. const getAddon = (config, name) => {
  21994. const configAddon = config[name];
  21995. if (typeof configAddon === 'function') {
  21996. return configAddon;
  21997. }
  21998. return () => configAddon || '';
  21999. };
  22000. const getDir = (config, file) => {
  22001. const { dir } = config;
  22002. if (typeof dir === 'string' && typeof file === 'string') {
  22003. return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  22004. }
  22005. return dir;
  22006. };
  22007. const getDynamicImportFunction = (config, inputOptions) => {
  22008. const configDynamicImportFunction = config.dynamicImportFunction;
  22009. if (configDynamicImportFunction) {
  22010. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  22011. }
  22012. return configDynamicImportFunction;
  22013. };
  22014. const getEntryFileNames = (config, unsetOptions) => {
  22015. const configEntryFileNames = config.entryFileNames;
  22016. if (configEntryFileNames == null) {
  22017. unsetOptions.add('entryFileNames');
  22018. }
  22019. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  22020. };
  22021. function getExports(config, unsetOptions) {
  22022. const configExports = config.exports;
  22023. if (configExports == null) {
  22024. unsetOptions.add('exports');
  22025. }
  22026. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22027. return error(errInvalidExportOptionValue(configExports));
  22028. }
  22029. return configExports || 'auto';
  22030. }
  22031. const getGeneratedCode = (config, preferConst) => {
  22032. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
  22033. return {
  22034. arrowFunctions: configWithPreset.arrowFunctions === true,
  22035. constBindings: configWithPreset.constBindings === true || preferConst,
  22036. objectShorthand: configWithPreset.objectShorthand === true,
  22037. reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
  22038. symbols: configWithPreset.symbols === true
  22039. };
  22040. };
  22041. const getIndent = (config, compact) => {
  22042. if (compact) {
  22043. return '';
  22044. }
  22045. const configIndent = config.indent;
  22046. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  22047. };
  22048. const ALLOWED_INTEROP_TYPES = new Set([
  22049. 'auto',
  22050. 'esModule',
  22051. 'default',
  22052. 'defaultOnly',
  22053. true,
  22054. false
  22055. ]);
  22056. const getInterop = (config, inputOptions) => {
  22057. const configInterop = config.interop;
  22058. const validatedInteropTypes = new Set();
  22059. const validateInterop = (interop) => {
  22060. if (!validatedInteropTypes.has(interop)) {
  22061. validatedInteropTypes.add(interop);
  22062. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22063. return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22064. }
  22065. if (typeof interop === 'boolean') {
  22066. warnDeprecation({
  22067. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  22068. url: 'https://rollupjs.org/guide/en/#outputinterop'
  22069. }, false, inputOptions);
  22070. }
  22071. }
  22072. return interop;
  22073. };
  22074. if (typeof configInterop === 'function') {
  22075. const interopPerId = Object.create(null);
  22076. let defaultInterop = null;
  22077. return id => id === null
  22078. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22079. : id in interopPerId
  22080. ? interopPerId[id]
  22081. : validateInterop((interopPerId[id] = configInterop(id)));
  22082. }
  22083. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  22084. };
  22085. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  22086. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  22087. if (configManualChunks) {
  22088. if (inlineDynamicImports) {
  22089. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
  22090. }
  22091. if (preserveModules) {
  22092. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
  22093. }
  22094. }
  22095. return configManualChunks || {};
  22096. };
  22097. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  22098. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  22099. const configNamespaceToStringTag = config.namespaceToStringTag;
  22100. if (configNamespaceToStringTag != null) {
  22101. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
  22102. return configNamespaceToStringTag;
  22103. }
  22104. return generatedCode.symbols || false;
  22105. };
  22106. const getSourcemapBaseUrl = (config) => {
  22107. const { sourcemapBaseUrl } = config;
  22108. if (sourcemapBaseUrl) {
  22109. if (isValidUrl(sourcemapBaseUrl)) {
  22110. return sourcemapBaseUrl;
  22111. }
  22112. return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22113. }
  22114. };
  22115. function rollup(rawInputOptions) {
  22116. return rollupInternal(rawInputOptions, null);
  22117. }
  22118. async function rollupInternal(rawInputOptions, watcher) {
  22119. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22120. initialiseTimers(inputOptions);
  22121. const graph = new Graph(inputOptions, watcher);
  22122. // remove the cache option from the memory after graph creation (cache is not used anymore)
  22123. const useCache = rawInputOptions.cache !== false;
  22124. delete inputOptions.cache;
  22125. delete rawInputOptions.cache;
  22126. timeStart('BUILD', 1);
  22127. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22128. try {
  22129. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22130. await graph.build();
  22131. }
  22132. catch (err) {
  22133. const watchFiles = Object.keys(graph.watchFiles);
  22134. if (watchFiles.length > 0) {
  22135. err.watchFiles = watchFiles;
  22136. }
  22137. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  22138. await graph.pluginDriver.hookParallel('closeBundle', []);
  22139. throw err;
  22140. }
  22141. await graph.pluginDriver.hookParallel('buildEnd', []);
  22142. });
  22143. timeEnd('BUILD', 1);
  22144. const result = {
  22145. cache: useCache ? graph.getCache() : undefined,
  22146. async close() {
  22147. if (result.closed)
  22148. return;
  22149. result.closed = true;
  22150. await graph.pluginDriver.hookParallel('closeBundle', []);
  22151. },
  22152. closed: false,
  22153. async generate(rawOutputOptions) {
  22154. if (result.closed)
  22155. return error(errAlreadyClosed());
  22156. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22157. },
  22158. watchFiles: Object.keys(graph.watchFiles),
  22159. async write(rawOutputOptions) {
  22160. if (result.closed)
  22161. return error(errAlreadyClosed());
  22162. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22163. }
  22164. };
  22165. if (inputOptions.perf)
  22166. result.getTimings = getTimings;
  22167. return result;
  22168. }
  22169. async function getInputOptions(rawInputOptions, watchMode) {
  22170. if (!rawInputOptions) {
  22171. throw new Error('You must supply an options object to rollup');
  22172. }
  22173. const rawPlugins = ensureArray$1(rawInputOptions.plugins);
  22174. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  22175. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22176. return { options, unsetOptions };
  22177. }
  22178. function applyOptionHook(watchMode) {
  22179. return async (inputOptions, plugin) => {
  22180. if (plugin.options) {
  22181. return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  22182. }
  22183. return inputOptions;
  22184. };
  22185. }
  22186. function normalizePlugins(plugins, anonymousPrefix) {
  22187. plugins.forEach((plugin, index) => {
  22188. if (!plugin.name) {
  22189. plugin.name = `${anonymousPrefix}${index + 1}`;
  22190. }
  22191. });
  22192. }
  22193. function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22194. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22195. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22196. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22197. const generated = await bundle.generate(isWrite);
  22198. if (isWrite) {
  22199. if (!outputOptions.dir && !outputOptions.file) {
  22200. return error({
  22201. code: 'MISSING_OPTION',
  22202. message: 'You must specify "output.file" or "output.dir" for the build.'
  22203. });
  22204. }
  22205. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22206. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22207. }
  22208. return createOutput(generated);
  22209. });
  22210. }
  22211. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22212. if (!rawOutputOptions) {
  22213. throw new Error('You must supply an options object');
  22214. }
  22215. const rawPlugins = ensureArray$1(rawOutputOptions.plugins);
  22216. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22217. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22218. return {
  22219. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  22220. outputPluginDriver
  22221. };
  22222. }
  22223. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22224. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22225. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  22226. return {
  22227. ...pluginContext,
  22228. emitFile: emitError,
  22229. setAssetSource: emitError
  22230. };
  22231. }), inputOptions, unsetInputOptions);
  22232. }
  22233. function createOutput(outputBundle) {
  22234. return {
  22235. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  22236. const fileTypeA = getSortingFileType(outputFileA);
  22237. const fileTypeB = getSortingFileType(outputFileB);
  22238. if (fileTypeA === fileTypeB)
  22239. return 0;
  22240. return fileTypeA < fileTypeB ? -1 : 1;
  22241. })
  22242. };
  22243. }
  22244. var SortingFileType;
  22245. (function (SortingFileType) {
  22246. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22247. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22248. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22249. })(SortingFileType || (SortingFileType = {}));
  22250. function getSortingFileType(file) {
  22251. if (file.type === 'asset') {
  22252. return SortingFileType.ASSET;
  22253. }
  22254. if (file.isEntry) {
  22255. return SortingFileType.ENTRY_CHUNK;
  22256. }
  22257. return SortingFileType.SECONDARY_CHUNK;
  22258. }
  22259. async function writeOutputFile(outputFile, outputOptions) {
  22260. const fileName = require$$0.resolve(outputOptions.dir || require$$0.dirname(outputOptions.file), outputFile.fileName);
  22261. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22262. await require$$0$1.promises.mkdir(require$$0.dirname(fileName), { recursive: true });
  22263. let writeSourceMapPromise;
  22264. let source;
  22265. if (outputFile.type === 'asset') {
  22266. source = outputFile.source;
  22267. }
  22268. else {
  22269. source = outputFile.code;
  22270. if (outputOptions.sourcemap && outputFile.map) {
  22271. let url;
  22272. if (outputOptions.sourcemap === 'inline') {
  22273. url = outputFile.map.toUrl();
  22274. }
  22275. else {
  22276. const { sourcemapBaseUrl } = outputOptions;
  22277. const sourcemapFileName = `${require$$0.basename(outputFile.fileName)}.map`;
  22278. url = sourcemapBaseUrl
  22279. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  22280. : sourcemapFileName;
  22281. writeSourceMapPromise = require$$0$1.promises.writeFile(`${fileName}.map`, outputFile.map.toString());
  22282. }
  22283. if (outputOptions.sourcemap !== 'hidden') {
  22284. source += `//# ${exports.SOURCEMAPPING_URL}=${url}\n`;
  22285. }
  22286. }
  22287. }
  22288. return Promise.all([require$$0$1.promises.writeFile(fileName, source), writeSourceMapPromise]);
  22289. }
  22290. /**
  22291. * Auxiliary function for defining rollup configuration
  22292. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  22293. * @param options
  22294. */
  22295. function defineConfig(options) {
  22296. return options;
  22297. }
  22298. class WatchEmitter extends require$$0$2.EventEmitter {
  22299. constructor() {
  22300. super();
  22301. this.awaitedHandlers = Object.create(null);
  22302. // Allows more than 10 bundles to be watched without
  22303. // showing the `MaxListenersExceededWarning` to the user.
  22304. this.setMaxListeners(Infinity);
  22305. }
  22306. // Will be overwritten by Rollup
  22307. async close() { }
  22308. emitAndAwait(event, ...args) {
  22309. this.emit(event, ...args);
  22310. return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
  22311. }
  22312. onCurrentAwaited(event, listener) {
  22313. this.getHandlers(event).push(listener);
  22314. return this;
  22315. }
  22316. removeAwaited() {
  22317. this.awaitedHandlers = {};
  22318. return this;
  22319. }
  22320. getHandlers(event) {
  22321. return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
  22322. }
  22323. }
  22324. function watch(configs) {
  22325. const emitter = new WatchEmitter();
  22326. const configArray = ensureArray$1(configs);
  22327. const watchConfigs = configArray.filter(config => config.watch !== false);
  22328. if (watchConfigs.length === 0) {
  22329. return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
  22330. }
  22331. loadFsEvents()
  22332. .then(() => Promise.resolve().then(() => require('./watch.js')))
  22333. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  22334. return emitter;
  22335. }
  22336. exports.commonjsGlobal = commonjsGlobal;
  22337. exports.createFilter = createFilter;
  22338. exports.defaultOnWarn = defaultOnWarn;
  22339. exports.defineConfig = defineConfig;
  22340. exports.ensureArray = ensureArray$1;
  22341. exports.error = error;
  22342. exports.fseventsImporter = fseventsImporter;
  22343. exports.generatedCodePresets = generatedCodePresets;
  22344. exports.getAliasName = getAliasName;
  22345. exports.getAugmentedNamespace = getAugmentedNamespace;
  22346. exports.getOrCreate = getOrCreate;
  22347. exports.loadFsEvents = loadFsEvents;
  22348. exports.objectifyOption = objectifyOption;
  22349. exports.objectifyOptionWithPresets = objectifyOptionWithPresets;
  22350. exports.picomatch = picomatch$1;
  22351. exports.printQuotedStringList = printQuotedStringList;
  22352. exports.relativeId = relativeId;
  22353. exports.rollup = rollup;
  22354. exports.rollupInternal = rollupInternal;
  22355. exports.treeshakePresets = treeshakePresets;
  22356. exports.version = version$1;
  22357. exports.warnUnknownOptions = warnUnknownOptions;
  22358. exports.watch = watch;
  22359. //# sourceMappingURL=rollup.js.map