rollup.js 872 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918
  1. /*
  2. @license
  3. Rollup.js v2.78.0
  4. Sun, 14 Aug 2022 04:30:34 GMT - commit 105b264847892c8f7966364d73f6900554178f58
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import require$$0, { resolve, basename, extname, dirname, relative as relative$1, win32, posix, isAbsolute as isAbsolute$1 } from 'path';
  9. import process$1 from 'process';
  10. import { performance } from 'perf_hooks';
  11. import { createHash as createHash$1 } from 'crypto';
  12. import { promises } from 'fs';
  13. import { EventEmitter } from 'events';
  14. var version$1 = "2.78.0";
  15. var charToInteger = {};
  16. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17. for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
  18. charToInteger[chars$1.charCodeAt(i$1)] = i$1;
  19. }
  20. function decode(mappings) {
  21. var decoded = [];
  22. var line = [];
  23. var segment = [
  24. 0,
  25. 0,
  26. 0,
  27. 0,
  28. 0,
  29. ];
  30. var j = 0;
  31. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  32. var c = mappings.charCodeAt(i);
  33. if (c === 44) { // ","
  34. segmentify(line, segment, j);
  35. j = 0;
  36. }
  37. else if (c === 59) { // ";"
  38. segmentify(line, segment, j);
  39. j = 0;
  40. decoded.push(line);
  41. line = [];
  42. segment[0] = 0;
  43. }
  44. else {
  45. var integer = charToInteger[c];
  46. if (integer === undefined) {
  47. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  48. }
  49. var hasContinuationBit = integer & 32;
  50. integer &= 31;
  51. value += integer << shift;
  52. if (hasContinuationBit) {
  53. shift += 5;
  54. }
  55. else {
  56. var shouldNegate = value & 1;
  57. value >>>= 1;
  58. if (shouldNegate) {
  59. value = value === 0 ? -0x80000000 : -value;
  60. }
  61. segment[j] += value;
  62. j++;
  63. value = shift = 0; // reset
  64. }
  65. }
  66. }
  67. segmentify(line, segment, j);
  68. decoded.push(line);
  69. return decoded;
  70. }
  71. function segmentify(line, segment, j) {
  72. // This looks ugly, but we're creating specialized arrays with a specific
  73. // length. This is much faster than creating a new array (which v8 expands to
  74. // a capacity of 17 after pushing the first item), or slicing out a subarray
  75. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  76. // length 5 (since not everything will have an associated name), followed by
  77. // length 1 (it's probably rare for a source substring to not have an
  78. // associated segment data).
  79. if (j === 4)
  80. line.push([segment[0], segment[1], segment[2], segment[3]]);
  81. else if (j === 5)
  82. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  83. else if (j === 1)
  84. line.push([segment[0]]);
  85. }
  86. function encode(decoded) {
  87. var sourceFileIndex = 0; // second field
  88. var sourceCodeLine = 0; // third field
  89. var sourceCodeColumn = 0; // fourth field
  90. var nameIndex = 0; // fifth field
  91. var mappings = '';
  92. for (var i = 0; i < decoded.length; i++) {
  93. var line = decoded[i];
  94. if (i > 0)
  95. mappings += ';';
  96. if (line.length === 0)
  97. continue;
  98. var generatedCodeColumn = 0; // first field
  99. var lineMappings = [];
  100. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  101. var segment = line_1[_i];
  102. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  103. generatedCodeColumn = segment[0];
  104. if (segment.length > 1) {
  105. segmentMappings +=
  106. encodeInteger(segment[1] - sourceFileIndex) +
  107. encodeInteger(segment[2] - sourceCodeLine) +
  108. encodeInteger(segment[3] - sourceCodeColumn);
  109. sourceFileIndex = segment[1];
  110. sourceCodeLine = segment[2];
  111. sourceCodeColumn = segment[3];
  112. }
  113. if (segment.length === 5) {
  114. segmentMappings += encodeInteger(segment[4] - nameIndex);
  115. nameIndex = segment[4];
  116. }
  117. lineMappings.push(segmentMappings);
  118. }
  119. mappings += lineMappings.join(',');
  120. }
  121. return mappings;
  122. }
  123. function encodeInteger(num) {
  124. var result = '';
  125. num = num < 0 ? (-num << 1) | 1 : num << 1;
  126. do {
  127. var clamped = num & 31;
  128. num >>>= 5;
  129. if (num > 0) {
  130. clamped |= 32;
  131. }
  132. result += chars$1[clamped];
  133. } while (num > 0);
  134. return result;
  135. }
  136. class BitSet {
  137. constructor(arg) {
  138. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  139. }
  140. add(n) {
  141. this.bits[n >> 5] |= 1 << (n & 31);
  142. }
  143. has(n) {
  144. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  145. }
  146. }
  147. class Chunk$1 {
  148. constructor(start, end, content) {
  149. this.start = start;
  150. this.end = end;
  151. this.original = content;
  152. this.intro = '';
  153. this.outro = '';
  154. this.content = content;
  155. this.storeName = false;
  156. this.edited = false;
  157. // we make these non-enumerable, for sanity while debugging
  158. Object.defineProperties(this, {
  159. previous: { writable: true, value: null },
  160. next: { writable: true, value: null },
  161. });
  162. }
  163. appendLeft(content) {
  164. this.outro += content;
  165. }
  166. appendRight(content) {
  167. this.intro = this.intro + content;
  168. }
  169. clone() {
  170. const chunk = new Chunk$1(this.start, this.end, this.original);
  171. chunk.intro = this.intro;
  172. chunk.outro = this.outro;
  173. chunk.content = this.content;
  174. chunk.storeName = this.storeName;
  175. chunk.edited = this.edited;
  176. return chunk;
  177. }
  178. contains(index) {
  179. return this.start < index && index < this.end;
  180. }
  181. eachNext(fn) {
  182. let chunk = this;
  183. while (chunk) {
  184. fn(chunk);
  185. chunk = chunk.next;
  186. }
  187. }
  188. eachPrevious(fn) {
  189. let chunk = this;
  190. while (chunk) {
  191. fn(chunk);
  192. chunk = chunk.previous;
  193. }
  194. }
  195. edit(content, storeName, contentOnly) {
  196. this.content = content;
  197. if (!contentOnly) {
  198. this.intro = '';
  199. this.outro = '';
  200. }
  201. this.storeName = storeName;
  202. this.edited = true;
  203. return this;
  204. }
  205. prependLeft(content) {
  206. this.outro = content + this.outro;
  207. }
  208. prependRight(content) {
  209. this.intro = content + this.intro;
  210. }
  211. split(index) {
  212. const sliceIndex = index - this.start;
  213. const originalBefore = this.original.slice(0, sliceIndex);
  214. const originalAfter = this.original.slice(sliceIndex);
  215. this.original = originalBefore;
  216. const newChunk = new Chunk$1(index, this.end, originalAfter);
  217. newChunk.outro = this.outro;
  218. this.outro = '';
  219. this.end = index;
  220. if (this.edited) {
  221. // TODO is this block necessary?...
  222. newChunk.edit('', false);
  223. this.content = '';
  224. } else {
  225. this.content = originalBefore;
  226. }
  227. newChunk.next = this.next;
  228. if (newChunk.next) newChunk.next.previous = newChunk;
  229. newChunk.previous = this;
  230. this.next = newChunk;
  231. return newChunk;
  232. }
  233. toString() {
  234. return this.intro + this.content + this.outro;
  235. }
  236. trimEnd(rx) {
  237. this.outro = this.outro.replace(rx, '');
  238. if (this.outro.length) return true;
  239. const trimmed = this.content.replace(rx, '');
  240. if (trimmed.length) {
  241. if (trimmed !== this.content) {
  242. this.split(this.start + trimmed.length).edit('', undefined, true);
  243. }
  244. return true;
  245. } else {
  246. this.edit('', undefined, true);
  247. this.intro = this.intro.replace(rx, '');
  248. if (this.intro.length) return true;
  249. }
  250. }
  251. trimStart(rx) {
  252. this.intro = this.intro.replace(rx, '');
  253. if (this.intro.length) return true;
  254. const trimmed = this.content.replace(rx, '');
  255. if (trimmed.length) {
  256. if (trimmed !== this.content) {
  257. this.split(this.end - trimmed.length);
  258. this.edit('', undefined, true);
  259. }
  260. return true;
  261. } else {
  262. this.edit('', undefined, true);
  263. this.outro = this.outro.replace(rx, '');
  264. if (this.outro.length) return true;
  265. }
  266. }
  267. }
  268. let btoa = () => {
  269. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  270. };
  271. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  272. btoa = (str) => window.btoa(unescape(encodeURIComponent(str)));
  273. } else if (typeof Buffer === 'function') {
  274. btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
  275. }
  276. class SourceMap {
  277. constructor(properties) {
  278. this.version = 3;
  279. this.file = properties.file;
  280. this.sources = properties.sources;
  281. this.sourcesContent = properties.sourcesContent;
  282. this.names = properties.names;
  283. this.mappings = encode(properties.mappings);
  284. }
  285. toString() {
  286. return JSON.stringify(this);
  287. }
  288. toUrl() {
  289. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  290. }
  291. }
  292. function guessIndent(code) {
  293. const lines = code.split('\n');
  294. const tabbed = lines.filter((line) => /^\t+/.test(line));
  295. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  296. if (tabbed.length === 0 && spaced.length === 0) {
  297. return null;
  298. }
  299. // More lines tabbed than spaced? Assume tabs, and
  300. // default to tabs in the case of a tie (or nothing
  301. // to go on)
  302. if (tabbed.length >= spaced.length) {
  303. return '\t';
  304. }
  305. // Otherwise, we need to guess the multiple
  306. const min = spaced.reduce((previous, current) => {
  307. const numSpaces = /^ +/.exec(current)[0].length;
  308. return Math.min(numSpaces, previous);
  309. }, Infinity);
  310. return new Array(min + 1).join(' ');
  311. }
  312. function getRelativePath(from, to) {
  313. const fromParts = from.split(/[/\\]/);
  314. const toParts = to.split(/[/\\]/);
  315. fromParts.pop(); // get dirname
  316. while (fromParts[0] === toParts[0]) {
  317. fromParts.shift();
  318. toParts.shift();
  319. }
  320. if (fromParts.length) {
  321. let i = fromParts.length;
  322. while (i--) fromParts[i] = '..';
  323. }
  324. return fromParts.concat(toParts).join('/');
  325. }
  326. const toString$1 = Object.prototype.toString;
  327. function isObject$1(thing) {
  328. return toString$1.call(thing) === '[object Object]';
  329. }
  330. function getLocator$1(source) {
  331. const originalLines = source.split('\n');
  332. const lineOffsets = [];
  333. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  334. lineOffsets.push(pos);
  335. pos += originalLines[i].length + 1;
  336. }
  337. return function locate(index) {
  338. let i = 0;
  339. let j = lineOffsets.length;
  340. while (i < j) {
  341. const m = (i + j) >> 1;
  342. if (index < lineOffsets[m]) {
  343. j = m;
  344. } else {
  345. i = m + 1;
  346. }
  347. }
  348. const line = i - 1;
  349. const column = index - lineOffsets[line];
  350. return { line, column };
  351. };
  352. }
  353. class Mappings {
  354. constructor(hires) {
  355. this.hires = hires;
  356. this.generatedCodeLine = 0;
  357. this.generatedCodeColumn = 0;
  358. this.raw = [];
  359. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  360. this.pending = null;
  361. }
  362. addEdit(sourceIndex, content, loc, nameIndex) {
  363. if (content.length) {
  364. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  365. if (nameIndex >= 0) {
  366. segment.push(nameIndex);
  367. }
  368. this.rawSegments.push(segment);
  369. } else if (this.pending) {
  370. this.rawSegments.push(this.pending);
  371. }
  372. this.advance(content);
  373. this.pending = null;
  374. }
  375. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  376. let originalCharIndex = chunk.start;
  377. let first = true;
  378. while (originalCharIndex < chunk.end) {
  379. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  380. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  381. }
  382. if (original[originalCharIndex] === '\n') {
  383. loc.line += 1;
  384. loc.column = 0;
  385. this.generatedCodeLine += 1;
  386. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  387. this.generatedCodeColumn = 0;
  388. first = true;
  389. } else {
  390. loc.column += 1;
  391. this.generatedCodeColumn += 1;
  392. first = false;
  393. }
  394. originalCharIndex += 1;
  395. }
  396. this.pending = null;
  397. }
  398. advance(str) {
  399. if (!str) return;
  400. const lines = str.split('\n');
  401. if (lines.length > 1) {
  402. for (let i = 0; i < lines.length - 1; i++) {
  403. this.generatedCodeLine++;
  404. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  405. }
  406. this.generatedCodeColumn = 0;
  407. }
  408. this.generatedCodeColumn += lines[lines.length - 1].length;
  409. }
  410. }
  411. const n = '\n';
  412. const warned = {
  413. insertLeft: false,
  414. insertRight: false,
  415. storeName: false,
  416. };
  417. class MagicString {
  418. constructor(string, options = {}) {
  419. const chunk = new Chunk$1(0, string.length, string);
  420. Object.defineProperties(this, {
  421. original: { writable: true, value: string },
  422. outro: { writable: true, value: '' },
  423. intro: { writable: true, value: '' },
  424. firstChunk: { writable: true, value: chunk },
  425. lastChunk: { writable: true, value: chunk },
  426. lastSearchedChunk: { writable: true, value: chunk },
  427. byStart: { writable: true, value: {} },
  428. byEnd: { writable: true, value: {} },
  429. filename: { writable: true, value: options.filename },
  430. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  431. sourcemapLocations: { writable: true, value: new BitSet() },
  432. storedNames: { writable: true, value: {} },
  433. indentStr: { writable: true, value: guessIndent(string) },
  434. });
  435. this.byStart[0] = chunk;
  436. this.byEnd[string.length] = chunk;
  437. }
  438. addSourcemapLocation(char) {
  439. this.sourcemapLocations.add(char);
  440. }
  441. append(content) {
  442. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  443. this.outro += content;
  444. return this;
  445. }
  446. appendLeft(index, content) {
  447. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  448. this._split(index);
  449. const chunk = this.byEnd[index];
  450. if (chunk) {
  451. chunk.appendLeft(content);
  452. } else {
  453. this.intro += content;
  454. }
  455. return this;
  456. }
  457. appendRight(index, content) {
  458. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  459. this._split(index);
  460. const chunk = this.byStart[index];
  461. if (chunk) {
  462. chunk.appendRight(content);
  463. } else {
  464. this.outro += content;
  465. }
  466. return this;
  467. }
  468. clone() {
  469. const cloned = new MagicString(this.original, { filename: this.filename });
  470. let originalChunk = this.firstChunk;
  471. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  472. while (originalChunk) {
  473. cloned.byStart[clonedChunk.start] = clonedChunk;
  474. cloned.byEnd[clonedChunk.end] = clonedChunk;
  475. const nextOriginalChunk = originalChunk.next;
  476. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  477. if (nextClonedChunk) {
  478. clonedChunk.next = nextClonedChunk;
  479. nextClonedChunk.previous = clonedChunk;
  480. clonedChunk = nextClonedChunk;
  481. }
  482. originalChunk = nextOriginalChunk;
  483. }
  484. cloned.lastChunk = clonedChunk;
  485. if (this.indentExclusionRanges) {
  486. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  487. }
  488. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  489. cloned.intro = this.intro;
  490. cloned.outro = this.outro;
  491. return cloned;
  492. }
  493. generateDecodedMap(options) {
  494. options = options || {};
  495. const sourceIndex = 0;
  496. const names = Object.keys(this.storedNames);
  497. const mappings = new Mappings(options.hires);
  498. const locate = getLocator$1(this.original);
  499. if (this.intro) {
  500. mappings.advance(this.intro);
  501. }
  502. this.firstChunk.eachNext((chunk) => {
  503. const loc = locate(chunk.start);
  504. if (chunk.intro.length) mappings.advance(chunk.intro);
  505. if (chunk.edited) {
  506. mappings.addEdit(
  507. sourceIndex,
  508. chunk.content,
  509. loc,
  510. chunk.storeName ? names.indexOf(chunk.original) : -1
  511. );
  512. } else {
  513. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  514. }
  515. if (chunk.outro.length) mappings.advance(chunk.outro);
  516. });
  517. return {
  518. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  519. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  520. sourcesContent: options.includeContent ? [this.original] : [null],
  521. names,
  522. mappings: mappings.raw,
  523. };
  524. }
  525. generateMap(options) {
  526. return new SourceMap(this.generateDecodedMap(options));
  527. }
  528. getIndentString() {
  529. return this.indentStr === null ? '\t' : this.indentStr;
  530. }
  531. indent(indentStr, options) {
  532. const pattern = /^[^\r\n]/gm;
  533. if (isObject$1(indentStr)) {
  534. options = indentStr;
  535. indentStr = undefined;
  536. }
  537. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  538. if (indentStr === '') return this; // noop
  539. options = options || {};
  540. // Process exclusion ranges
  541. const isExcluded = {};
  542. if (options.exclude) {
  543. const exclusions =
  544. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  545. exclusions.forEach((exclusion) => {
  546. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  547. isExcluded[i] = true;
  548. }
  549. });
  550. }
  551. let shouldIndentNextCharacter = options.indentStart !== false;
  552. const replacer = (match) => {
  553. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  554. shouldIndentNextCharacter = true;
  555. return match;
  556. };
  557. this.intro = this.intro.replace(pattern, replacer);
  558. let charIndex = 0;
  559. let chunk = this.firstChunk;
  560. while (chunk) {
  561. const end = chunk.end;
  562. if (chunk.edited) {
  563. if (!isExcluded[charIndex]) {
  564. chunk.content = chunk.content.replace(pattern, replacer);
  565. if (chunk.content.length) {
  566. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  567. }
  568. }
  569. } else {
  570. charIndex = chunk.start;
  571. while (charIndex < end) {
  572. if (!isExcluded[charIndex]) {
  573. const char = this.original[charIndex];
  574. if (char === '\n') {
  575. shouldIndentNextCharacter = true;
  576. } else if (char !== '\r' && shouldIndentNextCharacter) {
  577. shouldIndentNextCharacter = false;
  578. if (charIndex === chunk.start) {
  579. chunk.prependRight(indentStr);
  580. } else {
  581. this._splitChunk(chunk, charIndex);
  582. chunk = chunk.next;
  583. chunk.prependRight(indentStr);
  584. }
  585. }
  586. }
  587. charIndex += 1;
  588. }
  589. }
  590. charIndex = chunk.end;
  591. chunk = chunk.next;
  592. }
  593. this.outro = this.outro.replace(pattern, replacer);
  594. return this;
  595. }
  596. insert() {
  597. throw new Error(
  598. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  599. );
  600. }
  601. insertLeft(index, content) {
  602. if (!warned.insertLeft) {
  603. console.warn(
  604. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  605. ); // eslint-disable-line no-console
  606. warned.insertLeft = true;
  607. }
  608. return this.appendLeft(index, content);
  609. }
  610. insertRight(index, content) {
  611. if (!warned.insertRight) {
  612. console.warn(
  613. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  614. ); // eslint-disable-line no-console
  615. warned.insertRight = true;
  616. }
  617. return this.prependRight(index, content);
  618. }
  619. move(start, end, index) {
  620. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  621. this._split(start);
  622. this._split(end);
  623. this._split(index);
  624. const first = this.byStart[start];
  625. const last = this.byEnd[end];
  626. const oldLeft = first.previous;
  627. const oldRight = last.next;
  628. const newRight = this.byStart[index];
  629. if (!newRight && last === this.lastChunk) return this;
  630. const newLeft = newRight ? newRight.previous : this.lastChunk;
  631. if (oldLeft) oldLeft.next = oldRight;
  632. if (oldRight) oldRight.previous = oldLeft;
  633. if (newLeft) newLeft.next = first;
  634. if (newRight) newRight.previous = last;
  635. if (!first.previous) this.firstChunk = last.next;
  636. if (!last.next) {
  637. this.lastChunk = first.previous;
  638. this.lastChunk.next = null;
  639. }
  640. first.previous = newLeft;
  641. last.next = newRight || null;
  642. if (!newLeft) this.firstChunk = first;
  643. if (!newRight) this.lastChunk = last;
  644. return this;
  645. }
  646. overwrite(start, end, content, options) {
  647. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  648. while (start < 0) start += this.original.length;
  649. while (end < 0) end += this.original.length;
  650. if (end > this.original.length) throw new Error('end is out of bounds');
  651. if (start === end)
  652. throw new Error(
  653. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  654. );
  655. this._split(start);
  656. this._split(end);
  657. if (options === true) {
  658. if (!warned.storeName) {
  659. console.warn(
  660. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  661. ); // eslint-disable-line no-console
  662. warned.storeName = true;
  663. }
  664. options = { storeName: true };
  665. }
  666. const storeName = options !== undefined ? options.storeName : false;
  667. const contentOnly = options !== undefined ? options.contentOnly : false;
  668. if (storeName) {
  669. const original = this.original.slice(start, end);
  670. Object.defineProperty(this.storedNames, original, {
  671. writable: true,
  672. value: true,
  673. enumerable: true,
  674. });
  675. }
  676. const first = this.byStart[start];
  677. const last = this.byEnd[end];
  678. if (first) {
  679. let chunk = first;
  680. while (chunk !== last) {
  681. if (chunk.next !== this.byStart[chunk.end]) {
  682. throw new Error('Cannot overwrite across a split point');
  683. }
  684. chunk = chunk.next;
  685. chunk.edit('', false);
  686. }
  687. first.edit(content, storeName, contentOnly);
  688. } else {
  689. // must be inserting at the end
  690. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  691. // TODO last chunk in the array may not be the last chunk, if it's moved...
  692. last.next = newChunk;
  693. newChunk.previous = last;
  694. }
  695. return this;
  696. }
  697. prepend(content) {
  698. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  699. this.intro = content + this.intro;
  700. return this;
  701. }
  702. prependLeft(index, content) {
  703. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  704. this._split(index);
  705. const chunk = this.byEnd[index];
  706. if (chunk) {
  707. chunk.prependLeft(content);
  708. } else {
  709. this.intro = content + this.intro;
  710. }
  711. return this;
  712. }
  713. prependRight(index, content) {
  714. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  715. this._split(index);
  716. const chunk = this.byStart[index];
  717. if (chunk) {
  718. chunk.prependRight(content);
  719. } else {
  720. this.outro = content + this.outro;
  721. }
  722. return this;
  723. }
  724. remove(start, end) {
  725. while (start < 0) start += this.original.length;
  726. while (end < 0) end += this.original.length;
  727. if (start === end) return this;
  728. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  729. if (start > end) throw new Error('end must be greater than start');
  730. this._split(start);
  731. this._split(end);
  732. let chunk = this.byStart[start];
  733. while (chunk) {
  734. chunk.intro = '';
  735. chunk.outro = '';
  736. chunk.edit('');
  737. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  738. }
  739. return this;
  740. }
  741. lastChar() {
  742. if (this.outro.length) return this.outro[this.outro.length - 1];
  743. let chunk = this.lastChunk;
  744. do {
  745. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  746. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  747. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  748. } while ((chunk = chunk.previous));
  749. if (this.intro.length) return this.intro[this.intro.length - 1];
  750. return '';
  751. }
  752. lastLine() {
  753. let lineIndex = this.outro.lastIndexOf(n);
  754. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  755. let lineStr = this.outro;
  756. let chunk = this.lastChunk;
  757. do {
  758. if (chunk.outro.length > 0) {
  759. lineIndex = chunk.outro.lastIndexOf(n);
  760. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  761. lineStr = chunk.outro + lineStr;
  762. }
  763. if (chunk.content.length > 0) {
  764. lineIndex = chunk.content.lastIndexOf(n);
  765. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  766. lineStr = chunk.content + lineStr;
  767. }
  768. if (chunk.intro.length > 0) {
  769. lineIndex = chunk.intro.lastIndexOf(n);
  770. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  771. lineStr = chunk.intro + lineStr;
  772. }
  773. } while ((chunk = chunk.previous));
  774. lineIndex = this.intro.lastIndexOf(n);
  775. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  776. return this.intro + lineStr;
  777. }
  778. slice(start = 0, end = this.original.length) {
  779. while (start < 0) start += this.original.length;
  780. while (end < 0) end += this.original.length;
  781. let result = '';
  782. // find start chunk
  783. let chunk = this.firstChunk;
  784. while (chunk && (chunk.start > start || chunk.end <= start)) {
  785. // found end chunk before start
  786. if (chunk.start < end && chunk.end >= end) {
  787. return result;
  788. }
  789. chunk = chunk.next;
  790. }
  791. if (chunk && chunk.edited && chunk.start !== start)
  792. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  793. const startChunk = chunk;
  794. while (chunk) {
  795. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  796. result += chunk.intro;
  797. }
  798. const containsEnd = chunk.start < end && chunk.end >= end;
  799. if (containsEnd && chunk.edited && chunk.end !== end)
  800. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  801. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  802. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  803. result += chunk.content.slice(sliceStart, sliceEnd);
  804. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  805. result += chunk.outro;
  806. }
  807. if (containsEnd) {
  808. break;
  809. }
  810. chunk = chunk.next;
  811. }
  812. return result;
  813. }
  814. // TODO deprecate this? not really very useful
  815. snip(start, end) {
  816. const clone = this.clone();
  817. clone.remove(0, start);
  818. clone.remove(end, clone.original.length);
  819. return clone;
  820. }
  821. _split(index) {
  822. if (this.byStart[index] || this.byEnd[index]) return;
  823. let chunk = this.lastSearchedChunk;
  824. const searchForward = index > chunk.end;
  825. while (chunk) {
  826. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  827. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  828. }
  829. }
  830. _splitChunk(chunk, index) {
  831. if (chunk.edited && chunk.content.length) {
  832. // zero-length edited chunks are a special case (overlapping replacements)
  833. const loc = getLocator$1(this.original)(index);
  834. throw new Error(
  835. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  836. );
  837. }
  838. const newChunk = chunk.split(index);
  839. this.byEnd[index] = chunk;
  840. this.byStart[index] = newChunk;
  841. this.byEnd[newChunk.end] = newChunk;
  842. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  843. this.lastSearchedChunk = chunk;
  844. return true;
  845. }
  846. toString() {
  847. let str = this.intro;
  848. let chunk = this.firstChunk;
  849. while (chunk) {
  850. str += chunk.toString();
  851. chunk = chunk.next;
  852. }
  853. return str + this.outro;
  854. }
  855. isEmpty() {
  856. let chunk = this.firstChunk;
  857. do {
  858. if (
  859. (chunk.intro.length && chunk.intro.trim()) ||
  860. (chunk.content.length && chunk.content.trim()) ||
  861. (chunk.outro.length && chunk.outro.trim())
  862. )
  863. return false;
  864. } while ((chunk = chunk.next));
  865. return true;
  866. }
  867. length() {
  868. let chunk = this.firstChunk;
  869. let length = 0;
  870. do {
  871. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  872. } while ((chunk = chunk.next));
  873. return length;
  874. }
  875. trimLines() {
  876. return this.trim('[\\r\\n]');
  877. }
  878. trim(charType) {
  879. return this.trimStart(charType).trimEnd(charType);
  880. }
  881. trimEndAborted(charType) {
  882. const rx = new RegExp((charType || '\\s') + '+$');
  883. this.outro = this.outro.replace(rx, '');
  884. if (this.outro.length) return true;
  885. let chunk = this.lastChunk;
  886. do {
  887. const end = chunk.end;
  888. const aborted = chunk.trimEnd(rx);
  889. // if chunk was trimmed, we have a new lastChunk
  890. if (chunk.end !== end) {
  891. if (this.lastChunk === chunk) {
  892. this.lastChunk = chunk.next;
  893. }
  894. this.byEnd[chunk.end] = chunk;
  895. this.byStart[chunk.next.start] = chunk.next;
  896. this.byEnd[chunk.next.end] = chunk.next;
  897. }
  898. if (aborted) return true;
  899. chunk = chunk.previous;
  900. } while (chunk);
  901. return false;
  902. }
  903. trimEnd(charType) {
  904. this.trimEndAborted(charType);
  905. return this;
  906. }
  907. trimStartAborted(charType) {
  908. const rx = new RegExp('^' + (charType || '\\s') + '+');
  909. this.intro = this.intro.replace(rx, '');
  910. if (this.intro.length) return true;
  911. let chunk = this.firstChunk;
  912. do {
  913. const end = chunk.end;
  914. const aborted = chunk.trimStart(rx);
  915. if (chunk.end !== end) {
  916. // special case...
  917. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  918. this.byEnd[chunk.end] = chunk;
  919. this.byStart[chunk.next.start] = chunk.next;
  920. this.byEnd[chunk.next.end] = chunk.next;
  921. }
  922. if (aborted) return true;
  923. chunk = chunk.next;
  924. } while (chunk);
  925. return false;
  926. }
  927. trimStart(charType) {
  928. this.trimStartAborted(charType);
  929. return this;
  930. }
  931. hasChanged() {
  932. return this.original !== this.toString();
  933. }
  934. replace(searchValue, replacement) {
  935. function getReplacement(match, str) {
  936. if (typeof replacement === 'string') {
  937. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  938. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  939. if (i === '$') return '$';
  940. if (i === '&') return match[0];
  941. const num = +i;
  942. if (num < match.length) return match[+i];
  943. return `$${i}`;
  944. });
  945. } else {
  946. return replacement(...match, match.index, str, match.groups);
  947. }
  948. }
  949. function matchAll(re, str) {
  950. let match;
  951. const matches = [];
  952. while ((match = re.exec(str))) {
  953. matches.push(match);
  954. }
  955. return matches;
  956. }
  957. if (typeof searchValue !== 'string' && searchValue.global) {
  958. const matches = matchAll(searchValue, this.original);
  959. matches.forEach((match) => {
  960. if (match.index != null)
  961. this.overwrite(
  962. match.index,
  963. match.index + match[0].length,
  964. getReplacement(match, this.original)
  965. );
  966. });
  967. } else {
  968. const match = this.original.match(searchValue);
  969. if (match && match.index != null)
  970. this.overwrite(
  971. match.index,
  972. match.index + match[0].length,
  973. getReplacement(match, this.original)
  974. );
  975. }
  976. return this;
  977. }
  978. }
  979. const hasOwnProp = Object.prototype.hasOwnProperty;
  980. class Bundle$1 {
  981. constructor(options = {}) {
  982. this.intro = options.intro || '';
  983. this.separator = options.separator !== undefined ? options.separator : '\n';
  984. this.sources = [];
  985. this.uniqueSources = [];
  986. this.uniqueSourceIndexByFilename = {};
  987. }
  988. addSource(source) {
  989. if (source instanceof MagicString) {
  990. return this.addSource({
  991. content: source,
  992. filename: source.filename,
  993. separator: this.separator,
  994. });
  995. }
  996. if (!isObject$1(source) || !source.content) {
  997. throw new Error(
  998. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`'
  999. );
  1000. }
  1001. ['filename', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1002. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1003. });
  1004. if (source.separator === undefined) {
  1005. // TODO there's a bunch of this sort of thing, needs cleaning up
  1006. source.separator = this.separator;
  1007. }
  1008. if (source.filename) {
  1009. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1010. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1011. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1012. } else {
  1013. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1014. if (source.content.original !== uniqueSource.content) {
  1015. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1016. }
  1017. }
  1018. }
  1019. this.sources.push(source);
  1020. return this;
  1021. }
  1022. append(str, options) {
  1023. this.addSource({
  1024. content: new MagicString(str),
  1025. separator: (options && options.separator) || '',
  1026. });
  1027. return this;
  1028. }
  1029. clone() {
  1030. const bundle = new Bundle$1({
  1031. intro: this.intro,
  1032. separator: this.separator,
  1033. });
  1034. this.sources.forEach((source) => {
  1035. bundle.addSource({
  1036. filename: source.filename,
  1037. content: source.content.clone(),
  1038. separator: source.separator,
  1039. });
  1040. });
  1041. return bundle;
  1042. }
  1043. generateDecodedMap(options = {}) {
  1044. const names = [];
  1045. this.sources.forEach((source) => {
  1046. Object.keys(source.content.storedNames).forEach((name) => {
  1047. if (!~names.indexOf(name)) names.push(name);
  1048. });
  1049. });
  1050. const mappings = new Mappings(options.hires);
  1051. if (this.intro) {
  1052. mappings.advance(this.intro);
  1053. }
  1054. this.sources.forEach((source, i) => {
  1055. if (i > 0) {
  1056. mappings.advance(this.separator);
  1057. }
  1058. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1059. const magicString = source.content;
  1060. const locate = getLocator$1(magicString.original);
  1061. if (magicString.intro) {
  1062. mappings.advance(magicString.intro);
  1063. }
  1064. magicString.firstChunk.eachNext((chunk) => {
  1065. const loc = locate(chunk.start);
  1066. if (chunk.intro.length) mappings.advance(chunk.intro);
  1067. if (source.filename) {
  1068. if (chunk.edited) {
  1069. mappings.addEdit(
  1070. sourceIndex,
  1071. chunk.content,
  1072. loc,
  1073. chunk.storeName ? names.indexOf(chunk.original) : -1
  1074. );
  1075. } else {
  1076. mappings.addUneditedChunk(
  1077. sourceIndex,
  1078. chunk,
  1079. magicString.original,
  1080. loc,
  1081. magicString.sourcemapLocations
  1082. );
  1083. }
  1084. } else {
  1085. mappings.advance(chunk.content);
  1086. }
  1087. if (chunk.outro.length) mappings.advance(chunk.outro);
  1088. });
  1089. if (magicString.outro) {
  1090. mappings.advance(magicString.outro);
  1091. }
  1092. });
  1093. return {
  1094. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1095. sources: this.uniqueSources.map((source) => {
  1096. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1097. }),
  1098. sourcesContent: this.uniqueSources.map((source) => {
  1099. return options.includeContent ? source.content : null;
  1100. }),
  1101. names,
  1102. mappings: mappings.raw,
  1103. };
  1104. }
  1105. generateMap(options) {
  1106. return new SourceMap(this.generateDecodedMap(options));
  1107. }
  1108. getIndentString() {
  1109. const indentStringCounts = {};
  1110. this.sources.forEach((source) => {
  1111. const indentStr = source.content.indentStr;
  1112. if (indentStr === null) return;
  1113. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1114. indentStringCounts[indentStr] += 1;
  1115. });
  1116. return (
  1117. Object.keys(indentStringCounts).sort((a, b) => {
  1118. return indentStringCounts[a] - indentStringCounts[b];
  1119. })[0] || '\t'
  1120. );
  1121. }
  1122. indent(indentStr) {
  1123. if (!arguments.length) {
  1124. indentStr = this.getIndentString();
  1125. }
  1126. if (indentStr === '') return this; // noop
  1127. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1128. this.sources.forEach((source, i) => {
  1129. const separator = source.separator !== undefined ? source.separator : this.separator;
  1130. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1131. source.content.indent(indentStr, {
  1132. exclude: source.indentExclusionRanges,
  1133. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1134. });
  1135. trailingNewline = source.content.lastChar() === '\n';
  1136. });
  1137. if (this.intro) {
  1138. this.intro =
  1139. indentStr +
  1140. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1141. return index > 0 ? indentStr + match : match;
  1142. });
  1143. }
  1144. return this;
  1145. }
  1146. prepend(str) {
  1147. this.intro = str + this.intro;
  1148. return this;
  1149. }
  1150. toString() {
  1151. const body = this.sources
  1152. .map((source, i) => {
  1153. const separator = source.separator !== undefined ? source.separator : this.separator;
  1154. const str = (i > 0 ? separator : '') + source.content.toString();
  1155. return str;
  1156. })
  1157. .join('');
  1158. return this.intro + body;
  1159. }
  1160. isEmpty() {
  1161. if (this.intro.length && this.intro.trim()) return false;
  1162. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1163. return true;
  1164. }
  1165. length() {
  1166. return this.sources.reduce(
  1167. (length, source) => length + source.content.length(),
  1168. this.intro.length
  1169. );
  1170. }
  1171. trimLines() {
  1172. return this.trim('[\\r\\n]');
  1173. }
  1174. trim(charType) {
  1175. return this.trimStart(charType).trimEnd(charType);
  1176. }
  1177. trimStart(charType) {
  1178. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1179. this.intro = this.intro.replace(rx, '');
  1180. if (!this.intro) {
  1181. let source;
  1182. let i = 0;
  1183. do {
  1184. source = this.sources[i++];
  1185. if (!source) {
  1186. break;
  1187. }
  1188. } while (!source.content.trimStartAborted(charType));
  1189. }
  1190. return this;
  1191. }
  1192. trimEnd(charType) {
  1193. const rx = new RegExp((charType || '\\s') + '+$');
  1194. let source;
  1195. let i = this.sources.length - 1;
  1196. do {
  1197. source = this.sources[i--];
  1198. if (!source) {
  1199. this.intro = this.intro.replace(rx, '');
  1200. break;
  1201. }
  1202. } while (!source.content.trimEndAborted(charType));
  1203. return this;
  1204. }
  1205. }
  1206. const ANY_SLASH_REGEX = /[/\\]/;
  1207. function relative(from, to) {
  1208. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  1209. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  1210. if (fromParts[0] === '.')
  1211. fromParts.shift();
  1212. if (toParts[0] === '.')
  1213. toParts.shift();
  1214. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1215. fromParts.shift();
  1216. toParts.shift();
  1217. }
  1218. while (toParts[0] === '..' && fromParts.length > 0) {
  1219. toParts.shift();
  1220. fromParts.pop();
  1221. }
  1222. while (fromParts.pop()) {
  1223. toParts.unshift('..');
  1224. }
  1225. return toParts.join('/');
  1226. }
  1227. function getOrCreate(map, key, init) {
  1228. const existing = map.get(key);
  1229. if (existing) {
  1230. return existing;
  1231. }
  1232. const value = init();
  1233. map.set(key, value);
  1234. return value;
  1235. }
  1236. const UnknownKey = Symbol('Unknown Key');
  1237. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1238. const UnknownInteger = Symbol('Unknown Integer');
  1239. const EMPTY_PATH = [];
  1240. const UNKNOWN_PATH = [UnknownKey];
  1241. // For deoptimizations, this means we are modifying an unknown property but did
  1242. // not lose track of the object or are creating a setter/getter;
  1243. // For assignment effects it means we do not check for setter/getter effects
  1244. // but only if something is mutated that is included, which is relevant for
  1245. // Object.defineProperty
  1246. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1247. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1248. const EntitiesKey = Symbol('Entities');
  1249. class PathTracker {
  1250. constructor() {
  1251. this.entityPaths = Object.create(null, {
  1252. [EntitiesKey]: { value: new Set() }
  1253. });
  1254. }
  1255. trackEntityAtPathAndGetIfTracked(path, entity) {
  1256. const trackedEntities = this.getEntities(path);
  1257. if (trackedEntities.has(entity))
  1258. return true;
  1259. trackedEntities.add(entity);
  1260. return false;
  1261. }
  1262. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1263. const trackedEntities = this.getEntities(path);
  1264. if (trackedEntities.has(entity))
  1265. return returnIfTracked;
  1266. trackedEntities.add(entity);
  1267. const result = onUntracked();
  1268. trackedEntities.delete(entity);
  1269. return result;
  1270. }
  1271. getEntities(path) {
  1272. let currentPaths = this.entityPaths;
  1273. for (const pathSegment of path) {
  1274. currentPaths = currentPaths[pathSegment] =
  1275. currentPaths[pathSegment] ||
  1276. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1277. }
  1278. return currentPaths[EntitiesKey];
  1279. }
  1280. }
  1281. const SHARED_RECURSION_TRACKER = new PathTracker();
  1282. class DiscriminatedPathTracker {
  1283. constructor() {
  1284. this.entityPaths = Object.create(null, {
  1285. [EntitiesKey]: { value: new Map() }
  1286. });
  1287. }
  1288. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1289. let currentPaths = this.entityPaths;
  1290. for (const pathSegment of path) {
  1291. currentPaths = currentPaths[pathSegment] =
  1292. currentPaths[pathSegment] ||
  1293. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1294. }
  1295. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1296. if (trackedEntities.has(entity))
  1297. return true;
  1298. trackedEntities.add(entity);
  1299. return false;
  1300. }
  1301. }
  1302. const UnknownValue = Symbol('Unknown Value');
  1303. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1304. class ExpressionEntity {
  1305. constructor() {
  1306. this.included = false;
  1307. }
  1308. deoptimizePath(_path) { }
  1309. deoptimizeThisOnInteractionAtPath({ thisArg }, _path, _recursionTracker) {
  1310. thisArg.deoptimizePath(UNKNOWN_PATH);
  1311. }
  1312. /**
  1313. * If possible it returns a stringifyable literal value for this node that can be used
  1314. * for inlining or comparing values.
  1315. * Otherwise it should return UnknownValue.
  1316. */
  1317. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1318. return UnknownValue;
  1319. }
  1320. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1321. return UNKNOWN_EXPRESSION;
  1322. }
  1323. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1324. return true;
  1325. }
  1326. include(_context, _includeChildrenRecursively, _options) {
  1327. this.included = true;
  1328. }
  1329. includeCallArguments(context, args) {
  1330. for (const arg of args) {
  1331. arg.include(context, false);
  1332. }
  1333. }
  1334. shouldBeIncluded(_context) {
  1335. return true;
  1336. }
  1337. }
  1338. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1339. })();
  1340. const INTERACTION_ACCESSED = 0;
  1341. const INTERACTION_ASSIGNED = 1;
  1342. const INTERACTION_CALLED = 2;
  1343. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1344. thisArg: null,
  1345. type: INTERACTION_ACCESSED
  1346. };
  1347. const UNKNOWN_ARG = [UNKNOWN_EXPRESSION];
  1348. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1349. args: UNKNOWN_ARG,
  1350. thisArg: null,
  1351. type: INTERACTION_ASSIGNED
  1352. };
  1353. const NO_ARGS = [];
  1354. // While this is technically a call without arguments, we can compare against
  1355. // this reference in places where precise values or thisArg would make a
  1356. // difference
  1357. const NODE_INTERACTION_UNKNOWN_CALL = {
  1358. args: NO_ARGS,
  1359. thisArg: null,
  1360. type: INTERACTION_CALLED,
  1361. withNew: false
  1362. };
  1363. class Variable extends ExpressionEntity {
  1364. constructor(name) {
  1365. super();
  1366. this.name = name;
  1367. this.alwaysRendered = false;
  1368. this.initReached = false;
  1369. this.isId = false;
  1370. this.isReassigned = false;
  1371. this.kind = null;
  1372. this.renderBaseName = null;
  1373. this.renderName = null;
  1374. }
  1375. /**
  1376. * Binds identifiers that reference this variable to this variable.
  1377. * Necessary to be able to change variable names.
  1378. */
  1379. addReference(_identifier) { }
  1380. getBaseVariableName() {
  1381. return this.renderBaseName || this.renderName || this.name;
  1382. }
  1383. getName(getPropertyAccess) {
  1384. const name = this.renderName || this.name;
  1385. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1386. }
  1387. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1388. return type !== INTERACTION_ACCESSED || path.length > 0;
  1389. }
  1390. /**
  1391. * Marks this variable as being part of the bundle, which is usually the case when one of
  1392. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1393. * previously.
  1394. * Once a variable is included, it should take care all its declarations are included.
  1395. */
  1396. include() {
  1397. this.included = true;
  1398. }
  1399. markCalledFromTryStatement() { }
  1400. setRenderNames(baseName, name) {
  1401. this.renderBaseName = baseName;
  1402. this.renderName = name;
  1403. }
  1404. }
  1405. class ExternalVariable extends Variable {
  1406. constructor(module, name) {
  1407. super(name);
  1408. this.referenced = false;
  1409. this.module = module;
  1410. this.isNamespace = name === '*';
  1411. }
  1412. addReference(identifier) {
  1413. this.referenced = true;
  1414. if (this.name === 'default' || this.name === '*') {
  1415. this.module.suggestName(identifier.name);
  1416. }
  1417. }
  1418. hasEffectsOnInteractionAtPath(path, { type }) {
  1419. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1420. }
  1421. include() {
  1422. if (!this.included) {
  1423. this.included = true;
  1424. this.module.used = true;
  1425. }
  1426. }
  1427. }
  1428. const BLANK = Object.freeze(Object.create(null));
  1429. const EMPTY_OBJECT = Object.freeze({});
  1430. const EMPTY_ARRAY = Object.freeze([]);
  1431. function getLocator(source, options) {
  1432. if (options === void 0) { options = {}; }
  1433. var offsetLine = options.offsetLine || 0;
  1434. var offsetColumn = options.offsetColumn || 0;
  1435. var originalLines = source.split('\n');
  1436. var start = 0;
  1437. var lineRanges = originalLines.map(function (line, i) {
  1438. var end = start + line.length + 1;
  1439. var range = { start: start, end: end, line: i };
  1440. start = end;
  1441. return range;
  1442. });
  1443. var i = 0;
  1444. function rangeContains(range, index) {
  1445. return range.start <= index && index < range.end;
  1446. }
  1447. function getLocation(range, index) {
  1448. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  1449. }
  1450. function locate(search, startIndex) {
  1451. if (typeof search === 'string') {
  1452. search = source.indexOf(search, startIndex || 0);
  1453. }
  1454. var range = lineRanges[i];
  1455. var d = search >= range.end ? 1 : -1;
  1456. while (range) {
  1457. if (rangeContains(range, search))
  1458. return getLocation(range, search);
  1459. i += d;
  1460. range = lineRanges[i];
  1461. }
  1462. }
  1463. return locate;
  1464. }
  1465. function locate(source, search, options) {
  1466. if (typeof options === 'number') {
  1467. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  1468. }
  1469. return getLocator(source, options)(search, options && options.startIndex);
  1470. }
  1471. function spaces(i) {
  1472. let result = '';
  1473. while (i--)
  1474. result += ' ';
  1475. return result;
  1476. }
  1477. function tabsToSpaces(str) {
  1478. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  1479. }
  1480. function getCodeFrame(source, line, column) {
  1481. let lines = source.split('\n');
  1482. const frameStart = Math.max(0, line - 3);
  1483. let frameEnd = Math.min(line + 2, lines.length);
  1484. lines = lines.slice(frameStart, frameEnd);
  1485. while (!/\S/.test(lines[lines.length - 1])) {
  1486. lines.pop();
  1487. frameEnd -= 1;
  1488. }
  1489. const digits = String(frameEnd).length;
  1490. return lines
  1491. .map((str, i) => {
  1492. const isErrorLine = frameStart + i + 1 === line;
  1493. let lineNum = String(i + frameStart + 1);
  1494. while (lineNum.length < digits)
  1495. lineNum = ` ${lineNum}`;
  1496. if (isErrorLine) {
  1497. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  1498. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  1499. }
  1500. return `${lineNum}: ${tabsToSpaces(str)}`;
  1501. })
  1502. .join('\n');
  1503. }
  1504. function printQuotedStringList(list, verbs) {
  1505. const isSingleItem = list.length <= 1;
  1506. const quotedList = list.map(item => `"${item}"`);
  1507. let output = isSingleItem
  1508. ? quotedList[0]
  1509. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  1510. if (verbs) {
  1511. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  1512. }
  1513. return output;
  1514. }
  1515. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  1516. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  1517. function isAbsolute(path) {
  1518. return ABSOLUTE_PATH_REGEX.test(path);
  1519. }
  1520. function isRelative(path) {
  1521. return RELATIVE_PATH_REGEX.test(path);
  1522. }
  1523. const BACKSLASH_REGEX = /\\/g;
  1524. function normalize(path) {
  1525. return path.replace(BACKSLASH_REGEX, '/');
  1526. }
  1527. function getAliasName(id) {
  1528. const base = basename(id);
  1529. return base.substring(0, base.length - extname(id).length);
  1530. }
  1531. function relativeId(id) {
  1532. if (!isAbsolute(id))
  1533. return id;
  1534. return relative(resolve(), id);
  1535. }
  1536. function isPathFragment(name) {
  1537. // starting with "/", "./", "../", "C:/"
  1538. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  1539. }
  1540. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  1541. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  1542. let relativePath = normalize(relative(dirname(importerId), targetPath));
  1543. if (stripJsExtension && relativePath.endsWith('.js')) {
  1544. relativePath = relativePath.slice(0, -3);
  1545. }
  1546. if (ensureFileName) {
  1547. if (relativePath === '')
  1548. return '../' + basename(targetPath);
  1549. if (UPPER_DIR_REGEX.test(relativePath)) {
  1550. return relativePath
  1551. .split('/')
  1552. .concat(['..', basename(targetPath)])
  1553. .join('/');
  1554. }
  1555. }
  1556. return !relativePath ? '.' : relativePath.startsWith('..') ? relativePath : './' + relativePath;
  1557. }
  1558. function error(base) {
  1559. if (!(base instanceof Error))
  1560. base = Object.assign(new Error(base.message), base);
  1561. throw base;
  1562. }
  1563. function augmentCodeLocation(props, pos, source, id) {
  1564. if (typeof pos === 'object') {
  1565. const { line, column } = pos;
  1566. props.loc = { column, file: id, line };
  1567. }
  1568. else {
  1569. props.pos = pos;
  1570. const { line, column } = locate(source, pos, { offsetLine: 1 });
  1571. props.loc = { column, file: id, line };
  1572. }
  1573. if (props.frame === undefined) {
  1574. const { line, column } = props.loc;
  1575. props.frame = getCodeFrame(source, line, column);
  1576. }
  1577. }
  1578. var Errors;
  1579. (function (Errors) {
  1580. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  1581. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  1582. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  1583. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  1584. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  1585. Errors["BAD_LOADER"] = "BAD_LOADER";
  1586. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  1587. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  1588. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  1589. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  1590. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  1591. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  1592. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  1593. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  1594. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  1595. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  1596. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  1597. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  1598. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  1599. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  1600. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  1601. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  1602. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  1603. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  1604. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  1605. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  1606. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  1607. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  1608. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  1609. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  1610. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  1611. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  1612. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  1613. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  1614. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  1615. })(Errors || (Errors = {}));
  1616. function errAssetNotFinalisedForFileName(name) {
  1617. return {
  1618. code: Errors.ASSET_NOT_FINALISED,
  1619. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  1620. };
  1621. }
  1622. function errCannotEmitFromOptionsHook() {
  1623. return {
  1624. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  1625. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  1626. };
  1627. }
  1628. function errChunkNotGeneratedForFileName(name) {
  1629. return {
  1630. code: Errors.CHUNK_NOT_GENERATED,
  1631. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  1632. };
  1633. }
  1634. function errChunkInvalid({ fileName, code }, exception) {
  1635. const errorProps = {
  1636. code: Errors.CHUNK_INVALID,
  1637. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  1638. };
  1639. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  1640. return errorProps;
  1641. }
  1642. function errCircularReexport(exportName, importedModule) {
  1643. return {
  1644. code: Errors.CIRCULAR_REEXPORT,
  1645. id: importedModule,
  1646. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  1647. };
  1648. }
  1649. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  1650. return {
  1651. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  1652. exporter,
  1653. importer,
  1654. message: `Export "${exportName}" of module ${relativeId(exporter)} was reexported through module ${relativeId(reexporter)} while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in ${relativeId(importer)} to point directly to the exporting module or do not use "preserveModules" to ensure these modules end up in the same chunk.`,
  1655. reexporter
  1656. };
  1657. }
  1658. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  1659. return {
  1660. code: Errors.ASSET_NOT_FOUND,
  1661. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  1662. };
  1663. }
  1664. function errAssetSourceAlreadySet(name) {
  1665. return {
  1666. code: Errors.ASSET_SOURCE_ALREADY_SET,
  1667. message: `Unable to set the source for asset "${name}", source already set.`
  1668. };
  1669. }
  1670. function errNoAssetSourceSet(assetName) {
  1671. return {
  1672. code: Errors.ASSET_SOURCE_MISSING,
  1673. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  1674. };
  1675. }
  1676. function errBadLoader(id) {
  1677. return {
  1678. code: Errors.BAD_LOADER,
  1679. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  1680. };
  1681. }
  1682. function errDeprecation(deprecation) {
  1683. return {
  1684. code: Errors.DEPRECATED_FEATURE,
  1685. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  1686. };
  1687. }
  1688. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  1689. return {
  1690. code: Errors.FILE_NOT_FOUND,
  1691. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  1692. };
  1693. }
  1694. function errFileNameConflict(fileName) {
  1695. return {
  1696. code: Errors.FILE_NAME_CONFLICT,
  1697. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  1698. };
  1699. }
  1700. function errInputHookInOutputPlugin(pluginName, hookName) {
  1701. return {
  1702. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  1703. message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
  1704. };
  1705. }
  1706. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  1707. return {
  1708. code: Errors.INVALID_CHUNK,
  1709. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  1710. };
  1711. }
  1712. function errInvalidExportOptionValue(optionValue) {
  1713. return {
  1714. code: Errors.INVALID_EXPORT_OPTION,
  1715. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  1716. url: `https://rollupjs.org/guide/en/#outputexports`
  1717. };
  1718. }
  1719. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  1720. return {
  1721. code: 'INVALID_EXPORT_OPTION',
  1722. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  1723. };
  1724. }
  1725. function errInternalIdCannotBeExternal(source, importer) {
  1726. return {
  1727. code: Errors.INVALID_EXTERNAL_ID,
  1728. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  1729. };
  1730. }
  1731. function errInvalidOption(option, urlHash, explanation, value) {
  1732. return {
  1733. code: Errors.INVALID_OPTION,
  1734. message: `Invalid value ${value !== undefined ? `${JSON.stringify(value)} ` : ''}for option "${option}" - ${explanation}.`,
  1735. url: `https://rollupjs.org/guide/en/#${urlHash}`
  1736. };
  1737. }
  1738. function errInvalidAddonPluginHook(hook, plugin) {
  1739. return {
  1740. code: Errors.INVALID_PLUGIN_HOOK,
  1741. hook,
  1742. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a string, a function hook or an object with a "handler" string or function.`,
  1743. plugin
  1744. };
  1745. }
  1746. function errInvalidFunctionPluginHook(hook, plugin) {
  1747. return {
  1748. code: Errors.INVALID_PLUGIN_HOOK,
  1749. hook,
  1750. message: `Error running plugin hook ${hook} for plugin ${plugin}, expected a function hook or an object with a "handler" function.`,
  1751. plugin
  1752. };
  1753. }
  1754. function errInvalidRollupPhaseForAddWatchFile() {
  1755. return {
  1756. code: Errors.INVALID_ROLLUP_PHASE,
  1757. message: `Cannot call addWatchFile after the build has finished.`
  1758. };
  1759. }
  1760. function errInvalidRollupPhaseForChunkEmission() {
  1761. return {
  1762. code: Errors.INVALID_ROLLUP_PHASE,
  1763. message: `Cannot emit chunks after module loading has finished.`
  1764. };
  1765. }
  1766. function errMissingExport(exportName, importingModule, importedModule) {
  1767. return {
  1768. code: Errors.MISSING_EXPORT,
  1769. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  1770. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  1771. };
  1772. }
  1773. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  1774. return {
  1775. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1776. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  1777. };
  1778. }
  1779. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  1780. return {
  1781. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1782. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  1783. };
  1784. }
  1785. function errImplicitDependantIsNotIncluded(module) {
  1786. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  1787. return {
  1788. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  1789. 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.`
  1790. };
  1791. }
  1792. function errMixedExport(facadeModuleId, name) {
  1793. return {
  1794. code: Errors.MIXED_EXPORTS,
  1795. id: facadeModuleId,
  1796. 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`,
  1797. url: `https://rollupjs.org/guide/en/#outputexports`
  1798. };
  1799. }
  1800. function errNamespaceConflict(name, reexportingModuleId, sources) {
  1801. return {
  1802. code: Errors.NAMESPACE_CONFLICT,
  1803. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${name}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored)`,
  1804. name,
  1805. reexporter: reexportingModuleId,
  1806. sources
  1807. };
  1808. }
  1809. function errAmbiguousExternalNamespaces(name, reexportingModule, usedModule, sources) {
  1810. return {
  1811. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  1812. 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)}".`,
  1813. name,
  1814. reexporter: reexportingModule,
  1815. sources
  1816. };
  1817. }
  1818. function errNoTransformMapOrAstWithoutCode(pluginName) {
  1819. return {
  1820. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  1821. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  1822. 'a "code". This will be ignored.'
  1823. };
  1824. }
  1825. function errPreferNamedExports(facadeModuleId) {
  1826. const file = relativeId(facadeModuleId);
  1827. return {
  1828. code: Errors.PREFER_NAMED_EXPORTS,
  1829. id: facadeModuleId,
  1830. 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.`,
  1831. url: `https://rollupjs.org/guide/en/#outputexports`
  1832. };
  1833. }
  1834. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  1835. return {
  1836. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  1837. id,
  1838. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  1839. ? `an explicit export named "${syntheticNamedExportsOption}"`
  1840. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  1841. };
  1842. }
  1843. function errUnexpectedNamedImport(id, imported, isReexport) {
  1844. const importType = isReexport ? 'reexport' : 'import';
  1845. return {
  1846. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1847. id,
  1848. 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.`,
  1849. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1850. };
  1851. }
  1852. function errUnexpectedNamespaceReexport(id) {
  1853. return {
  1854. code: Errors.UNEXPECTED_NAMED_IMPORT,
  1855. id,
  1856. 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.`,
  1857. url: 'https://rollupjs.org/guide/en/#outputinterop'
  1858. };
  1859. }
  1860. function errEntryCannotBeExternal(unresolvedId) {
  1861. return {
  1862. code: Errors.UNRESOLVED_ENTRY,
  1863. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  1864. };
  1865. }
  1866. function errUnresolvedEntry(unresolvedId) {
  1867. return {
  1868. code: Errors.UNRESOLVED_ENTRY,
  1869. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  1870. };
  1871. }
  1872. function errUnresolvedImport(source, importer) {
  1873. return {
  1874. code: Errors.UNRESOLVED_IMPORT,
  1875. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  1876. };
  1877. }
  1878. function errUnresolvedImportTreatedAsExternal(source, importer) {
  1879. return {
  1880. code: Errors.UNRESOLVED_IMPORT,
  1881. importer: relativeId(importer),
  1882. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  1883. source,
  1884. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  1885. };
  1886. }
  1887. function errExternalSyntheticExports(source, importer) {
  1888. return {
  1889. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  1890. importer: relativeId(importer),
  1891. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  1892. source
  1893. };
  1894. }
  1895. function errFailedValidation(message) {
  1896. return {
  1897. code: Errors.VALIDATION_ERROR,
  1898. message
  1899. };
  1900. }
  1901. function errAlreadyClosed() {
  1902. return {
  1903. code: Errors.ALREADY_CLOSED,
  1904. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  1905. };
  1906. }
  1907. function warnDeprecation(deprecation, activeDeprecation, options) {
  1908. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  1909. }
  1910. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  1911. if (activeDeprecation || strictDeprecations) {
  1912. const warning = errDeprecation(deprecation);
  1913. if (strictDeprecations) {
  1914. return error(warning);
  1915. }
  1916. warn(warning);
  1917. }
  1918. }
  1919. const RESERVED_NAMES = new Set([
  1920. 'await',
  1921. 'break',
  1922. 'case',
  1923. 'catch',
  1924. 'class',
  1925. 'const',
  1926. 'continue',
  1927. 'debugger',
  1928. 'default',
  1929. 'delete',
  1930. 'do',
  1931. 'else',
  1932. 'enum',
  1933. 'eval',
  1934. 'export',
  1935. 'extends',
  1936. 'false',
  1937. 'finally',
  1938. 'for',
  1939. 'function',
  1940. 'if',
  1941. 'implements',
  1942. 'import',
  1943. 'in',
  1944. 'instanceof',
  1945. 'interface',
  1946. 'let',
  1947. 'NaN',
  1948. 'new',
  1949. 'null',
  1950. 'package',
  1951. 'private',
  1952. 'protected',
  1953. 'public',
  1954. 'return',
  1955. 'static',
  1956. 'super',
  1957. 'switch',
  1958. 'this',
  1959. 'throw',
  1960. 'true',
  1961. 'try',
  1962. 'typeof',
  1963. 'undefined',
  1964. 'var',
  1965. 'void',
  1966. 'while',
  1967. 'with',
  1968. 'yield'
  1969. ]);
  1970. const RESERVED_NAMES$1 = RESERVED_NAMES;
  1971. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1972. const startsWithDigit = (str) => /\d/.test(str[0]);
  1973. function isLegal(str) {
  1974. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str)) {
  1975. return false;
  1976. }
  1977. return !illegalCharacters.test(str);
  1978. }
  1979. function makeLegal(str) {
  1980. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1981. if (startsWithDigit(str) || RESERVED_NAMES$1.has(str))
  1982. str = `_${str}`;
  1983. return str || '_';
  1984. }
  1985. class ExternalModule {
  1986. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath) {
  1987. this.options = options;
  1988. this.id = id;
  1989. this.renormalizeRenderPath = renormalizeRenderPath;
  1990. this.declarations = new Map();
  1991. this.defaultVariableName = '';
  1992. this.dynamicImporters = [];
  1993. this.execIndex = Infinity;
  1994. this.exportedVariables = new Map();
  1995. this.importers = [];
  1996. this.mostCommonSuggestion = 0;
  1997. this.nameSuggestions = new Map();
  1998. this.namespaceVariableName = '';
  1999. this.reexported = false;
  2000. this.renderPath = undefined;
  2001. this.used = false;
  2002. this.variableName = '';
  2003. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  2004. const { importers, dynamicImporters } = this;
  2005. const info = (this.info = {
  2006. ast: null,
  2007. code: null,
  2008. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2009. dynamicallyImportedIds: EMPTY_ARRAY,
  2010. get dynamicImporters() {
  2011. return dynamicImporters.sort();
  2012. },
  2013. hasDefaultExport: null,
  2014. get hasModuleSideEffects() {
  2015. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  2016. return info.moduleSideEffects;
  2017. },
  2018. id,
  2019. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2020. implicitlyLoadedBefore: EMPTY_ARRAY,
  2021. importedIdResolutions: EMPTY_ARRAY,
  2022. importedIds: EMPTY_ARRAY,
  2023. get importers() {
  2024. return importers.sort();
  2025. },
  2026. isEntry: false,
  2027. isExternal: true,
  2028. isIncluded: null,
  2029. meta,
  2030. moduleSideEffects,
  2031. syntheticNamedExports: false
  2032. });
  2033. // Hide the deprecated key so that it only warns when accessed explicitly
  2034. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2035. enumerable: false
  2036. });
  2037. }
  2038. getVariableForExportName(name) {
  2039. const declaration = this.declarations.get(name);
  2040. if (declaration)
  2041. return [declaration];
  2042. const externalVariable = new ExternalVariable(this, name);
  2043. this.declarations.set(name, externalVariable);
  2044. this.exportedVariables.set(externalVariable, name);
  2045. return [externalVariable];
  2046. }
  2047. setRenderPath(options, inputBase) {
  2048. this.renderPath =
  2049. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2050. if (!this.renderPath) {
  2051. this.renderPath = this.renormalizeRenderPath
  2052. ? normalize(relative$1(inputBase, this.id))
  2053. : this.id;
  2054. }
  2055. }
  2056. suggestName(name) {
  2057. var _a;
  2058. const value = ((_a = this.nameSuggestions.get(name)) !== null && _a !== void 0 ? _a : 0) + 1;
  2059. this.nameSuggestions.set(name, value);
  2060. if (value > this.mostCommonSuggestion) {
  2061. this.mostCommonSuggestion = value;
  2062. this.suggestedVariableName = name;
  2063. }
  2064. }
  2065. warnUnusedImports() {
  2066. const unused = Array.from(this.declarations)
  2067. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2068. .map(([name]) => name);
  2069. if (unused.length === 0)
  2070. return;
  2071. const importersSet = new Set();
  2072. for (const name of unused) {
  2073. for (const importer of this.declarations.get(name).module.importers) {
  2074. importersSet.add(importer);
  2075. }
  2076. }
  2077. const importersArray = [...importersSet];
  2078. this.options.onwarn({
  2079. code: 'UNUSED_EXTERNAL_IMPORT',
  2080. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  2081. names: unused,
  2082. source: this.id,
  2083. sources: importersArray
  2084. });
  2085. }
  2086. }
  2087. function getDefaultExportFromCjs (x) {
  2088. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2089. }
  2090. function getAugmentedNamespace(n) {
  2091. var f = n.default;
  2092. if (typeof f == "function") {
  2093. var a = function () {
  2094. return f.apply(this, arguments);
  2095. };
  2096. a.prototype = f.prototype;
  2097. } else a = {};
  2098. Object.defineProperty(a, '__esModule', {value: true});
  2099. Object.keys(n).forEach(function (k) {
  2100. var d = Object.getOwnPropertyDescriptor(n, k);
  2101. Object.defineProperty(a, k, d.get ? d : {
  2102. enumerable: true,
  2103. get: function () {
  2104. return n[k];
  2105. }
  2106. });
  2107. });
  2108. return a;
  2109. }
  2110. var picomatch$1 = {exports: {}};
  2111. var utils$3 = {};
  2112. const path$1 = require$$0;
  2113. const WIN_SLASH = '\\\\/';
  2114. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2115. /**
  2116. * Posix glob regex
  2117. */
  2118. const DOT_LITERAL = '\\.';
  2119. const PLUS_LITERAL = '\\+';
  2120. const QMARK_LITERAL = '\\?';
  2121. const SLASH_LITERAL = '\\/';
  2122. const ONE_CHAR = '(?=.)';
  2123. const QMARK = '[^/]';
  2124. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2125. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2126. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2127. const NO_DOT = `(?!${DOT_LITERAL})`;
  2128. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2129. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2130. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2131. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2132. const STAR = `${QMARK}*?`;
  2133. const POSIX_CHARS = {
  2134. DOT_LITERAL,
  2135. PLUS_LITERAL,
  2136. QMARK_LITERAL,
  2137. SLASH_LITERAL,
  2138. ONE_CHAR,
  2139. QMARK,
  2140. END_ANCHOR,
  2141. DOTS_SLASH,
  2142. NO_DOT,
  2143. NO_DOTS,
  2144. NO_DOT_SLASH,
  2145. NO_DOTS_SLASH,
  2146. QMARK_NO_DOT,
  2147. STAR,
  2148. START_ANCHOR
  2149. };
  2150. /**
  2151. * Windows glob regex
  2152. */
  2153. const WINDOWS_CHARS = {
  2154. ...POSIX_CHARS,
  2155. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2156. QMARK: WIN_NO_SLASH,
  2157. STAR: `${WIN_NO_SLASH}*?`,
  2158. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2159. NO_DOT: `(?!${DOT_LITERAL})`,
  2160. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2161. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2162. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2163. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2164. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2165. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2166. };
  2167. /**
  2168. * POSIX Bracket Regex
  2169. */
  2170. const POSIX_REGEX_SOURCE$1 = {
  2171. alnum: 'a-zA-Z0-9',
  2172. alpha: 'a-zA-Z',
  2173. ascii: '\\x00-\\x7F',
  2174. blank: ' \\t',
  2175. cntrl: '\\x00-\\x1F\\x7F',
  2176. digit: '0-9',
  2177. graph: '\\x21-\\x7E',
  2178. lower: 'a-z',
  2179. print: '\\x20-\\x7E ',
  2180. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2181. space: ' \\t\\r\\n\\v\\f',
  2182. upper: 'A-Z',
  2183. word: 'A-Za-z0-9_',
  2184. xdigit: 'A-Fa-f0-9'
  2185. };
  2186. var constants$2 = {
  2187. MAX_LENGTH: 1024 * 64,
  2188. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2189. // regular expressions
  2190. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2191. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2192. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2193. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2194. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2195. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2196. // Replace globs with equivalent patterns to reduce parsing time.
  2197. REPLACEMENTS: {
  2198. '***': '*',
  2199. '**/**': '**',
  2200. '**/**/**': '**'
  2201. },
  2202. // Digits
  2203. CHAR_0: 48, /* 0 */
  2204. CHAR_9: 57, /* 9 */
  2205. // Alphabet chars.
  2206. CHAR_UPPERCASE_A: 65, /* A */
  2207. CHAR_LOWERCASE_A: 97, /* a */
  2208. CHAR_UPPERCASE_Z: 90, /* Z */
  2209. CHAR_LOWERCASE_Z: 122, /* z */
  2210. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2211. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2212. CHAR_ASTERISK: 42, /* * */
  2213. // Non-alphabetic chars.
  2214. CHAR_AMPERSAND: 38, /* & */
  2215. CHAR_AT: 64, /* @ */
  2216. CHAR_BACKWARD_SLASH: 92, /* \ */
  2217. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2218. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2219. CHAR_COLON: 58, /* : */
  2220. CHAR_COMMA: 44, /* , */
  2221. CHAR_DOT: 46, /* . */
  2222. CHAR_DOUBLE_QUOTE: 34, /* " */
  2223. CHAR_EQUAL: 61, /* = */
  2224. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2225. CHAR_FORM_FEED: 12, /* \f */
  2226. CHAR_FORWARD_SLASH: 47, /* / */
  2227. CHAR_GRAVE_ACCENT: 96, /* ` */
  2228. CHAR_HASH: 35, /* # */
  2229. CHAR_HYPHEN_MINUS: 45, /* - */
  2230. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2231. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2232. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2233. CHAR_LINE_FEED: 10, /* \n */
  2234. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2235. CHAR_PERCENT: 37, /* % */
  2236. CHAR_PLUS: 43, /* + */
  2237. CHAR_QUESTION_MARK: 63, /* ? */
  2238. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2239. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2240. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2241. CHAR_SEMICOLON: 59, /* ; */
  2242. CHAR_SINGLE_QUOTE: 39, /* ' */
  2243. CHAR_SPACE: 32, /* */
  2244. CHAR_TAB: 9, /* \t */
  2245. CHAR_UNDERSCORE: 95, /* _ */
  2246. CHAR_VERTICAL_LINE: 124, /* | */
  2247. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2248. SEP: path$1.sep,
  2249. /**
  2250. * Create EXTGLOB_CHARS
  2251. */
  2252. extglobChars(chars) {
  2253. return {
  2254. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2255. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2256. '+': { type: 'plus', open: '(?:', close: ')+' },
  2257. '*': { type: 'star', open: '(?:', close: ')*' },
  2258. '@': { type: 'at', open: '(?:', close: ')' }
  2259. };
  2260. },
  2261. /**
  2262. * Create GLOB_CHARS
  2263. */
  2264. globChars(win32) {
  2265. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2266. }
  2267. };
  2268. (function (exports) {
  2269. const path = require$$0;
  2270. const win32 = process.platform === 'win32';
  2271. const {
  2272. REGEX_BACKSLASH,
  2273. REGEX_REMOVE_BACKSLASH,
  2274. REGEX_SPECIAL_CHARS,
  2275. REGEX_SPECIAL_CHARS_GLOBAL
  2276. } = constants$2;
  2277. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2278. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2279. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2280. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2281. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2282. exports.removeBackslashes = str => {
  2283. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2284. return match === '\\' ? '' : match;
  2285. });
  2286. };
  2287. exports.supportsLookbehinds = () => {
  2288. const segs = process.version.slice(1).split('.').map(Number);
  2289. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2290. return true;
  2291. }
  2292. return false;
  2293. };
  2294. exports.isWindows = options => {
  2295. if (options && typeof options.windows === 'boolean') {
  2296. return options.windows;
  2297. }
  2298. return win32 === true || path.sep === '\\';
  2299. };
  2300. exports.escapeLast = (input, char, lastIdx) => {
  2301. const idx = input.lastIndexOf(char, lastIdx);
  2302. if (idx === -1) return input;
  2303. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2304. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2305. };
  2306. exports.removePrefix = (input, state = {}) => {
  2307. let output = input;
  2308. if (output.startsWith('./')) {
  2309. output = output.slice(2);
  2310. state.prefix = './';
  2311. }
  2312. return output;
  2313. };
  2314. exports.wrapOutput = (input, state = {}, options = {}) => {
  2315. const prepend = options.contains ? '' : '^';
  2316. const append = options.contains ? '' : '$';
  2317. let output = `${prepend}(?:${input})${append}`;
  2318. if (state.negated === true) {
  2319. output = `(?:^(?!${output}).*$)`;
  2320. }
  2321. return output;
  2322. };
  2323. } (utils$3));
  2324. const utils$2 = utils$3;
  2325. const {
  2326. CHAR_ASTERISK, /* * */
  2327. CHAR_AT, /* @ */
  2328. CHAR_BACKWARD_SLASH, /* \ */
  2329. CHAR_COMMA, /* , */
  2330. CHAR_DOT, /* . */
  2331. CHAR_EXCLAMATION_MARK, /* ! */
  2332. CHAR_FORWARD_SLASH, /* / */
  2333. CHAR_LEFT_CURLY_BRACE, /* { */
  2334. CHAR_LEFT_PARENTHESES, /* ( */
  2335. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2336. CHAR_PLUS, /* + */
  2337. CHAR_QUESTION_MARK, /* ? */
  2338. CHAR_RIGHT_CURLY_BRACE, /* } */
  2339. CHAR_RIGHT_PARENTHESES, /* ) */
  2340. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2341. } = constants$2;
  2342. const isPathSeparator = code => {
  2343. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2344. };
  2345. const depth = token => {
  2346. if (token.isPrefix !== true) {
  2347. token.depth = token.isGlobstar ? Infinity : 1;
  2348. }
  2349. };
  2350. /**
  2351. * Quickly scans a glob pattern and returns an object with a handful of
  2352. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2353. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2354. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2355. *
  2356. * ```js
  2357. * const pm = require('picomatch');
  2358. * console.log(pm.scan('foo/bar/*.js'));
  2359. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2360. * ```
  2361. * @param {String} `str`
  2362. * @param {Object} `options`
  2363. * @return {Object} Returns an object with tokens and regex source string.
  2364. * @api public
  2365. */
  2366. const scan$1 = (input, options) => {
  2367. const opts = options || {};
  2368. const length = input.length - 1;
  2369. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2370. const slashes = [];
  2371. const tokens = [];
  2372. const parts = [];
  2373. let str = input;
  2374. let index = -1;
  2375. let start = 0;
  2376. let lastIndex = 0;
  2377. let isBrace = false;
  2378. let isBracket = false;
  2379. let isGlob = false;
  2380. let isExtglob = false;
  2381. let isGlobstar = false;
  2382. let braceEscaped = false;
  2383. let backslashes = false;
  2384. let negated = false;
  2385. let negatedExtglob = false;
  2386. let finished = false;
  2387. let braces = 0;
  2388. let prev;
  2389. let code;
  2390. let token = { value: '', depth: 0, isGlob: false };
  2391. const eos = () => index >= length;
  2392. const peek = () => str.charCodeAt(index + 1);
  2393. const advance = () => {
  2394. prev = code;
  2395. return str.charCodeAt(++index);
  2396. };
  2397. while (index < length) {
  2398. code = advance();
  2399. let next;
  2400. if (code === CHAR_BACKWARD_SLASH) {
  2401. backslashes = token.backslashes = true;
  2402. code = advance();
  2403. if (code === CHAR_LEFT_CURLY_BRACE) {
  2404. braceEscaped = true;
  2405. }
  2406. continue;
  2407. }
  2408. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2409. braces++;
  2410. while (eos() !== true && (code = advance())) {
  2411. if (code === CHAR_BACKWARD_SLASH) {
  2412. backslashes = token.backslashes = true;
  2413. advance();
  2414. continue;
  2415. }
  2416. if (code === CHAR_LEFT_CURLY_BRACE) {
  2417. braces++;
  2418. continue;
  2419. }
  2420. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2421. isBrace = token.isBrace = true;
  2422. isGlob = token.isGlob = true;
  2423. finished = true;
  2424. if (scanToEnd === true) {
  2425. continue;
  2426. }
  2427. break;
  2428. }
  2429. if (braceEscaped !== true && code === CHAR_COMMA) {
  2430. isBrace = token.isBrace = true;
  2431. isGlob = token.isGlob = true;
  2432. finished = true;
  2433. if (scanToEnd === true) {
  2434. continue;
  2435. }
  2436. break;
  2437. }
  2438. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2439. braces--;
  2440. if (braces === 0) {
  2441. braceEscaped = false;
  2442. isBrace = token.isBrace = true;
  2443. finished = true;
  2444. break;
  2445. }
  2446. }
  2447. }
  2448. if (scanToEnd === true) {
  2449. continue;
  2450. }
  2451. break;
  2452. }
  2453. if (code === CHAR_FORWARD_SLASH) {
  2454. slashes.push(index);
  2455. tokens.push(token);
  2456. token = { value: '', depth: 0, isGlob: false };
  2457. if (finished === true) continue;
  2458. if (prev === CHAR_DOT && index === (start + 1)) {
  2459. start += 2;
  2460. continue;
  2461. }
  2462. lastIndex = index + 1;
  2463. continue;
  2464. }
  2465. if (opts.noext !== true) {
  2466. const isExtglobChar = code === CHAR_PLUS
  2467. || code === CHAR_AT
  2468. || code === CHAR_ASTERISK
  2469. || code === CHAR_QUESTION_MARK
  2470. || code === CHAR_EXCLAMATION_MARK;
  2471. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  2472. isGlob = token.isGlob = true;
  2473. isExtglob = token.isExtglob = true;
  2474. finished = true;
  2475. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2476. negatedExtglob = true;
  2477. }
  2478. if (scanToEnd === true) {
  2479. while (eos() !== true && (code = advance())) {
  2480. if (code === CHAR_BACKWARD_SLASH) {
  2481. backslashes = token.backslashes = true;
  2482. code = advance();
  2483. continue;
  2484. }
  2485. if (code === CHAR_RIGHT_PARENTHESES) {
  2486. isGlob = token.isGlob = true;
  2487. finished = true;
  2488. break;
  2489. }
  2490. }
  2491. continue;
  2492. }
  2493. break;
  2494. }
  2495. }
  2496. if (code === CHAR_ASTERISK) {
  2497. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2498. isGlob = token.isGlob = true;
  2499. finished = true;
  2500. if (scanToEnd === true) {
  2501. continue;
  2502. }
  2503. break;
  2504. }
  2505. if (code === CHAR_QUESTION_MARK) {
  2506. isGlob = token.isGlob = true;
  2507. finished = true;
  2508. if (scanToEnd === true) {
  2509. continue;
  2510. }
  2511. break;
  2512. }
  2513. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  2514. while (eos() !== true && (next = advance())) {
  2515. if (next === CHAR_BACKWARD_SLASH) {
  2516. backslashes = token.backslashes = true;
  2517. advance();
  2518. continue;
  2519. }
  2520. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  2521. isBracket = token.isBracket = true;
  2522. isGlob = token.isGlob = true;
  2523. finished = true;
  2524. break;
  2525. }
  2526. }
  2527. if (scanToEnd === true) {
  2528. continue;
  2529. }
  2530. break;
  2531. }
  2532. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2533. negated = token.negated = true;
  2534. start++;
  2535. continue;
  2536. }
  2537. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  2538. isGlob = token.isGlob = true;
  2539. if (scanToEnd === true) {
  2540. while (eos() !== true && (code = advance())) {
  2541. if (code === CHAR_LEFT_PARENTHESES) {
  2542. backslashes = token.backslashes = true;
  2543. code = advance();
  2544. continue;
  2545. }
  2546. if (code === CHAR_RIGHT_PARENTHESES) {
  2547. finished = true;
  2548. break;
  2549. }
  2550. }
  2551. continue;
  2552. }
  2553. break;
  2554. }
  2555. if (isGlob === true) {
  2556. finished = true;
  2557. if (scanToEnd === true) {
  2558. continue;
  2559. }
  2560. break;
  2561. }
  2562. }
  2563. if (opts.noext === true) {
  2564. isExtglob = false;
  2565. isGlob = false;
  2566. }
  2567. let base = str;
  2568. let prefix = '';
  2569. let glob = '';
  2570. if (start > 0) {
  2571. prefix = str.slice(0, start);
  2572. str = str.slice(start);
  2573. lastIndex -= start;
  2574. }
  2575. if (base && isGlob === true && lastIndex > 0) {
  2576. base = str.slice(0, lastIndex);
  2577. glob = str.slice(lastIndex);
  2578. } else if (isGlob === true) {
  2579. base = '';
  2580. glob = str;
  2581. } else {
  2582. base = str;
  2583. }
  2584. if (base && base !== '' && base !== '/' && base !== str) {
  2585. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2586. base = base.slice(0, -1);
  2587. }
  2588. }
  2589. if (opts.unescape === true) {
  2590. if (glob) glob = utils$2.removeBackslashes(glob);
  2591. if (base && backslashes === true) {
  2592. base = utils$2.removeBackslashes(base);
  2593. }
  2594. }
  2595. const state = {
  2596. prefix,
  2597. input,
  2598. start,
  2599. base,
  2600. glob,
  2601. isBrace,
  2602. isBracket,
  2603. isGlob,
  2604. isExtglob,
  2605. isGlobstar,
  2606. negated,
  2607. negatedExtglob
  2608. };
  2609. if (opts.tokens === true) {
  2610. state.maxDepth = 0;
  2611. if (!isPathSeparator(code)) {
  2612. tokens.push(token);
  2613. }
  2614. state.tokens = tokens;
  2615. }
  2616. if (opts.parts === true || opts.tokens === true) {
  2617. let prevIndex;
  2618. for (let idx = 0; idx < slashes.length; idx++) {
  2619. const n = prevIndex ? prevIndex + 1 : start;
  2620. const i = slashes[idx];
  2621. const value = input.slice(n, i);
  2622. if (opts.tokens) {
  2623. if (idx === 0 && start !== 0) {
  2624. tokens[idx].isPrefix = true;
  2625. tokens[idx].value = prefix;
  2626. } else {
  2627. tokens[idx].value = value;
  2628. }
  2629. depth(tokens[idx]);
  2630. state.maxDepth += tokens[idx].depth;
  2631. }
  2632. if (idx !== 0 || value !== '') {
  2633. parts.push(value);
  2634. }
  2635. prevIndex = i;
  2636. }
  2637. if (prevIndex && prevIndex + 1 < input.length) {
  2638. const value = input.slice(prevIndex + 1);
  2639. parts.push(value);
  2640. if (opts.tokens) {
  2641. tokens[tokens.length - 1].value = value;
  2642. depth(tokens[tokens.length - 1]);
  2643. state.maxDepth += tokens[tokens.length - 1].depth;
  2644. }
  2645. }
  2646. state.slashes = slashes;
  2647. state.parts = parts;
  2648. }
  2649. return state;
  2650. };
  2651. var scan_1 = scan$1;
  2652. const constants$1 = constants$2;
  2653. const utils$1 = utils$3;
  2654. /**
  2655. * Constants
  2656. */
  2657. const {
  2658. MAX_LENGTH,
  2659. POSIX_REGEX_SOURCE,
  2660. REGEX_NON_SPECIAL_CHARS,
  2661. REGEX_SPECIAL_CHARS_BACKREF,
  2662. REPLACEMENTS
  2663. } = constants$1;
  2664. /**
  2665. * Helpers
  2666. */
  2667. const expandRange = (args, options) => {
  2668. if (typeof options.expandRange === 'function') {
  2669. return options.expandRange(...args, options);
  2670. }
  2671. args.sort();
  2672. const value = `[${args.join('-')}]`;
  2673. return value;
  2674. };
  2675. /**
  2676. * Create the message for a syntax error
  2677. */
  2678. const syntaxError = (type, char) => {
  2679. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2680. };
  2681. /**
  2682. * Parse the given input string.
  2683. * @param {String} input
  2684. * @param {Object} options
  2685. * @return {Object}
  2686. */
  2687. const parse$1 = (input, options) => {
  2688. if (typeof input !== 'string') {
  2689. throw new TypeError('Expected a string');
  2690. }
  2691. input = REPLACEMENTS[input] || input;
  2692. const opts = { ...options };
  2693. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  2694. let len = input.length;
  2695. if (len > max) {
  2696. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2697. }
  2698. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2699. const tokens = [bos];
  2700. const capture = opts.capture ? '' : '?:';
  2701. const win32 = utils$1.isWindows(options);
  2702. // create constants based on platform, for windows or posix
  2703. const PLATFORM_CHARS = constants$1.globChars(win32);
  2704. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  2705. const {
  2706. DOT_LITERAL,
  2707. PLUS_LITERAL,
  2708. SLASH_LITERAL,
  2709. ONE_CHAR,
  2710. DOTS_SLASH,
  2711. NO_DOT,
  2712. NO_DOT_SLASH,
  2713. NO_DOTS_SLASH,
  2714. QMARK,
  2715. QMARK_NO_DOT,
  2716. STAR,
  2717. START_ANCHOR
  2718. } = PLATFORM_CHARS;
  2719. const globstar = opts => {
  2720. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2721. };
  2722. const nodot = opts.dot ? '' : NO_DOT;
  2723. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2724. let star = opts.bash === true ? globstar(opts) : STAR;
  2725. if (opts.capture) {
  2726. star = `(${star})`;
  2727. }
  2728. // minimatch options support
  2729. if (typeof opts.noext === 'boolean') {
  2730. opts.noextglob = opts.noext;
  2731. }
  2732. const state = {
  2733. input,
  2734. index: -1,
  2735. start: 0,
  2736. dot: opts.dot === true,
  2737. consumed: '',
  2738. output: '',
  2739. prefix: '',
  2740. backtrack: false,
  2741. negated: false,
  2742. brackets: 0,
  2743. braces: 0,
  2744. parens: 0,
  2745. quotes: 0,
  2746. globstar: false,
  2747. tokens
  2748. };
  2749. input = utils$1.removePrefix(input, state);
  2750. len = input.length;
  2751. const extglobs = [];
  2752. const braces = [];
  2753. const stack = [];
  2754. let prev = bos;
  2755. let value;
  2756. /**
  2757. * Tokenizing helpers
  2758. */
  2759. const eos = () => state.index === len - 1;
  2760. const peek = state.peek = (n = 1) => input[state.index + n];
  2761. const advance = state.advance = () => input[++state.index] || '';
  2762. const remaining = () => input.slice(state.index + 1);
  2763. const consume = (value = '', num = 0) => {
  2764. state.consumed += value;
  2765. state.index += num;
  2766. };
  2767. const append = token => {
  2768. state.output += token.output != null ? token.output : token.value;
  2769. consume(token.value);
  2770. };
  2771. const negate = () => {
  2772. let count = 1;
  2773. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2774. advance();
  2775. state.start++;
  2776. count++;
  2777. }
  2778. if (count % 2 === 0) {
  2779. return false;
  2780. }
  2781. state.negated = true;
  2782. state.start++;
  2783. return true;
  2784. };
  2785. const increment = type => {
  2786. state[type]++;
  2787. stack.push(type);
  2788. };
  2789. const decrement = type => {
  2790. state[type]--;
  2791. stack.pop();
  2792. };
  2793. /**
  2794. * Push tokens onto the tokens array. This helper speeds up
  2795. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2796. * and 2) helping us avoid creating extra tokens when consecutive
  2797. * characters are plain text. This improves performance and simplifies
  2798. * lookbehinds.
  2799. */
  2800. const push = tok => {
  2801. if (prev.type === 'globstar') {
  2802. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2803. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2804. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2805. state.output = state.output.slice(0, -prev.output.length);
  2806. prev.type = 'star';
  2807. prev.value = '*';
  2808. prev.output = star;
  2809. state.output += prev.output;
  2810. }
  2811. }
  2812. if (extglobs.length && tok.type !== 'paren') {
  2813. extglobs[extglobs.length - 1].inner += tok.value;
  2814. }
  2815. if (tok.value || tok.output) append(tok);
  2816. if (prev && prev.type === 'text' && tok.type === 'text') {
  2817. prev.value += tok.value;
  2818. prev.output = (prev.output || '') + tok.value;
  2819. return;
  2820. }
  2821. tok.prev = prev;
  2822. tokens.push(tok);
  2823. prev = tok;
  2824. };
  2825. const extglobOpen = (type, value) => {
  2826. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2827. token.prev = prev;
  2828. token.parens = state.parens;
  2829. token.output = state.output;
  2830. const output = (opts.capture ? '(' : '') + token.open;
  2831. increment('parens');
  2832. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2833. push({ type: 'paren', extglob: true, value: advance(), output });
  2834. extglobs.push(token);
  2835. };
  2836. const extglobClose = token => {
  2837. let output = token.close + (opts.capture ? ')' : '');
  2838. let rest;
  2839. if (token.type === 'negate') {
  2840. let extglobStar = star;
  2841. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2842. extglobStar = globstar(opts);
  2843. }
  2844. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2845. output = token.close = `)$))${extglobStar}`;
  2846. }
  2847. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2848. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  2849. // In this case, we need to parse the string and use it in the output of the original pattern.
  2850. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  2851. //
  2852. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  2853. const expression = parse$1(rest, { ...options, fastpaths: false }).output;
  2854. output = token.close = `)${expression})${extglobStar})`;
  2855. }
  2856. if (token.prev.type === 'bos') {
  2857. state.negatedExtglob = true;
  2858. }
  2859. }
  2860. push({ type: 'paren', extglob: true, value, output });
  2861. decrement('parens');
  2862. };
  2863. /**
  2864. * Fast paths
  2865. */
  2866. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2867. let backslashes = false;
  2868. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2869. if (first === '\\') {
  2870. backslashes = true;
  2871. return m;
  2872. }
  2873. if (first === '?') {
  2874. if (esc) {
  2875. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2876. }
  2877. if (index === 0) {
  2878. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2879. }
  2880. return QMARK.repeat(chars.length);
  2881. }
  2882. if (first === '.') {
  2883. return DOT_LITERAL.repeat(chars.length);
  2884. }
  2885. if (first === '*') {
  2886. if (esc) {
  2887. return esc + first + (rest ? star : '');
  2888. }
  2889. return star;
  2890. }
  2891. return esc ? m : `\\${m}`;
  2892. });
  2893. if (backslashes === true) {
  2894. if (opts.unescape === true) {
  2895. output = output.replace(/\\/g, '');
  2896. } else {
  2897. output = output.replace(/\\+/g, m => {
  2898. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  2899. });
  2900. }
  2901. }
  2902. if (output === input && opts.contains === true) {
  2903. state.output = input;
  2904. return state;
  2905. }
  2906. state.output = utils$1.wrapOutput(output, state, options);
  2907. return state;
  2908. }
  2909. /**
  2910. * Tokenize input until we reach end-of-string
  2911. */
  2912. while (!eos()) {
  2913. value = advance();
  2914. if (value === '\u0000') {
  2915. continue;
  2916. }
  2917. /**
  2918. * Escaped characters
  2919. */
  2920. if (value === '\\') {
  2921. const next = peek();
  2922. if (next === '/' && opts.bash !== true) {
  2923. continue;
  2924. }
  2925. if (next === '.' || next === ';') {
  2926. continue;
  2927. }
  2928. if (!next) {
  2929. value += '\\';
  2930. push({ type: 'text', value });
  2931. continue;
  2932. }
  2933. // collapse slashes to reduce potential for exploits
  2934. const match = /^\\+/.exec(remaining());
  2935. let slashes = 0;
  2936. if (match && match[0].length > 2) {
  2937. slashes = match[0].length;
  2938. state.index += slashes;
  2939. if (slashes % 2 !== 0) {
  2940. value += '\\';
  2941. }
  2942. }
  2943. if (opts.unescape === true) {
  2944. value = advance();
  2945. } else {
  2946. value += advance();
  2947. }
  2948. if (state.brackets === 0) {
  2949. push({ type: 'text', value });
  2950. continue;
  2951. }
  2952. }
  2953. /**
  2954. * If we're inside a regex character class, continue
  2955. * until we reach the closing bracket.
  2956. */
  2957. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  2958. if (opts.posix !== false && value === ':') {
  2959. const inner = prev.value.slice(1);
  2960. if (inner.includes('[')) {
  2961. prev.posix = true;
  2962. if (inner.includes(':')) {
  2963. const idx = prev.value.lastIndexOf('[');
  2964. const pre = prev.value.slice(0, idx);
  2965. const rest = prev.value.slice(idx + 2);
  2966. const posix = POSIX_REGEX_SOURCE[rest];
  2967. if (posix) {
  2968. prev.value = pre + posix;
  2969. state.backtrack = true;
  2970. advance();
  2971. if (!bos.output && tokens.indexOf(prev) === 1) {
  2972. bos.output = ONE_CHAR;
  2973. }
  2974. continue;
  2975. }
  2976. }
  2977. }
  2978. }
  2979. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  2980. value = `\\${value}`;
  2981. }
  2982. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  2983. value = `\\${value}`;
  2984. }
  2985. if (opts.posix === true && value === '!' && prev.value === '[') {
  2986. value = '^';
  2987. }
  2988. prev.value += value;
  2989. append({ value });
  2990. continue;
  2991. }
  2992. /**
  2993. * If we're inside a quoted string, continue
  2994. * until we reach the closing double quote.
  2995. */
  2996. if (state.quotes === 1 && value !== '"') {
  2997. value = utils$1.escapeRegex(value);
  2998. prev.value += value;
  2999. append({ value });
  3000. continue;
  3001. }
  3002. /**
  3003. * Double quotes
  3004. */
  3005. if (value === '"') {
  3006. state.quotes = state.quotes === 1 ? 0 : 1;
  3007. if (opts.keepQuotes === true) {
  3008. push({ type: 'text', value });
  3009. }
  3010. continue;
  3011. }
  3012. /**
  3013. * Parentheses
  3014. */
  3015. if (value === '(') {
  3016. increment('parens');
  3017. push({ type: 'paren', value });
  3018. continue;
  3019. }
  3020. if (value === ')') {
  3021. if (state.parens === 0 && opts.strictBrackets === true) {
  3022. throw new SyntaxError(syntaxError('opening', '('));
  3023. }
  3024. const extglob = extglobs[extglobs.length - 1];
  3025. if (extglob && state.parens === extglob.parens + 1) {
  3026. extglobClose(extglobs.pop());
  3027. continue;
  3028. }
  3029. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3030. decrement('parens');
  3031. continue;
  3032. }
  3033. /**
  3034. * Square brackets
  3035. */
  3036. if (value === '[') {
  3037. if (opts.nobracket === true || !remaining().includes(']')) {
  3038. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3039. throw new SyntaxError(syntaxError('closing', ']'));
  3040. }
  3041. value = `\\${value}`;
  3042. } else {
  3043. increment('brackets');
  3044. }
  3045. push({ type: 'bracket', value });
  3046. continue;
  3047. }
  3048. if (value === ']') {
  3049. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3050. push({ type: 'text', value, output: `\\${value}` });
  3051. continue;
  3052. }
  3053. if (state.brackets === 0) {
  3054. if (opts.strictBrackets === true) {
  3055. throw new SyntaxError(syntaxError('opening', '['));
  3056. }
  3057. push({ type: 'text', value, output: `\\${value}` });
  3058. continue;
  3059. }
  3060. decrement('brackets');
  3061. const prevValue = prev.value.slice(1);
  3062. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3063. value = `/${value}`;
  3064. }
  3065. prev.value += value;
  3066. append({ value });
  3067. // when literal brackets are explicitly disabled
  3068. // assume we should match with a regex character class
  3069. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3070. continue;
  3071. }
  3072. const escaped = utils$1.escapeRegex(prev.value);
  3073. state.output = state.output.slice(0, -prev.value.length);
  3074. // when literal brackets are explicitly enabled
  3075. // assume we should escape the brackets to match literal characters
  3076. if (opts.literalBrackets === true) {
  3077. state.output += escaped;
  3078. prev.value = escaped;
  3079. continue;
  3080. }
  3081. // when the user specifies nothing, try to match both
  3082. prev.value = `(${capture}${escaped}|${prev.value})`;
  3083. state.output += prev.value;
  3084. continue;
  3085. }
  3086. /**
  3087. * Braces
  3088. */
  3089. if (value === '{' && opts.nobrace !== true) {
  3090. increment('braces');
  3091. const open = {
  3092. type: 'brace',
  3093. value,
  3094. output: '(',
  3095. outputIndex: state.output.length,
  3096. tokensIndex: state.tokens.length
  3097. };
  3098. braces.push(open);
  3099. push(open);
  3100. continue;
  3101. }
  3102. if (value === '}') {
  3103. const brace = braces[braces.length - 1];
  3104. if (opts.nobrace === true || !brace) {
  3105. push({ type: 'text', value, output: value });
  3106. continue;
  3107. }
  3108. let output = ')';
  3109. if (brace.dots === true) {
  3110. const arr = tokens.slice();
  3111. const range = [];
  3112. for (let i = arr.length - 1; i >= 0; i--) {
  3113. tokens.pop();
  3114. if (arr[i].type === 'brace') {
  3115. break;
  3116. }
  3117. if (arr[i].type !== 'dots') {
  3118. range.unshift(arr[i].value);
  3119. }
  3120. }
  3121. output = expandRange(range, opts);
  3122. state.backtrack = true;
  3123. }
  3124. if (brace.comma !== true && brace.dots !== true) {
  3125. const out = state.output.slice(0, brace.outputIndex);
  3126. const toks = state.tokens.slice(brace.tokensIndex);
  3127. brace.value = brace.output = '\\{';
  3128. value = output = '\\}';
  3129. state.output = out;
  3130. for (const t of toks) {
  3131. state.output += (t.output || t.value);
  3132. }
  3133. }
  3134. push({ type: 'brace', value, output });
  3135. decrement('braces');
  3136. braces.pop();
  3137. continue;
  3138. }
  3139. /**
  3140. * Pipes
  3141. */
  3142. if (value === '|') {
  3143. if (extglobs.length > 0) {
  3144. extglobs[extglobs.length - 1].conditions++;
  3145. }
  3146. push({ type: 'text', value });
  3147. continue;
  3148. }
  3149. /**
  3150. * Commas
  3151. */
  3152. if (value === ',') {
  3153. let output = value;
  3154. const brace = braces[braces.length - 1];
  3155. if (brace && stack[stack.length - 1] === 'braces') {
  3156. brace.comma = true;
  3157. output = '|';
  3158. }
  3159. push({ type: 'comma', value, output });
  3160. continue;
  3161. }
  3162. /**
  3163. * Slashes
  3164. */
  3165. if (value === '/') {
  3166. // if the beginning of the glob is "./", advance the start
  3167. // to the current index, and don't add the "./" characters
  3168. // to the state. This greatly simplifies lookbehinds when
  3169. // checking for BOS characters like "!" and "." (not "./")
  3170. if (prev.type === 'dot' && state.index === state.start + 1) {
  3171. state.start = state.index + 1;
  3172. state.consumed = '';
  3173. state.output = '';
  3174. tokens.pop();
  3175. prev = bos; // reset "prev" to the first token
  3176. continue;
  3177. }
  3178. push({ type: 'slash', value, output: SLASH_LITERAL });
  3179. continue;
  3180. }
  3181. /**
  3182. * Dots
  3183. */
  3184. if (value === '.') {
  3185. if (state.braces > 0 && prev.type === 'dot') {
  3186. if (prev.value === '.') prev.output = DOT_LITERAL;
  3187. const brace = braces[braces.length - 1];
  3188. prev.type = 'dots';
  3189. prev.output += value;
  3190. prev.value += value;
  3191. brace.dots = true;
  3192. continue;
  3193. }
  3194. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3195. push({ type: 'text', value, output: DOT_LITERAL });
  3196. continue;
  3197. }
  3198. push({ type: 'dot', value, output: DOT_LITERAL });
  3199. continue;
  3200. }
  3201. /**
  3202. * Question marks
  3203. */
  3204. if (value === '?') {
  3205. const isGroup = prev && prev.value === '(';
  3206. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3207. extglobOpen('qmark', value);
  3208. continue;
  3209. }
  3210. if (prev && prev.type === 'paren') {
  3211. const next = peek();
  3212. let output = value;
  3213. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3214. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3215. }
  3216. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3217. output = `\\${value}`;
  3218. }
  3219. push({ type: 'text', value, output });
  3220. continue;
  3221. }
  3222. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3223. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3224. continue;
  3225. }
  3226. push({ type: 'qmark', value, output: QMARK });
  3227. continue;
  3228. }
  3229. /**
  3230. * Exclamation
  3231. */
  3232. if (value === '!') {
  3233. if (opts.noextglob !== true && peek() === '(') {
  3234. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3235. extglobOpen('negate', value);
  3236. continue;
  3237. }
  3238. }
  3239. if (opts.nonegate !== true && state.index === 0) {
  3240. negate();
  3241. continue;
  3242. }
  3243. }
  3244. /**
  3245. * Plus
  3246. */
  3247. if (value === '+') {
  3248. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3249. extglobOpen('plus', value);
  3250. continue;
  3251. }
  3252. if ((prev && prev.value === '(') || opts.regex === false) {
  3253. push({ type: 'plus', value, output: PLUS_LITERAL });
  3254. continue;
  3255. }
  3256. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3257. push({ type: 'plus', value });
  3258. continue;
  3259. }
  3260. push({ type: 'plus', value: PLUS_LITERAL });
  3261. continue;
  3262. }
  3263. /**
  3264. * Plain text
  3265. */
  3266. if (value === '@') {
  3267. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3268. push({ type: 'at', extglob: true, value, output: '' });
  3269. continue;
  3270. }
  3271. push({ type: 'text', value });
  3272. continue;
  3273. }
  3274. /**
  3275. * Plain text
  3276. */
  3277. if (value !== '*') {
  3278. if (value === '$' || value === '^') {
  3279. value = `\\${value}`;
  3280. }
  3281. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3282. if (match) {
  3283. value += match[0];
  3284. state.index += match[0].length;
  3285. }
  3286. push({ type: 'text', value });
  3287. continue;
  3288. }
  3289. /**
  3290. * Stars
  3291. */
  3292. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3293. prev.type = 'star';
  3294. prev.star = true;
  3295. prev.value += value;
  3296. prev.output = star;
  3297. state.backtrack = true;
  3298. state.globstar = true;
  3299. consume(value);
  3300. continue;
  3301. }
  3302. let rest = remaining();
  3303. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3304. extglobOpen('star', value);
  3305. continue;
  3306. }
  3307. if (prev.type === 'star') {
  3308. if (opts.noglobstar === true) {
  3309. consume(value);
  3310. continue;
  3311. }
  3312. const prior = prev.prev;
  3313. const before = prior.prev;
  3314. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3315. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3316. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3317. push({ type: 'star', value, output: '' });
  3318. continue;
  3319. }
  3320. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3321. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3322. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3323. push({ type: 'star', value, output: '' });
  3324. continue;
  3325. }
  3326. // strip consecutive `/**/`
  3327. while (rest.slice(0, 3) === '/**') {
  3328. const after = input[state.index + 4];
  3329. if (after && after !== '/') {
  3330. break;
  3331. }
  3332. rest = rest.slice(3);
  3333. consume('/**', 3);
  3334. }
  3335. if (prior.type === 'bos' && eos()) {
  3336. prev.type = 'globstar';
  3337. prev.value += value;
  3338. prev.output = globstar(opts);
  3339. state.output = prev.output;
  3340. state.globstar = true;
  3341. consume(value);
  3342. continue;
  3343. }
  3344. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3345. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3346. prior.output = `(?:${prior.output}`;
  3347. prev.type = 'globstar';
  3348. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3349. prev.value += value;
  3350. state.globstar = true;
  3351. state.output += prior.output + prev.output;
  3352. consume(value);
  3353. continue;
  3354. }
  3355. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3356. const end = rest[1] !== void 0 ? '|$' : '';
  3357. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3358. prior.output = `(?:${prior.output}`;
  3359. prev.type = 'globstar';
  3360. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3361. prev.value += value;
  3362. state.output += prior.output + prev.output;
  3363. state.globstar = true;
  3364. consume(value + advance());
  3365. push({ type: 'slash', value: '/', output: '' });
  3366. continue;
  3367. }
  3368. if (prior.type === 'bos' && rest[0] === '/') {
  3369. prev.type = 'globstar';
  3370. prev.value += value;
  3371. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3372. state.output = prev.output;
  3373. state.globstar = true;
  3374. consume(value + advance());
  3375. push({ type: 'slash', value: '/', output: '' });
  3376. continue;
  3377. }
  3378. // remove single star from output
  3379. state.output = state.output.slice(0, -prev.output.length);
  3380. // reset previous token to globstar
  3381. prev.type = 'globstar';
  3382. prev.output = globstar(opts);
  3383. prev.value += value;
  3384. // reset output with globstar
  3385. state.output += prev.output;
  3386. state.globstar = true;
  3387. consume(value);
  3388. continue;
  3389. }
  3390. const token = { type: 'star', value, output: star };
  3391. if (opts.bash === true) {
  3392. token.output = '.*?';
  3393. if (prev.type === 'bos' || prev.type === 'slash') {
  3394. token.output = nodot + token.output;
  3395. }
  3396. push(token);
  3397. continue;
  3398. }
  3399. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3400. token.output = value;
  3401. push(token);
  3402. continue;
  3403. }
  3404. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3405. if (prev.type === 'dot') {
  3406. state.output += NO_DOT_SLASH;
  3407. prev.output += NO_DOT_SLASH;
  3408. } else if (opts.dot === true) {
  3409. state.output += NO_DOTS_SLASH;
  3410. prev.output += NO_DOTS_SLASH;
  3411. } else {
  3412. state.output += nodot;
  3413. prev.output += nodot;
  3414. }
  3415. if (peek() !== '*') {
  3416. state.output += ONE_CHAR;
  3417. prev.output += ONE_CHAR;
  3418. }
  3419. }
  3420. push(token);
  3421. }
  3422. while (state.brackets > 0) {
  3423. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3424. state.output = utils$1.escapeLast(state.output, '[');
  3425. decrement('brackets');
  3426. }
  3427. while (state.parens > 0) {
  3428. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3429. state.output = utils$1.escapeLast(state.output, '(');
  3430. decrement('parens');
  3431. }
  3432. while (state.braces > 0) {
  3433. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3434. state.output = utils$1.escapeLast(state.output, '{');
  3435. decrement('braces');
  3436. }
  3437. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3438. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3439. }
  3440. // rebuild the output if we had to backtrack at any point
  3441. if (state.backtrack === true) {
  3442. state.output = '';
  3443. for (const token of state.tokens) {
  3444. state.output += token.output != null ? token.output : token.value;
  3445. if (token.suffix) {
  3446. state.output += token.suffix;
  3447. }
  3448. }
  3449. }
  3450. return state;
  3451. };
  3452. /**
  3453. * Fast paths for creating regular expressions for common glob patterns.
  3454. * This can significantly speed up processing and has very little downside
  3455. * impact when none of the fast paths match.
  3456. */
  3457. parse$1.fastpaths = (input, options) => {
  3458. const opts = { ...options };
  3459. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3460. const len = input.length;
  3461. if (len > max) {
  3462. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3463. }
  3464. input = REPLACEMENTS[input] || input;
  3465. const win32 = utils$1.isWindows(options);
  3466. // create constants based on platform, for windows or posix
  3467. const {
  3468. DOT_LITERAL,
  3469. SLASH_LITERAL,
  3470. ONE_CHAR,
  3471. DOTS_SLASH,
  3472. NO_DOT,
  3473. NO_DOTS,
  3474. NO_DOTS_SLASH,
  3475. STAR,
  3476. START_ANCHOR
  3477. } = constants$1.globChars(win32);
  3478. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3479. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3480. const capture = opts.capture ? '' : '?:';
  3481. const state = { negated: false, prefix: '' };
  3482. let star = opts.bash === true ? '.*?' : STAR;
  3483. if (opts.capture) {
  3484. star = `(${star})`;
  3485. }
  3486. const globstar = opts => {
  3487. if (opts.noglobstar === true) return star;
  3488. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3489. };
  3490. const create = str => {
  3491. switch (str) {
  3492. case '*':
  3493. return `${nodot}${ONE_CHAR}${star}`;
  3494. case '.*':
  3495. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3496. case '*.*':
  3497. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3498. case '*/*':
  3499. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3500. case '**':
  3501. return nodot + globstar(opts);
  3502. case '**/*':
  3503. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3504. case '**/*.*':
  3505. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3506. case '**/.*':
  3507. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3508. default: {
  3509. const match = /^(.*?)\.(\w+)$/.exec(str);
  3510. if (!match) return;
  3511. const source = create(match[1]);
  3512. if (!source) return;
  3513. return source + DOT_LITERAL + match[2];
  3514. }
  3515. }
  3516. };
  3517. const output = utils$1.removePrefix(input, state);
  3518. let source = create(output);
  3519. if (source && opts.strictSlashes !== true) {
  3520. source += `${SLASH_LITERAL}?`;
  3521. }
  3522. return source;
  3523. };
  3524. var parse_1 = parse$1;
  3525. const path = require$$0;
  3526. const scan = scan_1;
  3527. const parse = parse_1;
  3528. const utils = utils$3;
  3529. const constants = constants$2;
  3530. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  3531. /**
  3532. * Creates a matcher function from one or more glob patterns. The
  3533. * returned function takes a string to match as its first argument,
  3534. * and returns true if the string is a match. The returned matcher
  3535. * function also takes a boolean as the second argument that, when true,
  3536. * returns an object with additional information.
  3537. *
  3538. * ```js
  3539. * const picomatch = require('picomatch');
  3540. * // picomatch(glob[, options]);
  3541. *
  3542. * const isMatch = picomatch('*.!(*a)');
  3543. * console.log(isMatch('a.a')); //=> false
  3544. * console.log(isMatch('a.b')); //=> true
  3545. * ```
  3546. * @name picomatch
  3547. * @param {String|Array} `globs` One or more glob patterns.
  3548. * @param {Object=} `options`
  3549. * @return {Function=} Returns a matcher function.
  3550. * @api public
  3551. */
  3552. const picomatch = (glob, options, returnState = false) => {
  3553. if (Array.isArray(glob)) {
  3554. const fns = glob.map(input => picomatch(input, options, returnState));
  3555. const arrayMatcher = str => {
  3556. for (const isMatch of fns) {
  3557. const state = isMatch(str);
  3558. if (state) return state;
  3559. }
  3560. return false;
  3561. };
  3562. return arrayMatcher;
  3563. }
  3564. const isState = isObject(glob) && glob.tokens && glob.input;
  3565. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3566. throw new TypeError('Expected pattern to be a non-empty string');
  3567. }
  3568. const opts = options || {};
  3569. const posix = utils.isWindows(options);
  3570. const regex = isState
  3571. ? picomatch.compileRe(glob, options)
  3572. : picomatch.makeRe(glob, options, false, true);
  3573. const state = regex.state;
  3574. delete regex.state;
  3575. let isIgnored = () => false;
  3576. if (opts.ignore) {
  3577. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3578. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  3579. }
  3580. const matcher = (input, returnObject = false) => {
  3581. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  3582. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3583. if (typeof opts.onResult === 'function') {
  3584. opts.onResult(result);
  3585. }
  3586. if (isMatch === false) {
  3587. result.isMatch = false;
  3588. return returnObject ? result : false;
  3589. }
  3590. if (isIgnored(input)) {
  3591. if (typeof opts.onIgnore === 'function') {
  3592. opts.onIgnore(result);
  3593. }
  3594. result.isMatch = false;
  3595. return returnObject ? result : false;
  3596. }
  3597. if (typeof opts.onMatch === 'function') {
  3598. opts.onMatch(result);
  3599. }
  3600. return returnObject ? result : true;
  3601. };
  3602. if (returnState) {
  3603. matcher.state = state;
  3604. }
  3605. return matcher;
  3606. };
  3607. /**
  3608. * Test `input` with the given `regex`. This is used by the main
  3609. * `picomatch()` function to test the input string.
  3610. *
  3611. * ```js
  3612. * const picomatch = require('picomatch');
  3613. * // picomatch.test(input, regex[, options]);
  3614. *
  3615. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3616. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3617. * ```
  3618. * @param {String} `input` String to test.
  3619. * @param {RegExp} `regex`
  3620. * @return {Object} Returns an object with matching info.
  3621. * @api public
  3622. */
  3623. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  3624. if (typeof input !== 'string') {
  3625. throw new TypeError('Expected input to be a string');
  3626. }
  3627. if (input === '') {
  3628. return { isMatch: false, output: '' };
  3629. }
  3630. const opts = options || {};
  3631. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  3632. let match = input === glob;
  3633. let output = (match && format) ? format(input) : input;
  3634. if (match === false) {
  3635. output = format ? format(input) : input;
  3636. match = output === glob;
  3637. }
  3638. if (match === false || opts.capture === true) {
  3639. if (opts.matchBase === true || opts.basename === true) {
  3640. match = picomatch.matchBase(input, regex, options, posix);
  3641. } else {
  3642. match = regex.exec(output);
  3643. }
  3644. }
  3645. return { isMatch: Boolean(match), match, output };
  3646. };
  3647. /**
  3648. * Match the basename of a filepath.
  3649. *
  3650. * ```js
  3651. * const picomatch = require('picomatch');
  3652. * // picomatch.matchBase(input, glob[, options]);
  3653. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3654. * ```
  3655. * @param {String} `input` String to test.
  3656. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3657. * @return {Boolean}
  3658. * @api public
  3659. */
  3660. picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  3661. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  3662. return regex.test(path.basename(input));
  3663. };
  3664. /**
  3665. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3666. *
  3667. * ```js
  3668. * const picomatch = require('picomatch');
  3669. * // picomatch.isMatch(string, patterns[, options]);
  3670. *
  3671. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3672. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3673. * ```
  3674. * @param {String|Array} str The string to test.
  3675. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3676. * @param {Object} [options] See available [options](#options).
  3677. * @return {Boolean} Returns true if any patterns match `str`
  3678. * @api public
  3679. */
  3680. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  3681. /**
  3682. * Parse a glob pattern to create the source string for a regular
  3683. * expression.
  3684. *
  3685. * ```js
  3686. * const picomatch = require('picomatch');
  3687. * const result = picomatch.parse(pattern[, options]);
  3688. * ```
  3689. * @param {String} `pattern`
  3690. * @param {Object} `options`
  3691. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3692. * @api public
  3693. */
  3694. picomatch.parse = (pattern, options) => {
  3695. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  3696. return parse(pattern, { ...options, fastpaths: false });
  3697. };
  3698. /**
  3699. * Scan a glob pattern to separate the pattern into segments.
  3700. *
  3701. * ```js
  3702. * const picomatch = require('picomatch');
  3703. * // picomatch.scan(input[, options]);
  3704. *
  3705. * const result = picomatch.scan('!./foo/*.js');
  3706. * console.log(result);
  3707. * { prefix: '!./',
  3708. * input: '!./foo/*.js',
  3709. * start: 3,
  3710. * base: 'foo',
  3711. * glob: '*.js',
  3712. * isBrace: false,
  3713. * isBracket: false,
  3714. * isGlob: true,
  3715. * isExtglob: false,
  3716. * isGlobstar: false,
  3717. * negated: true }
  3718. * ```
  3719. * @param {String} `input` Glob pattern to scan.
  3720. * @param {Object} `options`
  3721. * @return {Object} Returns an object with
  3722. * @api public
  3723. */
  3724. picomatch.scan = (input, options) => scan(input, options);
  3725. /**
  3726. * Compile a regular expression from the `state` object returned by the
  3727. * [parse()](#parse) method.
  3728. *
  3729. * @param {Object} `state`
  3730. * @param {Object} `options`
  3731. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3732. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3733. * @return {RegExp}
  3734. * @api public
  3735. */
  3736. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3737. if (returnOutput === true) {
  3738. return state.output;
  3739. }
  3740. const opts = options || {};
  3741. const prepend = opts.contains ? '' : '^';
  3742. const append = opts.contains ? '' : '$';
  3743. let source = `${prepend}(?:${state.output})${append}`;
  3744. if (state && state.negated === true) {
  3745. source = `^(?!${source}).*$`;
  3746. }
  3747. const regex = picomatch.toRegex(source, options);
  3748. if (returnState === true) {
  3749. regex.state = state;
  3750. }
  3751. return regex;
  3752. };
  3753. /**
  3754. * Create a regular expression from a parsed glob pattern.
  3755. *
  3756. * ```js
  3757. * const picomatch = require('picomatch');
  3758. * const state = picomatch.parse('*.js');
  3759. * // picomatch.compileRe(state[, options]);
  3760. *
  3761. * console.log(picomatch.compileRe(state));
  3762. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3763. * ```
  3764. * @param {String} `state` The object returned from the `.parse` method.
  3765. * @param {Object} `options`
  3766. * @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.
  3767. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3768. * @return {RegExp} Returns a regex created from the given pattern.
  3769. * @api public
  3770. */
  3771. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3772. if (!input || typeof input !== 'string') {
  3773. throw new TypeError('Expected a non-empty string');
  3774. }
  3775. let parsed = { negated: false, fastpaths: true };
  3776. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3777. parsed.output = parse.fastpaths(input, options);
  3778. }
  3779. if (!parsed.output) {
  3780. parsed = parse(input, options);
  3781. }
  3782. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  3783. };
  3784. /**
  3785. * Create a regular expression from the given regex source string.
  3786. *
  3787. * ```js
  3788. * const picomatch = require('picomatch');
  3789. * // picomatch.toRegex(source[, options]);
  3790. *
  3791. * const { output } = picomatch.parse('*.js');
  3792. * console.log(picomatch.toRegex(output));
  3793. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3794. * ```
  3795. * @param {String} `source` Regular expression source string.
  3796. * @param {Object} `options`
  3797. * @return {RegExp}
  3798. * @api public
  3799. */
  3800. picomatch.toRegex = (source, options) => {
  3801. try {
  3802. const opts = options || {};
  3803. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3804. } catch (err) {
  3805. if (options && options.debug === true) throw err;
  3806. return /$^/;
  3807. }
  3808. };
  3809. /**
  3810. * Picomatch constants.
  3811. * @return {Object}
  3812. */
  3813. picomatch.constants = constants;
  3814. /**
  3815. * Expose "picomatch"
  3816. */
  3817. var picomatch_1 = picomatch;
  3818. (function (module) {
  3819. module.exports = picomatch_1;
  3820. } (picomatch$1));
  3821. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch$1.exports);
  3822. const extractors = {
  3823. ArrayPattern(names, param) {
  3824. for (const element of param.elements) {
  3825. if (element)
  3826. extractors[element.type](names, element);
  3827. }
  3828. },
  3829. AssignmentPattern(names, param) {
  3830. extractors[param.left.type](names, param.left);
  3831. },
  3832. Identifier(names, param) {
  3833. names.push(param.name);
  3834. },
  3835. MemberExpression() { },
  3836. ObjectPattern(names, param) {
  3837. for (const prop of param.properties) {
  3838. // @ts-ignore Typescript reports that this is not a valid type
  3839. if (prop.type === 'RestElement') {
  3840. extractors.RestElement(names, prop);
  3841. }
  3842. else {
  3843. extractors[prop.value.type](names, prop.value);
  3844. }
  3845. }
  3846. },
  3847. RestElement(names, param) {
  3848. extractors[param.argument.type](names, param.argument);
  3849. }
  3850. };
  3851. const extractAssignedNames = function extractAssignedNames(param) {
  3852. const names = [];
  3853. extractors[param.type](names, param);
  3854. return names;
  3855. };
  3856. // Helper since Typescript can't detect readonly arrays with Array.isArray
  3857. function isArray$1(arg) {
  3858. return Array.isArray(arg);
  3859. }
  3860. function ensureArray$1(thing) {
  3861. if (isArray$1(thing))
  3862. return thing;
  3863. if (thing == null)
  3864. return [];
  3865. return [thing];
  3866. }
  3867. const normalizePath = function normalizePath(filename) {
  3868. return filename.split(win32.sep).join(posix.sep);
  3869. };
  3870. function getMatcherString(id, resolutionBase) {
  3871. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('*')) {
  3872. return normalizePath(id);
  3873. }
  3874. // resolve('') is valid and will default to process.cwd()
  3875. const basePath = normalizePath(resolve(resolutionBase || ''))
  3876. // escape all possible (posix + win) path characters that might interfere with regex
  3877. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  3878. // Note that we use posix.join because:
  3879. // 1. the basePath has been normalized to use /
  3880. // 2. the incoming glob (id) matcher, also uses /
  3881. // otherwise Node will force backslash (\) on windows
  3882. return posix.join(basePath, normalizePath(id));
  3883. }
  3884. const createFilter = function createFilter(include, exclude, options) {
  3885. const resolutionBase = options && options.resolve;
  3886. const getMatcher = (id) => id instanceof RegExp
  3887. ? id
  3888. : {
  3889. test: (what) => {
  3890. // this refactor is a tad overly verbose but makes for easy debugging
  3891. const pattern = getMatcherString(id, resolutionBase);
  3892. const fn = pm(pattern, { dot: true });
  3893. const result = fn(what);
  3894. return result;
  3895. }
  3896. };
  3897. const includeMatchers = ensureArray$1(include).map(getMatcher);
  3898. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  3899. return function result(id) {
  3900. if (typeof id !== 'string')
  3901. return false;
  3902. if (/\0/.test(id))
  3903. return false;
  3904. const pathId = normalizePath(id);
  3905. for (let i = 0; i < excludeMatchers.length; ++i) {
  3906. const matcher = excludeMatchers[i];
  3907. if (matcher.test(pathId))
  3908. return false;
  3909. }
  3910. for (let i = 0; i < includeMatchers.length; ++i) {
  3911. const matcher = includeMatchers[i];
  3912. if (matcher.test(pathId))
  3913. return true;
  3914. }
  3915. return !includeMatchers.length;
  3916. };
  3917. };
  3918. 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';
  3919. 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';
  3920. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  3921. forbiddenIdentifiers.add('');
  3922. const BROKEN_FLOW_NONE = 0;
  3923. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  3924. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  3925. function createInclusionContext() {
  3926. return {
  3927. brokenFlow: BROKEN_FLOW_NONE,
  3928. includedCallArguments: new Set(),
  3929. includedLabels: new Set()
  3930. };
  3931. }
  3932. function createHasEffectsContext() {
  3933. return {
  3934. accessed: new PathTracker(),
  3935. assigned: new PathTracker(),
  3936. brokenFlow: BROKEN_FLOW_NONE,
  3937. called: new DiscriminatedPathTracker(),
  3938. ignore: {
  3939. breaks: false,
  3940. continues: false,
  3941. labels: new Set(),
  3942. returnYield: false
  3943. },
  3944. includedLabels: new Set(),
  3945. instantiated: new DiscriminatedPathTracker(),
  3946. replacedVariableInits: new Map()
  3947. };
  3948. }
  3949. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  3950. return Object.create(inheritedDescriptions, memberDescriptions);
  3951. }
  3952. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  3953. getLiteralValueAtPath() {
  3954. return undefined;
  3955. }
  3956. })();
  3957. const returnsUnknown = {
  3958. value: {
  3959. hasEffectsWhenCalled: null,
  3960. returns: UNKNOWN_EXPRESSION
  3961. }
  3962. };
  3963. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  3964. getReturnExpressionWhenCalledAtPath(path) {
  3965. if (path.length === 1) {
  3966. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  3967. }
  3968. return UNKNOWN_EXPRESSION;
  3969. }
  3970. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3971. if (interaction.type === INTERACTION_ACCESSED) {
  3972. return path.length > 1;
  3973. }
  3974. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3975. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  3976. }
  3977. return true;
  3978. }
  3979. })();
  3980. const returnsBoolean = {
  3981. value: {
  3982. hasEffectsWhenCalled: null,
  3983. returns: UNKNOWN_LITERAL_BOOLEAN
  3984. }
  3985. };
  3986. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  3987. getReturnExpressionWhenCalledAtPath(path) {
  3988. if (path.length === 1) {
  3989. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  3990. }
  3991. return UNKNOWN_EXPRESSION;
  3992. }
  3993. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3994. if (interaction.type === INTERACTION_ACCESSED) {
  3995. return path.length > 1;
  3996. }
  3997. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  3998. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  3999. }
  4000. return true;
  4001. }
  4002. })();
  4003. const returnsNumber = {
  4004. value: {
  4005. hasEffectsWhenCalled: null,
  4006. returns: UNKNOWN_LITERAL_NUMBER
  4007. }
  4008. };
  4009. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4010. getReturnExpressionWhenCalledAtPath(path) {
  4011. if (path.length === 1) {
  4012. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4013. }
  4014. return UNKNOWN_EXPRESSION;
  4015. }
  4016. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4017. if (interaction.type === INTERACTION_ACCESSED) {
  4018. return path.length > 1;
  4019. }
  4020. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4021. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4022. }
  4023. return true;
  4024. }
  4025. })();
  4026. const returnsString = {
  4027. value: {
  4028. hasEffectsWhenCalled: null,
  4029. returns: UNKNOWN_LITERAL_STRING
  4030. }
  4031. };
  4032. const stringReplace = {
  4033. value: {
  4034. hasEffectsWhenCalled({ args }, context) {
  4035. const arg1 = args[1];
  4036. return (args.length < 2 ||
  4037. (typeof arg1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4038. deoptimizeCache() { }
  4039. }) === 'symbol' &&
  4040. arg1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4041. },
  4042. returns: UNKNOWN_LITERAL_STRING
  4043. }
  4044. };
  4045. const objectMembers = assembleMemberDescriptions({
  4046. hasOwnProperty: returnsBoolean,
  4047. isPrototypeOf: returnsBoolean,
  4048. propertyIsEnumerable: returnsBoolean,
  4049. toLocaleString: returnsString,
  4050. toString: returnsString,
  4051. valueOf: returnsUnknown
  4052. });
  4053. const literalBooleanMembers = assembleMemberDescriptions({
  4054. valueOf: returnsBoolean
  4055. }, objectMembers);
  4056. const literalNumberMembers = assembleMemberDescriptions({
  4057. toExponential: returnsString,
  4058. toFixed: returnsString,
  4059. toLocaleString: returnsString,
  4060. toPrecision: returnsString,
  4061. valueOf: returnsNumber
  4062. }, objectMembers);
  4063. const literalStringMembers = assembleMemberDescriptions({
  4064. anchor: returnsString,
  4065. at: returnsUnknown,
  4066. big: returnsString,
  4067. blink: returnsString,
  4068. bold: returnsString,
  4069. charAt: returnsString,
  4070. charCodeAt: returnsNumber,
  4071. codePointAt: returnsUnknown,
  4072. concat: returnsString,
  4073. endsWith: returnsBoolean,
  4074. fixed: returnsString,
  4075. fontcolor: returnsString,
  4076. fontsize: returnsString,
  4077. includes: returnsBoolean,
  4078. indexOf: returnsNumber,
  4079. italics: returnsString,
  4080. lastIndexOf: returnsNumber,
  4081. link: returnsString,
  4082. localeCompare: returnsNumber,
  4083. match: returnsUnknown,
  4084. matchAll: returnsUnknown,
  4085. normalize: returnsString,
  4086. padEnd: returnsString,
  4087. padStart: returnsString,
  4088. repeat: returnsString,
  4089. replace: stringReplace,
  4090. replaceAll: stringReplace,
  4091. search: returnsNumber,
  4092. slice: returnsString,
  4093. small: returnsString,
  4094. split: returnsUnknown,
  4095. startsWith: returnsBoolean,
  4096. strike: returnsString,
  4097. sub: returnsString,
  4098. substr: returnsString,
  4099. substring: returnsString,
  4100. sup: returnsString,
  4101. toLocaleLowerCase: returnsString,
  4102. toLocaleUpperCase: returnsString,
  4103. toLowerCase: returnsString,
  4104. toString: returnsString,
  4105. toUpperCase: returnsString,
  4106. trim: returnsString,
  4107. trimEnd: returnsString,
  4108. trimLeft: returnsString,
  4109. trimRight: returnsString,
  4110. trimStart: returnsString,
  4111. valueOf: returnsString
  4112. }, objectMembers);
  4113. function getLiteralMembersForValue(value) {
  4114. switch (typeof value) {
  4115. case 'boolean':
  4116. return literalBooleanMembers;
  4117. case 'number':
  4118. return literalNumberMembers;
  4119. case 'string':
  4120. return literalStringMembers;
  4121. }
  4122. return Object.create(null);
  4123. }
  4124. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4125. var _a, _b;
  4126. if (typeof memberName !== 'string' || !members[memberName]) {
  4127. return true;
  4128. }
  4129. return ((_b = (_a = members[memberName]).hasEffectsWhenCalled) === null || _b === void 0 ? void 0 : _b.call(_a, interaction, context)) || false;
  4130. }
  4131. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4132. if (typeof memberName !== 'string' || !members[memberName])
  4133. return UNKNOWN_EXPRESSION;
  4134. return members[memberName].returns;
  4135. }
  4136. // AST walker module for Mozilla Parser API compatible trees
  4137. function skipThrough(node, st, c) { c(node, st); }
  4138. function ignore(_node, _st, _c) {}
  4139. // Node walkers.
  4140. var base$1 = {};
  4141. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4142. for (var i = 0, list = node.body; i < list.length; i += 1)
  4143. {
  4144. var stmt = list[i];
  4145. c(stmt, st, "Statement");
  4146. }
  4147. };
  4148. base$1.Statement = skipThrough;
  4149. base$1.EmptyStatement = ignore;
  4150. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4151. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4152. base$1.IfStatement = function (node, st, c) {
  4153. c(node.test, st, "Expression");
  4154. c(node.consequent, st, "Statement");
  4155. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4156. };
  4157. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4158. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4159. base$1.WithStatement = function (node, st, c) {
  4160. c(node.object, st, "Expression");
  4161. c(node.body, st, "Statement");
  4162. };
  4163. base$1.SwitchStatement = function (node, st, c) {
  4164. c(node.discriminant, st, "Expression");
  4165. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4166. var cs = list$1[i$1];
  4167. if (cs.test) { c(cs.test, st, "Expression"); }
  4168. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4169. {
  4170. var cons = list[i];
  4171. c(cons, st, "Statement");
  4172. }
  4173. }
  4174. };
  4175. base$1.SwitchCase = function (node, st, c) {
  4176. if (node.test) { c(node.test, st, "Expression"); }
  4177. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4178. {
  4179. var cons = list[i];
  4180. c(cons, st, "Statement");
  4181. }
  4182. };
  4183. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4184. if (node.argument) { c(node.argument, st, "Expression"); }
  4185. };
  4186. base$1.ThrowStatement = base$1.SpreadElement =
  4187. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4188. base$1.TryStatement = function (node, st, c) {
  4189. c(node.block, st, "Statement");
  4190. if (node.handler) { c(node.handler, st); }
  4191. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4192. };
  4193. base$1.CatchClause = function (node, st, c) {
  4194. if (node.param) { c(node.param, st, "Pattern"); }
  4195. c(node.body, st, "Statement");
  4196. };
  4197. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4198. c(node.test, st, "Expression");
  4199. c(node.body, st, "Statement");
  4200. };
  4201. base$1.ForStatement = function (node, st, c) {
  4202. if (node.init) { c(node.init, st, "ForInit"); }
  4203. if (node.test) { c(node.test, st, "Expression"); }
  4204. if (node.update) { c(node.update, st, "Expression"); }
  4205. c(node.body, st, "Statement");
  4206. };
  4207. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4208. c(node.left, st, "ForInit");
  4209. c(node.right, st, "Expression");
  4210. c(node.body, st, "Statement");
  4211. };
  4212. base$1.ForInit = function (node, st, c) {
  4213. if (node.type === "VariableDeclaration") { c(node, st); }
  4214. else { c(node, st, "Expression"); }
  4215. };
  4216. base$1.DebuggerStatement = ignore;
  4217. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4218. base$1.VariableDeclaration = function (node, st, c) {
  4219. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4220. {
  4221. var decl = list[i];
  4222. c(decl, st);
  4223. }
  4224. };
  4225. base$1.VariableDeclarator = function (node, st, c) {
  4226. c(node.id, st, "Pattern");
  4227. if (node.init) { c(node.init, st, "Expression"); }
  4228. };
  4229. base$1.Function = function (node, st, c) {
  4230. if (node.id) { c(node.id, st, "Pattern"); }
  4231. for (var i = 0, list = node.params; i < list.length; i += 1)
  4232. {
  4233. var param = list[i];
  4234. c(param, st, "Pattern");
  4235. }
  4236. c(node.body, st, node.expression ? "Expression" : "Statement");
  4237. };
  4238. base$1.Pattern = function (node, st, c) {
  4239. if (node.type === "Identifier")
  4240. { c(node, st, "VariablePattern"); }
  4241. else if (node.type === "MemberExpression")
  4242. { c(node, st, "MemberPattern"); }
  4243. else
  4244. { c(node, st); }
  4245. };
  4246. base$1.VariablePattern = ignore;
  4247. base$1.MemberPattern = skipThrough;
  4248. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4249. base$1.ArrayPattern = function (node, st, c) {
  4250. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4251. var elt = list[i];
  4252. if (elt) { c(elt, st, "Pattern"); }
  4253. }
  4254. };
  4255. base$1.ObjectPattern = function (node, st, c) {
  4256. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4257. var prop = list[i];
  4258. if (prop.type === "Property") {
  4259. if (prop.computed) { c(prop.key, st, "Expression"); }
  4260. c(prop.value, st, "Pattern");
  4261. } else if (prop.type === "RestElement") {
  4262. c(prop.argument, st, "Pattern");
  4263. }
  4264. }
  4265. };
  4266. base$1.Expression = skipThrough;
  4267. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4268. base$1.ArrayExpression = function (node, st, c) {
  4269. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4270. var elt = list[i];
  4271. if (elt) { c(elt, st, "Expression"); }
  4272. }
  4273. };
  4274. base$1.ObjectExpression = function (node, st, c) {
  4275. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4276. {
  4277. var prop = list[i];
  4278. c(prop, st);
  4279. }
  4280. };
  4281. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4282. base$1.SequenceExpression = function (node, st, c) {
  4283. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4284. {
  4285. var expr = list[i];
  4286. c(expr, st, "Expression");
  4287. }
  4288. };
  4289. base$1.TemplateLiteral = function (node, st, c) {
  4290. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4291. {
  4292. var quasi = list[i];
  4293. c(quasi, st);
  4294. }
  4295. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4296. {
  4297. var expr = list$1[i$1];
  4298. c(expr, st, "Expression");
  4299. }
  4300. };
  4301. base$1.TemplateElement = ignore;
  4302. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4303. c(node.argument, st, "Expression");
  4304. };
  4305. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4306. c(node.left, st, "Expression");
  4307. c(node.right, st, "Expression");
  4308. };
  4309. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4310. c(node.left, st, "Pattern");
  4311. c(node.right, st, "Expression");
  4312. };
  4313. base$1.ConditionalExpression = function (node, st, c) {
  4314. c(node.test, st, "Expression");
  4315. c(node.consequent, st, "Expression");
  4316. c(node.alternate, st, "Expression");
  4317. };
  4318. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4319. c(node.callee, st, "Expression");
  4320. if (node.arguments)
  4321. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4322. {
  4323. var arg = list[i];
  4324. c(arg, st, "Expression");
  4325. } }
  4326. };
  4327. base$1.MemberExpression = function (node, st, c) {
  4328. c(node.object, st, "Expression");
  4329. if (node.computed) { c(node.property, st, "Expression"); }
  4330. };
  4331. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4332. if (node.declaration)
  4333. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4334. if (node.source) { c(node.source, st, "Expression"); }
  4335. };
  4336. base$1.ExportAllDeclaration = function (node, st, c) {
  4337. if (node.exported)
  4338. { c(node.exported, st); }
  4339. c(node.source, st, "Expression");
  4340. };
  4341. base$1.ImportDeclaration = function (node, st, c) {
  4342. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4343. {
  4344. var spec = list[i];
  4345. c(spec, st);
  4346. }
  4347. c(node.source, st, "Expression");
  4348. };
  4349. base$1.ImportExpression = function (node, st, c) {
  4350. c(node.source, st, "Expression");
  4351. };
  4352. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4353. base$1.TaggedTemplateExpression = function (node, st, c) {
  4354. c(node.tag, st, "Expression");
  4355. c(node.quasi, st, "Expression");
  4356. };
  4357. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4358. base$1.Class = function (node, st, c) {
  4359. if (node.id) { c(node.id, st, "Pattern"); }
  4360. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4361. c(node.body, st);
  4362. };
  4363. base$1.ClassBody = function (node, st, c) {
  4364. for (var i = 0, list = node.body; i < list.length; i += 1)
  4365. {
  4366. var elt = list[i];
  4367. c(elt, st);
  4368. }
  4369. };
  4370. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4371. if (node.computed) { c(node.key, st, "Expression"); }
  4372. if (node.value) { c(node.value, st, "Expression"); }
  4373. };
  4374. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4375. const BinaryExpression$1 = 'BinaryExpression';
  4376. const BlockStatement$1 = 'BlockStatement';
  4377. const CallExpression$1 = 'CallExpression';
  4378. const ChainExpression$1 = 'ChainExpression';
  4379. const ConditionalExpression$1 = 'ConditionalExpression';
  4380. const ExpressionStatement$1 = 'ExpressionStatement';
  4381. const Identifier$1 = 'Identifier';
  4382. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  4383. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  4384. const LogicalExpression$1 = 'LogicalExpression';
  4385. const NewExpression$1 = 'NewExpression';
  4386. const Program$1 = 'Program';
  4387. const Property$1 = 'Property';
  4388. const ReturnStatement$1 = 'ReturnStatement';
  4389. const SequenceExpression$1 = 'SequenceExpression';
  4390. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4391. // this for an actual sourceMappingURL
  4392. let SOURCEMAPPING_URL = 'sourceMa';
  4393. SOURCEMAPPING_URL += 'ppingURL';
  4394. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4395. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  4396. const ANNOTATION_KEY = '_rollupAnnotations';
  4397. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4398. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4399. const { annotations } = state;
  4400. let comment = annotations[state.annotationIndex];
  4401. while (comment && node.start >= comment.end) {
  4402. markPureNode(node, comment, state.code);
  4403. comment = annotations[++state.annotationIndex];
  4404. }
  4405. if (comment && comment.end <= node.end) {
  4406. base$1[type](node, state, handlePureAnnotationsOfNode);
  4407. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4408. ++state.annotationIndex;
  4409. annotateNode(node, comment, false);
  4410. }
  4411. }
  4412. }
  4413. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4414. const noWhitespace = /\S/g;
  4415. function markPureNode(node, comment, code) {
  4416. const annotatedNodes = [];
  4417. let invalidAnnotation;
  4418. const codeInBetween = code.slice(comment.end, node.start);
  4419. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4420. const parentStart = node.start;
  4421. while (true) {
  4422. annotatedNodes.push(node);
  4423. switch (node.type) {
  4424. case ExpressionStatement$1:
  4425. case ChainExpression$1:
  4426. node = node.expression;
  4427. continue;
  4428. case SequenceExpression$1:
  4429. // if there are parentheses, the annotation would apply to the entire expression
  4430. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4431. node = node.expressions[0];
  4432. continue;
  4433. }
  4434. invalidAnnotation = true;
  4435. break;
  4436. case ConditionalExpression$1:
  4437. // if there are parentheses, the annotation would apply to the entire expression
  4438. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4439. node = node.test;
  4440. continue;
  4441. }
  4442. invalidAnnotation = true;
  4443. break;
  4444. case LogicalExpression$1:
  4445. case BinaryExpression$1:
  4446. // if there are parentheses, the annotation would apply to the entire expression
  4447. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4448. node = node.left;
  4449. continue;
  4450. }
  4451. invalidAnnotation = true;
  4452. break;
  4453. case CallExpression$1:
  4454. case NewExpression$1:
  4455. break;
  4456. default:
  4457. invalidAnnotation = true;
  4458. }
  4459. break;
  4460. }
  4461. }
  4462. else {
  4463. invalidAnnotation = true;
  4464. }
  4465. if (invalidAnnotation) {
  4466. annotateNode(node, comment, false);
  4467. }
  4468. else {
  4469. for (const node of annotatedNodes) {
  4470. annotateNode(node, comment, true);
  4471. }
  4472. }
  4473. }
  4474. function doesNotMatchOutsideComment(code, forbiddenChars) {
  4475. let nextMatch;
  4476. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  4477. if (nextMatch[0] === '/') {
  4478. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  4479. if (charCodeAfterSlash === 42 /*"*"*/) {
  4480. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  4481. continue;
  4482. }
  4483. else if (charCodeAfterSlash === 47 /*"/"*/) {
  4484. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  4485. continue;
  4486. }
  4487. }
  4488. forbiddenChars.lastIndex = 0;
  4489. return false;
  4490. }
  4491. return true;
  4492. }
  4493. const pureCommentRegex = /[@#]__PURE__/;
  4494. function addAnnotations(comments, esTreeAst, code) {
  4495. const annotations = [];
  4496. const sourceMappingComments = [];
  4497. for (const comment of comments) {
  4498. if (pureCommentRegex.test(comment.value)) {
  4499. annotations.push(comment);
  4500. }
  4501. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  4502. sourceMappingComments.push(comment);
  4503. }
  4504. }
  4505. for (const comment of sourceMappingComments) {
  4506. annotateNode(esTreeAst, comment, false);
  4507. }
  4508. handlePureAnnotationsOfNode(esTreeAst, {
  4509. annotationIndex: 0,
  4510. annotations,
  4511. code
  4512. });
  4513. }
  4514. function annotateNode(node, comment, valid) {
  4515. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  4516. const property = node[key];
  4517. if (property) {
  4518. property.push(comment);
  4519. }
  4520. else {
  4521. node[key] = [comment];
  4522. }
  4523. }
  4524. const keys = {
  4525. Literal: [],
  4526. Program: ['body']
  4527. };
  4528. function getAndCreateKeys(esTreeNode) {
  4529. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  4530. return keys[esTreeNode.type];
  4531. }
  4532. const INCLUDE_PARAMETERS = 'variables';
  4533. class NodeBase extends ExpressionEntity {
  4534. constructor(esTreeNode, parent, parentScope) {
  4535. super();
  4536. /**
  4537. * Nodes can apply custom deoptimizations once they become part of the
  4538. * executed code. To do this, they must initialize this as false, implement
  4539. * applyDeoptimizations and call this from include and hasEffects if they have
  4540. * custom handlers
  4541. */
  4542. this.deoptimized = false;
  4543. this.esTreeNode = esTreeNode;
  4544. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  4545. this.parent = parent;
  4546. this.context = parent.context;
  4547. this.createScope(parentScope);
  4548. this.parseNode(esTreeNode);
  4549. this.initialise();
  4550. this.context.magicString.addSourcemapLocation(this.start);
  4551. this.context.magicString.addSourcemapLocation(this.end);
  4552. }
  4553. addExportedVariables(_variables, _exportNamesByVariable) { }
  4554. /**
  4555. * Override this to bind assignments to variables and do any initialisations that
  4556. * require the scopes to be populated with variables.
  4557. */
  4558. bind() {
  4559. for (const key of this.keys) {
  4560. const value = this[key];
  4561. if (value === null)
  4562. continue;
  4563. if (Array.isArray(value)) {
  4564. for (const child of value) {
  4565. child === null || child === void 0 ? void 0 : child.bind();
  4566. }
  4567. }
  4568. else {
  4569. value.bind();
  4570. }
  4571. }
  4572. }
  4573. /**
  4574. * Override if this node should receive a different scope than the parent scope.
  4575. */
  4576. createScope(parentScope) {
  4577. this.scope = parentScope;
  4578. }
  4579. hasEffects(context) {
  4580. if (!this.deoptimized)
  4581. this.applyDeoptimizations();
  4582. for (const key of this.keys) {
  4583. const value = this[key];
  4584. if (value === null)
  4585. continue;
  4586. if (Array.isArray(value)) {
  4587. for (const child of value) {
  4588. if (child === null || child === void 0 ? void 0 : child.hasEffects(context))
  4589. return true;
  4590. }
  4591. }
  4592. else if (value.hasEffects(context))
  4593. return true;
  4594. }
  4595. return false;
  4596. }
  4597. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  4598. return (this.hasEffects(context) ||
  4599. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  4600. }
  4601. include(context, includeChildrenRecursively, _options) {
  4602. if (!this.deoptimized)
  4603. this.applyDeoptimizations();
  4604. this.included = true;
  4605. for (const key of this.keys) {
  4606. const value = this[key];
  4607. if (value === null)
  4608. continue;
  4609. if (Array.isArray(value)) {
  4610. for (const child of value) {
  4611. child === null || child === void 0 ? void 0 : child.include(context, includeChildrenRecursively);
  4612. }
  4613. }
  4614. else {
  4615. value.include(context, includeChildrenRecursively);
  4616. }
  4617. }
  4618. }
  4619. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  4620. this.include(context, includeChildrenRecursively);
  4621. }
  4622. /**
  4623. * Override to perform special initialisation steps after the scope is initialised
  4624. */
  4625. initialise() { }
  4626. insertSemicolon(code) {
  4627. if (code.original[this.end - 1] !== ';') {
  4628. code.appendLeft(this.end, ';');
  4629. }
  4630. }
  4631. parseNode(esTreeNode) {
  4632. for (const [key, value] of Object.entries(esTreeNode)) {
  4633. // That way, we can override this function to add custom initialisation and then call super.parseNode
  4634. if (this.hasOwnProperty(key))
  4635. continue;
  4636. if (key.charCodeAt(0) === 95 /* _ */) {
  4637. if (key === ANNOTATION_KEY) {
  4638. this.annotations = value;
  4639. }
  4640. else if (key === INVALID_COMMENT_KEY) {
  4641. for (const { start, end } of value)
  4642. this.context.magicString.remove(start, end);
  4643. }
  4644. }
  4645. else if (typeof value !== 'object' || value === null) {
  4646. this[key] = value;
  4647. }
  4648. else if (Array.isArray(value)) {
  4649. this[key] = [];
  4650. for (const child of value) {
  4651. this[key].push(child === null
  4652. ? null
  4653. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope));
  4654. }
  4655. }
  4656. else {
  4657. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope);
  4658. }
  4659. }
  4660. }
  4661. render(code, options) {
  4662. for (const key of this.keys) {
  4663. const value = this[key];
  4664. if (value === null)
  4665. continue;
  4666. if (Array.isArray(value)) {
  4667. for (const child of value) {
  4668. child === null || child === void 0 ? void 0 : child.render(code, options);
  4669. }
  4670. }
  4671. else {
  4672. value.render(code, options);
  4673. }
  4674. }
  4675. }
  4676. setAssignedValue(value) {
  4677. this.assignmentInteraction = { args: [value], thisArg: null, type: INTERACTION_ASSIGNED };
  4678. }
  4679. shouldBeIncluded(context) {
  4680. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  4681. }
  4682. /**
  4683. * Just deoptimize everything by default so that when e.g. we do not track
  4684. * something properly, it is deoptimized.
  4685. * @protected
  4686. */
  4687. applyDeoptimizations() {
  4688. this.deoptimized = true;
  4689. for (const key of this.keys) {
  4690. const value = this[key];
  4691. if (value === null)
  4692. continue;
  4693. if (Array.isArray(value)) {
  4694. for (const child of value) {
  4695. child === null || child === void 0 ? void 0 : child.deoptimizePath(UNKNOWN_PATH);
  4696. }
  4697. }
  4698. else {
  4699. value.deoptimizePath(UNKNOWN_PATH);
  4700. }
  4701. }
  4702. this.context.requestTreeshakingPass();
  4703. }
  4704. }
  4705. class SpreadElement extends NodeBase {
  4706. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4707. if (path.length > 0) {
  4708. this.argument.deoptimizeThisOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  4709. }
  4710. }
  4711. hasEffects(context) {
  4712. if (!this.deoptimized)
  4713. this.applyDeoptimizations();
  4714. const { propertyReadSideEffects } = this.context.options
  4715. .treeshake;
  4716. return (this.argument.hasEffects(context) ||
  4717. (propertyReadSideEffects &&
  4718. (propertyReadSideEffects === 'always' ||
  4719. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  4720. }
  4721. applyDeoptimizations() {
  4722. this.deoptimized = true;
  4723. // Only properties of properties of the argument could become subject to reassignment
  4724. // This will also reassign the return values of iterators
  4725. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4726. this.context.requestTreeshakingPass();
  4727. }
  4728. }
  4729. class Method extends ExpressionEntity {
  4730. constructor(description) {
  4731. super();
  4732. this.description = description;
  4733. }
  4734. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  4735. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4736. thisArg.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4737. }
  4738. }
  4739. getReturnExpressionWhenCalledAtPath(path, { thisArg }) {
  4740. if (path.length > 0) {
  4741. return UNKNOWN_EXPRESSION;
  4742. }
  4743. return (this.description.returnsPrimitive ||
  4744. (this.description.returns === 'self'
  4745. ? thisArg || UNKNOWN_EXPRESSION
  4746. : this.description.returns()));
  4747. }
  4748. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4749. var _a, _b;
  4750. const { type } = interaction;
  4751. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  4752. return true;
  4753. }
  4754. if (type === INTERACTION_CALLED) {
  4755. if (this.description.mutatesSelfAsArray === true &&
  4756. ((_a = interaction.thisArg) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context))) {
  4757. return true;
  4758. }
  4759. if (this.description.callsArgs) {
  4760. for (const argIndex of this.description.callsArgs) {
  4761. if ((_b = interaction.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  4762. return true;
  4763. }
  4764. }
  4765. }
  4766. }
  4767. return false;
  4768. }
  4769. }
  4770. const METHOD_RETURNS_BOOLEAN = [
  4771. new Method({
  4772. callsArgs: null,
  4773. mutatesSelfAsArray: false,
  4774. returns: null,
  4775. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4776. })
  4777. ];
  4778. const METHOD_RETURNS_STRING = [
  4779. new Method({
  4780. callsArgs: null,
  4781. mutatesSelfAsArray: false,
  4782. returns: null,
  4783. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4784. })
  4785. ];
  4786. const METHOD_RETURNS_NUMBER = [
  4787. new Method({
  4788. callsArgs: null,
  4789. mutatesSelfAsArray: false,
  4790. returns: null,
  4791. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4792. })
  4793. ];
  4794. const METHOD_RETURNS_UNKNOWN = [
  4795. new Method({
  4796. callsArgs: null,
  4797. mutatesSelfAsArray: false,
  4798. returns: null,
  4799. returnsPrimitive: UNKNOWN_EXPRESSION
  4800. })
  4801. ];
  4802. const INTEGER_REG_EXP = /^\d+$/;
  4803. class ObjectEntity extends ExpressionEntity {
  4804. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  4805. // and we assume there are no setters or getters
  4806. constructor(properties, prototypeExpression, immutable = false) {
  4807. super();
  4808. this.prototypeExpression = prototypeExpression;
  4809. this.immutable = immutable;
  4810. this.allProperties = [];
  4811. this.deoptimizedPaths = Object.create(null);
  4812. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4813. this.gettersByKey = Object.create(null);
  4814. this.hasLostTrack = false;
  4815. this.hasUnknownDeoptimizedInteger = false;
  4816. this.hasUnknownDeoptimizedProperty = false;
  4817. this.propertiesAndGettersByKey = Object.create(null);
  4818. this.propertiesAndSettersByKey = Object.create(null);
  4819. this.settersByKey = Object.create(null);
  4820. this.thisParametersToBeDeoptimized = new Set();
  4821. this.unknownIntegerProps = [];
  4822. this.unmatchableGetters = [];
  4823. this.unmatchablePropertiesAndGetters = [];
  4824. this.unmatchableSetters = [];
  4825. if (Array.isArray(properties)) {
  4826. this.buildPropertyMaps(properties);
  4827. }
  4828. else {
  4829. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4830. for (const propertiesForKey of Object.values(properties)) {
  4831. this.allProperties.push(...propertiesForKey);
  4832. }
  4833. }
  4834. }
  4835. deoptimizeAllProperties(noAccessors) {
  4836. var _a;
  4837. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  4838. if (noAccessors) {
  4839. this.hasUnknownDeoptimizedProperty = true;
  4840. }
  4841. else {
  4842. this.hasLostTrack = true;
  4843. }
  4844. if (isDeoptimized) {
  4845. return;
  4846. }
  4847. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4848. for (const property of properties) {
  4849. property.deoptimizePath(UNKNOWN_PATH);
  4850. }
  4851. }
  4852. // While the prototype itself cannot be mutated, each property can
  4853. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4854. this.deoptimizeCachedEntities();
  4855. }
  4856. deoptimizeIntegerProperties() {
  4857. if (this.hasLostTrack ||
  4858. this.hasUnknownDeoptimizedProperty ||
  4859. this.hasUnknownDeoptimizedInteger) {
  4860. return;
  4861. }
  4862. this.hasUnknownDeoptimizedInteger = true;
  4863. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4864. if (INTEGER_REG_EXP.test(key)) {
  4865. for (const property of propertiesAndGetters) {
  4866. property.deoptimizePath(UNKNOWN_PATH);
  4867. }
  4868. }
  4869. }
  4870. this.deoptimizeCachedIntegerEntities();
  4871. }
  4872. // Assumption: If only a specific path is deoptimized, no accessors are created
  4873. deoptimizePath(path) {
  4874. var _a;
  4875. if (this.hasLostTrack || this.immutable) {
  4876. return;
  4877. }
  4878. const key = path[0];
  4879. if (path.length === 1) {
  4880. if (typeof key !== 'string') {
  4881. if (key === UnknownInteger) {
  4882. return this.deoptimizeIntegerProperties();
  4883. }
  4884. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  4885. }
  4886. if (!this.deoptimizedPaths[key]) {
  4887. this.deoptimizedPaths[key] = true;
  4888. // we only deoptimizeCache exact matches as in all other cases,
  4889. // we do not return a literal value or return expression
  4890. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4891. if (expressionsToBeDeoptimized) {
  4892. for (const expression of expressionsToBeDeoptimized) {
  4893. expression.deoptimizeCache();
  4894. }
  4895. }
  4896. }
  4897. }
  4898. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4899. for (const property of typeof key === 'string'
  4900. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  4901. : this.allProperties) {
  4902. property.deoptimizePath(subPath);
  4903. }
  4904. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  4905. }
  4906. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  4907. var _a;
  4908. const [key, ...subPath] = path;
  4909. if (this.hasLostTrack ||
  4910. // single paths that are deoptimized will not become getters or setters
  4911. ((interaction.type === INTERACTION_CALLED || path.length > 1) &&
  4912. (this.hasUnknownDeoptimizedProperty ||
  4913. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  4914. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  4915. return;
  4916. }
  4917. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = interaction.type === INTERACTION_CALLED || path.length > 1
  4918. ? [
  4919. this.propertiesAndGettersByKey,
  4920. this.propertiesAndGettersByKey,
  4921. this.unmatchablePropertiesAndGetters
  4922. ]
  4923. : interaction.type === INTERACTION_ACCESSED
  4924. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4925. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4926. if (typeof key === 'string') {
  4927. if (propertiesForExactMatchByKey[key]) {
  4928. const properties = relevantPropertiesByKey[key];
  4929. if (properties) {
  4930. for (const property of properties) {
  4931. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4932. }
  4933. }
  4934. if (!this.immutable) {
  4935. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4936. }
  4937. return;
  4938. }
  4939. for (const property of relevantUnmatchableProperties) {
  4940. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4941. }
  4942. if (INTEGER_REG_EXP.test(key)) {
  4943. for (const property of this.unknownIntegerProps) {
  4944. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4945. }
  4946. }
  4947. }
  4948. else {
  4949. for (const properties of Object.values(relevantPropertiesByKey).concat([
  4950. relevantUnmatchableProperties
  4951. ])) {
  4952. for (const property of properties) {
  4953. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4954. }
  4955. }
  4956. for (const property of this.unknownIntegerProps) {
  4957. property.deoptimizeThisOnInteractionAtPath(interaction, subPath, recursionTracker);
  4958. }
  4959. }
  4960. if (!this.immutable) {
  4961. this.thisParametersToBeDeoptimized.add(interaction.thisArg);
  4962. }
  4963. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  4964. }
  4965. getLiteralValueAtPath(path, recursionTracker, origin) {
  4966. if (path.length === 0) {
  4967. return UnknownTruthyValue;
  4968. }
  4969. const key = path[0];
  4970. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4971. if (expressionAtPath) {
  4972. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4973. }
  4974. if (this.prototypeExpression) {
  4975. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4976. }
  4977. if (path.length === 1) {
  4978. return undefined;
  4979. }
  4980. return UnknownValue;
  4981. }
  4982. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4983. if (path.length === 0) {
  4984. return UNKNOWN_EXPRESSION;
  4985. }
  4986. const [key, ...subPath] = path;
  4987. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4988. if (expressionAtPath) {
  4989. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  4990. }
  4991. if (this.prototypeExpression) {
  4992. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4993. }
  4994. return UNKNOWN_EXPRESSION;
  4995. }
  4996. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4997. const [key, ...subPath] = path;
  4998. if (subPath.length || interaction.type === INTERACTION_CALLED) {
  4999. const expressionAtPath = this.getMemberExpression(key);
  5000. if (expressionAtPath) {
  5001. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5002. }
  5003. if (this.prototypeExpression) {
  5004. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5005. }
  5006. return true;
  5007. }
  5008. if (key === UnknownNonAccessorKey)
  5009. return false;
  5010. if (this.hasLostTrack)
  5011. return true;
  5012. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5013. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5014. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5015. if (typeof key === 'string') {
  5016. if (propertiesAndAccessorsByKey[key]) {
  5017. const accessors = accessorsByKey[key];
  5018. if (accessors) {
  5019. for (const accessor of accessors) {
  5020. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5021. return true;
  5022. }
  5023. }
  5024. return false;
  5025. }
  5026. for (const accessor of unmatchableAccessors) {
  5027. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5028. return true;
  5029. }
  5030. }
  5031. }
  5032. else {
  5033. for (const accessors of Object.values(accessorsByKey).concat([unmatchableAccessors])) {
  5034. for (const accessor of accessors) {
  5035. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5036. return true;
  5037. }
  5038. }
  5039. }
  5040. if (this.prototypeExpression) {
  5041. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5042. }
  5043. return false;
  5044. }
  5045. buildPropertyMaps(properties) {
  5046. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5047. const unmatchablePropertiesAndSetters = [];
  5048. for (let index = properties.length - 1; index >= 0; index--) {
  5049. const { key, kind, property } = properties[index];
  5050. allProperties.push(property);
  5051. if (typeof key !== 'string') {
  5052. if (key === UnknownInteger) {
  5053. unknownIntegerProps.push(property);
  5054. continue;
  5055. }
  5056. if (kind === 'set')
  5057. unmatchableSetters.push(property);
  5058. if (kind === 'get')
  5059. unmatchableGetters.push(property);
  5060. if (kind !== 'get')
  5061. unmatchablePropertiesAndSetters.push(property);
  5062. if (kind !== 'set')
  5063. unmatchablePropertiesAndGetters.push(property);
  5064. }
  5065. else {
  5066. if (kind === 'set') {
  5067. if (!propertiesAndSettersByKey[key]) {
  5068. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5069. settersByKey[key] = [property, ...unmatchableSetters];
  5070. }
  5071. }
  5072. else if (kind === 'get') {
  5073. if (!propertiesAndGettersByKey[key]) {
  5074. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5075. gettersByKey[key] = [property, ...unmatchableGetters];
  5076. }
  5077. }
  5078. else {
  5079. if (!propertiesAndSettersByKey[key]) {
  5080. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5081. }
  5082. if (!propertiesAndGettersByKey[key]) {
  5083. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5084. }
  5085. }
  5086. }
  5087. }
  5088. }
  5089. deoptimizeCachedEntities() {
  5090. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5091. for (const expression of expressionsToBeDeoptimized) {
  5092. expression.deoptimizeCache();
  5093. }
  5094. }
  5095. for (const expression of this.thisParametersToBeDeoptimized) {
  5096. expression.deoptimizePath(UNKNOWN_PATH);
  5097. }
  5098. }
  5099. deoptimizeCachedIntegerEntities() {
  5100. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5101. if (INTEGER_REG_EXP.test(key)) {
  5102. for (const expression of expressionsToBeDeoptimized) {
  5103. expression.deoptimizeCache();
  5104. }
  5105. }
  5106. }
  5107. for (const expression of this.thisParametersToBeDeoptimized) {
  5108. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5109. }
  5110. }
  5111. getMemberExpression(key) {
  5112. if (this.hasLostTrack ||
  5113. this.hasUnknownDeoptimizedProperty ||
  5114. typeof key !== 'string' ||
  5115. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5116. this.deoptimizedPaths[key]) {
  5117. return UNKNOWN_EXPRESSION;
  5118. }
  5119. const properties = this.propertiesAndGettersByKey[key];
  5120. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  5121. return properties[0];
  5122. }
  5123. if (properties ||
  5124. this.unmatchablePropertiesAndGetters.length > 0 ||
  5125. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  5126. return UNKNOWN_EXPRESSION;
  5127. }
  5128. return null;
  5129. }
  5130. getMemberExpressionAndTrackDeopt(key, origin) {
  5131. if (typeof key !== 'string') {
  5132. return UNKNOWN_EXPRESSION;
  5133. }
  5134. const expression = this.getMemberExpression(key);
  5135. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5136. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5137. this.expressionsToBeDeoptimizedByKey[key] || []);
  5138. expressionsToBeDeoptimized.push(origin);
  5139. }
  5140. return expression;
  5141. }
  5142. }
  5143. const isInteger = (prop) => typeof prop === 'string' && /^\d+$/.test(prop);
  5144. // This makes sure unknown properties are not handled as "undefined" but as
  5145. // "unknown" but without access side effects. An exception is done for numeric
  5146. // properties as we do not expect new builtin properties to be numbers, this
  5147. // will improve tree-shaking for out-of-bounds array properties
  5148. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5149. deoptimizeThisOnInteractionAtPath({ type, thisArg }, path) {
  5150. if (type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5151. thisArg.deoptimizePath(UNKNOWN_PATH);
  5152. }
  5153. }
  5154. getLiteralValueAtPath(path) {
  5155. // We ignore number properties as we do not expect new properties to be
  5156. // numbers and also want to keep handling out-of-bound array elements as
  5157. // "undefined"
  5158. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5159. }
  5160. hasEffectsOnInteractionAtPath(path, { type }) {
  5161. return path.length > 1 || type === INTERACTION_CALLED;
  5162. }
  5163. })();
  5164. const OBJECT_PROTOTYPE = new ObjectEntity({
  5165. __proto__: null,
  5166. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5167. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5168. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5169. toLocaleString: METHOD_RETURNS_STRING,
  5170. toString: METHOD_RETURNS_STRING,
  5171. valueOf: METHOD_RETURNS_UNKNOWN
  5172. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5173. const NEW_ARRAY_PROPERTIES = [
  5174. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5175. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5176. ];
  5177. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5178. new Method({
  5179. callsArgs: [0],
  5180. mutatesSelfAsArray: 'deopt-only',
  5181. returns: null,
  5182. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5183. })
  5184. ];
  5185. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5186. new Method({
  5187. callsArgs: [0],
  5188. mutatesSelfAsArray: 'deopt-only',
  5189. returns: null,
  5190. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5191. })
  5192. ];
  5193. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5194. new Method({
  5195. callsArgs: null,
  5196. mutatesSelfAsArray: true,
  5197. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5198. returnsPrimitive: null
  5199. })
  5200. ];
  5201. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5202. new Method({
  5203. callsArgs: null,
  5204. mutatesSelfAsArray: 'deopt-only',
  5205. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5206. returnsPrimitive: null
  5207. })
  5208. ];
  5209. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5210. new Method({
  5211. callsArgs: [0],
  5212. mutatesSelfAsArray: 'deopt-only',
  5213. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5214. returnsPrimitive: null
  5215. })
  5216. ];
  5217. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5218. new Method({
  5219. callsArgs: null,
  5220. mutatesSelfAsArray: true,
  5221. returns: null,
  5222. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5223. })
  5224. ];
  5225. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5226. new Method({
  5227. callsArgs: null,
  5228. mutatesSelfAsArray: true,
  5229. returns: null,
  5230. returnsPrimitive: UNKNOWN_EXPRESSION
  5231. })
  5232. ];
  5233. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5234. new Method({
  5235. callsArgs: null,
  5236. mutatesSelfAsArray: 'deopt-only',
  5237. returns: null,
  5238. returnsPrimitive: UNKNOWN_EXPRESSION
  5239. })
  5240. ];
  5241. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5242. new Method({
  5243. callsArgs: [0],
  5244. mutatesSelfAsArray: 'deopt-only',
  5245. returns: null,
  5246. returnsPrimitive: UNKNOWN_EXPRESSION
  5247. })
  5248. ];
  5249. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5250. new Method({
  5251. callsArgs: null,
  5252. mutatesSelfAsArray: true,
  5253. returns: 'self',
  5254. returnsPrimitive: null
  5255. })
  5256. ];
  5257. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5258. new Method({
  5259. callsArgs: [0],
  5260. mutatesSelfAsArray: true,
  5261. returns: 'self',
  5262. returnsPrimitive: null
  5263. })
  5264. ];
  5265. const ARRAY_PROTOTYPE = new ObjectEntity({
  5266. __proto__: null,
  5267. // We assume that accessors have effects as we do not track the accessed value afterwards
  5268. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5269. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5270. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5271. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5272. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5273. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5274. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5275. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5276. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5277. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5278. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5279. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5280. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5281. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5282. group: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5283. groupToMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5284. includes: METHOD_RETURNS_BOOLEAN,
  5285. indexOf: METHOD_RETURNS_NUMBER,
  5286. join: METHOD_RETURNS_STRING,
  5287. keys: METHOD_RETURNS_UNKNOWN,
  5288. lastIndexOf: METHOD_RETURNS_NUMBER,
  5289. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5290. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5291. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5292. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5293. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5294. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5295. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5296. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5297. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5298. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5299. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5300. toLocaleString: METHOD_RETURNS_STRING,
  5301. toString: METHOD_RETURNS_STRING,
  5302. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5303. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5304. }, OBJECT_PROTOTYPE, true);
  5305. class ArrayExpression extends NodeBase {
  5306. constructor() {
  5307. super(...arguments);
  5308. this.objectEntity = null;
  5309. }
  5310. deoptimizePath(path) {
  5311. this.getObjectEntity().deoptimizePath(path);
  5312. }
  5313. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5314. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  5315. }
  5316. getLiteralValueAtPath(path, recursionTracker, origin) {
  5317. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5318. }
  5319. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5320. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5321. }
  5322. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5323. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5324. }
  5325. applyDeoptimizations() {
  5326. this.deoptimized = true;
  5327. let hasSpread = false;
  5328. for (let index = 0; index < this.elements.length; index++) {
  5329. const element = this.elements[index];
  5330. if (element) {
  5331. if (hasSpread || element instanceof SpreadElement) {
  5332. hasSpread = true;
  5333. element.deoptimizePath(UNKNOWN_PATH);
  5334. }
  5335. }
  5336. }
  5337. this.context.requestTreeshakingPass();
  5338. }
  5339. getObjectEntity() {
  5340. if (this.objectEntity !== null) {
  5341. return this.objectEntity;
  5342. }
  5343. const properties = [
  5344. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5345. ];
  5346. let hasSpread = false;
  5347. for (let index = 0; index < this.elements.length; index++) {
  5348. const element = this.elements[index];
  5349. if (hasSpread || element instanceof SpreadElement) {
  5350. if (element) {
  5351. hasSpread = true;
  5352. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5353. }
  5354. }
  5355. else if (!element) {
  5356. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5357. }
  5358. else {
  5359. properties.push({ key: String(index), kind: 'init', property: element });
  5360. }
  5361. }
  5362. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5363. }
  5364. }
  5365. class ArrayPattern extends NodeBase {
  5366. addExportedVariables(variables, exportNamesByVariable) {
  5367. for (const element of this.elements) {
  5368. element === null || element === void 0 ? void 0 : element.addExportedVariables(variables, exportNamesByVariable);
  5369. }
  5370. }
  5371. declare(kind) {
  5372. const variables = [];
  5373. for (const element of this.elements) {
  5374. if (element !== null) {
  5375. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5376. }
  5377. }
  5378. return variables;
  5379. }
  5380. // Patterns can only be deoptimized at the empty path at the moment
  5381. deoptimizePath() {
  5382. for (const element of this.elements) {
  5383. element === null || element === void 0 ? void 0 : element.deoptimizePath(EMPTY_PATH);
  5384. }
  5385. }
  5386. // Patterns are only checked at the emtpy path at the moment
  5387. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5388. for (const element of this.elements) {
  5389. if (element === null || element === void 0 ? void 0 : element.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5390. return true;
  5391. }
  5392. return false;
  5393. }
  5394. markDeclarationReached() {
  5395. for (const element of this.elements) {
  5396. element === null || element === void 0 ? void 0 : element.markDeclarationReached();
  5397. }
  5398. }
  5399. }
  5400. class LocalVariable extends Variable {
  5401. constructor(name, declarator, init, context) {
  5402. super(name);
  5403. this.calledFromTryStatement = false;
  5404. this.additionalInitializers = null;
  5405. this.expressionsToBeDeoptimized = [];
  5406. this.declarations = declarator ? [declarator] : [];
  5407. this.init = init;
  5408. this.deoptimizationTracker = context.deoptimizationTracker;
  5409. this.module = context.module;
  5410. }
  5411. addDeclaration(identifier, init) {
  5412. this.declarations.push(identifier);
  5413. const additionalInitializers = this.markInitializersForDeoptimization();
  5414. if (init !== null) {
  5415. additionalInitializers.push(init);
  5416. }
  5417. }
  5418. consolidateInitializers() {
  5419. if (this.additionalInitializers !== null) {
  5420. for (const initializer of this.additionalInitializers) {
  5421. initializer.deoptimizePath(UNKNOWN_PATH);
  5422. }
  5423. this.additionalInitializers = null;
  5424. }
  5425. }
  5426. deoptimizePath(path) {
  5427. var _a, _b;
  5428. if (this.isReassigned ||
  5429. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  5430. return;
  5431. }
  5432. if (path.length === 0) {
  5433. if (!this.isReassigned) {
  5434. this.isReassigned = true;
  5435. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  5436. this.expressionsToBeDeoptimized = [];
  5437. for (const expression of expressionsToBeDeoptimized) {
  5438. expression.deoptimizeCache();
  5439. }
  5440. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  5441. }
  5442. }
  5443. else {
  5444. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  5445. }
  5446. }
  5447. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  5448. if (this.isReassigned || !this.init) {
  5449. return interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  5450. }
  5451. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  5452. }
  5453. getLiteralValueAtPath(path, recursionTracker, origin) {
  5454. if (this.isReassigned || !this.init) {
  5455. return UnknownValue;
  5456. }
  5457. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5458. this.expressionsToBeDeoptimized.push(origin);
  5459. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  5460. }, UnknownValue);
  5461. }
  5462. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5463. if (this.isReassigned || !this.init) {
  5464. return UNKNOWN_EXPRESSION;
  5465. }
  5466. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  5467. this.expressionsToBeDeoptimized.push(origin);
  5468. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5469. }, UNKNOWN_EXPRESSION);
  5470. }
  5471. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5472. switch (interaction.type) {
  5473. case INTERACTION_ACCESSED:
  5474. if (this.isReassigned)
  5475. return true;
  5476. return (this.init &&
  5477. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  5478. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5479. case INTERACTION_ASSIGNED:
  5480. if (this.included)
  5481. return true;
  5482. if (path.length === 0)
  5483. return false;
  5484. if (this.isReassigned)
  5485. return true;
  5486. return (this.init &&
  5487. !context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  5488. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5489. case INTERACTION_CALLED:
  5490. if (this.isReassigned)
  5491. return true;
  5492. return (this.init &&
  5493. !(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  5494. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  5495. }
  5496. }
  5497. include() {
  5498. if (!this.included) {
  5499. this.included = true;
  5500. for (const declaration of this.declarations) {
  5501. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  5502. if (!declaration.included)
  5503. declaration.include(createInclusionContext(), false);
  5504. let node = declaration.parent;
  5505. while (!node.included) {
  5506. // We do not want to properly include parents in case they are part of a dead branch
  5507. // in which case .include() might pull in more dead code
  5508. node.included = true;
  5509. if (node.type === Program$1)
  5510. break;
  5511. node = node.parent;
  5512. }
  5513. }
  5514. }
  5515. }
  5516. includeCallArguments(context, args) {
  5517. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  5518. for (const arg of args) {
  5519. arg.include(context, false);
  5520. }
  5521. }
  5522. else if (this.init) {
  5523. context.includedCallArguments.add(this.init);
  5524. this.init.includeCallArguments(context, args);
  5525. context.includedCallArguments.delete(this.init);
  5526. }
  5527. }
  5528. markCalledFromTryStatement() {
  5529. this.calledFromTryStatement = true;
  5530. }
  5531. markInitializersForDeoptimization() {
  5532. if (this.additionalInitializers === null) {
  5533. this.additionalInitializers = this.init === null ? [] : [this.init];
  5534. this.init = UNKNOWN_EXPRESSION;
  5535. this.isReassigned = true;
  5536. }
  5537. return this.additionalInitializers;
  5538. }
  5539. }
  5540. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5541. const base = 64;
  5542. function toBase64(num) {
  5543. let outStr = '';
  5544. do {
  5545. const curDigit = num % base;
  5546. num = Math.floor(num / base);
  5547. outStr = chars[curDigit] + outStr;
  5548. } while (num !== 0);
  5549. return outStr;
  5550. }
  5551. function getSafeName(baseName, usedNames) {
  5552. let safeName = baseName;
  5553. let count = 1;
  5554. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName)) {
  5555. safeName = `${baseName}$${toBase64(count++)}`;
  5556. }
  5557. usedNames.add(safeName);
  5558. return safeName;
  5559. }
  5560. class Scope$1 {
  5561. constructor() {
  5562. this.children = [];
  5563. this.variables = new Map();
  5564. }
  5565. addDeclaration(identifier, context, init, _isHoisted) {
  5566. const name = identifier.name;
  5567. let variable = this.variables.get(name);
  5568. if (variable) {
  5569. variable.addDeclaration(identifier, init);
  5570. }
  5571. else {
  5572. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  5573. this.variables.set(name, variable);
  5574. }
  5575. return variable;
  5576. }
  5577. contains(name) {
  5578. return this.variables.has(name);
  5579. }
  5580. findVariable(_name) {
  5581. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5582. }
  5583. }
  5584. class ChildScope extends Scope$1 {
  5585. constructor(parent) {
  5586. super();
  5587. this.accessedOutsideVariables = new Map();
  5588. this.parent = parent;
  5589. parent.children.push(this);
  5590. }
  5591. addAccessedDynamicImport(importExpression) {
  5592. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5593. if (this.parent instanceof ChildScope) {
  5594. this.parent.addAccessedDynamicImport(importExpression);
  5595. }
  5596. }
  5597. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5598. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5599. for (const name of globals) {
  5600. accessedGlobals.add(name);
  5601. }
  5602. accessedGlobalsByScope.set(this, accessedGlobals);
  5603. if (this.parent instanceof ChildScope) {
  5604. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5605. }
  5606. }
  5607. addNamespaceMemberAccess(name, variable) {
  5608. this.accessedOutsideVariables.set(name, variable);
  5609. this.parent.addNamespaceMemberAccess(name, variable);
  5610. }
  5611. addReturnExpression(expression) {
  5612. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  5613. }
  5614. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  5615. for (const variable of this.accessedOutsideVariables.values()) {
  5616. if (variable.included) {
  5617. usedNames.add(variable.getBaseVariableName());
  5618. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5619. usedNames.add('exports');
  5620. }
  5621. }
  5622. }
  5623. const accessedGlobals = accessedGlobalsByScope.get(this);
  5624. if (accessedGlobals) {
  5625. for (const name of accessedGlobals) {
  5626. usedNames.add(name);
  5627. }
  5628. }
  5629. }
  5630. contains(name) {
  5631. return this.variables.has(name) || this.parent.contains(name);
  5632. }
  5633. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5634. const usedNames = new Set();
  5635. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  5636. if (this.accessedDynamicImports) {
  5637. for (const importExpression of this.accessedDynamicImports) {
  5638. if (importExpression.inlineNamespace) {
  5639. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5640. }
  5641. }
  5642. }
  5643. for (const [name, variable] of this.variables) {
  5644. if (variable.included || variable.alwaysRendered) {
  5645. variable.setRenderNames(null, getSafeName(name, usedNames));
  5646. }
  5647. }
  5648. for (const scope of this.children) {
  5649. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5650. }
  5651. }
  5652. findLexicalBoundary() {
  5653. return this.parent.findLexicalBoundary();
  5654. }
  5655. findVariable(name) {
  5656. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5657. if (knownVariable) {
  5658. return knownVariable;
  5659. }
  5660. const variable = this.parent.findVariable(name);
  5661. this.accessedOutsideVariables.set(name, variable);
  5662. return variable;
  5663. }
  5664. }
  5665. class ParameterScope extends ChildScope {
  5666. constructor(parent, context) {
  5667. super(parent);
  5668. this.parameters = [];
  5669. this.hasRest = false;
  5670. this.context = context;
  5671. this.hoistedBodyVarScope = new ChildScope(this);
  5672. }
  5673. /**
  5674. * Adds a parameter to this scope. Parameters must be added in the correct
  5675. * order, e.g. from left to right.
  5676. */
  5677. addParameterDeclaration(identifier) {
  5678. const name = identifier.name;
  5679. let variable = this.hoistedBodyVarScope.variables.get(name);
  5680. if (variable) {
  5681. variable.addDeclaration(identifier, null);
  5682. }
  5683. else {
  5684. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  5685. }
  5686. this.variables.set(name, variable);
  5687. return variable;
  5688. }
  5689. addParameterVariables(parameters, hasRest) {
  5690. this.parameters = parameters;
  5691. for (const parameterList of parameters) {
  5692. for (const parameter of parameterList) {
  5693. parameter.alwaysRendered = true;
  5694. }
  5695. }
  5696. this.hasRest = hasRest;
  5697. }
  5698. includeCallArguments(context, args) {
  5699. let calledFromTryStatement = false;
  5700. let argIncluded = false;
  5701. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  5702. for (const checkedArg of args) {
  5703. if (checkedArg instanceof SpreadElement) {
  5704. for (const arg of args) {
  5705. arg.include(context, false);
  5706. }
  5707. break;
  5708. }
  5709. }
  5710. for (let index = args.length - 1; index >= 0; index--) {
  5711. const paramVars = this.parameters[index] || restParam;
  5712. const arg = args[index];
  5713. if (paramVars) {
  5714. calledFromTryStatement = false;
  5715. if (paramVars.length === 0) {
  5716. // handle empty destructuring
  5717. argIncluded = true;
  5718. }
  5719. else {
  5720. for (const variable of paramVars) {
  5721. if (variable.included) {
  5722. argIncluded = true;
  5723. }
  5724. if (variable.calledFromTryStatement) {
  5725. calledFromTryStatement = true;
  5726. }
  5727. }
  5728. }
  5729. }
  5730. if (!argIncluded && arg.shouldBeIncluded(context)) {
  5731. argIncluded = true;
  5732. }
  5733. if (argIncluded) {
  5734. arg.include(context, calledFromTryStatement);
  5735. }
  5736. }
  5737. }
  5738. }
  5739. class ReturnValueScope extends ParameterScope {
  5740. constructor() {
  5741. super(...arguments);
  5742. this.returnExpression = null;
  5743. this.returnExpressions = [];
  5744. }
  5745. addReturnExpression(expression) {
  5746. this.returnExpressions.push(expression);
  5747. }
  5748. getReturnExpression() {
  5749. if (this.returnExpression === null)
  5750. this.updateReturnExpression();
  5751. return this.returnExpression;
  5752. }
  5753. updateReturnExpression() {
  5754. if (this.returnExpressions.length === 1) {
  5755. this.returnExpression = this.returnExpressions[0];
  5756. }
  5757. else {
  5758. this.returnExpression = UNKNOWN_EXPRESSION;
  5759. for (const expression of this.returnExpressions) {
  5760. expression.deoptimizePath(UNKNOWN_PATH);
  5761. }
  5762. }
  5763. }
  5764. }
  5765. //@ts-check
  5766. /** @typedef { import('estree').Node} Node */
  5767. /** @typedef {Node | {
  5768. * type: 'PropertyDefinition';
  5769. * computed: boolean;
  5770. * value: Node
  5771. * }} NodeWithPropertyDefinition */
  5772. /**
  5773. *
  5774. * @param {NodeWithPropertyDefinition} node
  5775. * @param {NodeWithPropertyDefinition} parent
  5776. * @returns boolean
  5777. */
  5778. function is_reference (node, parent) {
  5779. if (node.type === 'MemberExpression') {
  5780. return !node.computed && is_reference(node.object, node);
  5781. }
  5782. if (node.type === 'Identifier') {
  5783. if (!parent) return true;
  5784. switch (parent.type) {
  5785. // disregard `bar` in `foo.bar`
  5786. case 'MemberExpression': return parent.computed || node === parent.object;
  5787. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  5788. case 'MethodDefinition': return parent.computed;
  5789. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  5790. case 'PropertyDefinition': return parent.computed || node === parent.value;
  5791. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  5792. case 'Property': return parent.computed || node === parent.value;
  5793. // disregard the `bar` in `export { foo as bar }` or
  5794. // the foo in `import { foo as bar }`
  5795. case 'ExportSpecifier':
  5796. case 'ImportSpecifier': return node === parent.local;
  5797. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  5798. case 'LabeledStatement':
  5799. case 'BreakStatement':
  5800. case 'ContinueStatement': return false;
  5801. default: return true;
  5802. }
  5803. }
  5804. return false;
  5805. }
  5806. /* eslint sort-keys: "off" */
  5807. const ValueProperties = Symbol('Value Properties');
  5808. const PURE = {
  5809. hasEffectsWhenCalled() {
  5810. return false;
  5811. }
  5812. };
  5813. const IMPURE = {
  5814. hasEffectsWhenCalled() {
  5815. return true;
  5816. }
  5817. };
  5818. // We use shortened variables to reduce file size here
  5819. /* OBJECT */
  5820. const O = {
  5821. __proto__: null,
  5822. [ValueProperties]: IMPURE
  5823. };
  5824. /* PURE FUNCTION */
  5825. const PF = {
  5826. __proto__: null,
  5827. [ValueProperties]: PURE
  5828. };
  5829. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  5830. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  5831. __proto__: null,
  5832. [ValueProperties]: {
  5833. hasEffectsWhenCalled({ args }, context) {
  5834. return (!args.length ||
  5835. args[0].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  5836. }
  5837. }
  5838. };
  5839. /* CONSTRUCTOR */
  5840. const C = {
  5841. __proto__: null,
  5842. [ValueProperties]: IMPURE,
  5843. prototype: O
  5844. };
  5845. /* PURE CONSTRUCTOR */
  5846. const PC = {
  5847. __proto__: null,
  5848. [ValueProperties]: PURE,
  5849. prototype: O
  5850. };
  5851. const ARRAY_TYPE = {
  5852. __proto__: null,
  5853. [ValueProperties]: PURE,
  5854. from: PF,
  5855. of: PF,
  5856. prototype: O
  5857. };
  5858. const INTL_MEMBER = {
  5859. __proto__: null,
  5860. [ValueProperties]: PURE,
  5861. supportedLocalesOf: PC
  5862. };
  5863. const knownGlobals = {
  5864. // Placeholders for global objects to avoid shape mutations
  5865. global: O,
  5866. globalThis: O,
  5867. self: O,
  5868. window: O,
  5869. // Common globals
  5870. __proto__: null,
  5871. [ValueProperties]: IMPURE,
  5872. Array: {
  5873. __proto__: null,
  5874. [ValueProperties]: IMPURE,
  5875. from: O,
  5876. isArray: PF,
  5877. of: PF,
  5878. prototype: O
  5879. },
  5880. ArrayBuffer: {
  5881. __proto__: null,
  5882. [ValueProperties]: PURE,
  5883. isView: PF,
  5884. prototype: O
  5885. },
  5886. Atomics: O,
  5887. BigInt: C,
  5888. BigInt64Array: C,
  5889. BigUint64Array: C,
  5890. Boolean: PC,
  5891. constructor: C,
  5892. DataView: PC,
  5893. Date: {
  5894. __proto__: null,
  5895. [ValueProperties]: PURE,
  5896. now: PF,
  5897. parse: PF,
  5898. prototype: O,
  5899. UTC: PF
  5900. },
  5901. decodeURI: PF,
  5902. decodeURIComponent: PF,
  5903. encodeURI: PF,
  5904. encodeURIComponent: PF,
  5905. Error: PC,
  5906. escape: PF,
  5907. eval: O,
  5908. EvalError: PC,
  5909. Float32Array: ARRAY_TYPE,
  5910. Float64Array: ARRAY_TYPE,
  5911. Function: C,
  5912. hasOwnProperty: O,
  5913. Infinity: O,
  5914. Int16Array: ARRAY_TYPE,
  5915. Int32Array: ARRAY_TYPE,
  5916. Int8Array: ARRAY_TYPE,
  5917. isFinite: PF,
  5918. isNaN: PF,
  5919. isPrototypeOf: O,
  5920. JSON: O,
  5921. Map: PC,
  5922. Math: {
  5923. __proto__: null,
  5924. [ValueProperties]: IMPURE,
  5925. abs: PF,
  5926. acos: PF,
  5927. acosh: PF,
  5928. asin: PF,
  5929. asinh: PF,
  5930. atan: PF,
  5931. atan2: PF,
  5932. atanh: PF,
  5933. cbrt: PF,
  5934. ceil: PF,
  5935. clz32: PF,
  5936. cos: PF,
  5937. cosh: PF,
  5938. exp: PF,
  5939. expm1: PF,
  5940. floor: PF,
  5941. fround: PF,
  5942. hypot: PF,
  5943. imul: PF,
  5944. log: PF,
  5945. log10: PF,
  5946. log1p: PF,
  5947. log2: PF,
  5948. max: PF,
  5949. min: PF,
  5950. pow: PF,
  5951. random: PF,
  5952. round: PF,
  5953. sign: PF,
  5954. sin: PF,
  5955. sinh: PF,
  5956. sqrt: PF,
  5957. tan: PF,
  5958. tanh: PF,
  5959. trunc: PF
  5960. },
  5961. NaN: O,
  5962. Number: {
  5963. __proto__: null,
  5964. [ValueProperties]: PURE,
  5965. isFinite: PF,
  5966. isInteger: PF,
  5967. isNaN: PF,
  5968. isSafeInteger: PF,
  5969. parseFloat: PF,
  5970. parseInt: PF,
  5971. prototype: O
  5972. },
  5973. Object: {
  5974. __proto__: null,
  5975. [ValueProperties]: PURE,
  5976. create: PF,
  5977. // Technically those can throw in certain situations, but we ignore this as
  5978. // code that relies on this will hopefully wrap this in a try-catch, which
  5979. // deoptimizes everything anyway
  5980. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  5981. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  5982. getOwnPropertyDescriptor: PF,
  5983. getOwnPropertyNames: PF,
  5984. getOwnPropertySymbols: PF,
  5985. getPrototypeOf: PF,
  5986. hasOwn: PF,
  5987. is: PF,
  5988. isExtensible: PF,
  5989. isFrozen: PF,
  5990. isSealed: PF,
  5991. keys: PF,
  5992. fromEntries: PF,
  5993. entries: PF,
  5994. prototype: O
  5995. },
  5996. parseFloat: PF,
  5997. parseInt: PF,
  5998. Promise: {
  5999. __proto__: null,
  6000. [ValueProperties]: IMPURE,
  6001. all: O,
  6002. prototype: O,
  6003. race: O,
  6004. reject: O,
  6005. resolve: O
  6006. },
  6007. propertyIsEnumerable: O,
  6008. Proxy: O,
  6009. RangeError: PC,
  6010. ReferenceError: PC,
  6011. Reflect: O,
  6012. RegExp: PC,
  6013. Set: PC,
  6014. SharedArrayBuffer: C,
  6015. String: {
  6016. __proto__: null,
  6017. [ValueProperties]: PURE,
  6018. fromCharCode: PF,
  6019. fromCodePoint: PF,
  6020. prototype: O,
  6021. raw: PF
  6022. },
  6023. Symbol: {
  6024. __proto__: null,
  6025. [ValueProperties]: PURE,
  6026. for: PF,
  6027. keyFor: PF,
  6028. prototype: O
  6029. },
  6030. SyntaxError: PC,
  6031. toLocaleString: O,
  6032. toString: O,
  6033. TypeError: PC,
  6034. Uint16Array: ARRAY_TYPE,
  6035. Uint32Array: ARRAY_TYPE,
  6036. Uint8Array: ARRAY_TYPE,
  6037. Uint8ClampedArray: ARRAY_TYPE,
  6038. // Technically, this is a global, but it needs special handling
  6039. // undefined: ?,
  6040. unescape: PF,
  6041. URIError: PC,
  6042. valueOf: O,
  6043. WeakMap: PC,
  6044. WeakSet: PC,
  6045. // Additional globals shared by Node and Browser that are not strictly part of the language
  6046. clearInterval: C,
  6047. clearTimeout: C,
  6048. console: O,
  6049. Intl: {
  6050. __proto__: null,
  6051. [ValueProperties]: IMPURE,
  6052. Collator: INTL_MEMBER,
  6053. DateTimeFormat: INTL_MEMBER,
  6054. ListFormat: INTL_MEMBER,
  6055. NumberFormat: INTL_MEMBER,
  6056. PluralRules: INTL_MEMBER,
  6057. RelativeTimeFormat: INTL_MEMBER
  6058. },
  6059. setInterval: C,
  6060. setTimeout: C,
  6061. TextDecoder: C,
  6062. TextEncoder: C,
  6063. URL: C,
  6064. URLSearchParams: C,
  6065. // Browser specific globals
  6066. AbortController: C,
  6067. AbortSignal: C,
  6068. addEventListener: O,
  6069. alert: O,
  6070. AnalyserNode: C,
  6071. Animation: C,
  6072. AnimationEvent: C,
  6073. applicationCache: O,
  6074. ApplicationCache: C,
  6075. ApplicationCacheErrorEvent: C,
  6076. atob: O,
  6077. Attr: C,
  6078. Audio: C,
  6079. AudioBuffer: C,
  6080. AudioBufferSourceNode: C,
  6081. AudioContext: C,
  6082. AudioDestinationNode: C,
  6083. AudioListener: C,
  6084. AudioNode: C,
  6085. AudioParam: C,
  6086. AudioProcessingEvent: C,
  6087. AudioScheduledSourceNode: C,
  6088. AudioWorkletNode: C,
  6089. BarProp: C,
  6090. BaseAudioContext: C,
  6091. BatteryManager: C,
  6092. BeforeUnloadEvent: C,
  6093. BiquadFilterNode: C,
  6094. Blob: C,
  6095. BlobEvent: C,
  6096. blur: O,
  6097. BroadcastChannel: C,
  6098. btoa: O,
  6099. ByteLengthQueuingStrategy: C,
  6100. Cache: C,
  6101. caches: O,
  6102. CacheStorage: C,
  6103. cancelAnimationFrame: O,
  6104. cancelIdleCallback: O,
  6105. CanvasCaptureMediaStreamTrack: C,
  6106. CanvasGradient: C,
  6107. CanvasPattern: C,
  6108. CanvasRenderingContext2D: C,
  6109. ChannelMergerNode: C,
  6110. ChannelSplitterNode: C,
  6111. CharacterData: C,
  6112. clientInformation: O,
  6113. ClipboardEvent: C,
  6114. close: O,
  6115. closed: O,
  6116. CloseEvent: C,
  6117. Comment: C,
  6118. CompositionEvent: C,
  6119. confirm: O,
  6120. ConstantSourceNode: C,
  6121. ConvolverNode: C,
  6122. CountQueuingStrategy: C,
  6123. createImageBitmap: O,
  6124. Credential: C,
  6125. CredentialsContainer: C,
  6126. crypto: O,
  6127. Crypto: C,
  6128. CryptoKey: C,
  6129. CSS: C,
  6130. CSSConditionRule: C,
  6131. CSSFontFaceRule: C,
  6132. CSSGroupingRule: C,
  6133. CSSImportRule: C,
  6134. CSSKeyframeRule: C,
  6135. CSSKeyframesRule: C,
  6136. CSSMediaRule: C,
  6137. CSSNamespaceRule: C,
  6138. CSSPageRule: C,
  6139. CSSRule: C,
  6140. CSSRuleList: C,
  6141. CSSStyleDeclaration: C,
  6142. CSSStyleRule: C,
  6143. CSSStyleSheet: C,
  6144. CSSSupportsRule: C,
  6145. CustomElementRegistry: C,
  6146. customElements: O,
  6147. CustomEvent: C,
  6148. DataTransfer: C,
  6149. DataTransferItem: C,
  6150. DataTransferItemList: C,
  6151. defaultstatus: O,
  6152. defaultStatus: O,
  6153. DelayNode: C,
  6154. DeviceMotionEvent: C,
  6155. DeviceOrientationEvent: C,
  6156. devicePixelRatio: O,
  6157. dispatchEvent: O,
  6158. document: O,
  6159. Document: C,
  6160. DocumentFragment: C,
  6161. DocumentType: C,
  6162. DOMError: C,
  6163. DOMException: C,
  6164. DOMImplementation: C,
  6165. DOMMatrix: C,
  6166. DOMMatrixReadOnly: C,
  6167. DOMParser: C,
  6168. DOMPoint: C,
  6169. DOMPointReadOnly: C,
  6170. DOMQuad: C,
  6171. DOMRect: C,
  6172. DOMRectReadOnly: C,
  6173. DOMStringList: C,
  6174. DOMStringMap: C,
  6175. DOMTokenList: C,
  6176. DragEvent: C,
  6177. DynamicsCompressorNode: C,
  6178. Element: C,
  6179. ErrorEvent: C,
  6180. Event: C,
  6181. EventSource: C,
  6182. EventTarget: C,
  6183. external: O,
  6184. fetch: O,
  6185. File: C,
  6186. FileList: C,
  6187. FileReader: C,
  6188. find: O,
  6189. focus: O,
  6190. FocusEvent: C,
  6191. FontFace: C,
  6192. FontFaceSetLoadEvent: C,
  6193. FormData: C,
  6194. frames: O,
  6195. GainNode: C,
  6196. Gamepad: C,
  6197. GamepadButton: C,
  6198. GamepadEvent: C,
  6199. getComputedStyle: O,
  6200. getSelection: O,
  6201. HashChangeEvent: C,
  6202. Headers: C,
  6203. history: O,
  6204. History: C,
  6205. HTMLAllCollection: C,
  6206. HTMLAnchorElement: C,
  6207. HTMLAreaElement: C,
  6208. HTMLAudioElement: C,
  6209. HTMLBaseElement: C,
  6210. HTMLBodyElement: C,
  6211. HTMLBRElement: C,
  6212. HTMLButtonElement: C,
  6213. HTMLCanvasElement: C,
  6214. HTMLCollection: C,
  6215. HTMLContentElement: C,
  6216. HTMLDataElement: C,
  6217. HTMLDataListElement: C,
  6218. HTMLDetailsElement: C,
  6219. HTMLDialogElement: C,
  6220. HTMLDirectoryElement: C,
  6221. HTMLDivElement: C,
  6222. HTMLDListElement: C,
  6223. HTMLDocument: C,
  6224. HTMLElement: C,
  6225. HTMLEmbedElement: C,
  6226. HTMLFieldSetElement: C,
  6227. HTMLFontElement: C,
  6228. HTMLFormControlsCollection: C,
  6229. HTMLFormElement: C,
  6230. HTMLFrameElement: C,
  6231. HTMLFrameSetElement: C,
  6232. HTMLHeadElement: C,
  6233. HTMLHeadingElement: C,
  6234. HTMLHRElement: C,
  6235. HTMLHtmlElement: C,
  6236. HTMLIFrameElement: C,
  6237. HTMLImageElement: C,
  6238. HTMLInputElement: C,
  6239. HTMLLabelElement: C,
  6240. HTMLLegendElement: C,
  6241. HTMLLIElement: C,
  6242. HTMLLinkElement: C,
  6243. HTMLMapElement: C,
  6244. HTMLMarqueeElement: C,
  6245. HTMLMediaElement: C,
  6246. HTMLMenuElement: C,
  6247. HTMLMetaElement: C,
  6248. HTMLMeterElement: C,
  6249. HTMLModElement: C,
  6250. HTMLObjectElement: C,
  6251. HTMLOListElement: C,
  6252. HTMLOptGroupElement: C,
  6253. HTMLOptionElement: C,
  6254. HTMLOptionsCollection: C,
  6255. HTMLOutputElement: C,
  6256. HTMLParagraphElement: C,
  6257. HTMLParamElement: C,
  6258. HTMLPictureElement: C,
  6259. HTMLPreElement: C,
  6260. HTMLProgressElement: C,
  6261. HTMLQuoteElement: C,
  6262. HTMLScriptElement: C,
  6263. HTMLSelectElement: C,
  6264. HTMLShadowElement: C,
  6265. HTMLSlotElement: C,
  6266. HTMLSourceElement: C,
  6267. HTMLSpanElement: C,
  6268. HTMLStyleElement: C,
  6269. HTMLTableCaptionElement: C,
  6270. HTMLTableCellElement: C,
  6271. HTMLTableColElement: C,
  6272. HTMLTableElement: C,
  6273. HTMLTableRowElement: C,
  6274. HTMLTableSectionElement: C,
  6275. HTMLTemplateElement: C,
  6276. HTMLTextAreaElement: C,
  6277. HTMLTimeElement: C,
  6278. HTMLTitleElement: C,
  6279. HTMLTrackElement: C,
  6280. HTMLUListElement: C,
  6281. HTMLUnknownElement: C,
  6282. HTMLVideoElement: C,
  6283. IDBCursor: C,
  6284. IDBCursorWithValue: C,
  6285. IDBDatabase: C,
  6286. IDBFactory: C,
  6287. IDBIndex: C,
  6288. IDBKeyRange: C,
  6289. IDBObjectStore: C,
  6290. IDBOpenDBRequest: C,
  6291. IDBRequest: C,
  6292. IDBTransaction: C,
  6293. IDBVersionChangeEvent: C,
  6294. IdleDeadline: C,
  6295. IIRFilterNode: C,
  6296. Image: C,
  6297. ImageBitmap: C,
  6298. ImageBitmapRenderingContext: C,
  6299. ImageCapture: C,
  6300. ImageData: C,
  6301. indexedDB: O,
  6302. innerHeight: O,
  6303. innerWidth: O,
  6304. InputEvent: C,
  6305. IntersectionObserver: C,
  6306. IntersectionObserverEntry: C,
  6307. isSecureContext: O,
  6308. KeyboardEvent: C,
  6309. KeyframeEffect: C,
  6310. length: O,
  6311. localStorage: O,
  6312. location: O,
  6313. Location: C,
  6314. locationbar: O,
  6315. matchMedia: O,
  6316. MediaDeviceInfo: C,
  6317. MediaDevices: C,
  6318. MediaElementAudioSourceNode: C,
  6319. MediaEncryptedEvent: C,
  6320. MediaError: C,
  6321. MediaKeyMessageEvent: C,
  6322. MediaKeySession: C,
  6323. MediaKeyStatusMap: C,
  6324. MediaKeySystemAccess: C,
  6325. MediaList: C,
  6326. MediaQueryList: C,
  6327. MediaQueryListEvent: C,
  6328. MediaRecorder: C,
  6329. MediaSettingsRange: C,
  6330. MediaSource: C,
  6331. MediaStream: C,
  6332. MediaStreamAudioDestinationNode: C,
  6333. MediaStreamAudioSourceNode: C,
  6334. MediaStreamEvent: C,
  6335. MediaStreamTrack: C,
  6336. MediaStreamTrackEvent: C,
  6337. menubar: O,
  6338. MessageChannel: C,
  6339. MessageEvent: C,
  6340. MessagePort: C,
  6341. MIDIAccess: C,
  6342. MIDIConnectionEvent: C,
  6343. MIDIInput: C,
  6344. MIDIInputMap: C,
  6345. MIDIMessageEvent: C,
  6346. MIDIOutput: C,
  6347. MIDIOutputMap: C,
  6348. MIDIPort: C,
  6349. MimeType: C,
  6350. MimeTypeArray: C,
  6351. MouseEvent: C,
  6352. moveBy: O,
  6353. moveTo: O,
  6354. MutationEvent: C,
  6355. MutationObserver: C,
  6356. MutationRecord: C,
  6357. name: O,
  6358. NamedNodeMap: C,
  6359. NavigationPreloadManager: C,
  6360. navigator: O,
  6361. Navigator: C,
  6362. NetworkInformation: C,
  6363. Node: C,
  6364. NodeFilter: O,
  6365. NodeIterator: C,
  6366. NodeList: C,
  6367. Notification: C,
  6368. OfflineAudioCompletionEvent: C,
  6369. OfflineAudioContext: C,
  6370. offscreenBuffering: O,
  6371. OffscreenCanvas: C,
  6372. open: O,
  6373. openDatabase: O,
  6374. Option: C,
  6375. origin: O,
  6376. OscillatorNode: C,
  6377. outerHeight: O,
  6378. outerWidth: O,
  6379. PageTransitionEvent: C,
  6380. pageXOffset: O,
  6381. pageYOffset: O,
  6382. PannerNode: C,
  6383. parent: O,
  6384. Path2D: C,
  6385. PaymentAddress: C,
  6386. PaymentRequest: C,
  6387. PaymentRequestUpdateEvent: C,
  6388. PaymentResponse: C,
  6389. performance: O,
  6390. Performance: C,
  6391. PerformanceEntry: C,
  6392. PerformanceLongTaskTiming: C,
  6393. PerformanceMark: C,
  6394. PerformanceMeasure: C,
  6395. PerformanceNavigation: C,
  6396. PerformanceNavigationTiming: C,
  6397. PerformanceObserver: C,
  6398. PerformanceObserverEntryList: C,
  6399. PerformancePaintTiming: C,
  6400. PerformanceResourceTiming: C,
  6401. PerformanceTiming: C,
  6402. PeriodicWave: C,
  6403. Permissions: C,
  6404. PermissionStatus: C,
  6405. personalbar: O,
  6406. PhotoCapabilities: C,
  6407. Plugin: C,
  6408. PluginArray: C,
  6409. PointerEvent: C,
  6410. PopStateEvent: C,
  6411. postMessage: O,
  6412. Presentation: C,
  6413. PresentationAvailability: C,
  6414. PresentationConnection: C,
  6415. PresentationConnectionAvailableEvent: C,
  6416. PresentationConnectionCloseEvent: C,
  6417. PresentationConnectionList: C,
  6418. PresentationReceiver: C,
  6419. PresentationRequest: C,
  6420. print: O,
  6421. ProcessingInstruction: C,
  6422. ProgressEvent: C,
  6423. PromiseRejectionEvent: C,
  6424. prompt: O,
  6425. PushManager: C,
  6426. PushSubscription: C,
  6427. PushSubscriptionOptions: C,
  6428. queueMicrotask: O,
  6429. RadioNodeList: C,
  6430. Range: C,
  6431. ReadableStream: C,
  6432. RemotePlayback: C,
  6433. removeEventListener: O,
  6434. Request: C,
  6435. requestAnimationFrame: O,
  6436. requestIdleCallback: O,
  6437. resizeBy: O,
  6438. ResizeObserver: C,
  6439. ResizeObserverEntry: C,
  6440. resizeTo: O,
  6441. Response: C,
  6442. RTCCertificate: C,
  6443. RTCDataChannel: C,
  6444. RTCDataChannelEvent: C,
  6445. RTCDtlsTransport: C,
  6446. RTCIceCandidate: C,
  6447. RTCIceTransport: C,
  6448. RTCPeerConnection: C,
  6449. RTCPeerConnectionIceEvent: C,
  6450. RTCRtpReceiver: C,
  6451. RTCRtpSender: C,
  6452. RTCSctpTransport: C,
  6453. RTCSessionDescription: C,
  6454. RTCStatsReport: C,
  6455. RTCTrackEvent: C,
  6456. screen: O,
  6457. Screen: C,
  6458. screenLeft: O,
  6459. ScreenOrientation: C,
  6460. screenTop: O,
  6461. screenX: O,
  6462. screenY: O,
  6463. ScriptProcessorNode: C,
  6464. scroll: O,
  6465. scrollbars: O,
  6466. scrollBy: O,
  6467. scrollTo: O,
  6468. scrollX: O,
  6469. scrollY: O,
  6470. SecurityPolicyViolationEvent: C,
  6471. Selection: C,
  6472. ServiceWorker: C,
  6473. ServiceWorkerContainer: C,
  6474. ServiceWorkerRegistration: C,
  6475. sessionStorage: O,
  6476. ShadowRoot: C,
  6477. SharedWorker: C,
  6478. SourceBuffer: C,
  6479. SourceBufferList: C,
  6480. speechSynthesis: O,
  6481. SpeechSynthesisEvent: C,
  6482. SpeechSynthesisUtterance: C,
  6483. StaticRange: C,
  6484. status: O,
  6485. statusbar: O,
  6486. StereoPannerNode: C,
  6487. stop: O,
  6488. Storage: C,
  6489. StorageEvent: C,
  6490. StorageManager: C,
  6491. styleMedia: O,
  6492. StyleSheet: C,
  6493. StyleSheetList: C,
  6494. SubtleCrypto: C,
  6495. SVGAElement: C,
  6496. SVGAngle: C,
  6497. SVGAnimatedAngle: C,
  6498. SVGAnimatedBoolean: C,
  6499. SVGAnimatedEnumeration: C,
  6500. SVGAnimatedInteger: C,
  6501. SVGAnimatedLength: C,
  6502. SVGAnimatedLengthList: C,
  6503. SVGAnimatedNumber: C,
  6504. SVGAnimatedNumberList: C,
  6505. SVGAnimatedPreserveAspectRatio: C,
  6506. SVGAnimatedRect: C,
  6507. SVGAnimatedString: C,
  6508. SVGAnimatedTransformList: C,
  6509. SVGAnimateElement: C,
  6510. SVGAnimateMotionElement: C,
  6511. SVGAnimateTransformElement: C,
  6512. SVGAnimationElement: C,
  6513. SVGCircleElement: C,
  6514. SVGClipPathElement: C,
  6515. SVGComponentTransferFunctionElement: C,
  6516. SVGDefsElement: C,
  6517. SVGDescElement: C,
  6518. SVGDiscardElement: C,
  6519. SVGElement: C,
  6520. SVGEllipseElement: C,
  6521. SVGFEBlendElement: C,
  6522. SVGFEColorMatrixElement: C,
  6523. SVGFEComponentTransferElement: C,
  6524. SVGFECompositeElement: C,
  6525. SVGFEConvolveMatrixElement: C,
  6526. SVGFEDiffuseLightingElement: C,
  6527. SVGFEDisplacementMapElement: C,
  6528. SVGFEDistantLightElement: C,
  6529. SVGFEDropShadowElement: C,
  6530. SVGFEFloodElement: C,
  6531. SVGFEFuncAElement: C,
  6532. SVGFEFuncBElement: C,
  6533. SVGFEFuncGElement: C,
  6534. SVGFEFuncRElement: C,
  6535. SVGFEGaussianBlurElement: C,
  6536. SVGFEImageElement: C,
  6537. SVGFEMergeElement: C,
  6538. SVGFEMergeNodeElement: C,
  6539. SVGFEMorphologyElement: C,
  6540. SVGFEOffsetElement: C,
  6541. SVGFEPointLightElement: C,
  6542. SVGFESpecularLightingElement: C,
  6543. SVGFESpotLightElement: C,
  6544. SVGFETileElement: C,
  6545. SVGFETurbulenceElement: C,
  6546. SVGFilterElement: C,
  6547. SVGForeignObjectElement: C,
  6548. SVGGElement: C,
  6549. SVGGeometryElement: C,
  6550. SVGGradientElement: C,
  6551. SVGGraphicsElement: C,
  6552. SVGImageElement: C,
  6553. SVGLength: C,
  6554. SVGLengthList: C,
  6555. SVGLinearGradientElement: C,
  6556. SVGLineElement: C,
  6557. SVGMarkerElement: C,
  6558. SVGMaskElement: C,
  6559. SVGMatrix: C,
  6560. SVGMetadataElement: C,
  6561. SVGMPathElement: C,
  6562. SVGNumber: C,
  6563. SVGNumberList: C,
  6564. SVGPathElement: C,
  6565. SVGPatternElement: C,
  6566. SVGPoint: C,
  6567. SVGPointList: C,
  6568. SVGPolygonElement: C,
  6569. SVGPolylineElement: C,
  6570. SVGPreserveAspectRatio: C,
  6571. SVGRadialGradientElement: C,
  6572. SVGRect: C,
  6573. SVGRectElement: C,
  6574. SVGScriptElement: C,
  6575. SVGSetElement: C,
  6576. SVGStopElement: C,
  6577. SVGStringList: C,
  6578. SVGStyleElement: C,
  6579. SVGSVGElement: C,
  6580. SVGSwitchElement: C,
  6581. SVGSymbolElement: C,
  6582. SVGTextContentElement: C,
  6583. SVGTextElement: C,
  6584. SVGTextPathElement: C,
  6585. SVGTextPositioningElement: C,
  6586. SVGTitleElement: C,
  6587. SVGTransform: C,
  6588. SVGTransformList: C,
  6589. SVGTSpanElement: C,
  6590. SVGUnitTypes: C,
  6591. SVGUseElement: C,
  6592. SVGViewElement: C,
  6593. TaskAttributionTiming: C,
  6594. Text: C,
  6595. TextEvent: C,
  6596. TextMetrics: C,
  6597. TextTrack: C,
  6598. TextTrackCue: C,
  6599. TextTrackCueList: C,
  6600. TextTrackList: C,
  6601. TimeRanges: C,
  6602. toolbar: O,
  6603. top: O,
  6604. Touch: C,
  6605. TouchEvent: C,
  6606. TouchList: C,
  6607. TrackEvent: C,
  6608. TransitionEvent: C,
  6609. TreeWalker: C,
  6610. UIEvent: C,
  6611. ValidityState: C,
  6612. visualViewport: O,
  6613. VisualViewport: C,
  6614. VTTCue: C,
  6615. WaveShaperNode: C,
  6616. WebAssembly: O,
  6617. WebGL2RenderingContext: C,
  6618. WebGLActiveInfo: C,
  6619. WebGLBuffer: C,
  6620. WebGLContextEvent: C,
  6621. WebGLFramebuffer: C,
  6622. WebGLProgram: C,
  6623. WebGLQuery: C,
  6624. WebGLRenderbuffer: C,
  6625. WebGLRenderingContext: C,
  6626. WebGLSampler: C,
  6627. WebGLShader: C,
  6628. WebGLShaderPrecisionFormat: C,
  6629. WebGLSync: C,
  6630. WebGLTexture: C,
  6631. WebGLTransformFeedback: C,
  6632. WebGLUniformLocation: C,
  6633. WebGLVertexArrayObject: C,
  6634. WebSocket: C,
  6635. WheelEvent: C,
  6636. Window: C,
  6637. Worker: C,
  6638. WritableStream: C,
  6639. XMLDocument: C,
  6640. XMLHttpRequest: C,
  6641. XMLHttpRequestEventTarget: C,
  6642. XMLHttpRequestUpload: C,
  6643. XMLSerializer: C,
  6644. XPathEvaluator: C,
  6645. XPathExpression: C,
  6646. XPathResult: C,
  6647. XSLTProcessor: C
  6648. };
  6649. for (const global of ['window', 'global', 'self', 'globalThis']) {
  6650. knownGlobals[global] = knownGlobals;
  6651. }
  6652. function getGlobalAtPath(path) {
  6653. let currentGlobal = knownGlobals;
  6654. for (const pathSegment of path) {
  6655. if (typeof pathSegment !== 'string') {
  6656. return null;
  6657. }
  6658. currentGlobal = currentGlobal[pathSegment];
  6659. if (!currentGlobal) {
  6660. return null;
  6661. }
  6662. }
  6663. return currentGlobal[ValueProperties];
  6664. }
  6665. class GlobalVariable extends Variable {
  6666. constructor() {
  6667. super(...arguments);
  6668. // Ensure we use live-bindings for globals as we do not know if they have
  6669. // been reassigned
  6670. this.isReassigned = true;
  6671. }
  6672. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  6673. return getGlobalAtPath([this.name, ...path]) ? UnknownTruthyValue : UnknownValue;
  6674. }
  6675. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6676. switch (interaction.type) {
  6677. case INTERACTION_ACCESSED:
  6678. if (path.length === 0) {
  6679. // Technically, "undefined" is a global variable of sorts
  6680. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  6681. }
  6682. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  6683. case INTERACTION_ASSIGNED:
  6684. return true;
  6685. case INTERACTION_CALLED: {
  6686. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  6687. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  6688. }
  6689. }
  6690. }
  6691. }
  6692. const tdzVariableKinds = {
  6693. __proto__: null,
  6694. class: true,
  6695. const: true,
  6696. let: true,
  6697. var: true
  6698. };
  6699. class Identifier extends NodeBase {
  6700. constructor() {
  6701. super(...arguments);
  6702. this.variable = null;
  6703. this.isTDZAccess = null;
  6704. }
  6705. addExportedVariables(variables, exportNamesByVariable) {
  6706. if (exportNamesByVariable.has(this.variable)) {
  6707. variables.push(this.variable);
  6708. }
  6709. }
  6710. bind() {
  6711. if (!this.variable && is_reference(this, this.parent)) {
  6712. this.variable = this.scope.findVariable(this.name);
  6713. this.variable.addReference(this);
  6714. }
  6715. }
  6716. declare(kind, init) {
  6717. let variable;
  6718. const { treeshake } = this.context.options;
  6719. switch (kind) {
  6720. case 'var':
  6721. variable = this.scope.addDeclaration(this, this.context, init, true);
  6722. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  6723. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  6724. variable.markInitializersForDeoptimization();
  6725. }
  6726. break;
  6727. case 'function':
  6728. // in strict mode, functions are only hoisted within a scope but not across block scopes
  6729. variable = this.scope.addDeclaration(this, this.context, init, false);
  6730. break;
  6731. case 'let':
  6732. case 'const':
  6733. case 'class':
  6734. variable = this.scope.addDeclaration(this, this.context, init, false);
  6735. break;
  6736. case 'parameter':
  6737. variable = this.scope.addParameterDeclaration(this);
  6738. break;
  6739. /* istanbul ignore next */
  6740. default:
  6741. /* istanbul ignore next */
  6742. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  6743. }
  6744. variable.kind = kind;
  6745. return [(this.variable = variable)];
  6746. }
  6747. deoptimizePath(path) {
  6748. var _a;
  6749. if (path.length === 0 && !this.scope.contains(this.name)) {
  6750. this.disallowImportReassignment();
  6751. }
  6752. // We keep conditional chaining because an unknown Node could have an
  6753. // Identifier as property that might be deoptimized by default
  6754. (_a = this.variable) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  6755. }
  6756. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  6757. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  6758. }
  6759. getLiteralValueAtPath(path, recursionTracker, origin) {
  6760. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  6761. }
  6762. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6763. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6764. }
  6765. hasEffects(context) {
  6766. if (!this.deoptimized)
  6767. this.applyDeoptimizations();
  6768. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  6769. return true;
  6770. }
  6771. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  6772. this.variable instanceof GlobalVariable &&
  6773. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6774. }
  6775. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6776. switch (interaction.type) {
  6777. case INTERACTION_ACCESSED:
  6778. return (this.variable !== null &&
  6779. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  6780. case INTERACTION_ASSIGNED:
  6781. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  6782. case INTERACTION_CALLED:
  6783. return this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context);
  6784. }
  6785. }
  6786. include() {
  6787. if (!this.deoptimized)
  6788. this.applyDeoptimizations();
  6789. if (!this.included) {
  6790. this.included = true;
  6791. if (this.variable !== null) {
  6792. this.context.includeVariableInModule(this.variable);
  6793. }
  6794. }
  6795. }
  6796. includeCallArguments(context, args) {
  6797. this.variable.includeCallArguments(context, args);
  6798. }
  6799. isPossibleTDZ() {
  6800. // return cached value to avoid issues with the next tree-shaking pass
  6801. if (this.isTDZAccess !== null)
  6802. return this.isTDZAccess;
  6803. if (!(this.variable instanceof LocalVariable) ||
  6804. !this.variable.kind ||
  6805. !(this.variable.kind in tdzVariableKinds)) {
  6806. return (this.isTDZAccess = false);
  6807. }
  6808. let decl_id;
  6809. if (this.variable.declarations &&
  6810. this.variable.declarations.length === 1 &&
  6811. (decl_id = this.variable.declarations[0]) &&
  6812. this.start < decl_id.start &&
  6813. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  6814. // a variable accessed before its declaration
  6815. // in the same function or at top level of module
  6816. return (this.isTDZAccess = true);
  6817. }
  6818. if (!this.variable.initReached) {
  6819. // Either a const/let TDZ violation or
  6820. // var use before declaration was encountered.
  6821. return (this.isTDZAccess = true);
  6822. }
  6823. return (this.isTDZAccess = false);
  6824. }
  6825. markDeclarationReached() {
  6826. this.variable.initReached = true;
  6827. }
  6828. render(code, { snippets: { getPropertyAccess } }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  6829. if (this.variable) {
  6830. const name = this.variable.getName(getPropertyAccess);
  6831. if (name !== this.name) {
  6832. code.overwrite(this.start, this.end, name, {
  6833. contentOnly: true,
  6834. storeName: true
  6835. });
  6836. if (isShorthandProperty) {
  6837. code.prependRight(this.start, `${this.name}: `);
  6838. }
  6839. }
  6840. // In strict mode, any variable named "eval" must be the actual "eval" function
  6841. if (name === 'eval' &&
  6842. renderedParentType === CallExpression$1 &&
  6843. isCalleeOfRenderedParent) {
  6844. code.appendRight(this.start, '0, ');
  6845. }
  6846. }
  6847. }
  6848. applyDeoptimizations() {
  6849. this.deoptimized = true;
  6850. if (this.variable instanceof LocalVariable) {
  6851. this.variable.consolidateInitializers();
  6852. this.context.requestTreeshakingPass();
  6853. }
  6854. }
  6855. disallowImportReassignment() {
  6856. return this.context.error({
  6857. code: 'ILLEGAL_REASSIGNMENT',
  6858. message: `Illegal reassignment to import '${this.name}'`
  6859. }, this.start);
  6860. }
  6861. getVariableRespectingTDZ() {
  6862. if (this.isPossibleTDZ()) {
  6863. return UNKNOWN_EXPRESSION;
  6864. }
  6865. return this.variable;
  6866. }
  6867. }
  6868. function closestParentFunctionOrProgram(node) {
  6869. while (node && !/^Program|Function/.test(node.type)) {
  6870. node = node.parent;
  6871. }
  6872. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  6873. return node;
  6874. }
  6875. function treeshakeNode(node, code, start, end) {
  6876. code.remove(start, end);
  6877. if (node.annotations) {
  6878. for (const annotation of node.annotations) {
  6879. if (annotation.start < start) {
  6880. code.remove(annotation.start, annotation.end);
  6881. }
  6882. else {
  6883. return;
  6884. }
  6885. }
  6886. }
  6887. }
  6888. function removeAnnotations(node, code) {
  6889. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  6890. node = node.parent;
  6891. }
  6892. if (node.annotations) {
  6893. for (const annotation of node.annotations) {
  6894. code.remove(annotation.start, annotation.end);
  6895. }
  6896. }
  6897. }
  6898. const NO_SEMICOLON = { isNoStatement: true };
  6899. // This assumes there are only white-space and comments between start and the string we are looking for
  6900. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  6901. let searchPos, charCodeAfterSlash;
  6902. searchPos = code.indexOf(searchString, start);
  6903. while (true) {
  6904. start = code.indexOf('/', start);
  6905. if (start === -1 || start >= searchPos)
  6906. return searchPos;
  6907. charCodeAfterSlash = code.charCodeAt(++start);
  6908. ++start;
  6909. // With our assumption, '/' always starts a comment. Determine comment type:
  6910. start =
  6911. charCodeAfterSlash === 47 /*"/"*/
  6912. ? code.indexOf('\n', start) + 1
  6913. : code.indexOf('*/', start) + 2;
  6914. if (start > searchPos) {
  6915. searchPos = code.indexOf(searchString, start);
  6916. }
  6917. }
  6918. }
  6919. const NON_WHITESPACE = /\S/g;
  6920. function findNonWhiteSpace(code, index) {
  6921. NON_WHITESPACE.lastIndex = index;
  6922. const result = NON_WHITESPACE.exec(code);
  6923. return result.index;
  6924. }
  6925. // This assumes "code" only contains white-space and comments
  6926. // Returns position of line-comment if applicable
  6927. function findFirstLineBreakOutsideComment(code) {
  6928. let lineBreakPos, charCodeAfterSlash, start = 0;
  6929. lineBreakPos = code.indexOf('\n', start);
  6930. while (true) {
  6931. start = code.indexOf('/', start);
  6932. if (start === -1 || start > lineBreakPos)
  6933. return [lineBreakPos, lineBreakPos + 1];
  6934. // With our assumption, '/' always starts a comment. Determine comment type:
  6935. charCodeAfterSlash = code.charCodeAt(start + 1);
  6936. if (charCodeAfterSlash === 47 /*"/"*/)
  6937. return [start, lineBreakPos + 1];
  6938. start = code.indexOf('*/', start + 3) + 2;
  6939. if (start > lineBreakPos) {
  6940. lineBreakPos = code.indexOf('\n', start);
  6941. }
  6942. }
  6943. }
  6944. function renderStatementList(statements, code, start, end, options) {
  6945. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  6946. let nextNode = statements[0];
  6947. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  6948. if (nextNodeNeedsBoundaries) {
  6949. nextNodeStart =
  6950. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  6951. }
  6952. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  6953. currentNode = nextNode;
  6954. currentNodeStart = nextNodeStart;
  6955. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  6956. nextNode = statements[nextIndex];
  6957. nextNodeNeedsBoundaries =
  6958. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  6959. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  6960. nextNodeStart =
  6961. currentNode.end +
  6962. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  6963. if (currentNode.included) {
  6964. currentNodeNeedsBoundaries
  6965. ? currentNode.render(code, options, {
  6966. end: nextNodeStart,
  6967. start: currentNodeStart
  6968. })
  6969. : currentNode.render(code, options);
  6970. }
  6971. else {
  6972. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  6973. }
  6974. }
  6975. else {
  6976. currentNode.render(code, options);
  6977. }
  6978. }
  6979. }
  6980. // This assumes that the first character is not part of the first node
  6981. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  6982. const splitUpNodes = [];
  6983. let node, nextNode, nextNodeStart, contentEnd, char;
  6984. let separator = start - 1;
  6985. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  6986. nextNode = nodes[nextIndex];
  6987. if (node !== undefined) {
  6988. separator =
  6989. node.end +
  6990. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  6991. }
  6992. nextNodeStart = contentEnd =
  6993. separator +
  6994. 1 +
  6995. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  6996. while (((char = code.original.charCodeAt(nextNodeStart)),
  6997. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  6998. nextNodeStart++;
  6999. if (node !== undefined) {
  7000. splitUpNodes.push({
  7001. contentEnd,
  7002. end: nextNodeStart,
  7003. node,
  7004. separator,
  7005. start
  7006. });
  7007. }
  7008. node = nextNode;
  7009. start = nextNodeStart;
  7010. }
  7011. splitUpNodes.push({
  7012. contentEnd: end,
  7013. end,
  7014. node: node,
  7015. separator: null,
  7016. start
  7017. });
  7018. return splitUpNodes;
  7019. }
  7020. // This assumes there are only white-space and comments between start and end
  7021. function removeLineBreaks(code, start, end) {
  7022. while (true) {
  7023. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7024. if (removeStart === -1) {
  7025. break;
  7026. }
  7027. code.remove(start + removeStart, (start += removeEnd));
  7028. }
  7029. }
  7030. class BlockScope extends ChildScope {
  7031. addDeclaration(identifier, context, init, isHoisted) {
  7032. if (isHoisted) {
  7033. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7034. // Necessary to make sure the init is deoptimized for conditional declarations.
  7035. // We cannot call deoptimizePath here.
  7036. variable.markInitializersForDeoptimization();
  7037. return variable;
  7038. }
  7039. else {
  7040. return super.addDeclaration(identifier, context, init, false);
  7041. }
  7042. }
  7043. }
  7044. class ExpressionStatement extends NodeBase {
  7045. initialise() {
  7046. if (this.directive &&
  7047. this.directive !== 'use strict' &&
  7048. this.parent.type === Program$1) {
  7049. this.context.warn(
  7050. // This is necessary, because either way (deleting or not) can lead to errors.
  7051. {
  7052. code: 'MODULE_LEVEL_DIRECTIVE',
  7053. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  7054. }, this.start);
  7055. }
  7056. }
  7057. render(code, options) {
  7058. super.render(code, options);
  7059. if (this.included)
  7060. this.insertSemicolon(code);
  7061. }
  7062. shouldBeIncluded(context) {
  7063. if (this.directive && this.directive !== 'use strict')
  7064. return this.parent.type !== Program$1;
  7065. return super.shouldBeIncluded(context);
  7066. }
  7067. applyDeoptimizations() { }
  7068. }
  7069. class BlockStatement extends NodeBase {
  7070. constructor() {
  7071. super(...arguments);
  7072. this.directlyIncluded = false;
  7073. }
  7074. addImplicitReturnExpressionToScope() {
  7075. const lastStatement = this.body[this.body.length - 1];
  7076. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7077. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7078. }
  7079. }
  7080. createScope(parentScope) {
  7081. this.scope = this.parent.preventChildBlockScope
  7082. ? parentScope
  7083. : new BlockScope(parentScope);
  7084. }
  7085. hasEffects(context) {
  7086. if (this.deoptimizeBody)
  7087. return true;
  7088. for (const node of this.body) {
  7089. if (context.brokenFlow)
  7090. break;
  7091. if (node.hasEffects(context))
  7092. return true;
  7093. }
  7094. return false;
  7095. }
  7096. include(context, includeChildrenRecursively) {
  7097. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7098. this.included = true;
  7099. this.directlyIncluded = true;
  7100. if (this.deoptimizeBody)
  7101. includeChildrenRecursively = true;
  7102. for (const node of this.body) {
  7103. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7104. node.include(context, includeChildrenRecursively);
  7105. }
  7106. }
  7107. }
  7108. initialise() {
  7109. const firstBodyStatement = this.body[0];
  7110. this.deoptimizeBody =
  7111. firstBodyStatement instanceof ExpressionStatement &&
  7112. firstBodyStatement.directive === 'use asm';
  7113. }
  7114. render(code, options) {
  7115. if (this.body.length) {
  7116. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7117. }
  7118. else {
  7119. super.render(code, options);
  7120. }
  7121. }
  7122. }
  7123. class RestElement extends NodeBase {
  7124. constructor() {
  7125. super(...arguments);
  7126. this.declarationInit = null;
  7127. }
  7128. addExportedVariables(variables, exportNamesByVariable) {
  7129. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7130. }
  7131. declare(kind, init) {
  7132. this.declarationInit = init;
  7133. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7134. }
  7135. deoptimizePath(path) {
  7136. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  7137. }
  7138. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7139. return (path.length > 0 ||
  7140. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7141. }
  7142. markDeclarationReached() {
  7143. this.argument.markDeclarationReached();
  7144. }
  7145. applyDeoptimizations() {
  7146. this.deoptimized = true;
  7147. if (this.declarationInit !== null) {
  7148. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  7149. this.context.requestTreeshakingPass();
  7150. }
  7151. }
  7152. }
  7153. class FunctionBase extends NodeBase {
  7154. constructor() {
  7155. super(...arguments);
  7156. this.objectEntity = null;
  7157. this.deoptimizedReturn = false;
  7158. }
  7159. deoptimizePath(path) {
  7160. this.getObjectEntity().deoptimizePath(path);
  7161. if (path.length === 1 && path[0] === UnknownKey) {
  7162. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  7163. // which means the return expression needs to be reassigned
  7164. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7165. }
  7166. }
  7167. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7168. if (path.length > 0) {
  7169. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7170. }
  7171. }
  7172. getLiteralValueAtPath(path, recursionTracker, origin) {
  7173. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7174. }
  7175. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7176. if (path.length > 0) {
  7177. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7178. }
  7179. if (this.async) {
  7180. if (!this.deoptimizedReturn) {
  7181. this.deoptimizedReturn = true;
  7182. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  7183. this.context.requestTreeshakingPass();
  7184. }
  7185. return UNKNOWN_EXPRESSION;
  7186. }
  7187. return this.scope.getReturnExpression();
  7188. }
  7189. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7190. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  7191. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7192. }
  7193. if (this.async) {
  7194. const { propertyReadSideEffects } = this.context.options
  7195. .treeshake;
  7196. const returnExpression = this.scope.getReturnExpression();
  7197. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  7198. (propertyReadSideEffects &&
  7199. (propertyReadSideEffects === 'always' ||
  7200. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  7201. return true;
  7202. }
  7203. }
  7204. for (const param of this.params) {
  7205. if (param.hasEffects(context))
  7206. return true;
  7207. }
  7208. return false;
  7209. }
  7210. include(context, includeChildrenRecursively) {
  7211. if (!this.deoptimized)
  7212. this.applyDeoptimizations();
  7213. this.included = true;
  7214. const { brokenFlow } = context;
  7215. context.brokenFlow = BROKEN_FLOW_NONE;
  7216. this.body.include(context, includeChildrenRecursively);
  7217. context.brokenFlow = brokenFlow;
  7218. }
  7219. includeCallArguments(context, args) {
  7220. this.scope.includeCallArguments(context, args);
  7221. }
  7222. initialise() {
  7223. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  7224. if (this.body instanceof BlockStatement) {
  7225. this.body.addImplicitReturnExpressionToScope();
  7226. }
  7227. else {
  7228. this.scope.addReturnExpression(this.body);
  7229. }
  7230. }
  7231. parseNode(esTreeNode) {
  7232. if (esTreeNode.body.type === BlockStatement$1) {
  7233. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  7234. }
  7235. super.parseNode(esTreeNode);
  7236. }
  7237. applyDeoptimizations() { }
  7238. }
  7239. FunctionBase.prototype.preventChildBlockScope = true;
  7240. class ArrowFunctionExpression extends FunctionBase {
  7241. constructor() {
  7242. super(...arguments);
  7243. this.objectEntity = null;
  7244. }
  7245. createScope(parentScope) {
  7246. this.scope = new ReturnValueScope(parentScope, this.context);
  7247. }
  7248. hasEffects() {
  7249. if (!this.deoptimized)
  7250. this.applyDeoptimizations();
  7251. return false;
  7252. }
  7253. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7254. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7255. return true;
  7256. if (interaction.type === INTERACTION_CALLED) {
  7257. const { ignore, brokenFlow } = context;
  7258. context.ignore = {
  7259. breaks: false,
  7260. continues: false,
  7261. labels: new Set(),
  7262. returnYield: true
  7263. };
  7264. if (this.body.hasEffects(context))
  7265. return true;
  7266. context.ignore = ignore;
  7267. context.brokenFlow = brokenFlow;
  7268. }
  7269. return false;
  7270. }
  7271. include(context, includeChildrenRecursively) {
  7272. super.include(context, includeChildrenRecursively);
  7273. for (const param of this.params) {
  7274. if (!(param instanceof Identifier)) {
  7275. param.include(context, includeChildrenRecursively);
  7276. }
  7277. }
  7278. }
  7279. getObjectEntity() {
  7280. if (this.objectEntity !== null) {
  7281. return this.objectEntity;
  7282. }
  7283. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  7284. }
  7285. }
  7286. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  7287. if (exportedVariables.length === 1 &&
  7288. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  7289. const variable = exportedVariables[0];
  7290. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  7291. }
  7292. else {
  7293. const fields = [];
  7294. for (const variable of exportedVariables) {
  7295. for (const exportName of exportNamesByVariable.get(variable)) {
  7296. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  7297. }
  7298. }
  7299. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  7300. }
  7301. }
  7302. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  7303. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  7304. code.appendLeft(expressionEnd, ')');
  7305. }
  7306. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  7307. const { _, getDirectReturnIifeLeft } = options.snippets;
  7308. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  7309. code.appendLeft(expressionEnd, ')');
  7310. }
  7311. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  7312. const { _, getPropertyAccess } = options.snippets;
  7313. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  7314. if (needsParens) {
  7315. code.prependRight(expressionStart, '(');
  7316. code.appendLeft(expressionEnd, ')');
  7317. }
  7318. }
  7319. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  7320. const { _ } = options.snippets;
  7321. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  7322. if (needsParens) {
  7323. code.prependRight(expressionStart, '(');
  7324. code.appendLeft(expressionEnd, ')');
  7325. }
  7326. }
  7327. class ObjectPattern extends NodeBase {
  7328. addExportedVariables(variables, exportNamesByVariable) {
  7329. for (const property of this.properties) {
  7330. if (property.type === Property$1) {
  7331. property.value.addExportedVariables(variables, exportNamesByVariable);
  7332. }
  7333. else {
  7334. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7335. }
  7336. }
  7337. }
  7338. declare(kind, init) {
  7339. const variables = [];
  7340. for (const property of this.properties) {
  7341. variables.push(...property.declare(kind, init));
  7342. }
  7343. return variables;
  7344. }
  7345. deoptimizePath(path) {
  7346. if (path.length === 0) {
  7347. for (const property of this.properties) {
  7348. property.deoptimizePath(path);
  7349. }
  7350. }
  7351. }
  7352. hasEffectsOnInteractionAtPath(
  7353. // At the moment, this is only triggered for assignment left-hand sides,
  7354. // where the path is empty
  7355. _path, interaction, context) {
  7356. for (const property of this.properties) {
  7357. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7358. return true;
  7359. }
  7360. return false;
  7361. }
  7362. markDeclarationReached() {
  7363. for (const property of this.properties) {
  7364. property.markDeclarationReached();
  7365. }
  7366. }
  7367. }
  7368. class AssignmentExpression extends NodeBase {
  7369. hasEffects(context) {
  7370. const { deoptimized, left, right } = this;
  7371. if (!deoptimized)
  7372. this.applyDeoptimizations();
  7373. // MemberExpressions do not access the property before assignments if the
  7374. // operator is '='.
  7375. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, this.operator !== '='));
  7376. }
  7377. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7378. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  7379. }
  7380. include(context, includeChildrenRecursively) {
  7381. const { deoptimized, left, right, operator } = this;
  7382. if (!deoptimized)
  7383. this.applyDeoptimizations();
  7384. this.included = true;
  7385. if (includeChildrenRecursively ||
  7386. operator !== '=' ||
  7387. left.included ||
  7388. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  7389. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  7390. }
  7391. right.include(context, includeChildrenRecursively);
  7392. }
  7393. initialise() {
  7394. this.left.setAssignedValue(this.right);
  7395. }
  7396. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7397. const { left, right, start, end, parent } = this;
  7398. if (left.included) {
  7399. left.render(code, options);
  7400. right.render(code, options);
  7401. }
  7402. else {
  7403. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  7404. code.remove(start, inclusionStart);
  7405. if (preventASI) {
  7406. removeLineBreaks(code, inclusionStart, right.start);
  7407. }
  7408. right.render(code, options, {
  7409. renderedParentType: renderedParentType || parent.type,
  7410. renderedSurroundingElement: renderedSurroundingElement || parent.type
  7411. });
  7412. }
  7413. if (options.format === 'system') {
  7414. if (left instanceof Identifier) {
  7415. const variable = left.variable;
  7416. const exportNames = options.exportNamesByVariable.get(variable);
  7417. if (exportNames) {
  7418. if (exportNames.length === 1) {
  7419. renderSystemExportExpression(variable, start, end, code, options);
  7420. }
  7421. else {
  7422. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  7423. }
  7424. return;
  7425. }
  7426. }
  7427. else {
  7428. const systemPatternExports = [];
  7429. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  7430. if (systemPatternExports.length > 0) {
  7431. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  7432. return;
  7433. }
  7434. }
  7435. }
  7436. if (left.included &&
  7437. left instanceof ObjectPattern &&
  7438. (renderedSurroundingElement === ExpressionStatement$1 ||
  7439. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  7440. code.appendRight(start, '(');
  7441. code.prependLeft(end, ')');
  7442. }
  7443. }
  7444. applyDeoptimizations() {
  7445. this.deoptimized = true;
  7446. this.left.deoptimizePath(EMPTY_PATH);
  7447. this.right.deoptimizePath(UNKNOWN_PATH);
  7448. this.context.requestTreeshakingPass();
  7449. }
  7450. }
  7451. class AssignmentPattern extends NodeBase {
  7452. addExportedVariables(variables, exportNamesByVariable) {
  7453. this.left.addExportedVariables(variables, exportNamesByVariable);
  7454. }
  7455. declare(kind, init) {
  7456. return this.left.declare(kind, init);
  7457. }
  7458. deoptimizePath(path) {
  7459. path.length === 0 && this.left.deoptimizePath(path);
  7460. }
  7461. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7462. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  7463. }
  7464. markDeclarationReached() {
  7465. this.left.markDeclarationReached();
  7466. }
  7467. render(code, options, { isShorthandProperty } = BLANK) {
  7468. this.left.render(code, options, { isShorthandProperty });
  7469. this.right.render(code, options);
  7470. }
  7471. applyDeoptimizations() {
  7472. this.deoptimized = true;
  7473. this.left.deoptimizePath(EMPTY_PATH);
  7474. this.right.deoptimizePath(UNKNOWN_PATH);
  7475. this.context.requestTreeshakingPass();
  7476. }
  7477. }
  7478. class ArgumentsVariable extends LocalVariable {
  7479. constructor(context) {
  7480. super('arguments', null, UNKNOWN_EXPRESSION, context);
  7481. }
  7482. hasEffectsOnInteractionAtPath(path, { type }) {
  7483. return type !== INTERACTION_ACCESSED || path.length > 1;
  7484. }
  7485. }
  7486. class ThisVariable extends LocalVariable {
  7487. constructor(context) {
  7488. super('this', null, null, context);
  7489. this.deoptimizedPaths = [];
  7490. this.entitiesToBeDeoptimized = new Set();
  7491. this.thisDeoptimizationList = [];
  7492. this.thisDeoptimizations = new DiscriminatedPathTracker();
  7493. }
  7494. addEntityToBeDeoptimized(entity) {
  7495. for (const path of this.deoptimizedPaths) {
  7496. entity.deoptimizePath(path);
  7497. }
  7498. for (const { interaction, path } of this.thisDeoptimizationList) {
  7499. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7500. }
  7501. this.entitiesToBeDeoptimized.add(entity);
  7502. }
  7503. deoptimizePath(path) {
  7504. if (path.length === 0 ||
  7505. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7506. return;
  7507. }
  7508. this.deoptimizedPaths.push(path);
  7509. for (const entity of this.entitiesToBeDeoptimized) {
  7510. entity.deoptimizePath(path);
  7511. }
  7512. }
  7513. deoptimizeThisOnInteractionAtPath(interaction, path) {
  7514. const thisDeoptimization = {
  7515. interaction,
  7516. path
  7517. };
  7518. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.type, interaction.thisArg)) {
  7519. for (const entity of this.entitiesToBeDeoptimized) {
  7520. entity.deoptimizeThisOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7521. }
  7522. this.thisDeoptimizationList.push(thisDeoptimization);
  7523. }
  7524. }
  7525. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7526. return (this.getInit(context).hasEffectsOnInteractionAtPath(path, interaction, context) ||
  7527. super.hasEffectsOnInteractionAtPath(path, interaction, context));
  7528. }
  7529. getInit(context) {
  7530. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  7531. }
  7532. }
  7533. class FunctionScope extends ReturnValueScope {
  7534. constructor(parent, context) {
  7535. super(parent, context);
  7536. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  7537. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  7538. }
  7539. findLexicalBoundary() {
  7540. return this;
  7541. }
  7542. includeCallArguments(context, args) {
  7543. super.includeCallArguments(context, args);
  7544. if (this.argumentsVariable.included) {
  7545. for (const arg of args) {
  7546. if (!arg.included) {
  7547. arg.include(context, false);
  7548. }
  7549. }
  7550. }
  7551. }
  7552. }
  7553. class FunctionNode extends FunctionBase {
  7554. constructor() {
  7555. super(...arguments);
  7556. this.objectEntity = null;
  7557. }
  7558. createScope(parentScope) {
  7559. this.scope = new FunctionScope(parentScope, this.context);
  7560. }
  7561. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7562. super.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7563. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  7564. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.thisArg);
  7565. }
  7566. }
  7567. hasEffects(context) {
  7568. var _a;
  7569. if (!this.deoptimized)
  7570. this.applyDeoptimizations();
  7571. return !!((_a = this.id) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  7572. }
  7573. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7574. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  7575. return true;
  7576. if (interaction.type === INTERACTION_CALLED) {
  7577. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  7578. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew
  7579. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  7580. : UNKNOWN_EXPRESSION);
  7581. const { brokenFlow, ignore } = context;
  7582. context.ignore = {
  7583. breaks: false,
  7584. continues: false,
  7585. labels: new Set(),
  7586. returnYield: true
  7587. };
  7588. if (this.body.hasEffects(context))
  7589. return true;
  7590. context.brokenFlow = brokenFlow;
  7591. if (thisInit) {
  7592. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  7593. }
  7594. else {
  7595. context.replacedVariableInits.delete(this.scope.thisVariable);
  7596. }
  7597. context.ignore = ignore;
  7598. }
  7599. return false;
  7600. }
  7601. include(context, includeChildrenRecursively) {
  7602. var _a;
  7603. super.include(context, includeChildrenRecursively);
  7604. (_a = this.id) === null || _a === void 0 ? void 0 : _a.include();
  7605. const hasArguments = this.scope.argumentsVariable.included;
  7606. for (const param of this.params) {
  7607. if (!(param instanceof Identifier) || hasArguments) {
  7608. param.include(context, includeChildrenRecursively);
  7609. }
  7610. }
  7611. }
  7612. initialise() {
  7613. var _a;
  7614. super.initialise();
  7615. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('function', this);
  7616. }
  7617. getObjectEntity() {
  7618. if (this.objectEntity !== null) {
  7619. return this.objectEntity;
  7620. }
  7621. return (this.objectEntity = new ObjectEntity([
  7622. {
  7623. key: 'prototype',
  7624. kind: 'init',
  7625. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  7626. }
  7627. ], OBJECT_PROTOTYPE));
  7628. }
  7629. }
  7630. class AwaitExpression extends NodeBase {
  7631. hasEffects() {
  7632. if (!this.deoptimized)
  7633. this.applyDeoptimizations();
  7634. return true;
  7635. }
  7636. include(context, includeChildrenRecursively) {
  7637. if (!this.deoptimized)
  7638. this.applyDeoptimizations();
  7639. if (!this.included) {
  7640. this.included = true;
  7641. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  7642. let parent = this.parent;
  7643. do {
  7644. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  7645. break checkTopLevelAwait;
  7646. } while ((parent = parent.parent));
  7647. this.context.usesTopLevelAwait = true;
  7648. }
  7649. }
  7650. this.argument.include(context, includeChildrenRecursively);
  7651. }
  7652. }
  7653. const binaryOperators = {
  7654. '!=': (left, right) => left != right,
  7655. '!==': (left, right) => left !== right,
  7656. '%': (left, right) => left % right,
  7657. '&': (left, right) => left & right,
  7658. '*': (left, right) => left * right,
  7659. // At the moment, "**" will be transpiled to Math.pow
  7660. '**': (left, right) => left ** right,
  7661. '+': (left, right) => left + right,
  7662. '-': (left, right) => left - right,
  7663. '/': (left, right) => left / right,
  7664. '<': (left, right) => left < right,
  7665. '<<': (left, right) => left << right,
  7666. '<=': (left, right) => left <= right,
  7667. '==': (left, right) => left == right,
  7668. '===': (left, right) => left === right,
  7669. '>': (left, right) => left > right,
  7670. '>=': (left, right) => left >= right,
  7671. '>>': (left, right) => left >> right,
  7672. '>>>': (left, right) => left >>> right,
  7673. '^': (left, right) => left ^ right,
  7674. '|': (left, right) => left | right
  7675. // We use the fallback for cases where we return something unknown
  7676. // in: () => UnknownValue,
  7677. // instanceof: () => UnknownValue,
  7678. };
  7679. class BinaryExpression extends NodeBase {
  7680. deoptimizeCache() { }
  7681. getLiteralValueAtPath(path, recursionTracker, origin) {
  7682. if (path.length > 0)
  7683. return UnknownValue;
  7684. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7685. if (typeof leftValue === 'symbol')
  7686. return UnknownValue;
  7687. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  7688. if (typeof rightValue === 'symbol')
  7689. return UnknownValue;
  7690. const operatorFn = binaryOperators[this.operator];
  7691. if (!operatorFn)
  7692. return UnknownValue;
  7693. return operatorFn(leftValue, rightValue);
  7694. }
  7695. hasEffects(context) {
  7696. // support some implicit type coercion runtime errors
  7697. if (this.operator === '+' &&
  7698. this.parent instanceof ExpressionStatement &&
  7699. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  7700. return true;
  7701. }
  7702. return super.hasEffects(context);
  7703. }
  7704. hasEffectsOnInteractionAtPath(path, { type }) {
  7705. return type !== INTERACTION_ACCESSED || path.length > 1;
  7706. }
  7707. render(code, options, { renderedSurroundingElement } = BLANK) {
  7708. this.left.render(code, options, { renderedSurroundingElement });
  7709. this.right.render(code, options);
  7710. }
  7711. }
  7712. class BreakStatement extends NodeBase {
  7713. hasEffects(context) {
  7714. if (this.label) {
  7715. if (!context.ignore.labels.has(this.label.name))
  7716. return true;
  7717. context.includedLabels.add(this.label.name);
  7718. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7719. }
  7720. else {
  7721. if (!context.ignore.breaks)
  7722. return true;
  7723. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7724. }
  7725. return false;
  7726. }
  7727. include(context) {
  7728. this.included = true;
  7729. if (this.label) {
  7730. this.label.include();
  7731. context.includedLabels.add(this.label.name);
  7732. }
  7733. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7734. }
  7735. }
  7736. function renderCallArguments(code, options, node) {
  7737. if (node.arguments.length > 0) {
  7738. if (node.arguments[node.arguments.length - 1].included) {
  7739. for (const arg of node.arguments) {
  7740. arg.render(code, options);
  7741. }
  7742. }
  7743. else {
  7744. let lastIncludedIndex = node.arguments.length - 2;
  7745. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  7746. lastIncludedIndex--;
  7747. }
  7748. if (lastIncludedIndex >= 0) {
  7749. for (let index = 0; index <= lastIncludedIndex; index++) {
  7750. node.arguments[index].render(code, options);
  7751. }
  7752. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  7753. }
  7754. else {
  7755. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  7756. }
  7757. }
  7758. }
  7759. }
  7760. class Literal extends NodeBase {
  7761. deoptimizeThisOnInteractionAtPath() { }
  7762. getLiteralValueAtPath(path) {
  7763. if (path.length > 0 ||
  7764. // unknown literals can also be null but do not start with an "n"
  7765. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  7766. typeof this.value === 'bigint' ||
  7767. // to support shims for regular expressions
  7768. this.context.code.charCodeAt(this.start) === 47) {
  7769. return UnknownValue;
  7770. }
  7771. return this.value;
  7772. }
  7773. getReturnExpressionWhenCalledAtPath(path) {
  7774. if (path.length !== 1)
  7775. return UNKNOWN_EXPRESSION;
  7776. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  7777. }
  7778. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7779. switch (interaction.type) {
  7780. case INTERACTION_ACCESSED:
  7781. return path.length > (this.value === null ? 0 : 1);
  7782. case INTERACTION_ASSIGNED:
  7783. return true;
  7784. case INTERACTION_CALLED:
  7785. return (path.length !== 1 ||
  7786. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  7787. }
  7788. }
  7789. initialise() {
  7790. this.members = getLiteralMembersForValue(this.value);
  7791. }
  7792. parseNode(esTreeNode) {
  7793. this.value = esTreeNode.value;
  7794. this.regex = esTreeNode.regex;
  7795. super.parseNode(esTreeNode);
  7796. }
  7797. render(code) {
  7798. if (typeof this.value === 'string') {
  7799. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  7800. }
  7801. }
  7802. }
  7803. // To avoid infinite recursions
  7804. const MAX_PATH_DEPTH = 7;
  7805. function getResolvablePropertyKey(memberExpression) {
  7806. return memberExpression.computed
  7807. ? getResolvableComputedPropertyKey(memberExpression.property)
  7808. : memberExpression.property.name;
  7809. }
  7810. function getResolvableComputedPropertyKey(propertyKey) {
  7811. if (propertyKey instanceof Literal) {
  7812. return String(propertyKey.value);
  7813. }
  7814. return null;
  7815. }
  7816. function getPathIfNotComputed(memberExpression) {
  7817. const nextPathKey = memberExpression.propertyKey;
  7818. const object = memberExpression.object;
  7819. if (typeof nextPathKey === 'string') {
  7820. if (object instanceof Identifier) {
  7821. return [
  7822. { key: object.name, pos: object.start },
  7823. { key: nextPathKey, pos: memberExpression.property.start }
  7824. ];
  7825. }
  7826. if (object instanceof MemberExpression) {
  7827. const parentPath = getPathIfNotComputed(object);
  7828. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  7829. }
  7830. }
  7831. return null;
  7832. }
  7833. function getStringFromPath(path) {
  7834. let pathString = path[0].key;
  7835. for (let index = 1; index < path.length; index++) {
  7836. pathString += '.' + path[index].key;
  7837. }
  7838. return pathString;
  7839. }
  7840. class MemberExpression extends NodeBase {
  7841. constructor() {
  7842. super(...arguments);
  7843. this.variable = null;
  7844. this.assignmentDeoptimized = false;
  7845. this.bound = false;
  7846. this.expressionsToBeDeoptimized = [];
  7847. this.replacement = null;
  7848. }
  7849. bind() {
  7850. this.bound = true;
  7851. const path = getPathIfNotComputed(this);
  7852. const baseVariable = path && this.scope.findVariable(path[0].key);
  7853. if (baseVariable && baseVariable.isNamespace) {
  7854. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  7855. if (!resolvedVariable) {
  7856. super.bind();
  7857. }
  7858. else if (typeof resolvedVariable === 'string') {
  7859. this.replacement = resolvedVariable;
  7860. }
  7861. else {
  7862. this.variable = resolvedVariable;
  7863. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7864. }
  7865. }
  7866. else {
  7867. super.bind();
  7868. }
  7869. }
  7870. deoptimizeCache() {
  7871. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7872. this.expressionsToBeDeoptimized = [];
  7873. this.propertyKey = UnknownKey;
  7874. this.object.deoptimizePath(UNKNOWN_PATH);
  7875. for (const expression of expressionsToBeDeoptimized) {
  7876. expression.deoptimizeCache();
  7877. }
  7878. }
  7879. deoptimizePath(path) {
  7880. if (path.length === 0)
  7881. this.disallowNamespaceReassignment();
  7882. if (this.variable) {
  7883. this.variable.deoptimizePath(path);
  7884. }
  7885. else if (!this.replacement) {
  7886. if (path.length < MAX_PATH_DEPTH) {
  7887. const propertyKey = this.getPropertyKey();
  7888. this.object.deoptimizePath([
  7889. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7890. ...path
  7891. ]);
  7892. }
  7893. }
  7894. }
  7895. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  7896. if (this.variable) {
  7897. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  7898. }
  7899. else if (!this.replacement) {
  7900. if (path.length < MAX_PATH_DEPTH) {
  7901. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  7902. }
  7903. else {
  7904. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  7905. }
  7906. }
  7907. }
  7908. getLiteralValueAtPath(path, recursionTracker, origin) {
  7909. if (this.variable) {
  7910. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7911. }
  7912. if (this.replacement) {
  7913. return UnknownValue;
  7914. }
  7915. this.expressionsToBeDeoptimized.push(origin);
  7916. if (path.length < MAX_PATH_DEPTH) {
  7917. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  7918. }
  7919. return UnknownValue;
  7920. }
  7921. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7922. if (this.variable) {
  7923. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7924. }
  7925. if (this.replacement) {
  7926. return UNKNOWN_EXPRESSION;
  7927. }
  7928. this.expressionsToBeDeoptimized.push(origin);
  7929. if (path.length < MAX_PATH_DEPTH) {
  7930. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  7931. }
  7932. return UNKNOWN_EXPRESSION;
  7933. }
  7934. hasEffects(context) {
  7935. if (!this.deoptimized)
  7936. this.applyDeoptimizations();
  7937. return (this.property.hasEffects(context) ||
  7938. this.object.hasEffects(context) ||
  7939. this.hasAccessEffect(context));
  7940. }
  7941. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7942. if (checkAccess && !this.deoptimized)
  7943. this.applyDeoptimizations();
  7944. if (!this.assignmentDeoptimized)
  7945. this.applyAssignmentDeoptimization();
  7946. return (this.property.hasEffects(context) ||
  7947. this.object.hasEffects(context) ||
  7948. (checkAccess && this.hasAccessEffect(context)) ||
  7949. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7950. }
  7951. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7952. if (this.variable) {
  7953. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7954. }
  7955. if (this.replacement) {
  7956. return true;
  7957. }
  7958. if (path.length < MAX_PATH_DEPTH) {
  7959. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  7960. }
  7961. return true;
  7962. }
  7963. include(context, includeChildrenRecursively) {
  7964. if (!this.deoptimized)
  7965. this.applyDeoptimizations();
  7966. this.includeProperties(context, includeChildrenRecursively);
  7967. }
  7968. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7969. if (!this.assignmentDeoptimized)
  7970. this.applyAssignmentDeoptimization();
  7971. if (deoptimizeAccess) {
  7972. this.include(context, includeChildrenRecursively);
  7973. }
  7974. else {
  7975. this.includeProperties(context, includeChildrenRecursively);
  7976. }
  7977. }
  7978. includeCallArguments(context, args) {
  7979. if (this.variable) {
  7980. this.variable.includeCallArguments(context, args);
  7981. }
  7982. else {
  7983. super.includeCallArguments(context, args);
  7984. }
  7985. }
  7986. initialise() {
  7987. this.propertyKey = getResolvablePropertyKey(this);
  7988. this.accessInteraction = { thisArg: this.object, type: INTERACTION_ACCESSED };
  7989. }
  7990. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7991. if (this.variable || this.replacement) {
  7992. const { snippets: { getPropertyAccess } } = options;
  7993. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : this.replacement;
  7994. if (renderedParentType && isCalleeOfRenderedParent)
  7995. replacement = '0, ' + replacement;
  7996. code.overwrite(this.start, this.end, replacement, {
  7997. contentOnly: true,
  7998. storeName: true
  7999. });
  8000. }
  8001. else {
  8002. if (renderedParentType && isCalleeOfRenderedParent) {
  8003. code.appendRight(this.start, '0, ');
  8004. }
  8005. this.object.render(code, options, { renderedSurroundingElement });
  8006. this.property.render(code, options);
  8007. }
  8008. }
  8009. setAssignedValue(value) {
  8010. this.assignmentInteraction = {
  8011. args: [value],
  8012. thisArg: this.object,
  8013. type: INTERACTION_ASSIGNED
  8014. };
  8015. }
  8016. applyDeoptimizations() {
  8017. this.deoptimized = true;
  8018. const { propertyReadSideEffects } = this.context.options
  8019. .treeshake;
  8020. if (
  8021. // Namespaces are not bound and should not be deoptimized
  8022. this.bound &&
  8023. propertyReadSideEffects &&
  8024. !(this.variable || this.replacement)) {
  8025. const propertyKey = this.getPropertyKey();
  8026. this.object.deoptimizeThisOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8027. this.context.requestTreeshakingPass();
  8028. }
  8029. }
  8030. applyAssignmentDeoptimization() {
  8031. this.assignmentDeoptimized = true;
  8032. const { propertyReadSideEffects } = this.context.options
  8033. .treeshake;
  8034. if (
  8035. // Namespaces are not bound and should not be deoptimized
  8036. this.bound &&
  8037. propertyReadSideEffects &&
  8038. !(this.variable || this.replacement)) {
  8039. this.object.deoptimizeThisOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8040. this.context.requestTreeshakingPass();
  8041. }
  8042. }
  8043. disallowNamespaceReassignment() {
  8044. if (this.object instanceof Identifier) {
  8045. const variable = this.scope.findVariable(this.object.name);
  8046. if (variable.isNamespace) {
  8047. if (this.variable) {
  8048. this.context.includeVariableInModule(this.variable);
  8049. }
  8050. this.context.warn({
  8051. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  8052. message: `Illegal reassignment to import '${this.object.name}'`
  8053. }, this.start);
  8054. }
  8055. }
  8056. }
  8057. getPropertyKey() {
  8058. if (this.propertyKey === null) {
  8059. this.propertyKey = UnknownKey;
  8060. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8061. return (this.propertyKey = typeof value === 'symbol' ? UnknownKey : String(value));
  8062. }
  8063. return this.propertyKey;
  8064. }
  8065. hasAccessEffect(context) {
  8066. const { propertyReadSideEffects } = this.context.options
  8067. .treeshake;
  8068. return (!(this.variable || this.replacement) &&
  8069. propertyReadSideEffects &&
  8070. (propertyReadSideEffects === 'always' ||
  8071. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8072. }
  8073. includeProperties(context, includeChildrenRecursively) {
  8074. if (!this.included) {
  8075. this.included = true;
  8076. if (this.variable) {
  8077. this.context.includeVariableInModule(this.variable);
  8078. }
  8079. }
  8080. this.object.include(context, includeChildrenRecursively);
  8081. this.property.include(context, includeChildrenRecursively);
  8082. }
  8083. }
  8084. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8085. if (path.length === 0)
  8086. return baseVariable;
  8087. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8088. return null;
  8089. const exportName = path[0].key;
  8090. const variable = baseVariable.context.traceExport(exportName);
  8091. if (!variable) {
  8092. const fileName = baseVariable.context.fileName;
  8093. astContext.warn({
  8094. code: 'MISSING_EXPORT',
  8095. exporter: relativeId(fileName),
  8096. importer: relativeId(astContext.fileName),
  8097. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  8098. missing: exportName,
  8099. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  8100. }, path[0].pos);
  8101. return 'undefined';
  8102. }
  8103. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  8104. }
  8105. class CallExpressionBase extends NodeBase {
  8106. constructor() {
  8107. super(...arguments);
  8108. this.returnExpression = null;
  8109. this.deoptimizableDependentExpressions = [];
  8110. this.expressionsToBeDeoptimized = new Set();
  8111. }
  8112. deoptimizeCache() {
  8113. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  8114. this.returnExpression = UNKNOWN_EXPRESSION;
  8115. for (const expression of this.deoptimizableDependentExpressions) {
  8116. expression.deoptimizeCache();
  8117. }
  8118. for (const expression of this.expressionsToBeDeoptimized) {
  8119. expression.deoptimizePath(UNKNOWN_PATH);
  8120. }
  8121. }
  8122. }
  8123. deoptimizePath(path) {
  8124. if (path.length === 0 ||
  8125. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  8126. return;
  8127. }
  8128. const returnExpression = this.getReturnExpression();
  8129. if (returnExpression !== UNKNOWN_EXPRESSION) {
  8130. returnExpression.deoptimizePath(path);
  8131. }
  8132. }
  8133. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8134. const returnExpression = this.getReturnExpression(recursionTracker);
  8135. if (returnExpression === UNKNOWN_EXPRESSION) {
  8136. interaction.thisArg.deoptimizePath(UNKNOWN_PATH);
  8137. }
  8138. else {
  8139. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8140. this.expressionsToBeDeoptimized.add(interaction.thisArg);
  8141. returnExpression.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8142. }, undefined);
  8143. }
  8144. }
  8145. getLiteralValueAtPath(path, recursionTracker, origin) {
  8146. const returnExpression = this.getReturnExpression(recursionTracker);
  8147. if (returnExpression === UNKNOWN_EXPRESSION) {
  8148. return UnknownValue;
  8149. }
  8150. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8151. this.deoptimizableDependentExpressions.push(origin);
  8152. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  8153. }, UnknownValue);
  8154. }
  8155. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8156. const returnExpression = this.getReturnExpression(recursionTracker);
  8157. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  8158. return UNKNOWN_EXPRESSION;
  8159. }
  8160. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  8161. this.deoptimizableDependentExpressions.push(origin);
  8162. return returnExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8163. }, UNKNOWN_EXPRESSION);
  8164. }
  8165. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8166. const { type } = interaction;
  8167. if (type === INTERACTION_CALLED) {
  8168. if ((interaction.withNew
  8169. ? context.instantiated
  8170. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)) {
  8171. return false;
  8172. }
  8173. }
  8174. else if ((type === INTERACTION_ASSIGNED
  8175. ? context.assigned
  8176. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  8177. return false;
  8178. }
  8179. return this.getReturnExpression().hasEffectsOnInteractionAtPath(path, interaction, context);
  8180. }
  8181. }
  8182. class CallExpression extends CallExpressionBase {
  8183. bind() {
  8184. super.bind();
  8185. if (this.callee instanceof Identifier) {
  8186. const variable = this.scope.findVariable(this.callee.name);
  8187. if (variable.isNamespace) {
  8188. this.context.warn({
  8189. code: 'CANNOT_CALL_NAMESPACE',
  8190. message: `Cannot call a namespace ('${this.callee.name}')`
  8191. }, this.start);
  8192. }
  8193. if (this.callee.name === 'eval') {
  8194. this.context.warn({
  8195. code: 'EVAL',
  8196. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8197. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8198. }, this.start);
  8199. }
  8200. }
  8201. this.interaction = {
  8202. args: this.arguments,
  8203. thisArg: this.callee instanceof MemberExpression && !this.callee.variable
  8204. ? this.callee.object
  8205. : null,
  8206. type: INTERACTION_CALLED,
  8207. withNew: false
  8208. };
  8209. }
  8210. hasEffects(context) {
  8211. try {
  8212. for (const argument of this.arguments) {
  8213. if (argument.hasEffects(context))
  8214. return true;
  8215. }
  8216. if (this.context.options.treeshake.annotations &&
  8217. this.annotations)
  8218. return false;
  8219. return (this.callee.hasEffects(context) ||
  8220. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  8221. }
  8222. finally {
  8223. if (!this.deoptimized)
  8224. this.applyDeoptimizations();
  8225. }
  8226. }
  8227. include(context, includeChildrenRecursively) {
  8228. if (!this.deoptimized)
  8229. this.applyDeoptimizations();
  8230. if (includeChildrenRecursively) {
  8231. super.include(context, includeChildrenRecursively);
  8232. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  8233. this.callee instanceof Identifier &&
  8234. this.callee.variable) {
  8235. this.callee.variable.markCalledFromTryStatement();
  8236. }
  8237. }
  8238. else {
  8239. this.included = true;
  8240. this.callee.include(context, false);
  8241. }
  8242. this.callee.includeCallArguments(context, this.arguments);
  8243. }
  8244. render(code, options, { renderedSurroundingElement } = BLANK) {
  8245. this.callee.render(code, options, {
  8246. isCalleeOfRenderedParent: true,
  8247. renderedSurroundingElement
  8248. });
  8249. renderCallArguments(code, options, this);
  8250. }
  8251. applyDeoptimizations() {
  8252. this.deoptimized = true;
  8253. if (this.interaction.thisArg) {
  8254. this.callee.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  8255. }
  8256. for (const argument of this.arguments) {
  8257. // This will make sure all properties of parameters behave as "unknown"
  8258. argument.deoptimizePath(UNKNOWN_PATH);
  8259. }
  8260. this.context.requestTreeshakingPass();
  8261. }
  8262. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  8263. if (this.returnExpression === null) {
  8264. this.returnExpression = UNKNOWN_EXPRESSION;
  8265. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  8266. }
  8267. return this.returnExpression;
  8268. }
  8269. }
  8270. class CatchScope extends ParameterScope {
  8271. addDeclaration(identifier, context, init, isHoisted) {
  8272. const existingParameter = this.variables.get(identifier.name);
  8273. if (existingParameter) {
  8274. // While we still create a hoisted declaration, the initializer goes to
  8275. // the parameter. Note that technically, the declaration now belongs to
  8276. // two variables, which is not correct but should not cause issues.
  8277. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  8278. existingParameter.addDeclaration(identifier, init);
  8279. return existingParameter;
  8280. }
  8281. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  8282. }
  8283. }
  8284. class CatchClause extends NodeBase {
  8285. createScope(parentScope) {
  8286. this.scope = new CatchScope(parentScope, this.context);
  8287. }
  8288. parseNode(esTreeNode) {
  8289. // Parameters need to be declared first as the logic is that initializers
  8290. // of hoisted body variables are associated with parameters of the same
  8291. // name instead of the variable
  8292. const { param } = esTreeNode;
  8293. if (param) {
  8294. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  8295. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  8296. }
  8297. super.parseNode(esTreeNode);
  8298. }
  8299. }
  8300. class ChainExpression extends NodeBase {
  8301. }
  8302. class ClassBodyScope extends ChildScope {
  8303. constructor(parent, classNode, context) {
  8304. super(parent);
  8305. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  8306. this.instanceScope = new ChildScope(this);
  8307. this.instanceScope.variables.set('this', new ThisVariable(context));
  8308. }
  8309. findLexicalBoundary() {
  8310. return this;
  8311. }
  8312. }
  8313. class ClassBody extends NodeBase {
  8314. createScope(parentScope) {
  8315. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  8316. }
  8317. include(context, includeChildrenRecursively) {
  8318. this.included = true;
  8319. this.context.includeVariableInModule(this.scope.thisVariable);
  8320. for (const definition of this.body) {
  8321. definition.include(context, includeChildrenRecursively);
  8322. }
  8323. }
  8324. parseNode(esTreeNode) {
  8325. const body = (this.body = []);
  8326. for (const definition of esTreeNode.body) {
  8327. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  8328. }
  8329. super.parseNode(esTreeNode);
  8330. }
  8331. applyDeoptimizations() { }
  8332. }
  8333. class MethodBase extends NodeBase {
  8334. constructor() {
  8335. super(...arguments);
  8336. this.accessedValue = null;
  8337. }
  8338. // As getter properties directly receive their values from fixed function
  8339. // expressions, there is no known situation where a getter is deoptimized.
  8340. deoptimizeCache() { }
  8341. deoptimizePath(path) {
  8342. this.getAccessedValue().deoptimizePath(path);
  8343. }
  8344. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8345. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  8346. return this.value.deoptimizeThisOnInteractionAtPath({
  8347. args: NO_ARGS,
  8348. thisArg: interaction.thisArg,
  8349. type: INTERACTION_CALLED,
  8350. withNew: false
  8351. }, EMPTY_PATH, recursionTracker);
  8352. }
  8353. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  8354. return this.value.deoptimizeThisOnInteractionAtPath({
  8355. args: interaction.args,
  8356. thisArg: interaction.thisArg,
  8357. type: INTERACTION_CALLED,
  8358. withNew: false
  8359. }, EMPTY_PATH, recursionTracker);
  8360. }
  8361. this.getAccessedValue().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8362. }
  8363. getLiteralValueAtPath(path, recursionTracker, origin) {
  8364. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  8365. }
  8366. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8367. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8368. }
  8369. hasEffects(context) {
  8370. return this.key.hasEffects(context);
  8371. }
  8372. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8373. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  8374. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8375. args: NO_ARGS,
  8376. thisArg: interaction.thisArg,
  8377. type: INTERACTION_CALLED,
  8378. withNew: false
  8379. }, context);
  8380. }
  8381. // setters are only called for empty paths
  8382. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  8383. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  8384. args: interaction.args,
  8385. thisArg: interaction.thisArg,
  8386. type: INTERACTION_CALLED,
  8387. withNew: false
  8388. }, context);
  8389. }
  8390. return this.getAccessedValue().hasEffectsOnInteractionAtPath(path, interaction, context);
  8391. }
  8392. applyDeoptimizations() { }
  8393. getAccessedValue() {
  8394. if (this.accessedValue === null) {
  8395. if (this.kind === 'get') {
  8396. this.accessedValue = UNKNOWN_EXPRESSION;
  8397. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  8398. }
  8399. else {
  8400. return (this.accessedValue = this.value);
  8401. }
  8402. }
  8403. return this.accessedValue;
  8404. }
  8405. }
  8406. class MethodDefinition extends MethodBase {
  8407. applyDeoptimizations() { }
  8408. }
  8409. class ObjectMember extends ExpressionEntity {
  8410. constructor(object, key) {
  8411. super();
  8412. this.object = object;
  8413. this.key = key;
  8414. }
  8415. deoptimizePath(path) {
  8416. this.object.deoptimizePath([this.key, ...path]);
  8417. }
  8418. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8419. this.object.deoptimizeThisOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  8420. }
  8421. getLiteralValueAtPath(path, recursionTracker, origin) {
  8422. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  8423. }
  8424. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8425. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  8426. }
  8427. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8428. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  8429. }
  8430. }
  8431. class ClassNode extends NodeBase {
  8432. constructor() {
  8433. super(...arguments);
  8434. this.objectEntity = null;
  8435. }
  8436. createScope(parentScope) {
  8437. this.scope = new ChildScope(parentScope);
  8438. }
  8439. deoptimizeCache() {
  8440. this.getObjectEntity().deoptimizeAllProperties();
  8441. }
  8442. deoptimizePath(path) {
  8443. this.getObjectEntity().deoptimizePath(path);
  8444. }
  8445. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8446. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8447. }
  8448. getLiteralValueAtPath(path, recursionTracker, origin) {
  8449. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8450. }
  8451. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8452. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8453. }
  8454. hasEffects(context) {
  8455. var _a, _b;
  8456. if (!this.deoptimized)
  8457. this.applyDeoptimizations();
  8458. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  8459. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  8460. return initEffect || super.hasEffects(context);
  8461. }
  8462. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8463. var _a;
  8464. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  8465. return (!interaction.withNew ||
  8466. (this.classConstructor !== null
  8467. ? this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)
  8468. : (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  8469. false);
  8470. }
  8471. else {
  8472. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8473. }
  8474. }
  8475. include(context, includeChildrenRecursively) {
  8476. var _a;
  8477. if (!this.deoptimized)
  8478. this.applyDeoptimizations();
  8479. this.included = true;
  8480. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  8481. this.body.include(context, includeChildrenRecursively);
  8482. if (this.id) {
  8483. this.id.markDeclarationReached();
  8484. this.id.include();
  8485. }
  8486. }
  8487. initialise() {
  8488. var _a;
  8489. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  8490. for (const method of this.body.body) {
  8491. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  8492. this.classConstructor = method;
  8493. return;
  8494. }
  8495. }
  8496. this.classConstructor = null;
  8497. }
  8498. applyDeoptimizations() {
  8499. this.deoptimized = true;
  8500. for (const definition of this.body.body) {
  8501. if (!(definition.static ||
  8502. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  8503. // Calls to methods are not tracked, ensure that the return value is deoptimized
  8504. definition.deoptimizePath(UNKNOWN_PATH);
  8505. }
  8506. }
  8507. this.context.requestTreeshakingPass();
  8508. }
  8509. getObjectEntity() {
  8510. if (this.objectEntity !== null) {
  8511. return this.objectEntity;
  8512. }
  8513. const staticProperties = [];
  8514. const dynamicMethods = [];
  8515. for (const definition of this.body.body) {
  8516. const properties = definition.static ? staticProperties : dynamicMethods;
  8517. const definitionKind = definition.kind;
  8518. // Note that class fields do not end up on the prototype
  8519. if (properties === dynamicMethods && !definitionKind)
  8520. continue;
  8521. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  8522. let key;
  8523. if (definition.computed) {
  8524. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8525. if (typeof keyValue === 'symbol') {
  8526. properties.push({ key: UnknownKey, kind, property: definition });
  8527. continue;
  8528. }
  8529. else {
  8530. key = String(keyValue);
  8531. }
  8532. }
  8533. else {
  8534. key =
  8535. definition.key instanceof Identifier
  8536. ? definition.key.name
  8537. : String(definition.key.value);
  8538. }
  8539. properties.push({ key, kind, property: definition });
  8540. }
  8541. staticProperties.unshift({
  8542. key: 'prototype',
  8543. kind: 'init',
  8544. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  8545. });
  8546. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  8547. }
  8548. }
  8549. class ClassDeclaration extends ClassNode {
  8550. initialise() {
  8551. super.initialise();
  8552. if (this.id !== null) {
  8553. this.id.variable.isId = true;
  8554. }
  8555. }
  8556. parseNode(esTreeNode) {
  8557. if (esTreeNode.id !== null) {
  8558. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8559. }
  8560. super.parseNode(esTreeNode);
  8561. }
  8562. render(code, options) {
  8563. const { exportNamesByVariable, format, snippets: { _ } } = options;
  8564. if (format === 'system' && this.id && exportNamesByVariable.has(this.id.variable)) {
  8565. code.appendLeft(this.end, `${_}${getSystemExportStatement([this.id.variable], options)};`);
  8566. }
  8567. super.render(code, options);
  8568. }
  8569. }
  8570. class ClassExpression extends ClassNode {
  8571. render(code, options, { renderedSurroundingElement } = BLANK) {
  8572. super.render(code, options);
  8573. if (renderedSurroundingElement === ExpressionStatement$1) {
  8574. code.appendRight(this.start, '(');
  8575. code.prependLeft(this.end, ')');
  8576. }
  8577. }
  8578. }
  8579. class MultiExpression extends ExpressionEntity {
  8580. constructor(expressions) {
  8581. super();
  8582. this.expressions = expressions;
  8583. this.included = false;
  8584. }
  8585. deoptimizePath(path) {
  8586. for (const expression of this.expressions) {
  8587. expression.deoptimizePath(path);
  8588. }
  8589. }
  8590. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8591. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)));
  8592. }
  8593. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8594. for (const expression of this.expressions) {
  8595. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  8596. return true;
  8597. }
  8598. return false;
  8599. }
  8600. }
  8601. class ConditionalExpression extends NodeBase {
  8602. constructor() {
  8603. super(...arguments);
  8604. this.expressionsToBeDeoptimized = [];
  8605. this.isBranchResolutionAnalysed = false;
  8606. this.usedBranch = null;
  8607. }
  8608. deoptimizeCache() {
  8609. if (this.usedBranch !== null) {
  8610. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  8611. this.usedBranch = null;
  8612. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  8613. for (const expression of this.expressionsToBeDeoptimized) {
  8614. expression.deoptimizeCache();
  8615. }
  8616. }
  8617. }
  8618. deoptimizePath(path) {
  8619. const usedBranch = this.getUsedBranch();
  8620. if (!usedBranch) {
  8621. this.consequent.deoptimizePath(path);
  8622. this.alternate.deoptimizePath(path);
  8623. }
  8624. else {
  8625. usedBranch.deoptimizePath(path);
  8626. }
  8627. }
  8628. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  8629. this.consequent.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8630. this.alternate.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  8631. }
  8632. getLiteralValueAtPath(path, recursionTracker, origin) {
  8633. const usedBranch = this.getUsedBranch();
  8634. if (!usedBranch)
  8635. return UnknownValue;
  8636. this.expressionsToBeDeoptimized.push(origin);
  8637. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  8638. }
  8639. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8640. const usedBranch = this.getUsedBranch();
  8641. if (!usedBranch)
  8642. return new MultiExpression([
  8643. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  8644. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  8645. ]);
  8646. this.expressionsToBeDeoptimized.push(origin);
  8647. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8648. }
  8649. hasEffects(context) {
  8650. if (this.test.hasEffects(context))
  8651. return true;
  8652. const usedBranch = this.getUsedBranch();
  8653. if (!usedBranch) {
  8654. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  8655. }
  8656. return usedBranch.hasEffects(context);
  8657. }
  8658. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8659. const usedBranch = this.getUsedBranch();
  8660. if (!usedBranch) {
  8661. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  8662. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  8663. }
  8664. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  8665. }
  8666. include(context, includeChildrenRecursively) {
  8667. this.included = true;
  8668. const usedBranch = this.getUsedBranch();
  8669. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  8670. this.test.include(context, includeChildrenRecursively);
  8671. this.consequent.include(context, includeChildrenRecursively);
  8672. this.alternate.include(context, includeChildrenRecursively);
  8673. }
  8674. else {
  8675. usedBranch.include(context, includeChildrenRecursively);
  8676. }
  8677. }
  8678. includeCallArguments(context, args) {
  8679. const usedBranch = this.getUsedBranch();
  8680. if (!usedBranch) {
  8681. this.consequent.includeCallArguments(context, args);
  8682. this.alternate.includeCallArguments(context, args);
  8683. }
  8684. else {
  8685. usedBranch.includeCallArguments(context, args);
  8686. }
  8687. }
  8688. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8689. const usedBranch = this.getUsedBranch();
  8690. if (!this.test.included) {
  8691. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  8692. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  8693. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  8694. : colonPos) + 1);
  8695. if (preventASI) {
  8696. removeLineBreaks(code, inclusionStart, usedBranch.start);
  8697. }
  8698. code.remove(this.start, inclusionStart);
  8699. if (this.consequent.included) {
  8700. code.remove(colonPos, this.end);
  8701. }
  8702. removeAnnotations(this, code);
  8703. usedBranch.render(code, options, {
  8704. isCalleeOfRenderedParent,
  8705. preventASI: true,
  8706. renderedParentType: renderedParentType || this.parent.type,
  8707. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  8708. });
  8709. }
  8710. else {
  8711. this.test.render(code, options, { renderedSurroundingElement });
  8712. this.consequent.render(code, options);
  8713. this.alternate.render(code, options);
  8714. }
  8715. }
  8716. getUsedBranch() {
  8717. if (this.isBranchResolutionAnalysed) {
  8718. return this.usedBranch;
  8719. }
  8720. this.isBranchResolutionAnalysed = true;
  8721. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8722. return typeof testValue === 'symbol'
  8723. ? null
  8724. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  8725. }
  8726. }
  8727. class ContinueStatement extends NodeBase {
  8728. hasEffects(context) {
  8729. if (this.label) {
  8730. if (!context.ignore.labels.has(this.label.name))
  8731. return true;
  8732. context.includedLabels.add(this.label.name);
  8733. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8734. }
  8735. else {
  8736. if (!context.ignore.continues)
  8737. return true;
  8738. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  8739. }
  8740. return false;
  8741. }
  8742. include(context) {
  8743. this.included = true;
  8744. if (this.label) {
  8745. this.label.include();
  8746. context.includedLabels.add(this.label.name);
  8747. }
  8748. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  8749. }
  8750. }
  8751. class DoWhileStatement extends NodeBase {
  8752. hasEffects(context) {
  8753. if (this.test.hasEffects(context))
  8754. return true;
  8755. const { brokenFlow, ignore: { breaks, continues } } = context;
  8756. context.ignore.breaks = true;
  8757. context.ignore.continues = true;
  8758. if (this.body.hasEffects(context))
  8759. return true;
  8760. context.ignore.breaks = breaks;
  8761. context.ignore.continues = continues;
  8762. context.brokenFlow = brokenFlow;
  8763. return false;
  8764. }
  8765. include(context, includeChildrenRecursively) {
  8766. this.included = true;
  8767. this.test.include(context, includeChildrenRecursively);
  8768. const { brokenFlow } = context;
  8769. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8770. context.brokenFlow = brokenFlow;
  8771. }
  8772. }
  8773. class EmptyStatement extends NodeBase {
  8774. hasEffects() {
  8775. return false;
  8776. }
  8777. }
  8778. class ExportAllDeclaration extends NodeBase {
  8779. hasEffects() {
  8780. return false;
  8781. }
  8782. initialise() {
  8783. this.context.addExport(this);
  8784. }
  8785. render(code, _options, nodeRenderOptions) {
  8786. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  8787. }
  8788. applyDeoptimizations() { }
  8789. }
  8790. ExportAllDeclaration.prototype.needsBoundaries = true;
  8791. class FunctionDeclaration extends FunctionNode {
  8792. initialise() {
  8793. super.initialise();
  8794. if (this.id !== null) {
  8795. this.id.variable.isId = true;
  8796. }
  8797. }
  8798. parseNode(esTreeNode) {
  8799. if (esTreeNode.id !== null) {
  8800. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  8801. }
  8802. super.parseNode(esTreeNode);
  8803. }
  8804. }
  8805. // The header ends at the first non-white-space after "default"
  8806. function getDeclarationStart(code, start) {
  8807. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  8808. }
  8809. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  8810. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  8811. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  8812. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  8813. if (generatorStarPos === -1) {
  8814. return declarationEnd;
  8815. }
  8816. return declarationEnd + generatorStarPos + 1;
  8817. }
  8818. class ExportDefaultDeclaration extends NodeBase {
  8819. include(context, includeChildrenRecursively) {
  8820. super.include(context, includeChildrenRecursively);
  8821. if (includeChildrenRecursively) {
  8822. this.context.includeVariableInModule(this.variable);
  8823. }
  8824. }
  8825. initialise() {
  8826. const declaration = this.declaration;
  8827. this.declarationName =
  8828. (declaration.id && declaration.id.name) || this.declaration.name;
  8829. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  8830. this.context.addExport(this);
  8831. }
  8832. render(code, options, nodeRenderOptions) {
  8833. const { start, end } = nodeRenderOptions;
  8834. const declarationStart = getDeclarationStart(code.original, this.start);
  8835. if (this.declaration instanceof FunctionDeclaration) {
  8836. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  8837. }
  8838. else if (this.declaration instanceof ClassDeclaration) {
  8839. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  8840. }
  8841. else if (this.variable.getOriginalVariable() !== this.variable) {
  8842. // Remove altogether to prevent re-declaring the same variable
  8843. treeshakeNode(this, code, start, end);
  8844. return;
  8845. }
  8846. else if (this.variable.included) {
  8847. this.renderVariableDeclaration(code, declarationStart, options);
  8848. }
  8849. else {
  8850. code.remove(this.start, declarationStart);
  8851. this.declaration.render(code, options, {
  8852. renderedSurroundingElement: ExpressionStatement$1
  8853. });
  8854. if (code.original[this.end - 1] !== ';') {
  8855. code.appendLeft(this.end, ';');
  8856. }
  8857. return;
  8858. }
  8859. this.declaration.render(code, options);
  8860. }
  8861. applyDeoptimizations() { }
  8862. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  8863. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  8864. const name = this.variable.getName(getPropertyAccess);
  8865. // Remove `export default`
  8866. code.remove(this.start, declarationStart);
  8867. if (needsId) {
  8868. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  8869. }
  8870. if (format === 'system' &&
  8871. this.declaration instanceof ClassDeclaration &&
  8872. exportNamesByVariable.has(this.variable)) {
  8873. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  8874. }
  8875. }
  8876. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  8877. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  8878. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  8879. if (systemExportNames) {
  8880. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  8881. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  8882. }
  8883. else {
  8884. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  8885. if (!hasTrailingSemicolon) {
  8886. code.appendLeft(this.end, ';');
  8887. }
  8888. }
  8889. }
  8890. }
  8891. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  8892. class ExportNamedDeclaration extends NodeBase {
  8893. bind() {
  8894. var _a;
  8895. // Do not bind specifiers
  8896. (_a = this.declaration) === null || _a === void 0 ? void 0 : _a.bind();
  8897. }
  8898. hasEffects(context) {
  8899. var _a;
  8900. return !!((_a = this.declaration) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  8901. }
  8902. initialise() {
  8903. this.context.addExport(this);
  8904. }
  8905. render(code, options, nodeRenderOptions) {
  8906. const { start, end } = nodeRenderOptions;
  8907. if (this.declaration === null) {
  8908. code.remove(start, end);
  8909. }
  8910. else {
  8911. code.remove(this.start, this.declaration.start);
  8912. this.declaration.render(code, options, { end, start });
  8913. }
  8914. }
  8915. applyDeoptimizations() { }
  8916. }
  8917. ExportNamedDeclaration.prototype.needsBoundaries = true;
  8918. class ExportSpecifier extends NodeBase {
  8919. applyDeoptimizations() { }
  8920. }
  8921. class ForInStatement extends NodeBase {
  8922. createScope(parentScope) {
  8923. this.scope = new BlockScope(parentScope);
  8924. }
  8925. hasEffects(context) {
  8926. const { deoptimized, left, right } = this;
  8927. if (!deoptimized)
  8928. this.applyDeoptimizations();
  8929. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  8930. return true;
  8931. const { brokenFlow, ignore: { breaks, continues } } = context;
  8932. context.ignore.breaks = true;
  8933. context.ignore.continues = true;
  8934. if (this.body.hasEffects(context))
  8935. return true;
  8936. context.ignore.breaks = breaks;
  8937. context.ignore.continues = continues;
  8938. context.brokenFlow = brokenFlow;
  8939. return false;
  8940. }
  8941. include(context, includeChildrenRecursively) {
  8942. const { body, deoptimized, left, right } = this;
  8943. if (!deoptimized)
  8944. this.applyDeoptimizations();
  8945. this.included = true;
  8946. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8947. right.include(context, includeChildrenRecursively);
  8948. const { brokenFlow } = context;
  8949. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8950. context.brokenFlow = brokenFlow;
  8951. }
  8952. initialise() {
  8953. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8954. }
  8955. render(code, options) {
  8956. this.left.render(code, options, NO_SEMICOLON);
  8957. this.right.render(code, options, NO_SEMICOLON);
  8958. // handle no space between "in" and the right side
  8959. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  8960. code.prependLeft(this.right.start, ' ');
  8961. }
  8962. this.body.render(code, options);
  8963. }
  8964. applyDeoptimizations() {
  8965. this.deoptimized = true;
  8966. this.left.deoptimizePath(EMPTY_PATH);
  8967. this.context.requestTreeshakingPass();
  8968. }
  8969. }
  8970. class ForOfStatement extends NodeBase {
  8971. createScope(parentScope) {
  8972. this.scope = new BlockScope(parentScope);
  8973. }
  8974. hasEffects() {
  8975. if (!this.deoptimized)
  8976. this.applyDeoptimizations();
  8977. // Placeholder until proper Symbol.Iterator support
  8978. return true;
  8979. }
  8980. include(context, includeChildrenRecursively) {
  8981. const { body, deoptimized, left, right } = this;
  8982. if (!deoptimized)
  8983. this.applyDeoptimizations();
  8984. this.included = true;
  8985. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  8986. right.include(context, includeChildrenRecursively);
  8987. const { brokenFlow } = context;
  8988. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  8989. context.brokenFlow = brokenFlow;
  8990. }
  8991. initialise() {
  8992. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  8993. }
  8994. render(code, options) {
  8995. this.left.render(code, options, NO_SEMICOLON);
  8996. this.right.render(code, options, NO_SEMICOLON);
  8997. // handle no space between "of" and the right side
  8998. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  8999. code.prependLeft(this.right.start, ' ');
  9000. }
  9001. this.body.render(code, options);
  9002. }
  9003. applyDeoptimizations() {
  9004. this.deoptimized = true;
  9005. this.left.deoptimizePath(EMPTY_PATH);
  9006. this.context.requestTreeshakingPass();
  9007. }
  9008. }
  9009. class ForStatement extends NodeBase {
  9010. createScope(parentScope) {
  9011. this.scope = new BlockScope(parentScope);
  9012. }
  9013. hasEffects(context) {
  9014. var _a, _b, _c;
  9015. if (((_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) ||
  9016. ((_b = this.test) === null || _b === void 0 ? void 0 : _b.hasEffects(context)) ||
  9017. ((_c = this.update) === null || _c === void 0 ? void 0 : _c.hasEffects(context)))
  9018. return true;
  9019. const { brokenFlow, ignore: { breaks, continues } } = context;
  9020. context.ignore.breaks = true;
  9021. context.ignore.continues = true;
  9022. if (this.body.hasEffects(context))
  9023. return true;
  9024. context.ignore.breaks = breaks;
  9025. context.ignore.continues = continues;
  9026. context.brokenFlow = brokenFlow;
  9027. return false;
  9028. }
  9029. include(context, includeChildrenRecursively) {
  9030. var _a, _b, _c;
  9031. this.included = true;
  9032. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9033. (_b = this.test) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  9034. const { brokenFlow } = context;
  9035. (_c = this.update) === null || _c === void 0 ? void 0 : _c.include(context, includeChildrenRecursively);
  9036. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9037. context.brokenFlow = brokenFlow;
  9038. }
  9039. render(code, options) {
  9040. var _a, _b, _c;
  9041. (_a = this.init) === null || _a === void 0 ? void 0 : _a.render(code, options, NO_SEMICOLON);
  9042. (_b = this.test) === null || _b === void 0 ? void 0 : _b.render(code, options, NO_SEMICOLON);
  9043. (_c = this.update) === null || _c === void 0 ? void 0 : _c.render(code, options, NO_SEMICOLON);
  9044. this.body.render(code, options);
  9045. }
  9046. }
  9047. class FunctionExpression extends FunctionNode {
  9048. render(code, options, { renderedSurroundingElement } = BLANK) {
  9049. super.render(code, options);
  9050. if (renderedSurroundingElement === ExpressionStatement$1) {
  9051. code.appendRight(this.start, '(');
  9052. code.prependLeft(this.end, ')');
  9053. }
  9054. }
  9055. }
  9056. class TrackingScope extends BlockScope {
  9057. constructor() {
  9058. super(...arguments);
  9059. this.hoistedDeclarations = [];
  9060. }
  9061. addDeclaration(identifier, context, init, isHoisted) {
  9062. this.hoistedDeclarations.push(identifier);
  9063. return super.addDeclaration(identifier, context, init, isHoisted);
  9064. }
  9065. }
  9066. const unset = Symbol('unset');
  9067. class IfStatement extends NodeBase {
  9068. constructor() {
  9069. super(...arguments);
  9070. this.testValue = unset;
  9071. }
  9072. deoptimizeCache() {
  9073. this.testValue = UnknownValue;
  9074. }
  9075. hasEffects(context) {
  9076. var _a;
  9077. if (this.test.hasEffects(context)) {
  9078. return true;
  9079. }
  9080. const testValue = this.getTestValue();
  9081. if (typeof testValue === 'symbol') {
  9082. const { brokenFlow } = context;
  9083. if (this.consequent.hasEffects(context))
  9084. return true;
  9085. const consequentBrokenFlow = context.brokenFlow;
  9086. context.brokenFlow = brokenFlow;
  9087. if (this.alternate === null)
  9088. return false;
  9089. if (this.alternate.hasEffects(context))
  9090. return true;
  9091. context.brokenFlow =
  9092. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9093. return false;
  9094. }
  9095. return testValue ? this.consequent.hasEffects(context) : !!((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.hasEffects(context));
  9096. }
  9097. include(context, includeChildrenRecursively) {
  9098. this.included = true;
  9099. if (includeChildrenRecursively) {
  9100. this.includeRecursively(includeChildrenRecursively, context);
  9101. }
  9102. else {
  9103. const testValue = this.getTestValue();
  9104. if (typeof testValue === 'symbol') {
  9105. this.includeUnknownTest(context);
  9106. }
  9107. else {
  9108. this.includeKnownTest(context, testValue);
  9109. }
  9110. }
  9111. }
  9112. parseNode(esTreeNode) {
  9113. this.consequentScope = new TrackingScope(this.scope);
  9114. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  9115. if (esTreeNode.alternate) {
  9116. this.alternateScope = new TrackingScope(this.scope);
  9117. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  9118. }
  9119. super.parseNode(esTreeNode);
  9120. }
  9121. render(code, options) {
  9122. const { snippets: { getPropertyAccess } } = options;
  9123. // Note that unknown test values are always included
  9124. const testValue = this.getTestValue();
  9125. const hoistedDeclarations = [];
  9126. const includesIfElse = this.test.included;
  9127. const noTreeshake = !this.context.options.treeshake;
  9128. if (includesIfElse) {
  9129. this.test.render(code, options);
  9130. }
  9131. else {
  9132. code.remove(this.start, this.consequent.start);
  9133. }
  9134. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  9135. this.consequent.render(code, options);
  9136. }
  9137. else {
  9138. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  9139. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  9140. }
  9141. if (this.alternate) {
  9142. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  9143. if (includesIfElse) {
  9144. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  9145. code.prependLeft(this.alternate.start, ' ');
  9146. }
  9147. }
  9148. else {
  9149. code.remove(this.consequent.end, this.alternate.start);
  9150. }
  9151. this.alternate.render(code, options);
  9152. }
  9153. else {
  9154. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  9155. code.overwrite(this.alternate.start, this.end, ';');
  9156. }
  9157. else {
  9158. code.remove(this.consequent.end, this.end);
  9159. }
  9160. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  9161. }
  9162. }
  9163. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  9164. }
  9165. applyDeoptimizations() { }
  9166. getTestValue() {
  9167. if (this.testValue === unset) {
  9168. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  9169. }
  9170. return this.testValue;
  9171. }
  9172. includeKnownTest(context, testValue) {
  9173. var _a;
  9174. if (this.test.shouldBeIncluded(context)) {
  9175. this.test.include(context, false);
  9176. }
  9177. if (testValue && this.consequent.shouldBeIncluded(context)) {
  9178. this.consequent.include(context, false, { asSingleStatement: true });
  9179. }
  9180. if (!testValue && ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context))) {
  9181. this.alternate.include(context, false, { asSingleStatement: true });
  9182. }
  9183. }
  9184. includeRecursively(includeChildrenRecursively, context) {
  9185. var _a;
  9186. this.test.include(context, includeChildrenRecursively);
  9187. this.consequent.include(context, includeChildrenRecursively);
  9188. (_a = this.alternate) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  9189. }
  9190. includeUnknownTest(context) {
  9191. var _a;
  9192. this.test.include(context, false);
  9193. const { brokenFlow } = context;
  9194. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  9195. if (this.consequent.shouldBeIncluded(context)) {
  9196. this.consequent.include(context, false, { asSingleStatement: true });
  9197. consequentBrokenFlow = context.brokenFlow;
  9198. context.brokenFlow = brokenFlow;
  9199. }
  9200. if ((_a = this.alternate) === null || _a === void 0 ? void 0 : _a.shouldBeIncluded(context)) {
  9201. this.alternate.include(context, false, { asSingleStatement: true });
  9202. context.brokenFlow =
  9203. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  9204. }
  9205. }
  9206. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  9207. const hoistedVars = [
  9208. ...new Set(hoistedDeclarations.map(identifier => {
  9209. const variable = identifier.variable;
  9210. return variable.included ? variable.getName(getPropertyAccess) : '';
  9211. }))
  9212. ]
  9213. .filter(Boolean)
  9214. .join(', ');
  9215. if (hoistedVars) {
  9216. const parentType = this.parent.type;
  9217. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  9218. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  9219. if (needsBraces) {
  9220. code.appendLeft(this.end, ` }`);
  9221. }
  9222. }
  9223. }
  9224. shouldKeepAlternateBranch() {
  9225. let currentParent = this.parent;
  9226. do {
  9227. if (currentParent instanceof IfStatement && currentParent.alternate) {
  9228. return true;
  9229. }
  9230. if (currentParent instanceof BlockStatement) {
  9231. return false;
  9232. }
  9233. currentParent = currentParent.parent;
  9234. } while (currentParent);
  9235. return false;
  9236. }
  9237. }
  9238. class ImportDeclaration extends NodeBase {
  9239. // Do not bind specifiers
  9240. bind() { }
  9241. hasEffects() {
  9242. return false;
  9243. }
  9244. initialise() {
  9245. this.context.addImport(this);
  9246. }
  9247. render(code, _options, nodeRenderOptions) {
  9248. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9249. }
  9250. applyDeoptimizations() { }
  9251. }
  9252. ImportDeclaration.prototype.needsBoundaries = true;
  9253. class ImportDefaultSpecifier extends NodeBase {
  9254. applyDeoptimizations() { }
  9255. }
  9256. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  9257. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  9258. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  9259. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  9260. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  9261. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  9262. const defaultInteropHelpersByInteropType = {
  9263. auto: INTEROP_DEFAULT_VARIABLE,
  9264. default: null,
  9265. defaultOnly: null,
  9266. esModule: null,
  9267. false: null,
  9268. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  9269. };
  9270. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  9271. (externalLiveBindings && (interopType === 'auto' || interopType === 'true'));
  9272. const namespaceInteropHelpersByInteropType = {
  9273. auto: INTEROP_NAMESPACE_VARIABLE,
  9274. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  9275. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  9276. esModule: null,
  9277. false: null,
  9278. true: INTEROP_NAMESPACE_VARIABLE
  9279. };
  9280. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => isDefaultAProperty(interopType, externalLiveBindings) &&
  9281. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE;
  9282. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9283. const usedHelpers = new Set(additionalHelpers);
  9284. for (const variable of HELPER_NAMES) {
  9285. if (accessedGlobals.has(variable)) {
  9286. usedHelpers.add(variable);
  9287. }
  9288. }
  9289. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  9290. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  9291. : '').join('');
  9292. };
  9293. const HELPER_GENERATORS = {
  9294. [INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
  9295. const { _, getDirectReturnFunction, n } = snippets;
  9296. const [left, right] = getDirectReturnFunction(['e'], {
  9297. functionReturn: true,
  9298. lineBreakIndent: null,
  9299. name: INTEROP_DEFAULT_LEGACY_VARIABLE
  9300. });
  9301. return (`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  9302. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9303. },
  9304. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  9305. const { _, getDirectReturnFunction, n } = snippets;
  9306. const [left, right] = getDirectReturnFunction(['e'], {
  9307. functionReturn: true,
  9308. lineBreakIndent: null,
  9309. name: INTEROP_DEFAULT_VARIABLE
  9310. });
  9311. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  9312. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  9313. },
  9314. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  9315. const { getDirectReturnFunction, getObject, n } = snippets;
  9316. const [left, right] = getDirectReturnFunction(['e'], {
  9317. functionReturn: true,
  9318. lineBreakIndent: null,
  9319. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9320. });
  9321. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  9322. ['__proto__', 'null'],
  9323. ['default', 'e']
  9324. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  9325. },
  9326. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9327. const { _, n } = snippets;
  9328. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  9329. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9330. `}${n}${n}`);
  9331. },
  9332. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  9333. const { _, getDirectReturnFunction, n } = snippets;
  9334. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  9335. const [left, right] = getDirectReturnFunction(['e'], {
  9336. functionReturn: true,
  9337. lineBreakIndent: null,
  9338. name: INTEROP_NAMESPACE_VARIABLE
  9339. });
  9340. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  9341. }
  9342. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  9343. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  9344. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  9345. `}${n}${n}`);
  9346. },
  9347. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  9348. const { _, cnst, n } = snippets;
  9349. const useForEach = cnst === 'var' && liveBindings;
  9350. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  9351. `${t}${loopOverNamespaces(`{${n}` +
  9352. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  9353. (liveBindings
  9354. ? useForEach
  9355. ? copyOwnPropertyLiveBinding
  9356. : copyPropertyLiveBinding
  9357. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  9358. `${t}${t}${t}}${n}` +
  9359. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  9360. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  9361. `}${n}${n}`);
  9362. }
  9363. };
  9364. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  9365. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  9366. const createNamespaceObject = (t, i, snippets, liveBindings, freeze, namespaceToStringTag) => {
  9367. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  9368. const copyProperty = `{${n}` +
  9369. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, i + t + t, snippets) +
  9370. `${i}${t}}`;
  9371. return (`${i}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  9372. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  9373. : ''});${n}` +
  9374. `${i}if${_}(e)${_}{${n}` +
  9375. `${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  9376. `${i}}${n}` +
  9377. `${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  9378. `${i}return ${getFrozen(freeze, 'n')}${s}${n}`);
  9379. };
  9380. const loopOverKeys = (body, allowVarLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVarLoopVariable
  9381. ? `for${_}(${cnst} k in e)${_}${body}`
  9382. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9383. isAsync: false,
  9384. name: null
  9385. })}${body})${s}`;
  9386. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  9387. if (useForEach) {
  9388. const [left, right] = getDirectReturnFunction(['e'], {
  9389. functionReturn: false,
  9390. lineBreakIndent: { base: t, t },
  9391. name: null
  9392. });
  9393. return (`m.forEach(${left}` +
  9394. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  9395. isAsync: false,
  9396. name: null
  9397. })}${body})${right});`);
  9398. }
  9399. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  9400. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  9401. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  9402. };
  9403. const copyNonDefaultOwnPropertyLiveBinding = (t, i, snippets) => {
  9404. const { _, n } = snippets;
  9405. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  9406. copyOwnPropertyLiveBinding(t, i + t, snippets) +
  9407. `${i}}${n}`);
  9408. };
  9409. const copyOwnPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9410. const [left, right] = getDirectReturnFunction([], {
  9411. functionReturn: true,
  9412. lineBreakIndent: null,
  9413. name: null
  9414. });
  9415. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9416. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9417. `${i}${t}enumerable:${_}true,${n}` +
  9418. `${i}${t}get:${_}${left}e[k]${right}${n}` +
  9419. `${i}});${n}`);
  9420. };
  9421. const copyPropertyLiveBinding = (t, i, { _, cnst, getDirectReturnFunction, n }) => {
  9422. const [left, right] = getDirectReturnFunction([], {
  9423. functionReturn: true,
  9424. lineBreakIndent: null,
  9425. name: null
  9426. });
  9427. return (`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  9428. `${i}if${_}(d)${_}{${n}` +
  9429. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  9430. `${i}${t}${t}enumerable:${_}true,${n}` +
  9431. `${i}${t}${t}get:${_}${left}e[k]${right}${n}` +
  9432. `${i}${t}});${n}` +
  9433. `${i}}${n}`);
  9434. };
  9435. const copyPropertyStatic = (_t, i, { _, n }) => `${i}n[k]${_}=${_}e[k];${n}`;
  9436. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  9437. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  9438. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  9439. : fragment;
  9440. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  9441. function getToStringTagValue(getObject) {
  9442. return getObject([['value', "'Module'"]], {
  9443. lineBreakIndent: null
  9444. });
  9445. }
  9446. class ImportExpression extends NodeBase {
  9447. constructor() {
  9448. super(...arguments);
  9449. this.inlineNamespace = null;
  9450. this.mechanism = null;
  9451. this.resolution = null;
  9452. }
  9453. hasEffects() {
  9454. return true;
  9455. }
  9456. include(context, includeChildrenRecursively) {
  9457. if (!this.included) {
  9458. this.included = true;
  9459. this.context.includeDynamicImport(this);
  9460. this.scope.addAccessedDynamicImport(this);
  9461. }
  9462. this.source.include(context, includeChildrenRecursively);
  9463. }
  9464. initialise() {
  9465. this.context.addDynamicImport(this);
  9466. }
  9467. render(code, options) {
  9468. if (this.inlineNamespace) {
  9469. const { snippets: { getDirectReturnFunction, getPropertyAccess } } = options;
  9470. const [left, right] = getDirectReturnFunction([], {
  9471. functionReturn: true,
  9472. lineBreakIndent: null,
  9473. name: null
  9474. });
  9475. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`, { contentOnly: true });
  9476. return;
  9477. }
  9478. if (this.mechanism) {
  9479. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  9480. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  9481. }
  9482. this.source.render(code, options);
  9483. }
  9484. renderFinalResolution(code, resolution, namespaceExportName, { getDirectReturnFunction }) {
  9485. code.overwrite(this.source.start, this.source.end, resolution);
  9486. if (namespaceExportName) {
  9487. const [left, right] = getDirectReturnFunction(['n'], {
  9488. functionReturn: true,
  9489. lineBreakIndent: null,
  9490. name: null
  9491. });
  9492. code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
  9493. }
  9494. }
  9495. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope) {
  9496. const { format } = options;
  9497. this.inlineNamespace = null;
  9498. this.resolution = resolution;
  9499. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  9500. let helper;
  9501. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  9502. if (helper) {
  9503. accessedGlobals.push(helper);
  9504. }
  9505. if (accessedGlobals.length > 0) {
  9506. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9507. }
  9508. }
  9509. setInternalResolution(inlineNamespace) {
  9510. this.inlineNamespace = inlineNamespace;
  9511. }
  9512. applyDeoptimizations() { }
  9513. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  9514. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  9515. {
  9516. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  9517. format,
  9518. moduleId: this.context.module.id,
  9519. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  9520. }
  9521. ]);
  9522. if (mechanism) {
  9523. return { helper: null, mechanism };
  9524. }
  9525. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  9526. switch (format) {
  9527. case 'cjs': {
  9528. const helper = getInteropHelper(resolution, exportMode, interop);
  9529. let left = `require(`;
  9530. let right = `)`;
  9531. if (helper) {
  9532. left = `/*#__PURE__*/${helper}(${left}`;
  9533. right += ')';
  9534. }
  9535. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  9536. functionReturn: true,
  9537. lineBreakIndent: null,
  9538. name: null
  9539. });
  9540. left = `Promise.resolve().then(${functionLeft}${left}`;
  9541. right += `${functionRight})`;
  9542. if (!arrowFunctions && hasDynamicTarget) {
  9543. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9544. needsArrowReturnParens: false,
  9545. needsWrappedFunction: true
  9546. });
  9547. right = ')';
  9548. }
  9549. return {
  9550. helper,
  9551. mechanism: { left, right }
  9552. };
  9553. }
  9554. case 'amd': {
  9555. const resolve = compact ? 'c' : 'resolve';
  9556. const reject = compact ? 'e' : 'reject';
  9557. const helper = getInteropHelper(resolution, exportMode, interop);
  9558. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  9559. functionReturn: false,
  9560. lineBreakIndent: null,
  9561. name: null
  9562. });
  9563. const resolveNamespace = helper
  9564. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  9565. : resolve;
  9566. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  9567. functionReturn: false,
  9568. lineBreakIndent: null,
  9569. name: null
  9570. });
  9571. let left = `new Promise(${handlerLeft}require([`;
  9572. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  9573. if (!arrowFunctions && hasDynamicTarget) {
  9574. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  9575. needsArrowReturnParens: false,
  9576. needsWrappedFunction: true
  9577. });
  9578. right = ')';
  9579. }
  9580. return {
  9581. helper,
  9582. mechanism: { left, right }
  9583. };
  9584. }
  9585. case 'system':
  9586. return {
  9587. helper: null,
  9588. mechanism: {
  9589. left: 'module.import(',
  9590. right: ')'
  9591. }
  9592. };
  9593. case 'es':
  9594. if (dynamicImportFunction) {
  9595. return {
  9596. helper: null,
  9597. mechanism: {
  9598. left: `${dynamicImportFunction}(`,
  9599. right: ')'
  9600. }
  9601. };
  9602. }
  9603. }
  9604. return { helper: null, mechanism: null };
  9605. }
  9606. }
  9607. function getInteropHelper(resolution, exportMode, interop) {
  9608. return exportMode === 'external'
  9609. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  9610. : exportMode === 'default'
  9611. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  9612. : null;
  9613. }
  9614. const accessedImportGlobals = {
  9615. amd: ['require'],
  9616. cjs: ['require'],
  9617. system: ['module']
  9618. };
  9619. class ImportNamespaceSpecifier extends NodeBase {
  9620. applyDeoptimizations() { }
  9621. }
  9622. class ImportSpecifier extends NodeBase {
  9623. applyDeoptimizations() { }
  9624. }
  9625. class LabeledStatement extends NodeBase {
  9626. hasEffects(context) {
  9627. const brokenFlow = context.brokenFlow;
  9628. context.ignore.labels.add(this.label.name);
  9629. if (this.body.hasEffects(context))
  9630. return true;
  9631. context.ignore.labels.delete(this.label.name);
  9632. if (context.includedLabels.has(this.label.name)) {
  9633. context.includedLabels.delete(this.label.name);
  9634. context.brokenFlow = brokenFlow;
  9635. }
  9636. return false;
  9637. }
  9638. include(context, includeChildrenRecursively) {
  9639. this.included = true;
  9640. const brokenFlow = context.brokenFlow;
  9641. this.body.include(context, includeChildrenRecursively);
  9642. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  9643. this.label.include();
  9644. context.includedLabels.delete(this.label.name);
  9645. context.brokenFlow = brokenFlow;
  9646. }
  9647. }
  9648. render(code, options) {
  9649. if (this.label.included) {
  9650. this.label.render(code, options);
  9651. }
  9652. else {
  9653. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  9654. }
  9655. this.body.render(code, options);
  9656. }
  9657. }
  9658. class LogicalExpression extends NodeBase {
  9659. constructor() {
  9660. super(...arguments);
  9661. // We collect deoptimization information if usedBranch !== null
  9662. this.expressionsToBeDeoptimized = [];
  9663. this.isBranchResolutionAnalysed = false;
  9664. this.usedBranch = null;
  9665. }
  9666. deoptimizeCache() {
  9667. if (this.usedBranch) {
  9668. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  9669. this.usedBranch = null;
  9670. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9671. for (const expression of this.expressionsToBeDeoptimized) {
  9672. expression.deoptimizeCache();
  9673. }
  9674. // Request another pass because we need to ensure "include" runs again if
  9675. // it is rendered
  9676. this.context.requestTreeshakingPass();
  9677. }
  9678. }
  9679. deoptimizePath(path) {
  9680. const usedBranch = this.getUsedBranch();
  9681. if (!usedBranch) {
  9682. this.left.deoptimizePath(path);
  9683. this.right.deoptimizePath(path);
  9684. }
  9685. else {
  9686. usedBranch.deoptimizePath(path);
  9687. }
  9688. }
  9689. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  9690. this.left.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9691. this.right.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  9692. }
  9693. getLiteralValueAtPath(path, recursionTracker, origin) {
  9694. const usedBranch = this.getUsedBranch();
  9695. if (!usedBranch)
  9696. return UnknownValue;
  9697. this.expressionsToBeDeoptimized.push(origin);
  9698. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9699. }
  9700. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9701. const usedBranch = this.getUsedBranch();
  9702. if (!usedBranch)
  9703. return new MultiExpression([
  9704. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin),
  9705. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  9706. ]);
  9707. this.expressionsToBeDeoptimized.push(origin);
  9708. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9709. }
  9710. hasEffects(context) {
  9711. if (this.left.hasEffects(context)) {
  9712. return true;
  9713. }
  9714. if (this.getUsedBranch() !== this.left) {
  9715. return this.right.hasEffects(context);
  9716. }
  9717. return false;
  9718. }
  9719. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9720. const usedBranch = this.getUsedBranch();
  9721. if (!usedBranch) {
  9722. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9723. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  9724. }
  9725. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9726. }
  9727. include(context, includeChildrenRecursively) {
  9728. this.included = true;
  9729. const usedBranch = this.getUsedBranch();
  9730. if (includeChildrenRecursively ||
  9731. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  9732. !usedBranch) {
  9733. this.left.include(context, includeChildrenRecursively);
  9734. this.right.include(context, includeChildrenRecursively);
  9735. }
  9736. else {
  9737. usedBranch.include(context, includeChildrenRecursively);
  9738. }
  9739. }
  9740. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9741. if (!this.left.included || !this.right.included) {
  9742. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  9743. if (this.right.included) {
  9744. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  9745. code.remove(this.start, removePos);
  9746. if (preventASI) {
  9747. removeLineBreaks(code, removePos, this.right.start);
  9748. }
  9749. }
  9750. else {
  9751. code.remove(operatorPos, this.end);
  9752. }
  9753. removeAnnotations(this, code);
  9754. this.getUsedBranch().render(code, options, {
  9755. isCalleeOfRenderedParent,
  9756. preventASI,
  9757. renderedParentType: renderedParentType || this.parent.type,
  9758. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9759. });
  9760. }
  9761. else {
  9762. this.left.render(code, options, {
  9763. preventASI,
  9764. renderedSurroundingElement
  9765. });
  9766. this.right.render(code, options);
  9767. }
  9768. }
  9769. getUsedBranch() {
  9770. if (!this.isBranchResolutionAnalysed) {
  9771. this.isBranchResolutionAnalysed = true;
  9772. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9773. if (typeof leftValue === 'symbol') {
  9774. return null;
  9775. }
  9776. else {
  9777. this.usedBranch =
  9778. (this.operator === '||' && leftValue) ||
  9779. (this.operator === '&&' && !leftValue) ||
  9780. (this.operator === '??' && leftValue != null)
  9781. ? this.left
  9782. : this.right;
  9783. }
  9784. }
  9785. return this.usedBranch;
  9786. }
  9787. }
  9788. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  9789. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  9790. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  9791. class MetaProperty extends NodeBase {
  9792. addAccessedGlobals(format, accessedGlobalsByScope) {
  9793. const metaProperty = this.metaProperty;
  9794. const accessedGlobals = (metaProperty &&
  9795. (metaProperty.startsWith(FILE_PREFIX) ||
  9796. metaProperty.startsWith(ASSET_PREFIX) ||
  9797. metaProperty.startsWith(CHUNK_PREFIX))
  9798. ? accessedFileUrlGlobals
  9799. : accessedMetaUrlGlobals)[format];
  9800. if (accessedGlobals.length > 0) {
  9801. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  9802. }
  9803. }
  9804. getReferencedFileName(outputPluginDriver) {
  9805. const metaProperty = this.metaProperty;
  9806. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  9807. return outputPluginDriver.getFileName(metaProperty.substring(FILE_PREFIX.length));
  9808. }
  9809. return null;
  9810. }
  9811. hasEffects() {
  9812. return false;
  9813. }
  9814. hasEffectsOnInteractionAtPath(path, { type }) {
  9815. return path.length > 1 || type !== INTERACTION_ACCESSED;
  9816. }
  9817. include() {
  9818. if (!this.included) {
  9819. this.included = true;
  9820. if (this.meta.name === 'import') {
  9821. this.context.addImportMeta(this);
  9822. const parent = this.parent;
  9823. this.metaProperty =
  9824. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  9825. ? parent.propertyKey
  9826. : null;
  9827. }
  9828. }
  9829. }
  9830. renderFinalMechanism(code, chunkId, format, snippets, outputPluginDriver) {
  9831. var _a;
  9832. const parent = this.parent;
  9833. const metaProperty = this.metaProperty;
  9834. if (metaProperty &&
  9835. (metaProperty.startsWith(FILE_PREFIX) ||
  9836. metaProperty.startsWith(ASSET_PREFIX) ||
  9837. metaProperty.startsWith(CHUNK_PREFIX))) {
  9838. let referenceId = null;
  9839. let assetReferenceId = null;
  9840. let chunkReferenceId = null;
  9841. let fileName;
  9842. if (metaProperty.startsWith(FILE_PREFIX)) {
  9843. referenceId = metaProperty.substring(FILE_PREFIX.length);
  9844. fileName = outputPluginDriver.getFileName(referenceId);
  9845. }
  9846. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  9847. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9848. assetReferenceId = metaProperty.substring(ASSET_PREFIX.length);
  9849. fileName = outputPluginDriver.getFileName(assetReferenceId);
  9850. }
  9851. else {
  9852. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  9853. chunkReferenceId = metaProperty.substring(CHUNK_PREFIX.length);
  9854. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  9855. }
  9856. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  9857. let replacement;
  9858. if (assetReferenceId !== null) {
  9859. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  9860. {
  9861. assetFileName: fileName,
  9862. chunkId,
  9863. format,
  9864. moduleId: this.context.module.id,
  9865. relativeAssetPath: relativePath
  9866. }
  9867. ]);
  9868. }
  9869. if (!replacement) {
  9870. replacement =
  9871. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  9872. {
  9873. assetReferenceId,
  9874. chunkId,
  9875. chunkReferenceId,
  9876. fileName,
  9877. format,
  9878. moduleId: this.context.module.id,
  9879. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  9880. relativePath
  9881. }
  9882. ]) || relativeUrlMechanisms[format](relativePath);
  9883. }
  9884. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9885. return;
  9886. }
  9887. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  9888. metaProperty,
  9889. {
  9890. chunkId,
  9891. format,
  9892. moduleId: this.context.module.id
  9893. }
  9894. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, { chunkId, snippets }));
  9895. if (typeof replacement === 'string') {
  9896. if (parent instanceof MemberExpression) {
  9897. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  9898. }
  9899. else {
  9900. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  9901. }
  9902. }
  9903. }
  9904. }
  9905. const accessedMetaUrlGlobals = {
  9906. amd: ['document', 'module', 'URL'],
  9907. cjs: ['document', 'require', 'URL'],
  9908. es: [],
  9909. iife: ['document', 'URL'],
  9910. system: ['module'],
  9911. umd: ['document', 'require', 'URL']
  9912. };
  9913. const accessedFileUrlGlobals = {
  9914. amd: ['document', 'require', 'URL'],
  9915. cjs: ['document', 'require', 'URL'],
  9916. es: [],
  9917. iife: ['document', 'URL'],
  9918. system: ['module', 'URL'],
  9919. umd: ['document', 'require', 'URL']
  9920. };
  9921. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  9922. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  9923. const getGenericImportMetaMechanism = (getUrl) => (prop, { chunkId }) => {
  9924. const urlMechanism = getUrl(chunkId);
  9925. return prop === null
  9926. ? `({ url: ${urlMechanism} })`
  9927. : prop === 'url'
  9928. ? urlMechanism
  9929. : 'undefined';
  9930. };
  9931. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  9932. const relativeUrlMechanisms = {
  9933. amd: relativePath => {
  9934. if (relativePath[0] !== '.')
  9935. relativePath = './' + relativePath;
  9936. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  9937. },
  9938. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  9939. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  9940. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  9941. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  9942. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  9943. };
  9944. const importMetaMechanisms = {
  9945. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  9946. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  9947. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  9948. system: (prop, { snippets: { getPropertyAccess } }) => prop === null ? `module.meta` : `module.meta${getPropertyAccess(prop)}`,
  9949. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  9950. };
  9951. class NewExpression extends NodeBase {
  9952. hasEffects(context) {
  9953. try {
  9954. for (const argument of this.arguments) {
  9955. if (argument.hasEffects(context))
  9956. return true;
  9957. }
  9958. if (this.context.options.treeshake.annotations &&
  9959. this.annotations) {
  9960. return false;
  9961. }
  9962. return (this.callee.hasEffects(context) ||
  9963. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9964. }
  9965. finally {
  9966. if (!this.deoptimized)
  9967. this.applyDeoptimizations();
  9968. }
  9969. }
  9970. hasEffectsOnInteractionAtPath(path, { type }) {
  9971. return path.length > 0 || type !== INTERACTION_ACCESSED;
  9972. }
  9973. include(context, includeChildrenRecursively) {
  9974. if (!this.deoptimized)
  9975. this.applyDeoptimizations();
  9976. if (includeChildrenRecursively) {
  9977. super.include(context, includeChildrenRecursively);
  9978. }
  9979. else {
  9980. this.included = true;
  9981. this.callee.include(context, false);
  9982. }
  9983. this.callee.includeCallArguments(context, this.arguments);
  9984. }
  9985. initialise() {
  9986. this.interaction = {
  9987. args: this.arguments,
  9988. thisArg: null,
  9989. type: INTERACTION_CALLED,
  9990. withNew: true
  9991. };
  9992. }
  9993. render(code, options) {
  9994. this.callee.render(code, options);
  9995. renderCallArguments(code, options, this);
  9996. }
  9997. applyDeoptimizations() {
  9998. this.deoptimized = true;
  9999. for (const argument of this.arguments) {
  10000. // This will make sure all properties of parameters behave as "unknown"
  10001. argument.deoptimizePath(UNKNOWN_PATH);
  10002. }
  10003. this.context.requestTreeshakingPass();
  10004. }
  10005. }
  10006. class ObjectExpression extends NodeBase {
  10007. constructor() {
  10008. super(...arguments);
  10009. this.objectEntity = null;
  10010. }
  10011. deoptimizeCache() {
  10012. this.getObjectEntity().deoptimizeAllProperties();
  10013. }
  10014. deoptimizePath(path) {
  10015. this.getObjectEntity().deoptimizePath(path);
  10016. }
  10017. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10018. this.getObjectEntity().deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10019. }
  10020. getLiteralValueAtPath(path, recursionTracker, origin) {
  10021. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10022. }
  10023. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10024. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10025. }
  10026. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10027. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10028. }
  10029. render(code, options, { renderedSurroundingElement } = BLANK) {
  10030. super.render(code, options);
  10031. if (renderedSurroundingElement === ExpressionStatement$1 ||
  10032. renderedSurroundingElement === ArrowFunctionExpression$1) {
  10033. code.appendRight(this.start, '(');
  10034. code.prependLeft(this.end, ')');
  10035. }
  10036. }
  10037. applyDeoptimizations() { }
  10038. getObjectEntity() {
  10039. if (this.objectEntity !== null) {
  10040. return this.objectEntity;
  10041. }
  10042. let prototype = OBJECT_PROTOTYPE;
  10043. const properties = [];
  10044. for (const property of this.properties) {
  10045. if (property instanceof SpreadElement) {
  10046. properties.push({ key: UnknownKey, kind: 'init', property });
  10047. continue;
  10048. }
  10049. let key;
  10050. if (property.computed) {
  10051. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10052. if (typeof keyValue === 'symbol') {
  10053. properties.push({ key: UnknownKey, kind: property.kind, property });
  10054. continue;
  10055. }
  10056. else {
  10057. key = String(keyValue);
  10058. }
  10059. }
  10060. else {
  10061. key =
  10062. property.key instanceof Identifier
  10063. ? property.key.name
  10064. : String(property.key.value);
  10065. if (key === '__proto__' && property.kind === 'init') {
  10066. prototype =
  10067. property.value instanceof Literal && property.value.value === null
  10068. ? null
  10069. : property.value;
  10070. continue;
  10071. }
  10072. }
  10073. properties.push({ key, kind: property.kind, property });
  10074. }
  10075. return (this.objectEntity = new ObjectEntity(properties, prototype));
  10076. }
  10077. }
  10078. class PrivateIdentifier extends NodeBase {
  10079. }
  10080. class Program extends NodeBase {
  10081. constructor() {
  10082. super(...arguments);
  10083. this.hasCachedEffect = false;
  10084. }
  10085. hasEffects(context) {
  10086. // We are caching here to later more efficiently identify side-effect-free modules
  10087. if (this.hasCachedEffect)
  10088. return true;
  10089. for (const node of this.body) {
  10090. if (node.hasEffects(context)) {
  10091. return (this.hasCachedEffect = true);
  10092. }
  10093. }
  10094. return false;
  10095. }
  10096. include(context, includeChildrenRecursively) {
  10097. this.included = true;
  10098. for (const node of this.body) {
  10099. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  10100. node.include(context, includeChildrenRecursively);
  10101. }
  10102. }
  10103. }
  10104. render(code, options) {
  10105. if (this.body.length) {
  10106. renderStatementList(this.body, code, this.start, this.end, options);
  10107. }
  10108. else {
  10109. super.render(code, options);
  10110. }
  10111. }
  10112. applyDeoptimizations() { }
  10113. }
  10114. class Property extends MethodBase {
  10115. constructor() {
  10116. super(...arguments);
  10117. this.declarationInit = null;
  10118. }
  10119. declare(kind, init) {
  10120. this.declarationInit = init;
  10121. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  10122. }
  10123. hasEffects(context) {
  10124. if (!this.deoptimized)
  10125. this.applyDeoptimizations();
  10126. const propertyReadSideEffects = this.context.options.treeshake
  10127. .propertyReadSideEffects;
  10128. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  10129. this.key.hasEffects(context) ||
  10130. this.value.hasEffects(context));
  10131. }
  10132. markDeclarationReached() {
  10133. this.value.markDeclarationReached();
  10134. }
  10135. render(code, options) {
  10136. if (!this.shorthand) {
  10137. this.key.render(code, options);
  10138. }
  10139. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  10140. }
  10141. applyDeoptimizations() {
  10142. this.deoptimized = true;
  10143. if (this.declarationInit !== null) {
  10144. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  10145. this.context.requestTreeshakingPass();
  10146. }
  10147. }
  10148. }
  10149. class PropertyDefinition extends NodeBase {
  10150. deoptimizePath(path) {
  10151. var _a;
  10152. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  10153. }
  10154. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10155. var _a;
  10156. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10157. }
  10158. getLiteralValueAtPath(path, recursionTracker, origin) {
  10159. return this.value
  10160. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  10161. : UnknownValue;
  10162. }
  10163. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10164. return this.value
  10165. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  10166. : UNKNOWN_EXPRESSION;
  10167. }
  10168. hasEffects(context) {
  10169. var _a;
  10170. return this.key.hasEffects(context) || (this.static && !!((_a = this.value) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10171. }
  10172. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10173. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  10174. }
  10175. applyDeoptimizations() { }
  10176. }
  10177. class ReturnStatement extends NodeBase {
  10178. hasEffects(context) {
  10179. var _a;
  10180. if (!context.ignore.returnYield || ((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)))
  10181. return true;
  10182. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10183. return false;
  10184. }
  10185. include(context, includeChildrenRecursively) {
  10186. var _a;
  10187. this.included = true;
  10188. (_a = this.argument) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10189. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10190. }
  10191. initialise() {
  10192. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  10193. }
  10194. render(code, options) {
  10195. if (this.argument) {
  10196. this.argument.render(code, options, { preventASI: true });
  10197. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  10198. code.prependLeft(this.start + 6, ' ');
  10199. }
  10200. }
  10201. }
  10202. }
  10203. class SequenceExpression extends NodeBase {
  10204. deoptimizePath(path) {
  10205. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  10206. }
  10207. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10208. this.expressions[this.expressions.length - 1].deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10209. }
  10210. getLiteralValueAtPath(path, recursionTracker, origin) {
  10211. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  10212. }
  10213. hasEffects(context) {
  10214. for (const expression of this.expressions) {
  10215. if (expression.hasEffects(context))
  10216. return true;
  10217. }
  10218. return false;
  10219. }
  10220. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10221. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  10222. }
  10223. include(context, includeChildrenRecursively) {
  10224. this.included = true;
  10225. const lastExpression = this.expressions[this.expressions.length - 1];
  10226. for (const expression of this.expressions) {
  10227. if (includeChildrenRecursively ||
  10228. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  10229. expression.shouldBeIncluded(context))
  10230. expression.include(context, includeChildrenRecursively);
  10231. }
  10232. }
  10233. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  10234. let includedNodes = 0;
  10235. let lastSeparatorPos = null;
  10236. const lastNode = this.expressions[this.expressions.length - 1];
  10237. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  10238. if (!node.included) {
  10239. treeshakeNode(node, code, start, end);
  10240. continue;
  10241. }
  10242. includedNodes++;
  10243. lastSeparatorPos = separator;
  10244. if (includedNodes === 1 && preventASI) {
  10245. removeLineBreaks(code, start, node.start);
  10246. }
  10247. if (includedNodes === 1) {
  10248. const parentType = renderedParentType || this.parent.type;
  10249. node.render(code, options, {
  10250. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  10251. renderedParentType: parentType,
  10252. renderedSurroundingElement: parentType
  10253. });
  10254. }
  10255. else {
  10256. node.render(code, options);
  10257. }
  10258. }
  10259. if (lastSeparatorPos) {
  10260. code.remove(lastSeparatorPos, this.end);
  10261. }
  10262. }
  10263. }
  10264. class StaticBlock extends NodeBase {
  10265. createScope(parentScope) {
  10266. this.scope = new BlockScope(parentScope);
  10267. }
  10268. hasEffects(context) {
  10269. for (const node of this.body) {
  10270. if (node.hasEffects(context))
  10271. return true;
  10272. }
  10273. return false;
  10274. }
  10275. include(context, includeChildrenRecursively) {
  10276. this.included = true;
  10277. for (const node of this.body) {
  10278. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10279. node.include(context, includeChildrenRecursively);
  10280. }
  10281. }
  10282. render(code, options) {
  10283. if (this.body.length) {
  10284. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  10285. }
  10286. else {
  10287. super.render(code, options);
  10288. }
  10289. }
  10290. }
  10291. class Super extends NodeBase {
  10292. bind() {
  10293. this.variable = this.scope.findVariable('this');
  10294. }
  10295. deoptimizePath(path) {
  10296. this.variable.deoptimizePath(path);
  10297. }
  10298. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10299. this.variable.deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker);
  10300. }
  10301. include() {
  10302. if (!this.included) {
  10303. this.included = true;
  10304. this.context.includeVariableInModule(this.variable);
  10305. }
  10306. }
  10307. }
  10308. class SwitchCase extends NodeBase {
  10309. hasEffects(context) {
  10310. var _a;
  10311. if ((_a = this.test) === null || _a === void 0 ? void 0 : _a.hasEffects(context))
  10312. return true;
  10313. for (const node of this.consequent) {
  10314. if (context.brokenFlow)
  10315. break;
  10316. if (node.hasEffects(context))
  10317. return true;
  10318. }
  10319. return false;
  10320. }
  10321. include(context, includeChildrenRecursively) {
  10322. var _a;
  10323. this.included = true;
  10324. (_a = this.test) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  10325. for (const node of this.consequent) {
  10326. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  10327. node.include(context, includeChildrenRecursively);
  10328. }
  10329. }
  10330. render(code, options, nodeRenderOptions) {
  10331. if (this.consequent.length) {
  10332. this.test && this.test.render(code, options);
  10333. const testEnd = this.test
  10334. ? this.test.end
  10335. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  10336. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  10337. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  10338. }
  10339. else {
  10340. super.render(code, options);
  10341. }
  10342. }
  10343. }
  10344. SwitchCase.prototype.needsBoundaries = true;
  10345. class SwitchStatement extends NodeBase {
  10346. createScope(parentScope) {
  10347. this.scope = new BlockScope(parentScope);
  10348. }
  10349. hasEffects(context) {
  10350. if (this.discriminant.hasEffects(context))
  10351. return true;
  10352. const { brokenFlow, ignore: { breaks } } = context;
  10353. let minBrokenFlow = Infinity;
  10354. context.ignore.breaks = true;
  10355. for (const switchCase of this.cases) {
  10356. if (switchCase.hasEffects(context))
  10357. return true;
  10358. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  10359. context.brokenFlow = brokenFlow;
  10360. }
  10361. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10362. context.brokenFlow = minBrokenFlow;
  10363. }
  10364. context.ignore.breaks = breaks;
  10365. return false;
  10366. }
  10367. include(context, includeChildrenRecursively) {
  10368. this.included = true;
  10369. this.discriminant.include(context, includeChildrenRecursively);
  10370. const { brokenFlow } = context;
  10371. let minBrokenFlow = Infinity;
  10372. let isCaseIncluded = includeChildrenRecursively ||
  10373. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  10374. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  10375. const switchCase = this.cases[caseIndex];
  10376. if (switchCase.included) {
  10377. isCaseIncluded = true;
  10378. }
  10379. if (!isCaseIncluded) {
  10380. const hasEffectsContext = createHasEffectsContext();
  10381. hasEffectsContext.ignore.breaks = true;
  10382. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  10383. }
  10384. if (isCaseIncluded) {
  10385. switchCase.include(context, includeChildrenRecursively);
  10386. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  10387. context.brokenFlow = brokenFlow;
  10388. }
  10389. else {
  10390. minBrokenFlow = brokenFlow;
  10391. }
  10392. }
  10393. if (isCaseIncluded &&
  10394. this.defaultCase !== null &&
  10395. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  10396. context.brokenFlow = minBrokenFlow;
  10397. }
  10398. }
  10399. initialise() {
  10400. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  10401. if (this.cases[caseIndex].test === null) {
  10402. this.defaultCase = caseIndex;
  10403. return;
  10404. }
  10405. }
  10406. this.defaultCase = null;
  10407. }
  10408. render(code, options) {
  10409. this.discriminant.render(code, options);
  10410. if (this.cases.length > 0) {
  10411. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  10412. }
  10413. }
  10414. }
  10415. class TaggedTemplateExpression extends CallExpressionBase {
  10416. bind() {
  10417. super.bind();
  10418. if (this.tag.type === Identifier$1) {
  10419. const name = this.tag.name;
  10420. const variable = this.scope.findVariable(name);
  10421. if (variable.isNamespace) {
  10422. this.context.warn({
  10423. code: 'CANNOT_CALL_NAMESPACE',
  10424. message: `Cannot call a namespace ('${name}')`
  10425. }, this.start);
  10426. }
  10427. }
  10428. }
  10429. hasEffects(context) {
  10430. try {
  10431. for (const argument of this.quasi.expressions) {
  10432. if (argument.hasEffects(context))
  10433. return true;
  10434. }
  10435. return (this.tag.hasEffects(context) ||
  10436. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10437. }
  10438. finally {
  10439. if (!this.deoptimized)
  10440. this.applyDeoptimizations();
  10441. }
  10442. }
  10443. include(context, includeChildrenRecursively) {
  10444. if (!this.deoptimized)
  10445. this.applyDeoptimizations();
  10446. if (includeChildrenRecursively) {
  10447. super.include(context, includeChildrenRecursively);
  10448. }
  10449. else {
  10450. this.included = true;
  10451. this.tag.include(context, includeChildrenRecursively);
  10452. this.quasi.include(context, includeChildrenRecursively);
  10453. }
  10454. this.tag.includeCallArguments(context, this.interaction.args);
  10455. const returnExpression = this.getReturnExpression();
  10456. if (!returnExpression.included) {
  10457. returnExpression.include(context, false);
  10458. }
  10459. }
  10460. initialise() {
  10461. this.interaction = {
  10462. args: [UNKNOWN_EXPRESSION, ...this.quasi.expressions],
  10463. thisArg: this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  10464. type: INTERACTION_CALLED,
  10465. withNew: false
  10466. };
  10467. }
  10468. render(code, options) {
  10469. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  10470. this.quasi.render(code, options);
  10471. }
  10472. applyDeoptimizations() {
  10473. this.deoptimized = true;
  10474. if (this.interaction.thisArg) {
  10475. this.tag.deoptimizeThisOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10476. }
  10477. for (const argument of this.quasi.expressions) {
  10478. // This will make sure all properties of parameters behave as "unknown"
  10479. argument.deoptimizePath(UNKNOWN_PATH);
  10480. }
  10481. this.context.requestTreeshakingPass();
  10482. }
  10483. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10484. if (this.returnExpression === null) {
  10485. this.returnExpression = UNKNOWN_EXPRESSION;
  10486. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10487. }
  10488. return this.returnExpression;
  10489. }
  10490. }
  10491. class TemplateElement extends NodeBase {
  10492. // Do not try to bind value
  10493. bind() { }
  10494. hasEffects() {
  10495. return false;
  10496. }
  10497. include() {
  10498. this.included = true;
  10499. }
  10500. parseNode(esTreeNode) {
  10501. this.value = esTreeNode.value;
  10502. super.parseNode(esTreeNode);
  10503. }
  10504. render() { }
  10505. }
  10506. class TemplateLiteral extends NodeBase {
  10507. deoptimizeThisOnInteractionAtPath() { }
  10508. getLiteralValueAtPath(path) {
  10509. if (path.length > 0 || this.quasis.length !== 1) {
  10510. return UnknownValue;
  10511. }
  10512. return this.quasis[0].value.cooked;
  10513. }
  10514. getReturnExpressionWhenCalledAtPath(path) {
  10515. if (path.length !== 1) {
  10516. return UNKNOWN_EXPRESSION;
  10517. }
  10518. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  10519. }
  10520. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10521. if (interaction.type === INTERACTION_ACCESSED) {
  10522. return path.length > 1;
  10523. }
  10524. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  10525. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  10526. }
  10527. return true;
  10528. }
  10529. render(code, options) {
  10530. code.indentExclusionRanges.push([this.start, this.end]);
  10531. super.render(code, options);
  10532. }
  10533. }
  10534. class UndefinedVariable extends Variable {
  10535. constructor() {
  10536. super('undefined');
  10537. }
  10538. getLiteralValueAtPath() {
  10539. return undefined;
  10540. }
  10541. }
  10542. class ExportDefaultVariable extends LocalVariable {
  10543. constructor(name, exportDefaultDeclaration, context) {
  10544. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  10545. this.hasId = false;
  10546. this.originalId = null;
  10547. this.originalVariable = null;
  10548. const declaration = exportDefaultDeclaration.declaration;
  10549. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  10550. declaration.id) {
  10551. this.hasId = true;
  10552. this.originalId = declaration.id;
  10553. }
  10554. else if (declaration instanceof Identifier) {
  10555. this.originalId = declaration;
  10556. }
  10557. }
  10558. addReference(identifier) {
  10559. if (!this.hasId) {
  10560. this.name = identifier.name;
  10561. }
  10562. }
  10563. getAssignedVariableName() {
  10564. return (this.originalId && this.originalId.name) || null;
  10565. }
  10566. getBaseVariableName() {
  10567. const original = this.getOriginalVariable();
  10568. if (original === this) {
  10569. return super.getBaseVariableName();
  10570. }
  10571. else {
  10572. return original.getBaseVariableName();
  10573. }
  10574. }
  10575. getDirectOriginalVariable() {
  10576. return this.originalId &&
  10577. (this.hasId ||
  10578. !(this.originalId.isPossibleTDZ() ||
  10579. this.originalId.variable.isReassigned ||
  10580. this.originalId.variable instanceof UndefinedVariable ||
  10581. // this avoids a circular dependency
  10582. 'syntheticNamespace' in this.originalId.variable))
  10583. ? this.originalId.variable
  10584. : null;
  10585. }
  10586. getName(getPropertyAccess) {
  10587. const original = this.getOriginalVariable();
  10588. if (original === this) {
  10589. return super.getName(getPropertyAccess);
  10590. }
  10591. else {
  10592. return original.getName(getPropertyAccess);
  10593. }
  10594. }
  10595. getOriginalVariable() {
  10596. if (this.originalVariable)
  10597. return this.originalVariable;
  10598. // eslint-disable-next-line @typescript-eslint/no-this-alias
  10599. let original = this;
  10600. let currentVariable;
  10601. const checkedVariables = new Set();
  10602. do {
  10603. checkedVariables.add(original);
  10604. currentVariable = original;
  10605. original = currentVariable.getDirectOriginalVariable();
  10606. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  10607. return (this.originalVariable = original || currentVariable);
  10608. }
  10609. }
  10610. class ModuleScope extends ChildScope {
  10611. constructor(parent, context) {
  10612. super(parent);
  10613. this.context = context;
  10614. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  10615. }
  10616. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  10617. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  10618. this.variables.set('default', variable);
  10619. return variable;
  10620. }
  10621. addNamespaceMemberAccess() { }
  10622. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  10623. // all module level variables are already deconflicted when deconflicting the chunk
  10624. for (const scope of this.children)
  10625. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10626. }
  10627. findLexicalBoundary() {
  10628. return this;
  10629. }
  10630. findVariable(name) {
  10631. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  10632. if (knownVariable) {
  10633. return knownVariable;
  10634. }
  10635. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  10636. if (variable instanceof GlobalVariable) {
  10637. this.accessedOutsideVariables.set(name, variable);
  10638. }
  10639. return variable;
  10640. }
  10641. }
  10642. class ThisExpression extends NodeBase {
  10643. bind() {
  10644. this.variable = this.scope.findVariable('this');
  10645. }
  10646. deoptimizePath(path) {
  10647. this.variable.deoptimizePath(path);
  10648. }
  10649. deoptimizeThisOnInteractionAtPath(interaction, path, recursionTracker) {
  10650. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  10651. this.variable.deoptimizeThisOnInteractionAtPath(interaction.thisArg === this ? { ...interaction, thisArg: this.variable } : interaction, path, recursionTracker);
  10652. }
  10653. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10654. if (path.length === 0) {
  10655. return interaction.type !== INTERACTION_ACCESSED;
  10656. }
  10657. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10658. }
  10659. include() {
  10660. if (!this.included) {
  10661. this.included = true;
  10662. this.context.includeVariableInModule(this.variable);
  10663. }
  10664. }
  10665. initialise() {
  10666. this.alias =
  10667. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  10668. if (this.alias === 'undefined') {
  10669. this.context.warn({
  10670. code: 'THIS_IS_UNDEFINED',
  10671. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  10672. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  10673. }, this.start);
  10674. }
  10675. }
  10676. render(code) {
  10677. if (this.alias !== null) {
  10678. code.overwrite(this.start, this.end, this.alias, {
  10679. contentOnly: false,
  10680. storeName: true
  10681. });
  10682. }
  10683. }
  10684. }
  10685. class ThrowStatement extends NodeBase {
  10686. hasEffects() {
  10687. return true;
  10688. }
  10689. include(context, includeChildrenRecursively) {
  10690. this.included = true;
  10691. this.argument.include(context, includeChildrenRecursively);
  10692. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  10693. }
  10694. render(code, options) {
  10695. this.argument.render(code, options, { preventASI: true });
  10696. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  10697. code.prependLeft(this.start + 5, ' ');
  10698. }
  10699. }
  10700. }
  10701. class TryStatement extends NodeBase {
  10702. constructor() {
  10703. super(...arguments);
  10704. this.directlyIncluded = false;
  10705. this.includedLabelsAfterBlock = null;
  10706. }
  10707. hasEffects(context) {
  10708. var _a;
  10709. return ((this.context.options.treeshake.tryCatchDeoptimization
  10710. ? this.block.body.length > 0
  10711. : this.block.hasEffects(context)) || !!((_a = this.finalizer) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  10712. }
  10713. include(context, includeChildrenRecursively) {
  10714. var _a, _b;
  10715. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  10716. const { brokenFlow } = context;
  10717. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  10718. this.included = true;
  10719. this.directlyIncluded = true;
  10720. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  10721. if (context.includedLabels.size > 0) {
  10722. this.includedLabelsAfterBlock = [...context.includedLabels];
  10723. }
  10724. context.brokenFlow = brokenFlow;
  10725. }
  10726. else if (this.includedLabelsAfterBlock) {
  10727. for (const label of this.includedLabelsAfterBlock) {
  10728. context.includedLabels.add(label);
  10729. }
  10730. }
  10731. if (this.handler !== null) {
  10732. this.handler.include(context, includeChildrenRecursively);
  10733. context.brokenFlow = brokenFlow;
  10734. }
  10735. (_b = this.finalizer) === null || _b === void 0 ? void 0 : _b.include(context, includeChildrenRecursively);
  10736. }
  10737. }
  10738. const unaryOperators = {
  10739. '!': value => !value,
  10740. '+': value => +value,
  10741. '-': value => -value,
  10742. delete: () => UnknownValue,
  10743. typeof: value => typeof value,
  10744. void: () => undefined,
  10745. '~': value => ~value
  10746. };
  10747. class UnaryExpression extends NodeBase {
  10748. getLiteralValueAtPath(path, recursionTracker, origin) {
  10749. if (path.length > 0)
  10750. return UnknownValue;
  10751. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10752. if (typeof argumentValue === 'symbol')
  10753. return UnknownValue;
  10754. return unaryOperators[this.operator](argumentValue);
  10755. }
  10756. hasEffects(context) {
  10757. if (!this.deoptimized)
  10758. this.applyDeoptimizations();
  10759. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  10760. return false;
  10761. return (this.argument.hasEffects(context) ||
  10762. (this.operator === 'delete' &&
  10763. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  10764. }
  10765. hasEffectsOnInteractionAtPath(path, { type }) {
  10766. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  10767. }
  10768. applyDeoptimizations() {
  10769. this.deoptimized = true;
  10770. if (this.operator === 'delete') {
  10771. this.argument.deoptimizePath(EMPTY_PATH);
  10772. this.context.requestTreeshakingPass();
  10773. }
  10774. }
  10775. }
  10776. class UnknownNode extends NodeBase {
  10777. hasEffects() {
  10778. return true;
  10779. }
  10780. include(context) {
  10781. super.include(context, true);
  10782. }
  10783. }
  10784. class UpdateExpression extends NodeBase {
  10785. hasEffects(context) {
  10786. if (!this.deoptimized)
  10787. this.applyDeoptimizations();
  10788. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  10789. }
  10790. hasEffectsOnInteractionAtPath(path, { type }) {
  10791. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10792. }
  10793. include(context, includeChildrenRecursively) {
  10794. if (!this.deoptimized)
  10795. this.applyDeoptimizations();
  10796. this.included = true;
  10797. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  10798. }
  10799. initialise() {
  10800. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  10801. }
  10802. render(code, options) {
  10803. const { exportNamesByVariable, format, snippets: { _ } } = options;
  10804. this.argument.render(code, options);
  10805. if (format === 'system') {
  10806. const variable = this.argument.variable;
  10807. const exportNames = exportNamesByVariable.get(variable);
  10808. if (exportNames) {
  10809. if (this.prefix) {
  10810. if (exportNames.length === 1) {
  10811. renderSystemExportExpression(variable, this.start, this.end, code, options);
  10812. }
  10813. else {
  10814. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  10815. }
  10816. }
  10817. else {
  10818. const operator = this.operator[0];
  10819. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  10820. }
  10821. }
  10822. }
  10823. }
  10824. applyDeoptimizations() {
  10825. this.deoptimized = true;
  10826. this.argument.deoptimizePath(EMPTY_PATH);
  10827. if (this.argument instanceof Identifier) {
  10828. const variable = this.scope.findVariable(this.argument.name);
  10829. variable.isReassigned = true;
  10830. }
  10831. this.context.requestTreeshakingPass();
  10832. }
  10833. }
  10834. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10835. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10836. }
  10837. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  10838. for (const declarator of declarations) {
  10839. if (!declarator.id.included)
  10840. return false;
  10841. if (declarator.id.type === Identifier$1) {
  10842. if (exportNamesByVariable.has(declarator.id.variable))
  10843. return false;
  10844. }
  10845. else {
  10846. const exportedVariables = [];
  10847. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  10848. if (exportedVariables.length > 0)
  10849. return false;
  10850. }
  10851. }
  10852. return true;
  10853. }
  10854. class VariableDeclaration extends NodeBase {
  10855. deoptimizePath() {
  10856. for (const declarator of this.declarations) {
  10857. declarator.deoptimizePath(EMPTY_PATH);
  10858. }
  10859. }
  10860. hasEffectsOnInteractionAtPath() {
  10861. return false;
  10862. }
  10863. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  10864. this.included = true;
  10865. for (const declarator of this.declarations) {
  10866. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  10867. declarator.include(context, includeChildrenRecursively);
  10868. if (asSingleStatement) {
  10869. declarator.id.include(context, includeChildrenRecursively);
  10870. }
  10871. }
  10872. }
  10873. initialise() {
  10874. for (const declarator of this.declarations) {
  10875. declarator.declareDeclarator(this.kind);
  10876. }
  10877. }
  10878. render(code, options, nodeRenderOptions = BLANK) {
  10879. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  10880. for (const declarator of this.declarations) {
  10881. declarator.render(code, options);
  10882. }
  10883. if (!nodeRenderOptions.isNoStatement &&
  10884. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  10885. code.appendLeft(this.end, ';');
  10886. }
  10887. }
  10888. else {
  10889. this.renderReplacedDeclarations(code, options);
  10890. }
  10891. }
  10892. applyDeoptimizations() { }
  10893. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  10894. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  10895. code.remove(this.end - 1, this.end);
  10896. }
  10897. separatorString += ';';
  10898. if (lastSeparatorPos !== null) {
  10899. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  10900. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  10901. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  10902. actualContentEnd--;
  10903. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  10904. actualContentEnd--;
  10905. }
  10906. }
  10907. if (actualContentEnd === lastSeparatorPos + 1) {
  10908. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  10909. }
  10910. else {
  10911. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10912. code.remove(actualContentEnd, renderedContentEnd);
  10913. }
  10914. }
  10915. else {
  10916. code.appendLeft(renderedContentEnd, separatorString);
  10917. }
  10918. if (systemPatternExports.length > 0) {
  10919. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  10920. }
  10921. }
  10922. renderReplacedDeclarations(code, options) {
  10923. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  10924. let actualContentEnd, renderedContentEnd;
  10925. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  10926. let lastSeparatorPos = renderedContentEnd - 1;
  10927. code.remove(this.start, lastSeparatorPos);
  10928. let isInDeclaration = false;
  10929. let hasRenderedContent = false;
  10930. let separatorString = '', leadingString, nextSeparatorString;
  10931. const aggregatedSystemExports = [];
  10932. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  10933. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  10934. if (!node.included) {
  10935. code.remove(start, end);
  10936. continue;
  10937. }
  10938. node.render(code, options);
  10939. leadingString = '';
  10940. nextSeparatorString = '';
  10941. if (!node.id.included ||
  10942. (node.id instanceof Identifier &&
  10943. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  10944. if (hasRenderedContent) {
  10945. separatorString += ';';
  10946. }
  10947. isInDeclaration = false;
  10948. }
  10949. else {
  10950. if (singleSystemExport && singleSystemExport === node.id.variable) {
  10951. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  10952. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  10953. }
  10954. if (isInDeclaration) {
  10955. separatorString += ',';
  10956. }
  10957. else {
  10958. if (hasRenderedContent) {
  10959. separatorString += ';';
  10960. }
  10961. leadingString += `${this.kind} `;
  10962. isInDeclaration = true;
  10963. }
  10964. }
  10965. if (renderedContentEnd === lastSeparatorPos + 1) {
  10966. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  10967. }
  10968. else {
  10969. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  10970. code.appendLeft(renderedContentEnd, leadingString);
  10971. }
  10972. actualContentEnd = contentEnd;
  10973. renderedContentEnd = end;
  10974. hasRenderedContent = true;
  10975. lastSeparatorPos = separator;
  10976. separatorString = nextSeparatorString;
  10977. }
  10978. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  10979. }
  10980. }
  10981. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  10982. var _a;
  10983. let singleSystemExport = null;
  10984. if (options.format === 'system') {
  10985. for (const { node } of separatedNodes) {
  10986. if (node.id instanceof Identifier &&
  10987. node.init &&
  10988. aggregatedSystemExports.length === 0 &&
  10989. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  10990. singleSystemExport = node.id.variable;
  10991. aggregatedSystemExports.push(singleSystemExport);
  10992. }
  10993. else {
  10994. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  10995. }
  10996. }
  10997. if (aggregatedSystemExports.length > 1) {
  10998. singleSystemExport = null;
  10999. }
  11000. else if (singleSystemExport) {
  11001. aggregatedSystemExports.length = 0;
  11002. }
  11003. }
  11004. return singleSystemExport;
  11005. }
  11006. class VariableDeclarator extends NodeBase {
  11007. declareDeclarator(kind) {
  11008. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11009. }
  11010. deoptimizePath(path) {
  11011. this.id.deoptimizePath(path);
  11012. }
  11013. hasEffects(context) {
  11014. var _a;
  11015. const initEffect = (_a = this.init) === null || _a === void 0 ? void 0 : _a.hasEffects(context);
  11016. this.id.markDeclarationReached();
  11017. return initEffect || this.id.hasEffects(context);
  11018. }
  11019. include(context, includeChildrenRecursively) {
  11020. var _a;
  11021. this.included = true;
  11022. (_a = this.init) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  11023. this.id.markDeclarationReached();
  11024. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  11025. this.id.include(context, includeChildrenRecursively);
  11026. }
  11027. }
  11028. render(code, options) {
  11029. const { exportNamesByVariable, snippets: { _ } } = options;
  11030. const renderId = this.id.included;
  11031. if (renderId) {
  11032. this.id.render(code, options);
  11033. }
  11034. else {
  11035. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  11036. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  11037. }
  11038. if (this.init) {
  11039. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11040. }
  11041. else if (this.id instanceof Identifier &&
  11042. isReassignedExportsMember(this.id.variable, exportNamesByVariable)) {
  11043. code.appendLeft(this.end, `${_}=${_}void 0`);
  11044. }
  11045. }
  11046. applyDeoptimizations() { }
  11047. }
  11048. class WhileStatement extends NodeBase {
  11049. hasEffects(context) {
  11050. if (this.test.hasEffects(context))
  11051. return true;
  11052. const { brokenFlow, ignore: { breaks, continues } } = context;
  11053. context.ignore.breaks = true;
  11054. context.ignore.continues = true;
  11055. if (this.body.hasEffects(context))
  11056. return true;
  11057. context.ignore.breaks = breaks;
  11058. context.ignore.continues = continues;
  11059. context.brokenFlow = brokenFlow;
  11060. return false;
  11061. }
  11062. include(context, includeChildrenRecursively) {
  11063. this.included = true;
  11064. this.test.include(context, includeChildrenRecursively);
  11065. const { brokenFlow } = context;
  11066. this.body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11067. context.brokenFlow = brokenFlow;
  11068. }
  11069. }
  11070. class YieldExpression extends NodeBase {
  11071. hasEffects(context) {
  11072. var _a;
  11073. if (!this.deoptimized)
  11074. this.applyDeoptimizations();
  11075. return !(context.ignore.returnYield && !((_a = this.argument) === null || _a === void 0 ? void 0 : _a.hasEffects(context)));
  11076. }
  11077. render(code, options) {
  11078. if (this.argument) {
  11079. this.argument.render(code, options, { preventASI: true });
  11080. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  11081. code.prependLeft(this.start + 5, ' ');
  11082. }
  11083. }
  11084. }
  11085. }
  11086. const nodeConstructors = {
  11087. ArrayExpression,
  11088. ArrayPattern,
  11089. ArrowFunctionExpression,
  11090. AssignmentExpression,
  11091. AssignmentPattern,
  11092. AwaitExpression,
  11093. BinaryExpression,
  11094. BlockStatement,
  11095. BreakStatement,
  11096. CallExpression,
  11097. CatchClause,
  11098. ChainExpression,
  11099. ClassBody,
  11100. ClassDeclaration,
  11101. ClassExpression,
  11102. ConditionalExpression,
  11103. ContinueStatement,
  11104. DoWhileStatement,
  11105. EmptyStatement,
  11106. ExportAllDeclaration,
  11107. ExportDefaultDeclaration,
  11108. ExportNamedDeclaration,
  11109. ExportSpecifier,
  11110. ExpressionStatement,
  11111. ForInStatement,
  11112. ForOfStatement,
  11113. ForStatement,
  11114. FunctionDeclaration,
  11115. FunctionExpression,
  11116. Identifier,
  11117. IfStatement,
  11118. ImportDeclaration,
  11119. ImportDefaultSpecifier,
  11120. ImportExpression,
  11121. ImportNamespaceSpecifier,
  11122. ImportSpecifier,
  11123. LabeledStatement,
  11124. Literal,
  11125. LogicalExpression,
  11126. MemberExpression,
  11127. MetaProperty,
  11128. MethodDefinition,
  11129. NewExpression,
  11130. ObjectExpression,
  11131. ObjectPattern,
  11132. PrivateIdentifier,
  11133. Program,
  11134. Property,
  11135. PropertyDefinition,
  11136. RestElement,
  11137. ReturnStatement,
  11138. SequenceExpression,
  11139. SpreadElement,
  11140. StaticBlock,
  11141. Super,
  11142. SwitchCase,
  11143. SwitchStatement,
  11144. TaggedTemplateExpression,
  11145. TemplateElement,
  11146. TemplateLiteral,
  11147. ThisExpression,
  11148. ThrowStatement,
  11149. TryStatement,
  11150. UnaryExpression,
  11151. UnknownNode,
  11152. UpdateExpression,
  11153. VariableDeclaration,
  11154. VariableDeclarator,
  11155. WhileStatement,
  11156. YieldExpression
  11157. };
  11158. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  11159. class ExportShimVariable extends Variable {
  11160. constructor(module) {
  11161. super(MISSING_EXPORT_SHIM_VARIABLE);
  11162. this.module = module;
  11163. }
  11164. include() {
  11165. super.include();
  11166. this.module.needsExportShim = true;
  11167. }
  11168. }
  11169. class NamespaceVariable extends Variable {
  11170. constructor(context) {
  11171. super(context.getModuleName());
  11172. this.memberVariables = null;
  11173. this.mergedNamespaces = [];
  11174. this.referencedEarly = false;
  11175. this.references = [];
  11176. this.context = context;
  11177. this.module = context.module;
  11178. }
  11179. addReference(identifier) {
  11180. this.references.push(identifier);
  11181. this.name = identifier.name;
  11182. }
  11183. getMemberVariables() {
  11184. if (this.memberVariables) {
  11185. return this.memberVariables;
  11186. }
  11187. const memberVariables = Object.create(null);
  11188. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  11189. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  11190. const exportedVariable = this.context.traceExport(name);
  11191. if (exportedVariable) {
  11192. memberVariables[name] = exportedVariable;
  11193. }
  11194. }
  11195. }
  11196. return (this.memberVariables = memberVariables);
  11197. }
  11198. include() {
  11199. this.included = true;
  11200. this.context.includeAllExports();
  11201. }
  11202. prepare(accessedGlobalsByScope) {
  11203. if (this.mergedNamespaces.length > 0) {
  11204. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  11205. }
  11206. }
  11207. renderBlock(options) {
  11208. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  11209. const memberVariables = this.getMemberVariables();
  11210. const members = Object.entries(memberVariables).map(([name, original]) => {
  11211. if (this.referencedEarly || original.isReassigned) {
  11212. return [
  11213. null,
  11214. `get ${name}${_}()${_}{${_}return ${original.getName(getPropertyAccess)}${s}${_}}`
  11215. ];
  11216. }
  11217. return [name, original.getName(getPropertyAccess)];
  11218. });
  11219. members.unshift([null, `__proto__:${_}null`]);
  11220. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  11221. if (this.mergedNamespaces.length > 0) {
  11222. const assignmentArgs = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  11223. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArgs.join(`,${_}`)}])`;
  11224. }
  11225. else {
  11226. // The helper to merge namespaces will also take care of freezing and toStringTag
  11227. if (namespaceToStringTag) {
  11228. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  11229. }
  11230. if (freeze) {
  11231. output = `/*#__PURE__*/Object.freeze(${output})`;
  11232. }
  11233. }
  11234. const name = this.getName(getPropertyAccess);
  11235. output = `${cnst} ${name}${_}=${_}${output};`;
  11236. if (format === 'system' && exportNamesByVariable.has(this)) {
  11237. output += `${n}${getSystemExportStatement([this], options)};`;
  11238. }
  11239. return output;
  11240. }
  11241. renderFirst() {
  11242. return this.referencedEarly;
  11243. }
  11244. setMergedNamespaces(mergedNamespaces) {
  11245. this.mergedNamespaces = mergedNamespaces;
  11246. const moduleExecIndex = this.context.getModuleExecIndex();
  11247. for (const identifier of this.references) {
  11248. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  11249. this.referencedEarly = true;
  11250. break;
  11251. }
  11252. }
  11253. }
  11254. }
  11255. NamespaceVariable.prototype.isNamespace = true;
  11256. class SyntheticNamedExportVariable extends Variable {
  11257. constructor(context, name, syntheticNamespace) {
  11258. super(name);
  11259. this.baseVariable = null;
  11260. this.context = context;
  11261. this.module = context.module;
  11262. this.syntheticNamespace = syntheticNamespace;
  11263. }
  11264. getBaseVariable() {
  11265. if (this.baseVariable)
  11266. return this.baseVariable;
  11267. let baseVariable = this.syntheticNamespace;
  11268. while (baseVariable instanceof ExportDefaultVariable ||
  11269. baseVariable instanceof SyntheticNamedExportVariable) {
  11270. if (baseVariable instanceof ExportDefaultVariable) {
  11271. const original = baseVariable.getOriginalVariable();
  11272. if (original === baseVariable)
  11273. break;
  11274. baseVariable = original;
  11275. }
  11276. if (baseVariable instanceof SyntheticNamedExportVariable) {
  11277. baseVariable = baseVariable.syntheticNamespace;
  11278. }
  11279. }
  11280. return (this.baseVariable = baseVariable);
  11281. }
  11282. getBaseVariableName() {
  11283. return this.syntheticNamespace.getBaseVariableName();
  11284. }
  11285. getName(getPropertyAccess) {
  11286. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  11287. }
  11288. include() {
  11289. this.included = true;
  11290. this.context.includeVariableInModule(this.syntheticNamespace);
  11291. }
  11292. setRenderNames(baseName, name) {
  11293. super.setRenderNames(baseName, name);
  11294. }
  11295. }
  11296. var BuildPhase;
  11297. (function (BuildPhase) {
  11298. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11299. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11300. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11301. })(BuildPhase || (BuildPhase = {}));
  11302. function getId(m) {
  11303. return m.id;
  11304. }
  11305. function getOriginalLocation(sourcemapChain, location) {
  11306. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !!sourcemap.mappings);
  11307. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  11308. const sourcemap = filteredSourcemapChain.pop();
  11309. const line = sourcemap.mappings[location.line - 1];
  11310. if (line) {
  11311. const filteredLine = line.filter((segment) => segment.length > 1);
  11312. const lastSegment = filteredLine[filteredLine.length - 1];
  11313. for (const segment of filteredLine) {
  11314. if (segment[0] >= location.column || segment === lastSegment) {
  11315. location = {
  11316. column: segment[3],
  11317. line: segment[2] + 1
  11318. };
  11319. continue traceSourcemap;
  11320. }
  11321. }
  11322. }
  11323. throw new Error("Can't resolve original location of error.");
  11324. }
  11325. return location;
  11326. }
  11327. const NOOP = () => { };
  11328. let timers = new Map();
  11329. function getPersistedLabel(label, level) {
  11330. switch (level) {
  11331. case 1:
  11332. return `# ${label}`;
  11333. case 2:
  11334. return `## ${label}`;
  11335. case 3:
  11336. return label;
  11337. default:
  11338. return `${' '.repeat(level - 4)}- ${label}`;
  11339. }
  11340. }
  11341. function timeStartImpl(label, level = 3) {
  11342. label = getPersistedLabel(label, level);
  11343. const startMemory = process$1.memoryUsage().heapUsed;
  11344. const startTime = performance.now();
  11345. const timer = timers.get(label);
  11346. if (timer === undefined) {
  11347. timers.set(label, {
  11348. memory: 0,
  11349. startMemory,
  11350. startTime,
  11351. time: 0,
  11352. totalMemory: 0
  11353. });
  11354. }
  11355. else {
  11356. timer.startMemory = startMemory;
  11357. timer.startTime = startTime;
  11358. }
  11359. }
  11360. function timeEndImpl(label, level = 3) {
  11361. label = getPersistedLabel(label, level);
  11362. const timer = timers.get(label);
  11363. if (timer !== undefined) {
  11364. const currentMemory = process$1.memoryUsage().heapUsed;
  11365. timer.memory += currentMemory - timer.startMemory;
  11366. timer.time += performance.now() - timer.startTime;
  11367. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  11368. }
  11369. }
  11370. function getTimings() {
  11371. const newTimings = {};
  11372. for (const [label, { memory, time, totalMemory }] of timers) {
  11373. newTimings[label] = [time, memory, totalMemory];
  11374. }
  11375. return newTimings;
  11376. }
  11377. let timeStart = NOOP;
  11378. let timeEnd = NOOP;
  11379. const TIMED_PLUGIN_HOOKS = ['load', 'resolveDynamicImport', 'resolveId', 'transform'];
  11380. function getPluginWithTimers(plugin, index) {
  11381. for (const hook of TIMED_PLUGIN_HOOKS) {
  11382. if (hook in plugin) {
  11383. let timerLabel = `plugin ${index}`;
  11384. if (plugin.name) {
  11385. timerLabel += ` (${plugin.name})`;
  11386. }
  11387. timerLabel += ` - ${hook}`;
  11388. const func = plugin[hook];
  11389. plugin[hook] = function (...args) {
  11390. timeStart(timerLabel, 4);
  11391. const result = func.apply(this, args);
  11392. timeEnd(timerLabel, 4);
  11393. if (result && typeof result.then === 'function') {
  11394. timeStart(`${timerLabel} (async)`, 4);
  11395. return result.then((hookResult) => {
  11396. timeEnd(`${timerLabel} (async)`, 4);
  11397. return hookResult;
  11398. });
  11399. }
  11400. return result;
  11401. };
  11402. }
  11403. }
  11404. return plugin;
  11405. }
  11406. function initialiseTimers(inputOptions) {
  11407. if (inputOptions.perf) {
  11408. timers = new Map();
  11409. timeStart = timeStartImpl;
  11410. timeEnd = timeEndImpl;
  11411. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  11412. }
  11413. else {
  11414. timeStart = NOOP;
  11415. timeEnd = NOOP;
  11416. }
  11417. }
  11418. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  11419. baseModule.isExecuted = true;
  11420. const modules = [baseModule];
  11421. const visitedModules = new Set();
  11422. for (const module of modules) {
  11423. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  11424. if (!(dependency instanceof ExternalModule) &&
  11425. !dependency.isExecuted &&
  11426. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  11427. !visitedModules.has(dependency.id)) {
  11428. dependency.isExecuted = true;
  11429. visitedModules.add(dependency.id);
  11430. modules.push(dependency);
  11431. }
  11432. }
  11433. }
  11434. }
  11435. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  11436. identifier: null,
  11437. localName: MISSING_EXPORT_SHIM_VARIABLE
  11438. };
  11439. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  11440. const searchedModules = searchedNamesAndModules.get(name);
  11441. if (searchedModules) {
  11442. if (searchedModules.has(target)) {
  11443. return isExportAllSearch ? [null] : error(errCircularReexport(name, target.id));
  11444. }
  11445. searchedModules.add(target);
  11446. }
  11447. else {
  11448. searchedNamesAndModules.set(name, new Set([target]));
  11449. }
  11450. return target.getVariableForExportName(name, {
  11451. importerForSideEffects,
  11452. isExportAllSearch,
  11453. searchedNamesAndModules
  11454. });
  11455. }
  11456. function getAndExtendSideEffectModules(variable, module) {
  11457. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  11458. let currentVariable = variable;
  11459. const referencedVariables = new Set([currentVariable]);
  11460. while (true) {
  11461. const importingModule = currentVariable.module;
  11462. currentVariable =
  11463. currentVariable instanceof ExportDefaultVariable
  11464. ? currentVariable.getDirectOriginalVariable()
  11465. : currentVariable instanceof SyntheticNamedExportVariable
  11466. ? currentVariable.syntheticNamespace
  11467. : null;
  11468. if (!currentVariable || referencedVariables.has(currentVariable)) {
  11469. break;
  11470. }
  11471. referencedVariables.add(currentVariable);
  11472. sideEffectModules.add(importingModule);
  11473. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  11474. if (originalSideEffects) {
  11475. for (const module of originalSideEffects) {
  11476. sideEffectModules.add(module);
  11477. }
  11478. }
  11479. }
  11480. return sideEffectModules;
  11481. }
  11482. class Module {
  11483. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta) {
  11484. this.graph = graph;
  11485. this.id = id;
  11486. this.options = options;
  11487. this.alternativeReexportModules = new Map();
  11488. this.chunkFileNames = new Set();
  11489. this.chunkNames = [];
  11490. this.cycles = new Set();
  11491. this.dependencies = new Set();
  11492. this.dynamicDependencies = new Set();
  11493. this.dynamicImporters = [];
  11494. this.dynamicImports = [];
  11495. this.execIndex = Infinity;
  11496. this.implicitlyLoadedAfter = new Set();
  11497. this.implicitlyLoadedBefore = new Set();
  11498. this.importDescriptions = new Map();
  11499. this.importMetas = [];
  11500. this.importedFromNotTreeshaken = false;
  11501. this.importers = [];
  11502. this.includedDynamicImporters = [];
  11503. this.includedImports = new Set();
  11504. this.isExecuted = false;
  11505. this.isUserDefinedEntryPoint = false;
  11506. this.needsExportShim = false;
  11507. this.sideEffectDependenciesByVariable = new Map();
  11508. this.sources = new Set();
  11509. this.usesTopLevelAwait = false;
  11510. this.allExportNames = null;
  11511. this.ast = null;
  11512. this.exportAllModules = [];
  11513. this.exportAllSources = new Set();
  11514. this.exportNamesByVariable = null;
  11515. this.exportShimVariable = new ExportShimVariable(this);
  11516. this.exports = new Map();
  11517. this.namespaceReexportsByName = new Map();
  11518. this.reexportDescriptions = new Map();
  11519. this.relevantDependencies = null;
  11520. this.syntheticExports = new Map();
  11521. this.syntheticNamespace = null;
  11522. this.transformDependencies = [];
  11523. this.transitiveReexports = null;
  11524. this.excludeFromSourcemap = /\0/.test(id);
  11525. this.context = options.moduleContext(id);
  11526. this.preserveSignature = this.options.preserveEntrySignatures;
  11527. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11528. const module = this;
  11529. const { dynamicImports, dynamicImporters, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sources } = this;
  11530. this.info = {
  11531. ast: null,
  11532. code: null,
  11533. get dynamicallyImportedIdResolutions() {
  11534. return dynamicImports
  11535. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  11536. .filter(Boolean);
  11537. },
  11538. get dynamicallyImportedIds() {
  11539. // We cannot use this.dynamicDependencies because this is needed before
  11540. // dynamicDependencies are populated
  11541. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  11542. },
  11543. get dynamicImporters() {
  11544. return dynamicImporters.sort();
  11545. },
  11546. get hasDefaultExport() {
  11547. // This information is only valid after parsing
  11548. if (!module.ast) {
  11549. return null;
  11550. }
  11551. return module.exports.has('default') || reexportDescriptions.has('default');
  11552. },
  11553. get hasModuleSideEffects() {
  11554. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', false, options);
  11555. return this.moduleSideEffects;
  11556. },
  11557. id,
  11558. get implicitlyLoadedAfterOneOf() {
  11559. return Array.from(implicitlyLoadedAfter, getId).sort();
  11560. },
  11561. get implicitlyLoadedBefore() {
  11562. return Array.from(implicitlyLoadedBefore, getId).sort();
  11563. },
  11564. get importedIdResolutions() {
  11565. return Array.from(sources, source => module.resolvedIds[source]).filter(Boolean);
  11566. },
  11567. get importedIds() {
  11568. // We cannot use this.dependencies because this is needed before
  11569. // dependencies are populated
  11570. return Array.from(sources, source => { var _a; return (_a = module.resolvedIds[source]) === null || _a === void 0 ? void 0 : _a.id; }).filter(Boolean);
  11571. },
  11572. get importers() {
  11573. return importers.sort();
  11574. },
  11575. isEntry,
  11576. isExternal: false,
  11577. get isIncluded() {
  11578. if (graph.phase !== BuildPhase.GENERATE) {
  11579. return null;
  11580. }
  11581. return module.isIncluded();
  11582. },
  11583. meta: { ...meta },
  11584. moduleSideEffects,
  11585. syntheticNamedExports
  11586. };
  11587. // Hide the deprecated key so that it only warns when accessed explicitly
  11588. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  11589. enumerable: false
  11590. });
  11591. }
  11592. basename() {
  11593. const base = basename(this.id);
  11594. const ext = extname(this.id);
  11595. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  11596. }
  11597. bindReferences() {
  11598. this.ast.bind();
  11599. }
  11600. error(props, pos) {
  11601. this.addLocationToLogProps(props, pos);
  11602. return error(props);
  11603. }
  11604. getAllExportNames() {
  11605. if (this.allExportNames) {
  11606. return this.allExportNames;
  11607. }
  11608. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  11609. for (const module of this.exportAllModules) {
  11610. if (module instanceof ExternalModule) {
  11611. this.allExportNames.add(`*${module.id}`);
  11612. continue;
  11613. }
  11614. for (const name of module.getAllExportNames()) {
  11615. if (name !== 'default')
  11616. this.allExportNames.add(name);
  11617. }
  11618. }
  11619. // We do not count the synthetic namespace as a regular export to hide it
  11620. // from entry signatures and namespace objects
  11621. if (typeof this.info.syntheticNamedExports === 'string') {
  11622. this.allExportNames.delete(this.info.syntheticNamedExports);
  11623. }
  11624. return this.allExportNames;
  11625. }
  11626. getDependenciesToBeIncluded() {
  11627. if (this.relevantDependencies)
  11628. return this.relevantDependencies;
  11629. this.relevantDependencies = new Set();
  11630. const necessaryDependencies = new Set();
  11631. const alwaysCheckedDependencies = new Set();
  11632. const dependencyVariables = new Set(this.includedImports);
  11633. if (this.info.isEntry ||
  11634. this.includedDynamicImporters.length > 0 ||
  11635. this.namespace.included ||
  11636. this.implicitlyLoadedAfter.size > 0) {
  11637. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  11638. const [exportedVariable] = this.getVariableForExportName(exportName);
  11639. if (exportedVariable) {
  11640. dependencyVariables.add(exportedVariable);
  11641. }
  11642. }
  11643. }
  11644. for (let variable of dependencyVariables) {
  11645. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  11646. if (sideEffectDependencies) {
  11647. for (const module of sideEffectDependencies) {
  11648. alwaysCheckedDependencies.add(module);
  11649. }
  11650. }
  11651. if (variable instanceof SyntheticNamedExportVariable) {
  11652. variable = variable.getBaseVariable();
  11653. }
  11654. else if (variable instanceof ExportDefaultVariable) {
  11655. variable = variable.getOriginalVariable();
  11656. }
  11657. necessaryDependencies.add(variable.module);
  11658. }
  11659. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  11660. for (const dependency of this.dependencies) {
  11661. this.relevantDependencies.add(dependency);
  11662. }
  11663. }
  11664. else {
  11665. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  11666. }
  11667. for (const dependency of necessaryDependencies) {
  11668. this.relevantDependencies.add(dependency);
  11669. }
  11670. return this.relevantDependencies;
  11671. }
  11672. getExportNamesByVariable() {
  11673. if (this.exportNamesByVariable) {
  11674. return this.exportNamesByVariable;
  11675. }
  11676. const exportNamesByVariable = new Map();
  11677. for (const exportName of this.getAllExportNames()) {
  11678. let [tracedVariable] = this.getVariableForExportName(exportName);
  11679. if (tracedVariable instanceof ExportDefaultVariable) {
  11680. tracedVariable = tracedVariable.getOriginalVariable();
  11681. }
  11682. if (!tracedVariable ||
  11683. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  11684. continue;
  11685. }
  11686. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  11687. if (existingExportNames) {
  11688. existingExportNames.push(exportName);
  11689. }
  11690. else {
  11691. exportNamesByVariable.set(tracedVariable, [exportName]);
  11692. }
  11693. }
  11694. return (this.exportNamesByVariable = exportNamesByVariable);
  11695. }
  11696. getExports() {
  11697. return Array.from(this.exports.keys());
  11698. }
  11699. getReexports() {
  11700. if (this.transitiveReexports) {
  11701. return this.transitiveReexports;
  11702. }
  11703. // to avoid infinite recursion when using circular `export * from X`
  11704. this.transitiveReexports = [];
  11705. const reexports = new Set(this.reexportDescriptions.keys());
  11706. for (const module of this.exportAllModules) {
  11707. if (module instanceof ExternalModule) {
  11708. reexports.add(`*${module.id}`);
  11709. }
  11710. else {
  11711. for (const name of [...module.getReexports(), ...module.getExports()]) {
  11712. if (name !== 'default')
  11713. reexports.add(name);
  11714. }
  11715. }
  11716. }
  11717. return (this.transitiveReexports = [...reexports]);
  11718. }
  11719. getRenderedExports() {
  11720. // only direct exports are counted here, not reexports at all
  11721. const renderedExports = [];
  11722. const removedExports = [];
  11723. for (const exportName of this.exports.keys()) {
  11724. const [variable] = this.getVariableForExportName(exportName);
  11725. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  11726. }
  11727. return { removedExports, renderedExports };
  11728. }
  11729. getSyntheticNamespace() {
  11730. if (this.syntheticNamespace === null) {
  11731. this.syntheticNamespace = undefined;
  11732. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  11733. ? this.info.syntheticNamedExports
  11734. : 'default', { onlyExplicit: true });
  11735. }
  11736. if (!this.syntheticNamespace) {
  11737. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  11738. }
  11739. return this.syntheticNamespace;
  11740. }
  11741. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  11742. var _a;
  11743. if (name[0] === '*') {
  11744. if (name.length === 1) {
  11745. // export * from './other'
  11746. return [this.namespace];
  11747. }
  11748. // export * from 'external'
  11749. const module = this.graph.modulesById.get(name.slice(1));
  11750. return module.getVariableForExportName('*');
  11751. }
  11752. // export { foo } from './other'
  11753. const reexportDeclaration = this.reexportDescriptions.get(name);
  11754. if (reexportDeclaration) {
  11755. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  11756. if (!variable) {
  11757. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  11758. }
  11759. if (importerForSideEffects) {
  11760. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11761. }
  11762. return [variable];
  11763. }
  11764. const exportDeclaration = this.exports.get(name);
  11765. if (exportDeclaration) {
  11766. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  11767. return [this.exportShimVariable];
  11768. }
  11769. const name = exportDeclaration.localName;
  11770. const variable = this.traceVariable(name, {
  11771. importerForSideEffects,
  11772. searchedNamesAndModules
  11773. });
  11774. if (importerForSideEffects) {
  11775. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  11776. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  11777. }
  11778. return [variable];
  11779. }
  11780. if (onlyExplicit) {
  11781. return [null];
  11782. }
  11783. if (name !== 'default') {
  11784. const foundNamespaceReexport = (_a = this.namespaceReexportsByName.get(name)) !== null && _a !== void 0 ? _a : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  11785. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  11786. if (foundNamespaceReexport[0]) {
  11787. return foundNamespaceReexport;
  11788. }
  11789. }
  11790. if (this.info.syntheticNamedExports) {
  11791. return [
  11792. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  11793. ];
  11794. }
  11795. // we don't want to create shims when we are just
  11796. // probing export * modules for exports
  11797. if (!isExportAllSearch) {
  11798. if (this.options.shimMissingExports) {
  11799. this.shimMissingExport(name);
  11800. return [this.exportShimVariable];
  11801. }
  11802. }
  11803. return [null];
  11804. }
  11805. hasEffects() {
  11806. return (this.info.moduleSideEffects === 'no-treeshake' ||
  11807. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  11808. }
  11809. include() {
  11810. const context = createInclusionContext();
  11811. if (this.ast.shouldBeIncluded(context))
  11812. this.ast.include(context, false);
  11813. }
  11814. includeAllExports(includeNamespaceMembers) {
  11815. if (!this.isExecuted) {
  11816. markModuleAndImpureDependenciesAsExecuted(this);
  11817. this.graph.needsTreeshakingPass = true;
  11818. }
  11819. for (const exportName of this.exports.keys()) {
  11820. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  11821. const variable = this.getVariableForExportName(exportName)[0];
  11822. variable.deoptimizePath(UNKNOWN_PATH);
  11823. if (!variable.included) {
  11824. this.includeVariable(variable);
  11825. }
  11826. }
  11827. }
  11828. for (const name of this.getReexports()) {
  11829. const [variable] = this.getVariableForExportName(name);
  11830. if (variable) {
  11831. variable.deoptimizePath(UNKNOWN_PATH);
  11832. if (!variable.included) {
  11833. this.includeVariable(variable);
  11834. }
  11835. if (variable instanceof ExternalVariable) {
  11836. variable.module.reexported = true;
  11837. }
  11838. }
  11839. }
  11840. if (includeNamespaceMembers) {
  11841. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  11842. }
  11843. }
  11844. includeAllInBundle() {
  11845. this.ast.include(createInclusionContext(), true);
  11846. this.includeAllExports(false);
  11847. }
  11848. isIncluded() {
  11849. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  11850. }
  11851. linkImports() {
  11852. this.addModulesToImportDescriptions(this.importDescriptions);
  11853. this.addModulesToImportDescriptions(this.reexportDescriptions);
  11854. const externalExportAllModules = [];
  11855. for (const source of this.exportAllSources) {
  11856. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  11857. if (module instanceof ExternalModule) {
  11858. externalExportAllModules.push(module);
  11859. continue;
  11860. }
  11861. this.exportAllModules.push(module);
  11862. }
  11863. this.exportAllModules.push(...externalExportAllModules);
  11864. }
  11865. render(options) {
  11866. const magicString = this.magicString.clone();
  11867. this.ast.render(magicString, options);
  11868. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  11869. return magicString;
  11870. }
  11871. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  11872. this.info.code = code;
  11873. this.originalCode = originalCode;
  11874. this.originalSourcemap = originalSourcemap;
  11875. this.sourcemapChain = sourcemapChain;
  11876. if (transformFiles) {
  11877. this.transformFiles = transformFiles;
  11878. }
  11879. this.transformDependencies = transformDependencies;
  11880. this.customTransformCache = customTransformCache;
  11881. this.updateOptions(moduleOptions);
  11882. timeStart('generate ast', 3);
  11883. if (!ast) {
  11884. ast = this.tryParse();
  11885. }
  11886. timeEnd('generate ast', 3);
  11887. this.resolvedIds = resolvedIds || Object.create(null);
  11888. // By default, `id` is the file name. Custom resolvers and loaders
  11889. // can change that, but it makes sense to use it for the source file name
  11890. const fileName = this.id;
  11891. this.magicString = new MagicString(code, {
  11892. filename: (this.excludeFromSourcemap ? null : fileName),
  11893. indentExclusionRanges: []
  11894. });
  11895. timeStart('analyse ast', 3);
  11896. this.astContext = {
  11897. addDynamicImport: this.addDynamicImport.bind(this),
  11898. addExport: this.addExport.bind(this),
  11899. addImport: this.addImport.bind(this),
  11900. addImportMeta: this.addImportMeta.bind(this),
  11901. code,
  11902. deoptimizationTracker: this.graph.deoptimizationTracker,
  11903. error: this.error.bind(this),
  11904. fileName,
  11905. getExports: this.getExports.bind(this),
  11906. getModuleExecIndex: () => this.execIndex,
  11907. getModuleName: this.basename.bind(this),
  11908. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  11909. getReexports: this.getReexports.bind(this),
  11910. importDescriptions: this.importDescriptions,
  11911. includeAllExports: () => this.includeAllExports(true),
  11912. includeDynamicImport: this.includeDynamicImport.bind(this),
  11913. includeVariableInModule: this.includeVariableInModule.bind(this),
  11914. magicString: this.magicString,
  11915. module: this,
  11916. moduleContext: this.context,
  11917. options: this.options,
  11918. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  11919. traceExport: (name) => this.getVariableForExportName(name)[0],
  11920. traceVariable: this.traceVariable.bind(this),
  11921. usesTopLevelAwait: false,
  11922. warn: this.warn.bind(this)
  11923. };
  11924. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  11925. this.namespace = new NamespaceVariable(this.astContext);
  11926. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  11927. this.info.ast = ast;
  11928. timeEnd('analyse ast', 3);
  11929. }
  11930. toJSON() {
  11931. return {
  11932. ast: this.ast.esTreeNode,
  11933. code: this.info.code,
  11934. customTransformCache: this.customTransformCache,
  11935. dependencies: Array.from(this.dependencies, getId),
  11936. id: this.id,
  11937. meta: this.info.meta,
  11938. moduleSideEffects: this.info.moduleSideEffects,
  11939. originalCode: this.originalCode,
  11940. originalSourcemap: this.originalSourcemap,
  11941. resolvedIds: this.resolvedIds,
  11942. sourcemapChain: this.sourcemapChain,
  11943. syntheticNamedExports: this.info.syntheticNamedExports,
  11944. transformDependencies: this.transformDependencies,
  11945. transformFiles: this.transformFiles
  11946. };
  11947. }
  11948. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  11949. const localVariable = this.scope.variables.get(name);
  11950. if (localVariable) {
  11951. return localVariable;
  11952. }
  11953. const importDeclaration = this.importDescriptions.get(name);
  11954. if (importDeclaration) {
  11955. const otherModule = importDeclaration.module;
  11956. if (otherModule instanceof Module && importDeclaration.name === '*') {
  11957. return otherModule.namespace;
  11958. }
  11959. const [declaration] = getVariableForExportNameRecursive(otherModule, importDeclaration.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  11960. if (!declaration) {
  11961. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  11962. }
  11963. return declaration;
  11964. }
  11965. return null;
  11966. }
  11967. tryParse() {
  11968. try {
  11969. return this.graph.contextParse(this.info.code);
  11970. }
  11971. catch (err) {
  11972. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  11973. if (this.id.endsWith('.json')) {
  11974. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  11975. }
  11976. else if (!this.id.endsWith('.js')) {
  11977. message += ' (Note that you need plugins to import files that are not JavaScript)';
  11978. }
  11979. return this.error({
  11980. code: 'PARSE_ERROR',
  11981. message,
  11982. parserError: err
  11983. }, err.pos);
  11984. }
  11985. }
  11986. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  11987. if (moduleSideEffects != null) {
  11988. this.info.moduleSideEffects = moduleSideEffects;
  11989. }
  11990. if (syntheticNamedExports != null) {
  11991. this.info.syntheticNamedExports = syntheticNamedExports;
  11992. }
  11993. if (meta != null) {
  11994. Object.assign(this.info.meta, meta);
  11995. }
  11996. }
  11997. warn(props, pos) {
  11998. this.addLocationToLogProps(props, pos);
  11999. this.options.onwarn(props);
  12000. }
  12001. addDynamicImport(node) {
  12002. let argument = node.source;
  12003. if (argument instanceof TemplateLiteral) {
  12004. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  12005. argument = argument.quasis[0].value.cooked;
  12006. }
  12007. }
  12008. else if (argument instanceof Literal && typeof argument.value === 'string') {
  12009. argument = argument.value;
  12010. }
  12011. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  12012. }
  12013. addExport(node) {
  12014. if (node instanceof ExportDefaultDeclaration) {
  12015. // export default foo;
  12016. this.exports.set('default', {
  12017. identifier: node.variable.getAssignedVariableName(),
  12018. localName: 'default'
  12019. });
  12020. }
  12021. else if (node instanceof ExportAllDeclaration) {
  12022. const source = node.source.value;
  12023. this.sources.add(source);
  12024. if (node.exported) {
  12025. // export * as name from './other'
  12026. const name = node.exported.name;
  12027. this.reexportDescriptions.set(name, {
  12028. localName: '*',
  12029. module: null,
  12030. source,
  12031. start: node.start
  12032. });
  12033. }
  12034. else {
  12035. // export * from './other'
  12036. this.exportAllSources.add(source);
  12037. }
  12038. }
  12039. else if (node.source instanceof Literal) {
  12040. // export { name } from './other'
  12041. const source = node.source.value;
  12042. this.sources.add(source);
  12043. for (const specifier of node.specifiers) {
  12044. const name = specifier.exported.name;
  12045. this.reexportDescriptions.set(name, {
  12046. localName: specifier.local.name,
  12047. module: null,
  12048. source,
  12049. start: specifier.start
  12050. });
  12051. }
  12052. }
  12053. else if (node.declaration) {
  12054. const declaration = node.declaration;
  12055. if (declaration instanceof VariableDeclaration) {
  12056. // export var { foo, bar } = ...
  12057. // export var foo = 1, bar = 2;
  12058. for (const declarator of declaration.declarations) {
  12059. for (const localName of extractAssignedNames(declarator.id)) {
  12060. this.exports.set(localName, { identifier: null, localName });
  12061. }
  12062. }
  12063. }
  12064. else {
  12065. // export function foo () {}
  12066. const localName = declaration.id.name;
  12067. this.exports.set(localName, { identifier: null, localName });
  12068. }
  12069. }
  12070. else {
  12071. // export { foo, bar, baz }
  12072. for (const specifier of node.specifiers) {
  12073. const localName = specifier.local.name;
  12074. const exportedName = specifier.exported.name;
  12075. this.exports.set(exportedName, { identifier: null, localName });
  12076. }
  12077. }
  12078. }
  12079. addImport(node) {
  12080. const source = node.source.value;
  12081. this.sources.add(source);
  12082. for (const specifier of node.specifiers) {
  12083. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  12084. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  12085. const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
  12086. this.importDescriptions.set(specifier.local.name, {
  12087. module: null,
  12088. name,
  12089. source,
  12090. start: specifier.start
  12091. });
  12092. }
  12093. }
  12094. addImportMeta(node) {
  12095. this.importMetas.push(node);
  12096. }
  12097. addLocationToLogProps(props, pos) {
  12098. props.id = this.id;
  12099. props.pos = pos;
  12100. let code = this.info.code;
  12101. const location = locate(code, pos, { offsetLine: 1 });
  12102. if (location) {
  12103. let { column, line } = location;
  12104. try {
  12105. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  12106. code = this.originalCode;
  12107. }
  12108. catch (err) {
  12109. this.options.onwarn({
  12110. code: 'SOURCEMAP_ERROR',
  12111. id: this.id,
  12112. loc: {
  12113. column,
  12114. file: this.id,
  12115. line
  12116. },
  12117. message: `Error when using sourcemap for reporting an error: ${err.message}`,
  12118. pos
  12119. });
  12120. }
  12121. augmentCodeLocation(props, { column, line }, code, this.id);
  12122. }
  12123. }
  12124. addModulesToImportDescriptions(importDescription) {
  12125. for (const specifier of importDescription.values()) {
  12126. const { id } = this.resolvedIds[specifier.source];
  12127. specifier.module = this.graph.modulesById.get(id);
  12128. }
  12129. }
  12130. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  12131. const handledDependencies = new Set();
  12132. const addSideEffectDependencies = (possibleDependencies) => {
  12133. for (const dependency of possibleDependencies) {
  12134. if (handledDependencies.has(dependency)) {
  12135. continue;
  12136. }
  12137. handledDependencies.add(dependency);
  12138. if (necessaryDependencies.has(dependency)) {
  12139. relevantDependencies.add(dependency);
  12140. continue;
  12141. }
  12142. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  12143. continue;
  12144. }
  12145. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  12146. relevantDependencies.add(dependency);
  12147. continue;
  12148. }
  12149. addSideEffectDependencies(dependency.dependencies);
  12150. }
  12151. };
  12152. addSideEffectDependencies(this.dependencies);
  12153. addSideEffectDependencies(alwaysCheckedDependencies);
  12154. }
  12155. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  12156. let foundSyntheticDeclaration = null;
  12157. const foundInternalDeclarations = new Map();
  12158. const foundExternalDeclarations = new Set();
  12159. for (const module of this.exportAllModules) {
  12160. // Synthetic namespaces should not hide "regular" exports of the same name
  12161. if (module.info.syntheticNamedExports === name) {
  12162. continue;
  12163. }
  12164. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  12165. // We are creating a copy to handle the case where the same binding is
  12166. // imported through different namespace reexports gracefully
  12167. copyNameToModulesMap(searchedNamesAndModules));
  12168. if (module instanceof ExternalModule || indirectExternal) {
  12169. foundExternalDeclarations.add(variable);
  12170. }
  12171. else if (variable instanceof SyntheticNamedExportVariable) {
  12172. if (!foundSyntheticDeclaration) {
  12173. foundSyntheticDeclaration = variable;
  12174. }
  12175. }
  12176. else if (variable) {
  12177. foundInternalDeclarations.set(variable, module);
  12178. }
  12179. }
  12180. if (foundInternalDeclarations.size > 0) {
  12181. const foundDeclarationList = [...foundInternalDeclarations];
  12182. const usedDeclaration = foundDeclarationList[0][0];
  12183. if (foundDeclarationList.length === 1) {
  12184. return [usedDeclaration];
  12185. }
  12186. this.options.onwarn(errNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  12187. // TODO we are pretending it was not found while it should behave like "undefined"
  12188. return [null];
  12189. }
  12190. if (foundExternalDeclarations.size > 0) {
  12191. const foundDeclarationList = [...foundExternalDeclarations];
  12192. const usedDeclaration = foundDeclarationList[0];
  12193. if (foundDeclarationList.length > 1) {
  12194. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  12195. }
  12196. return [usedDeclaration, true];
  12197. }
  12198. if (foundSyntheticDeclaration) {
  12199. return [foundSyntheticDeclaration];
  12200. }
  12201. return [null];
  12202. }
  12203. includeAndGetAdditionalMergedNamespaces() {
  12204. const externalNamespaces = new Set();
  12205. const syntheticNamespaces = new Set();
  12206. for (const module of [this, ...this.exportAllModules]) {
  12207. if (module instanceof ExternalModule) {
  12208. const [externalVariable] = module.getVariableForExportName('*');
  12209. externalVariable.include();
  12210. this.includedImports.add(externalVariable);
  12211. externalNamespaces.add(externalVariable);
  12212. }
  12213. else if (module.info.syntheticNamedExports) {
  12214. const syntheticNamespace = module.getSyntheticNamespace();
  12215. syntheticNamespace.include();
  12216. this.includedImports.add(syntheticNamespace);
  12217. syntheticNamespaces.add(syntheticNamespace);
  12218. }
  12219. }
  12220. return [...syntheticNamespaces, ...externalNamespaces];
  12221. }
  12222. includeDynamicImport(node) {
  12223. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  12224. if (resolution instanceof Module) {
  12225. resolution.includedDynamicImporters.push(this);
  12226. resolution.includeAllExports(true);
  12227. }
  12228. }
  12229. includeVariable(variable) {
  12230. if (!variable.included) {
  12231. variable.include();
  12232. this.graph.needsTreeshakingPass = true;
  12233. const variableModule = variable.module;
  12234. if (variableModule instanceof Module) {
  12235. if (!variableModule.isExecuted) {
  12236. markModuleAndImpureDependenciesAsExecuted(variableModule);
  12237. }
  12238. if (variableModule !== this) {
  12239. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  12240. for (const module of sideEffectModules) {
  12241. if (!module.isExecuted) {
  12242. markModuleAndImpureDependenciesAsExecuted(module);
  12243. }
  12244. }
  12245. }
  12246. }
  12247. }
  12248. }
  12249. includeVariableInModule(variable) {
  12250. this.includeVariable(variable);
  12251. const variableModule = variable.module;
  12252. if (variableModule && variableModule !== this) {
  12253. this.includedImports.add(variable);
  12254. }
  12255. }
  12256. shimMissingExport(name) {
  12257. this.options.onwarn({
  12258. code: 'SHIMMED_EXPORT',
  12259. exporter: relativeId(this.id),
  12260. exportName: name,
  12261. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  12262. });
  12263. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  12264. }
  12265. }
  12266. // if there is a cyclic import in the reexport chain, we should not
  12267. // import from the original module but from the cyclic module to not
  12268. // mess up execution order.
  12269. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  12270. if (variable.module instanceof Module && variable.module !== reexporter) {
  12271. const exporterCycles = variable.module.cycles;
  12272. if (exporterCycles.size > 0) {
  12273. const importerCycles = reexporter.cycles;
  12274. for (const cycleSymbol of importerCycles) {
  12275. if (exporterCycles.has(cycleSymbol)) {
  12276. importer.alternativeReexportModules.set(variable, reexporter);
  12277. break;
  12278. }
  12279. }
  12280. }
  12281. }
  12282. }
  12283. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  12284. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  12285. function removeJsExtension(name) {
  12286. return name.endsWith('.js') ? name.slice(0, -3) : name;
  12287. }
  12288. function getCompleteAmdId(options, chunkId) {
  12289. if (options.autoId) {
  12290. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  12291. }
  12292. return options.id || '';
  12293. }
  12294. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  12295. const { _, cnst, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  12296. if (!namedExportsMode) {
  12297. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  12298. }
  12299. let exportBlock = '';
  12300. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12301. if (reexports && namedExportsMode) {
  12302. for (const specifier of reexports) {
  12303. if (specifier.reexported !== '*') {
  12304. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12305. if (exportBlock)
  12306. exportBlock += n;
  12307. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  12308. const [left, right] = getDirectReturnFunction([], {
  12309. functionReturn: true,
  12310. lineBreakIndent: null,
  12311. name: null
  12312. });
  12313. exportBlock +=
  12314. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  12315. `${t}enumerable:${_}true,${n}` +
  12316. `${t}get:${_}${left}${importName}${right}${n}});`;
  12317. }
  12318. else {
  12319. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  12320. }
  12321. }
  12322. }
  12323. }
  12324. }
  12325. for (const { exported, local } of exports) {
  12326. const lhs = `exports${getPropertyAccess(exported)}`;
  12327. const rhs = local;
  12328. if (lhs !== rhs) {
  12329. if (exportBlock)
  12330. exportBlock += n;
  12331. exportBlock += `${lhs}${_}=${_}${rhs};`;
  12332. }
  12333. }
  12334. for (const { name, reexports } of dependencies) {
  12335. if (reexports && namedExportsMode) {
  12336. for (const specifier of reexports) {
  12337. if (specifier.reexported === '*') {
  12338. if (exportBlock)
  12339. exportBlock += n;
  12340. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  12341. exportBlock +=
  12342. cnst === 'var' && specifier.needsLiveBinding
  12343. ? `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  12344. isAsync: false,
  12345. name: null
  12346. })}${copyPropertyIfNecessary});`
  12347. : `for${_}(${cnst} k in ${name})${_}${copyPropertyIfNecessary}`;
  12348. }
  12349. }
  12350. }
  12351. }
  12352. if (exportBlock) {
  12353. return `${n}${n}${exportBlock}`;
  12354. }
  12355. return '';
  12356. }
  12357. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  12358. if (exports.length > 0) {
  12359. return exports[0].local;
  12360. }
  12361. else {
  12362. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12363. if (reexports) {
  12364. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings, getPropertyAccess);
  12365. }
  12366. }
  12367. }
  12368. }
  12369. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  12370. if (imported === 'default') {
  12371. if (!isChunk) {
  12372. const moduleInterop = String(interop(moduleId));
  12373. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  12374. ? defaultVariableName
  12375. : moduleVariableName;
  12376. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  12377. ? `${variableName}${getPropertyAccess('default')}`
  12378. : variableName;
  12379. }
  12380. return depNamedExportsMode
  12381. ? `${moduleVariableName}${getPropertyAccess('default')}`
  12382. : moduleVariableName;
  12383. }
  12384. if (imported === '*') {
  12385. return (isChunk
  12386. ? !depNamedExportsMode
  12387. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  12388. ? namespaceVariableName
  12389. : moduleVariableName;
  12390. }
  12391. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  12392. }
  12393. function getEsModuleValue(getObject) {
  12394. return getObject([['value', 'true']], {
  12395. lineBreakIndent: null
  12396. });
  12397. }
  12398. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  12399. if (hasNamedExports) {
  12400. if (addEsModule) {
  12401. if (addNamespaceToStringTag) {
  12402. return `Object.defineProperties(exports,${_}${getObject([
  12403. ['__esModule', getEsModuleValue(getObject)],
  12404. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  12405. ], {
  12406. lineBreakIndent: null
  12407. })});`;
  12408. }
  12409. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  12410. }
  12411. if (addNamespaceToStringTag) {
  12412. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  12413. }
  12414. }
  12415. return '';
  12416. }
  12417. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  12418. if (needsLiveBinding) {
  12419. const [left, right] = getDirectReturnFunction([], {
  12420. functionReturn: true,
  12421. lineBreakIndent: null,
  12422. name: null
  12423. });
  12424. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  12425. `${t}${t}enumerable:${_}true,${n}` +
  12426. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  12427. }
  12428. return `exports[k]${_}=${_}${name}[k]`;
  12429. };
  12430. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  12431. const { _, cnst, n } = snippets;
  12432. const neededInteropHelpers = new Set();
  12433. const interopStatements = [];
  12434. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  12435. neededInteropHelpers.add(helper);
  12436. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  12437. };
  12438. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  12439. if (isChunk) {
  12440. for (const { imported, reexported } of [
  12441. ...(imports || []),
  12442. ...(reexports || [])
  12443. ]) {
  12444. if (imported === '*' && reexported !== '*') {
  12445. if (!namedExportsMode) {
  12446. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  12447. }
  12448. break;
  12449. }
  12450. }
  12451. }
  12452. else {
  12453. const moduleInterop = String(interop(id));
  12454. let hasDefault = false;
  12455. let hasNamespace = false;
  12456. for (const { imported, reexported } of [
  12457. ...(imports || []),
  12458. ...(reexports || [])
  12459. ]) {
  12460. let helper;
  12461. let variableName;
  12462. if (imported === 'default') {
  12463. if (!hasDefault) {
  12464. hasDefault = true;
  12465. if (defaultVariableName !== namespaceVariableName) {
  12466. variableName = defaultVariableName;
  12467. helper = defaultInteropHelpersByInteropType[moduleInterop];
  12468. }
  12469. }
  12470. }
  12471. else if (imported === '*' && reexported !== '*') {
  12472. if (!hasNamespace) {
  12473. hasNamespace = true;
  12474. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  12475. variableName = namespaceVariableName;
  12476. }
  12477. }
  12478. if (helper) {
  12479. addInteropStatement(variableName, helper, name);
  12480. }
  12481. }
  12482. }
  12483. }
  12484. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  12485. }
  12486. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  12487. // The assumption is that this makes sense for all relative ids:
  12488. // https://requirejs.org/docs/api.html#jsfiles
  12489. function removeExtensionFromRelativeAmdId(id) {
  12490. return id[0] === '.' ? removeJsExtension(id) : id;
  12491. }
  12492. const builtins = {
  12493. assert: true,
  12494. buffer: true,
  12495. console: true,
  12496. constants: true,
  12497. domain: true,
  12498. events: true,
  12499. http: true,
  12500. https: true,
  12501. os: true,
  12502. path: true,
  12503. process: true,
  12504. punycode: true,
  12505. querystring: true,
  12506. stream: true,
  12507. string_decoder: true,
  12508. timers: true,
  12509. tty: true,
  12510. url: true,
  12511. util: true,
  12512. vm: true,
  12513. zlib: true
  12514. };
  12515. function warnOnBuiltins(warn, dependencies) {
  12516. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  12517. if (!externalBuiltins.length)
  12518. return;
  12519. warn({
  12520. code: 'MISSING_NODE_BUILTINS',
  12521. 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`,
  12522. modules: externalBuiltins
  12523. });
  12524. }
  12525. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets, warn }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12526. warnOnBuiltins(warn, dependencies);
  12527. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  12528. const args = dependencies.map(m => m.name);
  12529. const { n, getNonArrowFunctionIntro, _ } = snippets;
  12530. if (namedExportsMode && hasExports) {
  12531. args.unshift(`exports`);
  12532. deps.unshift(`'exports'`);
  12533. }
  12534. if (accessedGlobals.has('require')) {
  12535. args.unshift('require');
  12536. deps.unshift(`'require'`);
  12537. }
  12538. if (accessedGlobals.has('module')) {
  12539. args.unshift('module');
  12540. deps.unshift(`'module'`);
  12541. }
  12542. const completeAmdId = getCompleteAmdId(amd, id);
  12543. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12544. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  12545. const useStrict = strict ? `${_}'use strict';` : '';
  12546. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  12547. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12548. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12549. if (namespaceMarkers) {
  12550. namespaceMarkers = n + n + namespaceMarkers;
  12551. }
  12552. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12553. return (magicString
  12554. .indent(t)
  12555. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12556. // cf. https://v8.dev/blog/preparser#pife
  12557. .prepend(`${amd.define}(${params}(${getNonArrowFunctionIntro(args, {
  12558. isAsync: false,
  12559. name: null
  12560. })}{${useStrict}${n}${n}`)
  12561. .append(`${n}${n}}));`));
  12562. }
  12563. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  12564. const { _, n } = snippets;
  12565. const useStrict = strict ? `'use strict';${n}${n}` : '';
  12566. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, snippets);
  12567. if (namespaceMarkers) {
  12568. namespaceMarkers += n + n;
  12569. }
  12570. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  12571. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12572. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  12573. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  12574. return magicString.append(`${exportBlock}${outro}`);
  12575. }
  12576. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  12577. let importBlock = '';
  12578. let definingVariable = false;
  12579. for (const { id, name, reexports, imports } of dependencies) {
  12580. if (!reexports && !imports) {
  12581. if (importBlock) {
  12582. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  12583. }
  12584. definingVariable = false;
  12585. importBlock += `require('${id}')`;
  12586. }
  12587. else {
  12588. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  12589. definingVariable = true;
  12590. importBlock += `${name}${_}=${_}require('${id}')`;
  12591. }
  12592. }
  12593. if (importBlock) {
  12594. return `${importBlock};${n}${n}`;
  12595. }
  12596. return '';
  12597. }
  12598. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  12599. const { _, n } = snippets;
  12600. const importBlock = getImportBlock(dependencies, _);
  12601. if (importBlock.length > 0)
  12602. intro += importBlock.join(n) + n + n;
  12603. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  12604. if (intro)
  12605. magicString.prepend(intro);
  12606. const exportBlock = getExportBlock(exports, snippets);
  12607. if (exportBlock.length)
  12608. magicString.append(n + n + exportBlock.join(n).trim());
  12609. if (outro)
  12610. magicString.append(outro);
  12611. return magicString.trim();
  12612. }
  12613. function getImportBlock(dependencies, _) {
  12614. const importBlock = [];
  12615. for (const { id, reexports, imports, name } of dependencies) {
  12616. if (!reexports && !imports) {
  12617. importBlock.push(`import${_}'${id}';`);
  12618. continue;
  12619. }
  12620. if (imports) {
  12621. let defaultImport = null;
  12622. let starImport = null;
  12623. const importedNames = [];
  12624. for (const specifier of imports) {
  12625. if (specifier.imported === 'default') {
  12626. defaultImport = specifier;
  12627. }
  12628. else if (specifier.imported === '*') {
  12629. starImport = specifier;
  12630. }
  12631. else {
  12632. importedNames.push(specifier);
  12633. }
  12634. }
  12635. if (starImport) {
  12636. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  12637. }
  12638. if (defaultImport && importedNames.length === 0) {
  12639. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  12640. }
  12641. else if (importedNames.length > 0) {
  12642. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  12643. .map(specifier => {
  12644. if (specifier.imported === specifier.local) {
  12645. return specifier.imported;
  12646. }
  12647. else {
  12648. return `${specifier.imported} as ${specifier.local}`;
  12649. }
  12650. })
  12651. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12652. }
  12653. }
  12654. if (reexports) {
  12655. let starExport = null;
  12656. const namespaceReexports = [];
  12657. const namedReexports = [];
  12658. for (const specifier of reexports) {
  12659. if (specifier.reexported === '*') {
  12660. starExport = specifier;
  12661. }
  12662. else if (specifier.imported === '*') {
  12663. namespaceReexports.push(specifier);
  12664. }
  12665. else {
  12666. namedReexports.push(specifier);
  12667. }
  12668. }
  12669. if (starExport) {
  12670. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  12671. }
  12672. if (namespaceReexports.length > 0) {
  12673. if (!imports ||
  12674. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  12675. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  12676. }
  12677. for (const specifier of namespaceReexports) {
  12678. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  12679. }
  12680. }
  12681. if (namedReexports.length > 0) {
  12682. importBlock.push(`export${_}{${_}${namedReexports
  12683. .map(specifier => {
  12684. if (specifier.imported === specifier.reexported) {
  12685. return specifier.imported;
  12686. }
  12687. else {
  12688. return `${specifier.imported} as ${specifier.reexported}`;
  12689. }
  12690. })
  12691. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  12692. }
  12693. }
  12694. }
  12695. return importBlock;
  12696. }
  12697. function getExportBlock(exports, { _, cnst }) {
  12698. const exportBlock = [];
  12699. const exportDeclaration = [];
  12700. for (const specifier of exports) {
  12701. if (specifier.expression) {
  12702. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  12703. }
  12704. exportDeclaration.push(specifier.exported === specifier.local
  12705. ? specifier.local
  12706. : `${specifier.local} as ${specifier.exported}`);
  12707. }
  12708. if (exportDeclaration.length) {
  12709. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  12710. }
  12711. return exportBlock;
  12712. }
  12713. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  12714. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  12715. const parts = name.split('.');
  12716. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12717. parts.pop();
  12718. let propertyPath = root;
  12719. return (parts
  12720. .map(part => {
  12721. propertyPath += getPropertyAccess(part);
  12722. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  12723. })
  12724. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  12725. }
  12726. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  12727. const parts = deepName.split('.');
  12728. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  12729. const last = parts.pop();
  12730. let propertyPath = root;
  12731. let deepAssignment = parts
  12732. .map(part => {
  12733. propertyPath += getPropertyAccess(part);
  12734. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  12735. })
  12736. .concat(`${propertyPath}${getPropertyAccess(last)}`)
  12737. .join(`,${_}`) + `${_}=${_}${assignment}`;
  12738. if (parts.length > 0) {
  12739. deepAssignment = `(${deepAssignment})`;
  12740. }
  12741. return deepAssignment;
  12742. }
  12743. function trimEmptyImports(dependencies) {
  12744. let i = dependencies.length;
  12745. while (i--) {
  12746. const { imports, reexports } = dependencies[i];
  12747. if (imports || reexports) {
  12748. return dependencies.slice(0, i + 1);
  12749. }
  12750. }
  12751. return [];
  12752. }
  12753. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, namedExportsMode, outro, snippets, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  12754. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  12755. const isNamespaced = name && name.includes('.');
  12756. const useVariableAssignment = !extend && !isNamespaced;
  12757. if (name && useVariableAssignment && !isLegal(name)) {
  12758. return error({
  12759. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  12760. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  12761. });
  12762. }
  12763. warnOnBuiltins(warn, dependencies);
  12764. const external = trimEmptyImports(dependencies);
  12765. const deps = external.map(dep => dep.globalName || 'null');
  12766. const args = external.map(m => m.name);
  12767. if (hasExports && !name) {
  12768. warn({
  12769. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12770. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  12771. });
  12772. }
  12773. if (namedExportsMode && hasExports) {
  12774. if (extend) {
  12775. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  12776. args.unshift('exports');
  12777. }
  12778. else {
  12779. deps.unshift('{}');
  12780. args.unshift('exports');
  12781. }
  12782. }
  12783. const useStrict = strict ? `${t}'use strict';${n}` : '';
  12784. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  12785. magicString.prepend(`${intro}${interopBlock}`);
  12786. let wrapperIntro = `(${getNonArrowFunctionIntro(args, {
  12787. isAsync: false,
  12788. name: null
  12789. })}{${n}${useStrict}${n}`;
  12790. if (hasExports) {
  12791. if (name && !(extend && namedExportsMode)) {
  12792. wrapperIntro =
  12793. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  12794. `${_}=${_}${wrapperIntro}`;
  12795. }
  12796. if (isNamespaced) {
  12797. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  12798. }
  12799. }
  12800. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  12801. if (hasExports && !extend && namedExportsMode) {
  12802. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  12803. }
  12804. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  12805. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  12806. if (namespaceMarkers) {
  12807. namespaceMarkers = n + n + namespaceMarkers;
  12808. }
  12809. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  12810. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  12811. }
  12812. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  12813. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  12814. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  12815. const registeredName = name ? `'${name}',${_}` : '';
  12816. const wrapperParams = accessedGlobals.has('module')
  12817. ? ['exports', 'module']
  12818. : hasExports
  12819. ? ['exports']
  12820. : [];
  12821. // factory function should be wrapped by parentheses to avoid lazy parsing,
  12822. // cf. https://v8.dev/blog/preparser#pife
  12823. let wrapperStart = `System.register(${registeredName}[` +
  12824. dependencies.map(({ id }) => `'${id}'`).join(`,${_}`) +
  12825. `],${_}(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}${t}${strict ? "'use strict';" : ''}` +
  12826. getStarExcludesBlock(starExcludes, t, snippets) +
  12827. getImportBindingsBlock(importBindings, t, snippets) +
  12828. `${n}${t}return${_}{${setters.length
  12829. ? `${n}${t}${t}setters:${_}[${setters
  12830. .map(setter => setter
  12831. ? `${getFunctionIntro(['module'], {
  12832. isAsync: false,
  12833. name: null
  12834. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  12835. : systemNullSetters
  12836. ? `null`
  12837. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  12838. .join(`,${_}`)}],`
  12839. : ''}${n}`;
  12840. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  12841. isAsync: usesTopLevelAwait,
  12842. name: null
  12843. })}{${n}${n}`;
  12844. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  12845. magicString.prepend(intro +
  12846. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  12847. getHoistedExportsBlock(exports, t, snippets));
  12848. magicString.append(`${outro}${n}${n}` +
  12849. getSyntheticExportsBlock(exports, t, snippets) +
  12850. getMissingExportsBlock(exports, t, snippets));
  12851. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  12852. }
  12853. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  12854. const importBindings = [];
  12855. const setters = [];
  12856. let starExcludes = null;
  12857. for (const { imports, reexports } of dependencies) {
  12858. const setter = [];
  12859. if (imports) {
  12860. for (const specifier of imports) {
  12861. importBindings.push(specifier.local);
  12862. if (specifier.imported === '*') {
  12863. setter.push(`${specifier.local}${_}=${_}module;`);
  12864. }
  12865. else {
  12866. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  12867. }
  12868. }
  12869. }
  12870. if (reexports) {
  12871. const reexportedNames = [];
  12872. let hasStarReexport = false;
  12873. for (const { imported, reexported } of reexports) {
  12874. if (reexported === '*') {
  12875. hasStarReexport = true;
  12876. }
  12877. else {
  12878. reexportedNames.push([
  12879. reexported,
  12880. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  12881. ]);
  12882. }
  12883. }
  12884. if (reexportedNames.length > 1 || hasStarReexport) {
  12885. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  12886. if (hasStarReexport) {
  12887. if (!starExcludes) {
  12888. starExcludes = getStarExcludes({ dependencies, exports });
  12889. }
  12890. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  12891. }
  12892. else {
  12893. setter.push(`exports(${exportMapping});`);
  12894. }
  12895. }
  12896. else {
  12897. const [key, value] = reexportedNames[0];
  12898. setter.push(`exports('${key}',${_}${value});`);
  12899. }
  12900. }
  12901. setters.push(setter.join(`${n}${t}${t}${t}`));
  12902. }
  12903. return { importBindings, setters, starExcludes };
  12904. }
  12905. const getStarExcludes = ({ dependencies, exports }) => {
  12906. const starExcludes = new Set(exports.map(expt => expt.exported));
  12907. starExcludes.add('default');
  12908. for (const { reexports } of dependencies) {
  12909. if (reexports) {
  12910. for (const reexport of reexports) {
  12911. if (reexport.reexported !== '*')
  12912. starExcludes.add(reexport.reexported);
  12913. }
  12914. }
  12915. }
  12916. return starExcludes;
  12917. };
  12918. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  12919. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(prop => [prop, '1']), { lineBreakIndent: { base: t, t } })};`
  12920. : '';
  12921. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  12922. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12923. function getExportsBlock(exports, t, { _, n }) {
  12924. if (exports.length === 0) {
  12925. return '';
  12926. }
  12927. if (exports.length === 1) {
  12928. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  12929. }
  12930. return (`exports({${n}` +
  12931. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  12932. `${n}});${n}${n}`);
  12933. }
  12934. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12935. .filter(expt => expt.expression)
  12936. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  12937. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  12938. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  12939. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  12940. function globalProp(name, globalVar, getPropertyAccess) {
  12941. if (!name)
  12942. return 'null';
  12943. return `${globalVar}${keypath(name, getPropertyAccess)}`;
  12944. }
  12945. function safeAccess(name, globalVar, { _, getPropertyAccess }) {
  12946. let propertyPath = globalVar;
  12947. return name
  12948. .split('.')
  12949. .map(part => (propertyPath += getPropertyAccess(part)))
  12950. .join(`${_}&&${_}`);
  12951. }
  12952. 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 }) {
  12953. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  12954. const factoryVar = compact ? 'f' : 'factory';
  12955. const globalVar = compact ? 'g' : 'global';
  12956. if (hasExports && !name) {
  12957. return error({
  12958. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  12959. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  12960. });
  12961. }
  12962. warnOnBuiltins(warn, dependencies);
  12963. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  12964. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  12965. const trimmedImports = trimEmptyImports(dependencies);
  12966. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar, getPropertyAccess));
  12967. const factoryParams = trimmedImports.map(m => m.name);
  12968. if (namedExportsMode && (hasExports || noConflict)) {
  12969. amdDeps.unshift(`'exports'`);
  12970. cjsDeps.unshift(`exports`);
  12971. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, `${extend ? `${globalProp(name, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  12972. factoryParams.unshift('exports');
  12973. }
  12974. const completeAmdId = getCompleteAmdId(amd, id);
  12975. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  12976. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  12977. const define = amd.define;
  12978. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  12979. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  12980. let iifeExport;
  12981. if (noConflict) {
  12982. const noConflictExportsVar = compact ? 'e' : 'exports';
  12983. let factory;
  12984. if (!namedExportsMode && hasExports) {
  12985. factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, `${factoryVar}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  12986. }
  12987. else {
  12988. const module = globalDeps.shift();
  12989. factory =
  12990. `${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
  12991. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  12992. }
  12993. iifeExport =
  12994. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  12995. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVar, snippets)};${n}` +
  12996. `${t}${t}${factory}${n}` +
  12997. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
  12998. isAsync: false,
  12999. name: null
  13000. })}{${_}` +
  13001. `${globalProp(name, globalVar, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
  13002. `${t}})()`;
  13003. }
  13004. else {
  13005. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  13006. if (!namedExportsMode && hasExports) {
  13007. iifeExport = assignToDeepVariable(name, globalVar, globals, iifeExport, snippets);
  13008. }
  13009. }
  13010. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  13011. const wrapperParams = [factoryVar];
  13012. if (iifeNeedsGlobal) {
  13013. wrapperParams.unshift(globalVar);
  13014. }
  13015. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  13016. const iifeStart = iifeNeedsGlobal
  13017. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  13018. : '';
  13019. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  13020. const cjsIntro = iifeNeedsGlobal
  13021. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  13022. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  13023. : '';
  13024. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
  13025. cjsIntro +
  13026. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  13027. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  13028. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13029. // cf. https://v8.dev/blog/preparser#pife
  13030. `})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
  13031. isAsync: false,
  13032. name: null
  13033. })}{${useStrict}${n}`;
  13034. const wrapperOutro = n + n + '}));';
  13035. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13036. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13037. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, snippets);
  13038. if (namespaceMarkers) {
  13039. namespaceMarkers = n + n + namespaceMarkers;
  13040. }
  13041. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  13042. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  13043. }
  13044. const finalisers = { amd, cjs, es, iife, system, umd };
  13045. class Source {
  13046. constructor(filename, content) {
  13047. this.isOriginal = true;
  13048. this.filename = filename;
  13049. this.content = content;
  13050. }
  13051. traceSegment(line, column, name) {
  13052. return { column, line, name, source: this };
  13053. }
  13054. }
  13055. class Link {
  13056. constructor(map, sources) {
  13057. this.sources = sources;
  13058. this.names = map.names;
  13059. this.mappings = map.mappings;
  13060. }
  13061. traceMappings() {
  13062. const sources = [];
  13063. const sourceIndexMap = new Map();
  13064. const sourcesContent = [];
  13065. const names = [];
  13066. const nameIndexMap = new Map();
  13067. const mappings = [];
  13068. for (const line of this.mappings) {
  13069. const tracedLine = [];
  13070. for (const segment of line) {
  13071. if (segment.length === 1)
  13072. continue;
  13073. const source = this.sources[segment[1]];
  13074. if (!source)
  13075. continue;
  13076. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  13077. if (traced) {
  13078. const { column, line, name, source: { content, filename } } = traced;
  13079. let sourceIndex = sourceIndexMap.get(filename);
  13080. if (sourceIndex === undefined) {
  13081. sourceIndex = sources.length;
  13082. sources.push(filename);
  13083. sourceIndexMap.set(filename, sourceIndex);
  13084. sourcesContent[sourceIndex] = content;
  13085. }
  13086. else if (sourcesContent[sourceIndex] == null) {
  13087. sourcesContent[sourceIndex] = content;
  13088. }
  13089. else if (content != null && sourcesContent[sourceIndex] !== content) {
  13090. return error({
  13091. message: `Multiple conflicting contents for sourcemap source ${filename}`
  13092. });
  13093. }
  13094. const tracedSegment = [segment[0], sourceIndex, line, column];
  13095. if (name) {
  13096. let nameIndex = nameIndexMap.get(name);
  13097. if (nameIndex === undefined) {
  13098. nameIndex = names.length;
  13099. names.push(name);
  13100. nameIndexMap.set(name, nameIndex);
  13101. }
  13102. tracedSegment[4] = nameIndex;
  13103. }
  13104. tracedLine.push(tracedSegment);
  13105. }
  13106. }
  13107. mappings.push(tracedLine);
  13108. }
  13109. return { mappings, names, sources, sourcesContent };
  13110. }
  13111. traceSegment(line, column, name) {
  13112. const segments = this.mappings[line];
  13113. if (!segments)
  13114. return null;
  13115. // binary search through segments for the given column
  13116. let searchStart = 0;
  13117. let searchEnd = segments.length - 1;
  13118. while (searchStart <= searchEnd) {
  13119. const m = (searchStart + searchEnd) >> 1;
  13120. const segment = segments[m];
  13121. // If a sourcemap does not have sufficient resolution to contain a
  13122. // necessary mapping, e.g. because it only contains line information, we
  13123. // use the best approximation we could find
  13124. if (segment[0] === column || searchStart === searchEnd) {
  13125. if (segment.length == 1)
  13126. return null;
  13127. const source = this.sources[segment[1]];
  13128. if (!source)
  13129. return null;
  13130. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  13131. }
  13132. if (segment[0] > column) {
  13133. searchEnd = m - 1;
  13134. }
  13135. else {
  13136. searchStart = m + 1;
  13137. }
  13138. }
  13139. return null;
  13140. }
  13141. }
  13142. function getLinkMap(warn) {
  13143. return function linkMap(source, map) {
  13144. if (map.mappings) {
  13145. return new Link(map, [source]);
  13146. }
  13147. warn({
  13148. code: 'SOURCEMAP_BROKEN',
  13149. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  13150. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  13151. 'documentation for help',
  13152. plugin: map.plugin,
  13153. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  13154. });
  13155. return new Link({
  13156. mappings: [],
  13157. names: []
  13158. }, [source]);
  13159. };
  13160. }
  13161. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  13162. let source;
  13163. if (!originalSourcemap) {
  13164. source = new Source(id, originalCode);
  13165. }
  13166. else {
  13167. const sources = originalSourcemap.sources;
  13168. const sourcesContent = originalSourcemap.sourcesContent || [];
  13169. const directory = dirname(id) || '.';
  13170. const sourceRoot = originalSourcemap.sourceRoot || '.';
  13171. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  13172. source = new Link(originalSourcemap, baseSources);
  13173. }
  13174. return sourcemapChain.reduce(linkMap, source);
  13175. }
  13176. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  13177. const linkMap = getLinkMap(warn);
  13178. const moduleSources = modules
  13179. .filter(module => !module.excludeFromSourcemap)
  13180. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  13181. const link = new Link(map, moduleSources);
  13182. const source = bundleSourcemapChain.reduce(linkMap, link);
  13183. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  13184. if (file) {
  13185. const directory = dirname(file);
  13186. sources = sources.map((source) => relative$1(directory, source));
  13187. file = basename(file);
  13188. }
  13189. sourcesContent = (excludeContent ? null : sourcesContent);
  13190. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  13191. }
  13192. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  13193. if (!sourcemapChain.length) {
  13194. return originalSourcemap;
  13195. }
  13196. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  13197. const map = source.traceMappings();
  13198. return { version: 3, ...map };
  13199. }
  13200. const createHash = () => createHash$1('sha256');
  13201. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  13202. amd: deconflictImportsOther,
  13203. cjs: deconflictImportsOther,
  13204. es: deconflictImportsEsmOrSystem,
  13205. iife: deconflictImportsOther,
  13206. system: deconflictImportsEsmOrSystem,
  13207. umd: deconflictImportsOther
  13208. };
  13209. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  13210. const reversedModules = modules.slice().reverse();
  13211. for (const module of reversedModules) {
  13212. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  13213. }
  13214. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  13215. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  13216. for (const module of reversedModules) {
  13217. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13218. }
  13219. }
  13220. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  13221. // This is needed for namespace reexports
  13222. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  13223. if (preserveModules || dependency instanceof ExternalModule) {
  13224. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  13225. }
  13226. }
  13227. for (const variable of imports) {
  13228. const module = variable.module;
  13229. const name = variable.name;
  13230. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  13231. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  13232. }
  13233. else if (module instanceof ExternalModule && name === 'default') {
  13234. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  13235. ? module.suggestedVariableName + '__default'
  13236. : module.suggestedVariableName, usedNames));
  13237. }
  13238. else {
  13239. variable.setRenderNames(null, getSafeName(name, usedNames));
  13240. }
  13241. }
  13242. for (const variable of syntheticExports) {
  13243. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13244. }
  13245. }
  13246. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  13247. for (const chunkOrExternalModule of dependencies) {
  13248. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  13249. }
  13250. for (const externalModuleOrChunk of deconflictedNamespace) {
  13251. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  13252. }
  13253. for (const externalModule of deconflictedDefault) {
  13254. if (deconflictedNamespace.has(externalModule) &&
  13255. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  13256. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  13257. }
  13258. else {
  13259. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  13260. }
  13261. }
  13262. for (const variable of imports) {
  13263. const module = variable.module;
  13264. if (module instanceof ExternalModule) {
  13265. const name = variable.name;
  13266. if (name === 'default') {
  13267. const moduleInterop = String(interop(module.id));
  13268. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13269. ? module.defaultVariableName
  13270. : module.variableName;
  13271. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  13272. variable.setRenderNames(variableName, 'default');
  13273. }
  13274. else {
  13275. variable.setRenderNames(null, variableName);
  13276. }
  13277. }
  13278. else if (name === '*') {
  13279. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  13280. ? module.namespaceVariableName
  13281. : module.variableName);
  13282. }
  13283. else {
  13284. // if the second parameter is `null`, it uses its "name" for the property name
  13285. variable.setRenderNames(module.variableName, null);
  13286. }
  13287. }
  13288. else {
  13289. const chunk = chunkByModule.get(module);
  13290. if (preserveModules && variable.isNamespace) {
  13291. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  13292. }
  13293. else if (chunk.exportMode === 'default') {
  13294. variable.setRenderNames(null, chunk.variableName);
  13295. }
  13296. else {
  13297. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  13298. }
  13299. }
  13300. }
  13301. }
  13302. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  13303. for (const module of modules) {
  13304. for (const variable of module.scope.variables.values()) {
  13305. if (variable.included &&
  13306. // this will only happen for exports in some formats
  13307. !(variable.renderBaseName ||
  13308. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  13309. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  13310. }
  13311. }
  13312. if (includedNamespaces.has(module)) {
  13313. const namespace = module.namespace;
  13314. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  13315. }
  13316. }
  13317. }
  13318. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  13319. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  13320. const backSlashRegEx = /\\/g;
  13321. function escapeId(id) {
  13322. if (!id.match(needsEscapeRegEx))
  13323. return id;
  13324. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  13325. }
  13326. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  13327. let nameIndex = 0;
  13328. for (const variable of exports) {
  13329. let [exportName] = variable.name;
  13330. if (exportsByName.has(exportName)) {
  13331. do {
  13332. exportName = toBase64(++nameIndex);
  13333. // skip past leading number identifiers
  13334. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  13335. nameIndex += 9 * 64 ** (exportName.length - 1);
  13336. exportName = toBase64(nameIndex);
  13337. }
  13338. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  13339. }
  13340. exportsByName.set(exportName, variable);
  13341. exportNamesByVariable.set(variable, [exportName]);
  13342. }
  13343. }
  13344. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  13345. for (const variable of exports) {
  13346. let nameIndex = 0;
  13347. let exportName = variable.name;
  13348. while (exportsByName.has(exportName)) {
  13349. exportName = variable.name + '$' + ++nameIndex;
  13350. }
  13351. exportsByName.set(exportName, variable);
  13352. exportNamesByVariable.set(variable, [exportName]);
  13353. }
  13354. }
  13355. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  13356. const exportKeys = chunk.getExportNames();
  13357. if (exportMode === 'default') {
  13358. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13359. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13360. }
  13361. }
  13362. else if (exportMode === 'none' && exportKeys.length) {
  13363. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13364. }
  13365. if (exportMode === 'auto') {
  13366. if (exportKeys.length === 0) {
  13367. exportMode = 'none';
  13368. }
  13369. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13370. if (format === 'cjs' && unsetOptions.has('exports')) {
  13371. warn(errPreferNamedExports(facadeModuleId));
  13372. }
  13373. exportMode = 'default';
  13374. }
  13375. else {
  13376. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  13377. warn(errMixedExport(facadeModuleId, name));
  13378. }
  13379. exportMode = 'named';
  13380. }
  13381. }
  13382. return exportMode;
  13383. }
  13384. function guessIndentString(code) {
  13385. const lines = code.split('\n');
  13386. const tabbed = lines.filter(line => /^\t+/.test(line));
  13387. const spaced = lines.filter(line => /^ {2,}/.test(line));
  13388. if (tabbed.length === 0 && spaced.length === 0) {
  13389. return null;
  13390. }
  13391. // More lines tabbed than spaced? Assume tabs, and
  13392. // default to tabs in the case of a tie (or nothing
  13393. // to go on)
  13394. if (tabbed.length >= spaced.length) {
  13395. return '\t';
  13396. }
  13397. // Otherwise, we need to guess the multiple
  13398. const min = spaced.reduce((previous, current) => {
  13399. const numSpaces = /^ +/.exec(current)[0].length;
  13400. return Math.min(numSpaces, previous);
  13401. }, Infinity);
  13402. return new Array(min + 1).join(' ');
  13403. }
  13404. function getIndentString(modules, options) {
  13405. if (options.indent !== true)
  13406. return options.indent;
  13407. for (const module of modules) {
  13408. const indent = guessIndentString(module.originalCode);
  13409. if (indent !== null)
  13410. return indent;
  13411. }
  13412. return '\t';
  13413. }
  13414. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  13415. const staticDependencyBlocks = [];
  13416. const handledDependencies = new Set();
  13417. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  13418. const module = orderedModules[modulePos];
  13419. if (!handledDependencies.has(module)) {
  13420. const staticDependencies = [];
  13421. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  13422. staticDependencyBlocks.unshift(staticDependencies);
  13423. }
  13424. }
  13425. const dependencies = new Set();
  13426. for (const block of staticDependencyBlocks) {
  13427. for (const dependency of block) {
  13428. dependencies.add(dependency);
  13429. }
  13430. }
  13431. return dependencies;
  13432. }
  13433. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  13434. const dependencies = module.getDependenciesToBeIncluded();
  13435. for (const dependency of dependencies) {
  13436. if (dependency instanceof ExternalModule) {
  13437. staticDependencies.push(dependency);
  13438. continue;
  13439. }
  13440. const dependencyChunk = chunkByModule.get(dependency);
  13441. if (dependencyChunk !== chunk) {
  13442. staticDependencies.push(dependencyChunk);
  13443. continue;
  13444. }
  13445. if (!handledModules.has(dependency)) {
  13446. handledModules.add(dependency);
  13447. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  13448. }
  13449. }
  13450. }
  13451. function decodedSourcemap(map) {
  13452. if (!map)
  13453. return null;
  13454. if (typeof map === 'string') {
  13455. map = JSON.parse(map);
  13456. }
  13457. if (map.mappings === '') {
  13458. return {
  13459. mappings: [],
  13460. names: [],
  13461. sources: [],
  13462. version: 3
  13463. };
  13464. }
  13465. const mappings = typeof map.mappings === 'string' ? decode(map.mappings) : map.mappings;
  13466. return { ...map, mappings };
  13467. }
  13468. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  13469. const renderChunkReducer = (code, result, plugin) => {
  13470. if (result == null)
  13471. return code;
  13472. if (typeof result === 'string')
  13473. result = {
  13474. code: result,
  13475. map: undefined
  13476. };
  13477. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  13478. if (result.map !== null) {
  13479. const map = decodedSourcemap(result.map);
  13480. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  13481. }
  13482. return result.code;
  13483. };
  13484. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  13485. }
  13486. function renderNamePattern(pattern, patternName, replacements) {
  13487. if (isPathFragment(pattern))
  13488. 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.`));
  13489. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  13490. if (!replacements.hasOwnProperty(type)) {
  13491. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  13492. }
  13493. const replacement = replacements[type]();
  13494. if (isPathFragment(replacement))
  13495. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  13496. return replacement;
  13497. });
  13498. }
  13499. function makeUnique(name, existingNames) {
  13500. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  13501. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  13502. return name;
  13503. const ext = extname(name);
  13504. name = name.substring(0, name.length - ext.length);
  13505. let uniqueName, uniqueIndex = 1;
  13506. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  13507. ;
  13508. return uniqueName;
  13509. }
  13510. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  13511. function getGlobalName(module, globals, hasExports, warn) {
  13512. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  13513. if (globalName) {
  13514. return globalName;
  13515. }
  13516. if (hasExports) {
  13517. warn({
  13518. code: 'MISSING_GLOBAL_NAME',
  13519. guess: module.variableName,
  13520. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  13521. source: module.id
  13522. });
  13523. return module.variableName;
  13524. }
  13525. }
  13526. class Chunk {
  13527. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  13528. this.orderedModules = orderedModules;
  13529. this.inputOptions = inputOptions;
  13530. this.outputOptions = outputOptions;
  13531. this.unsetOptions = unsetOptions;
  13532. this.pluginDriver = pluginDriver;
  13533. this.modulesById = modulesById;
  13534. this.chunkByModule = chunkByModule;
  13535. this.facadeChunkByModule = facadeChunkByModule;
  13536. this.includedNamespaces = includedNamespaces;
  13537. this.manualChunkAlias = manualChunkAlias;
  13538. this.entryModules = [];
  13539. this.exportMode = 'named';
  13540. this.facadeModule = null;
  13541. this.id = null;
  13542. this.namespaceVariableName = '';
  13543. this.needsExportsShim = false;
  13544. this.variableName = '';
  13545. this.accessedGlobalsByScope = new Map();
  13546. this.dependencies = new Set();
  13547. this.dynamicDependencies = new Set();
  13548. this.dynamicEntryModules = [];
  13549. this.dynamicName = null;
  13550. this.exportNamesByVariable = new Map();
  13551. this.exports = new Set();
  13552. this.exportsByName = new Map();
  13553. this.fileName = null;
  13554. this.implicitEntryModules = [];
  13555. this.implicitlyLoadedBefore = new Set();
  13556. this.imports = new Set();
  13557. this.includedReexportsByModule = new Map();
  13558. this.indentString = undefined;
  13559. // This may only be updated in the constructor
  13560. this.isEmpty = true;
  13561. this.name = null;
  13562. this.renderedDependencies = null;
  13563. this.renderedExports = null;
  13564. this.renderedHash = undefined;
  13565. this.renderedModuleSources = new Map();
  13566. this.renderedModules = Object.create(null);
  13567. this.renderedSource = null;
  13568. this.sortedExportNames = null;
  13569. this.strictFacade = false;
  13570. this.usedModules = undefined;
  13571. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  13572. const chunkModules = new Set(orderedModules);
  13573. for (const module of orderedModules) {
  13574. if (module.namespace.included) {
  13575. includedNamespaces.add(module);
  13576. }
  13577. if (this.isEmpty && module.isIncluded()) {
  13578. this.isEmpty = false;
  13579. }
  13580. if (module.info.isEntry || outputOptions.preserveModules) {
  13581. this.entryModules.push(module);
  13582. }
  13583. for (const importer of module.includedDynamicImporters) {
  13584. if (!chunkModules.has(importer)) {
  13585. this.dynamicEntryModules.push(module);
  13586. // Modules with synthetic exports need an artificial namespace for dynamic imports
  13587. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  13588. includedNamespaces.add(module);
  13589. this.exports.add(module.namespace);
  13590. }
  13591. }
  13592. }
  13593. if (module.implicitlyLoadedAfter.size > 0) {
  13594. this.implicitEntryModules.push(module);
  13595. }
  13596. }
  13597. this.suggestedVariableName = makeLegal(this.generateVariableName());
  13598. }
  13599. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  13600. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  13601. chunk.assignFacadeName(facadeName, facadedModule);
  13602. if (!facadeChunkByModule.has(facadedModule)) {
  13603. facadeChunkByModule.set(facadedModule, chunk);
  13604. }
  13605. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  13606. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  13607. }
  13608. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  13609. facadedModule.info.moduleSideEffects &&
  13610. facadedModule.hasEffects()) {
  13611. chunk.dependencies.add(chunkByModule.get(facadedModule));
  13612. }
  13613. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  13614. chunk.facadeModule = facadedModule;
  13615. chunk.strictFacade = true;
  13616. return chunk;
  13617. }
  13618. canModuleBeFacade(module, exposedVariables) {
  13619. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  13620. for (const exposedVariable of this.exports) {
  13621. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  13622. if (moduleExportNamesByVariable.size === 0 &&
  13623. module.isUserDefinedEntryPoint &&
  13624. module.preserveSignature === 'strict' &&
  13625. this.unsetOptions.has('preserveEntrySignatures')) {
  13626. this.inputOptions.onwarn({
  13627. code: 'EMPTY_FACADE',
  13628. id: module.id,
  13629. 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.`,
  13630. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  13631. });
  13632. }
  13633. return false;
  13634. }
  13635. }
  13636. for (const exposedVariable of exposedVariables) {
  13637. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  13638. return false;
  13639. }
  13640. }
  13641. return true;
  13642. }
  13643. generateExports() {
  13644. this.sortedExportNames = null;
  13645. const remainingExports = new Set(this.exports);
  13646. if (this.facadeModule !== null &&
  13647. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  13648. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  13649. for (const [variable, exportNames] of exportNamesByVariable) {
  13650. this.exportNamesByVariable.set(variable, [...exportNames]);
  13651. for (const exportName of exportNames) {
  13652. this.exportsByName.set(exportName, variable);
  13653. }
  13654. remainingExports.delete(variable);
  13655. }
  13656. }
  13657. if (this.outputOptions.minifyInternalExports) {
  13658. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13659. }
  13660. else {
  13661. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  13662. }
  13663. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  13664. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  13665. }
  13666. generateFacades() {
  13667. var _a;
  13668. const facades = [];
  13669. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  13670. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  13671. for (const module of entryModules) {
  13672. if (module.preserveSignature) {
  13673. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  13674. exposedVariables.add(exportedVariable);
  13675. }
  13676. }
  13677. }
  13678. for (const module of entryModules) {
  13679. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  13680. // mapping must run after Set 'name' dedupe
  13681. name => ({
  13682. name
  13683. }));
  13684. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  13685. requiredFacades.push({});
  13686. }
  13687. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  13688. if (requiredFacades.length === 0) {
  13689. requiredFacades.push({});
  13690. }
  13691. if (!this.facadeModule) {
  13692. const needsStrictFacade = module.preserveSignature === 'strict' ||
  13693. (module.preserveSignature === 'exports-only' &&
  13694. module.getExportNamesByVariable().size !== 0);
  13695. if (!needsStrictFacade ||
  13696. this.outputOptions.preserveModules ||
  13697. this.canModuleBeFacade(module, exposedVariables)) {
  13698. this.facadeModule = module;
  13699. this.facadeChunkByModule.set(module, this);
  13700. if (module.preserveSignature) {
  13701. this.strictFacade = needsStrictFacade;
  13702. }
  13703. this.assignFacadeName(requiredFacades.shift(), module);
  13704. }
  13705. }
  13706. for (const facadeName of requiredFacades) {
  13707. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  13708. }
  13709. }
  13710. for (const module of this.dynamicEntryModules) {
  13711. if (module.info.syntheticNamedExports)
  13712. continue;
  13713. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  13714. this.facadeModule = module;
  13715. this.facadeChunkByModule.set(module, this);
  13716. this.strictFacade = true;
  13717. this.dynamicName = getChunkNameFromModule(module);
  13718. }
  13719. else if (this.facadeModule === module &&
  13720. !this.strictFacade &&
  13721. this.canModuleBeFacade(module, exposedVariables)) {
  13722. this.strictFacade = true;
  13723. }
  13724. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  13725. this.includedNamespaces.add(module);
  13726. this.exports.add(module.namespace);
  13727. }
  13728. }
  13729. if (!this.outputOptions.preserveModules) {
  13730. this.addNecessaryImportsForFacades();
  13731. }
  13732. return facades;
  13733. }
  13734. generateId(addons, options, existingNames, includeHash) {
  13735. if (this.fileName !== null) {
  13736. return this.fileName;
  13737. }
  13738. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  13739. ? [options.entryFileNames, 'output.entryFileNames']
  13740. : [options.chunkFileNames, 'output.chunkFileNames'];
  13741. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  13742. format: () => options.format,
  13743. hash: () => includeHash
  13744. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  13745. : '[hash]',
  13746. name: () => this.getChunkName()
  13747. }), existingNames);
  13748. }
  13749. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  13750. const [{ id }] = this.orderedModules;
  13751. const sanitizedId = this.outputOptions.sanitizeFileName(id.split(QUERY_HASH_REGEX, 1)[0]);
  13752. let path;
  13753. const patternOpt = unsetOptions.has('entryFileNames')
  13754. ? '[name][assetExtname].js'
  13755. : options.entryFileNames;
  13756. const pattern = typeof patternOpt === 'function' ? patternOpt(this.getChunkInfo()) : patternOpt;
  13757. if (isAbsolute(sanitizedId)) {
  13758. const currentDir = dirname(sanitizedId);
  13759. const extension = extname(sanitizedId);
  13760. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13761. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13762. ext: () => extension.substring(1),
  13763. extname: () => extension,
  13764. format: () => options.format,
  13765. name: () => this.getChunkName()
  13766. });
  13767. const currentPath = `${currentDir}/${fileName}`;
  13768. const { preserveModulesRoot } = options;
  13769. if (preserveModulesRoot && resolve(currentPath).startsWith(preserveModulesRoot)) {
  13770. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  13771. }
  13772. else {
  13773. path = relative(preserveModulesRelativeDir, currentPath);
  13774. }
  13775. }
  13776. else {
  13777. const extension = extname(sanitizedId);
  13778. const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
  13779. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  13780. ext: () => extension.substring(1),
  13781. extname: () => extension,
  13782. format: () => options.format,
  13783. name: () => getAliasName(sanitizedId)
  13784. });
  13785. path = `_virtual/${fileName}`;
  13786. }
  13787. return makeUnique(normalize(path), existingNames);
  13788. }
  13789. getChunkInfo() {
  13790. const facadeModule = this.facadeModule;
  13791. const getChunkName = this.getChunkName.bind(this);
  13792. return {
  13793. exports: this.getExportNames(),
  13794. facadeModuleId: facadeModule && facadeModule.id,
  13795. isDynamicEntry: this.dynamicEntryModules.length > 0,
  13796. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  13797. isImplicitEntry: this.implicitEntryModules.length > 0,
  13798. modules: this.renderedModules,
  13799. get name() {
  13800. return getChunkName();
  13801. },
  13802. type: 'chunk'
  13803. };
  13804. }
  13805. getChunkInfoWithFileNames() {
  13806. return Object.assign(this.getChunkInfo(), {
  13807. code: undefined,
  13808. dynamicImports: Array.from(this.dynamicDependencies, getId),
  13809. fileName: this.id,
  13810. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  13811. importedBindings: this.getImportedBindingsPerDependency(),
  13812. imports: Array.from(this.dependencies, getId),
  13813. map: undefined,
  13814. referencedFiles: this.getReferencedFiles()
  13815. });
  13816. }
  13817. getChunkName() {
  13818. var _a;
  13819. return ((_a = this.name) !== null && _a !== void 0 ? _a : (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  13820. }
  13821. getExportNames() {
  13822. var _a;
  13823. return ((_a = this.sortedExportNames) !== null && _a !== void 0 ? _a : (this.sortedExportNames = Array.from(this.exportsByName.keys()).sort()));
  13824. }
  13825. getRenderedHash() {
  13826. if (this.renderedHash)
  13827. return this.renderedHash;
  13828. const hash = createHash();
  13829. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  13830. if (pluginHash) {
  13831. augmentation += pluginHash;
  13832. }
  13833. return augmentation;
  13834. });
  13835. hash.update(hashAugmentation);
  13836. hash.update(this.renderedSource.toString());
  13837. hash.update(this.getExportNames()
  13838. .map(exportName => {
  13839. const variable = this.exportsByName.get(exportName);
  13840. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  13841. })
  13842. .join(','));
  13843. return (this.renderedHash = hash.digest('hex'));
  13844. }
  13845. getVariableExportName(variable) {
  13846. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  13847. return '*';
  13848. }
  13849. return this.exportNamesByVariable.get(variable)[0];
  13850. }
  13851. link() {
  13852. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  13853. for (const module of this.orderedModules) {
  13854. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  13855. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  13856. this.setUpChunkImportsAndExportsForModule(module);
  13857. }
  13858. }
  13859. // prerender allows chunk hashes and names to be generated before finalizing
  13860. preRender(options, inputBase, snippets) {
  13861. const { _, getPropertyAccess, n } = snippets;
  13862. const magicString = new Bundle$1({ separator: `${n}${n}` });
  13863. this.usedModules = [];
  13864. this.indentString = getIndentString(this.orderedModules, options);
  13865. const renderOptions = {
  13866. dynamicImportFunction: options.dynamicImportFunction,
  13867. exportNamesByVariable: this.exportNamesByVariable,
  13868. format: options.format,
  13869. freeze: options.freeze,
  13870. indent: this.indentString,
  13871. namespaceToStringTag: options.namespaceToStringTag,
  13872. outputPluginDriver: this.pluginDriver,
  13873. snippets
  13874. };
  13875. // for static and dynamic entry points, inline the execution list to avoid loading latency
  13876. if (options.hoistTransitiveImports &&
  13877. !this.outputOptions.preserveModules &&
  13878. this.facadeModule !== null) {
  13879. for (const dep of this.dependencies) {
  13880. if (dep instanceof Chunk)
  13881. this.inlineChunkDependencies(dep);
  13882. }
  13883. }
  13884. this.prepareModulesForRendering(snippets);
  13885. this.setIdentifierRenderResolutions(options);
  13886. let hoistedSource = '';
  13887. const renderedModules = this.renderedModules;
  13888. for (const module of this.orderedModules) {
  13889. let renderedLength = 0;
  13890. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  13891. const source = module.render(renderOptions).trim();
  13892. renderedLength = source.length();
  13893. if (renderedLength) {
  13894. if (options.compact && source.lastLine().includes('//'))
  13895. source.append('\n');
  13896. this.renderedModuleSources.set(module, source);
  13897. magicString.addSource(source);
  13898. this.usedModules.push(module);
  13899. }
  13900. const namespace = module.namespace;
  13901. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  13902. const rendered = namespace.renderBlock(renderOptions);
  13903. if (namespace.renderFirst())
  13904. hoistedSource += n + rendered;
  13905. else
  13906. magicString.addSource(new MagicString(rendered));
  13907. }
  13908. }
  13909. const { renderedExports, removedExports } = module.getRenderedExports();
  13910. const { renderedModuleSources } = this;
  13911. renderedModules[module.id] = {
  13912. get code() {
  13913. var _a, _b;
  13914. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  13915. },
  13916. originalLength: module.originalCode.length,
  13917. removedExports,
  13918. renderedExports,
  13919. renderedLength
  13920. };
  13921. }
  13922. if (hoistedSource)
  13923. magicString.prepend(hoistedSource + n + n);
  13924. if (this.needsExportsShim) {
  13925. magicString.prepend(`${n}${snippets.cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  13926. }
  13927. if (options.compact) {
  13928. this.renderedSource = magicString;
  13929. }
  13930. else {
  13931. this.renderedSource = magicString.trim();
  13932. }
  13933. this.renderedHash = undefined;
  13934. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  13935. const chunkName = this.getChunkName();
  13936. this.inputOptions.onwarn({
  13937. chunkName,
  13938. code: 'EMPTY_BUNDLE',
  13939. message: `Generated an empty chunk: "${chunkName}"`
  13940. });
  13941. }
  13942. this.setExternalRenderPaths(options, inputBase);
  13943. this.renderedDependencies = this.getChunkDependencyDeclarations(options, getPropertyAccess);
  13944. this.renderedExports =
  13945. this.exportMode === 'none'
  13946. ? []
  13947. : this.getChunkExportDeclarations(options.format, getPropertyAccess);
  13948. }
  13949. async render(options, addons, outputChunk, snippets) {
  13950. timeStart('render format', 2);
  13951. const format = options.format;
  13952. const finalise = finalisers[format];
  13953. if (options.dynamicImportFunction && format !== 'es') {
  13954. this.inputOptions.onwarn(errInvalidOption('output.dynamicImportFunction', 'outputdynamicImportFunction', 'this option is ignored for formats other than "es"'));
  13955. }
  13956. // populate ids in the rendered declarations only here
  13957. // as chunk ids known only after prerender
  13958. for (const dependency of this.dependencies) {
  13959. const renderedDependency = this.renderedDependencies.get(dependency);
  13960. if (dependency instanceof ExternalModule) {
  13961. const originalId = dependency.renderPath;
  13962. renderedDependency.id = escapeId(dependency.renormalizeRenderPath
  13963. ? getImportPath(this.id, originalId, false, false)
  13964. : originalId);
  13965. }
  13966. else {
  13967. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  13968. renderedDependency.id = escapeId(getImportPath(this.id, dependency.id, false, true));
  13969. }
  13970. }
  13971. this.finaliseDynamicImports(options, snippets);
  13972. this.finaliseImportMetas(format, snippets);
  13973. const hasExports = this.renderedExports.length !== 0 ||
  13974. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  13975. let topLevelAwaitModule = null;
  13976. const accessedGlobals = new Set();
  13977. for (const module of this.orderedModules) {
  13978. if (module.usesTopLevelAwait) {
  13979. topLevelAwaitModule = module.id;
  13980. }
  13981. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  13982. if (accessedGlobalVariables) {
  13983. for (const name of accessedGlobalVariables) {
  13984. accessedGlobals.add(name);
  13985. }
  13986. }
  13987. }
  13988. if (topLevelAwaitModule !== null && format !== 'es' && format !== 'system') {
  13989. return error({
  13990. code: 'INVALID_TLA_FORMAT',
  13991. id: topLevelAwaitModule,
  13992. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  13993. });
  13994. }
  13995. /* istanbul ignore next */
  13996. if (!this.id) {
  13997. throw new Error('Internal Error: expecting chunk id');
  13998. }
  13999. const magicString = finalise(this.renderedSource, {
  14000. accessedGlobals,
  14001. dependencies: [...this.renderedDependencies.values()],
  14002. exports: this.renderedExports,
  14003. hasExports,
  14004. id: this.id,
  14005. indent: this.indentString,
  14006. intro: addons.intro,
  14007. isEntryFacade: this.outputOptions.preserveModules ||
  14008. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  14009. isModuleFacade: this.facadeModule !== null,
  14010. namedExportsMode: this.exportMode !== 'default',
  14011. outro: addons.outro,
  14012. snippets,
  14013. usesTopLevelAwait: topLevelAwaitModule !== null,
  14014. warn: this.inputOptions.onwarn
  14015. }, options);
  14016. if (addons.banner)
  14017. magicString.prepend(addons.banner);
  14018. if (addons.footer)
  14019. magicString.append(addons.footer);
  14020. const prevCode = magicString.toString();
  14021. timeEnd('render format', 2);
  14022. let map = null;
  14023. const chunkSourcemapChain = [];
  14024. let code = await renderChunk({
  14025. code: prevCode,
  14026. options,
  14027. outputPluginDriver: this.pluginDriver,
  14028. renderChunk: outputChunk,
  14029. sourcemapChain: chunkSourcemapChain
  14030. });
  14031. if (options.sourcemap) {
  14032. timeStart('sourcemap', 2);
  14033. let file;
  14034. if (options.file)
  14035. file = resolve(options.sourcemapFile || options.file);
  14036. else if (options.dir)
  14037. file = resolve(options.dir, this.id);
  14038. else
  14039. file = resolve(this.id);
  14040. const decodedMap = magicString.generateDecodedMap({});
  14041. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  14042. map.sources = map.sources
  14043. .map(sourcePath => {
  14044. const { sourcemapPathTransform } = options;
  14045. if (sourcemapPathTransform) {
  14046. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  14047. if (typeof newSourcePath !== 'string') {
  14048. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  14049. }
  14050. return newSourcePath;
  14051. }
  14052. return sourcePath;
  14053. })
  14054. .map(normalize);
  14055. timeEnd('sourcemap', 2);
  14056. }
  14057. if (!options.compact && code[code.length - 1] !== '\n')
  14058. code += '\n';
  14059. return { code, map };
  14060. }
  14061. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  14062. for (const module of moduleDependencies) {
  14063. if (module instanceof Module) {
  14064. const chunk = this.chunkByModule.get(module);
  14065. if (chunk && chunk !== this) {
  14066. chunkDependencies.add(chunk);
  14067. }
  14068. }
  14069. else {
  14070. chunkDependencies.add(module);
  14071. }
  14072. }
  14073. }
  14074. addNecessaryImportsForFacades() {
  14075. for (const [module, variables] of this.includedReexportsByModule) {
  14076. if (this.includedNamespaces.has(module)) {
  14077. for (const variable of variables) {
  14078. this.imports.add(variable);
  14079. }
  14080. }
  14081. }
  14082. }
  14083. assignFacadeName({ fileName, name }, facadedModule) {
  14084. if (fileName) {
  14085. this.fileName = fileName;
  14086. }
  14087. else {
  14088. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  14089. }
  14090. }
  14091. checkCircularDependencyImport(variable, importingModule) {
  14092. const variableModule = variable.module;
  14093. if (variableModule instanceof Module) {
  14094. const exportChunk = this.chunkByModule.get(variableModule);
  14095. let alternativeReexportModule;
  14096. do {
  14097. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  14098. if (alternativeReexportModule) {
  14099. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  14100. if (exportingChunk && exportingChunk !== exportChunk) {
  14101. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  14102. }
  14103. importingModule = alternativeReexportModule;
  14104. }
  14105. } while (alternativeReexportModule);
  14106. }
  14107. }
  14108. computeContentHashWithDependencies(addons, options, existingNames) {
  14109. const hash = createHash();
  14110. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].join(':'));
  14111. hash.update(options.format);
  14112. const dependenciesForHashing = new Set([this]);
  14113. for (const current of dependenciesForHashing) {
  14114. if (current instanceof ExternalModule) {
  14115. hash.update(`:${current.renderPath}`);
  14116. }
  14117. else {
  14118. hash.update(current.getRenderedHash());
  14119. hash.update(current.generateId(addons, options, existingNames, false));
  14120. }
  14121. if (current instanceof ExternalModule)
  14122. continue;
  14123. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  14124. dependenciesForHashing.add(dependency);
  14125. }
  14126. }
  14127. return hash.digest('hex').substr(0, 8);
  14128. }
  14129. ensureReexportsAreAvailableForModule(module) {
  14130. const includedReexports = [];
  14131. const map = module.getExportNamesByVariable();
  14132. for (const exportedVariable of map.keys()) {
  14133. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  14134. const importedVariable = isSynthetic
  14135. ? exportedVariable.getBaseVariable()
  14136. : exportedVariable;
  14137. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  14138. this.checkCircularDependencyImport(importedVariable, module);
  14139. const exportingModule = importedVariable.module;
  14140. if (exportingModule instanceof Module) {
  14141. const chunk = this.chunkByModule.get(exportingModule);
  14142. if (chunk && chunk !== this) {
  14143. chunk.exports.add(importedVariable);
  14144. includedReexports.push(importedVariable);
  14145. if (isSynthetic) {
  14146. this.imports.add(importedVariable);
  14147. }
  14148. }
  14149. }
  14150. }
  14151. }
  14152. if (includedReexports.length) {
  14153. this.includedReexportsByModule.set(module, includedReexports);
  14154. }
  14155. }
  14156. finaliseDynamicImports(options, snippets) {
  14157. const stripKnownJsExtensions = options.format === 'amd';
  14158. for (const [module, code] of this.renderedModuleSources) {
  14159. for (const { node, resolution } of module.dynamicImports) {
  14160. const chunk = this.chunkByModule.get(resolution);
  14161. const facadeChunk = this.facadeChunkByModule.get(resolution);
  14162. if (!resolution || !node.included || chunk === this) {
  14163. continue;
  14164. }
  14165. const renderedResolution = resolution instanceof Module
  14166. ? `'${escapeId(getImportPath(this.id, (facadeChunk || chunk).id, stripKnownJsExtensions, true))}'`
  14167. : resolution instanceof ExternalModule
  14168. ? `'${escapeId(resolution.renormalizeRenderPath
  14169. ? getImportPath(this.id, resolution.renderPath, stripKnownJsExtensions, false)
  14170. : resolution.renderPath)}'`
  14171. : resolution;
  14172. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  14173. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  14174. chunk.exportNamesByVariable.get(resolution.namespace)[0], snippets);
  14175. }
  14176. }
  14177. }
  14178. finaliseImportMetas(format, snippets) {
  14179. for (const [module, code] of this.renderedModuleSources) {
  14180. for (const importMeta of module.importMetas) {
  14181. importMeta.renderFinalMechanism(code, this.id, format, snippets, this.pluginDriver);
  14182. }
  14183. }
  14184. }
  14185. generateVariableName() {
  14186. if (this.manualChunkAlias) {
  14187. return this.manualChunkAlias;
  14188. }
  14189. const moduleForNaming = this.entryModules[0] ||
  14190. this.implicitEntryModules[0] ||
  14191. this.dynamicEntryModules[0] ||
  14192. this.orderedModules[this.orderedModules.length - 1];
  14193. if (moduleForNaming) {
  14194. return getChunkNameFromModule(moduleForNaming);
  14195. }
  14196. return 'chunk';
  14197. }
  14198. getChunkDependencyDeclarations(options, getPropertyAccess) {
  14199. const importSpecifiers = this.getImportSpecifiers(getPropertyAccess);
  14200. const reexportSpecifiers = this.getReexportSpecifiers();
  14201. const dependencyDeclaration = new Map();
  14202. for (const dep of this.dependencies) {
  14203. const imports = importSpecifiers.get(dep) || null;
  14204. const reexports = reexportSpecifiers.get(dep) || null;
  14205. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  14206. dependencyDeclaration.set(dep, {
  14207. defaultVariableName: dep.defaultVariableName,
  14208. globalName: (dep instanceof ExternalModule &&
  14209. (options.format === 'umd' || options.format === 'iife') &&
  14210. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  14211. id: undefined,
  14212. imports,
  14213. isChunk: dep instanceof Chunk,
  14214. name: dep.variableName,
  14215. namedExportsMode,
  14216. namespaceVariableName: dep.namespaceVariableName,
  14217. reexports
  14218. });
  14219. }
  14220. return dependencyDeclaration;
  14221. }
  14222. getChunkExportDeclarations(format, getPropertyAccess) {
  14223. const exports = [];
  14224. for (const exportName of this.getExportNames()) {
  14225. if (exportName[0] === '*')
  14226. continue;
  14227. const variable = this.exportsByName.get(exportName);
  14228. if (!(variable instanceof SyntheticNamedExportVariable)) {
  14229. const module = variable.module;
  14230. if (module && this.chunkByModule.get(module) !== this)
  14231. continue;
  14232. }
  14233. let expression = null;
  14234. let hoisted = false;
  14235. let local = variable.getName(getPropertyAccess);
  14236. if (variable instanceof LocalVariable) {
  14237. for (const declaration of variable.declarations) {
  14238. if (declaration.parent instanceof FunctionDeclaration ||
  14239. (declaration instanceof ExportDefaultDeclaration &&
  14240. declaration.declaration instanceof FunctionDeclaration)) {
  14241. hoisted = true;
  14242. break;
  14243. }
  14244. }
  14245. }
  14246. else if (variable instanceof SyntheticNamedExportVariable) {
  14247. expression = local;
  14248. if (format === 'es') {
  14249. local = variable.renderName;
  14250. }
  14251. }
  14252. exports.push({
  14253. exported: exportName,
  14254. expression,
  14255. hoisted,
  14256. local
  14257. });
  14258. }
  14259. return exports;
  14260. }
  14261. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  14262. const dependencies = new Set();
  14263. const deconflictedDefault = new Set();
  14264. const deconflictedNamespace = new Set();
  14265. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  14266. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  14267. const module = variable.module;
  14268. if (module instanceof ExternalModule) {
  14269. dependencies.add(module);
  14270. if (addNonNamespacesAndInteropHelpers) {
  14271. if (variable.name === 'default') {
  14272. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  14273. deconflictedDefault.add(module);
  14274. }
  14275. }
  14276. else if (variable.name === '*') {
  14277. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  14278. deconflictedNamespace.add(module);
  14279. }
  14280. }
  14281. }
  14282. }
  14283. else {
  14284. const chunk = this.chunkByModule.get(module);
  14285. if (chunk !== this) {
  14286. dependencies.add(chunk);
  14287. if (addNonNamespacesAndInteropHelpers &&
  14288. chunk.exportMode === 'default' &&
  14289. variable.isNamespace) {
  14290. deconflictedNamespace.add(chunk);
  14291. }
  14292. }
  14293. }
  14294. }
  14295. }
  14296. if (addDependenciesWithoutBindings) {
  14297. for (const dependency of this.dependencies) {
  14298. dependencies.add(dependency);
  14299. }
  14300. }
  14301. return { deconflictedDefault, deconflictedNamespace, dependencies };
  14302. }
  14303. getFallbackChunkName() {
  14304. if (this.manualChunkAlias) {
  14305. return this.manualChunkAlias;
  14306. }
  14307. if (this.dynamicName) {
  14308. return this.dynamicName;
  14309. }
  14310. if (this.fileName) {
  14311. return getAliasName(this.fileName);
  14312. }
  14313. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  14314. }
  14315. getImportSpecifiers(getPropertyAccess) {
  14316. const { interop } = this.outputOptions;
  14317. const importsByDependency = new Map();
  14318. for (const variable of this.imports) {
  14319. const module = variable.module;
  14320. let dependency;
  14321. let imported;
  14322. if (module instanceof ExternalModule) {
  14323. dependency = module;
  14324. imported = variable.name;
  14325. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14326. return error(errUnexpectedNamedImport(module.id, imported, false));
  14327. }
  14328. }
  14329. else {
  14330. dependency = this.chunkByModule.get(module);
  14331. imported = dependency.getVariableExportName(variable);
  14332. }
  14333. getOrCreate(importsByDependency, dependency, () => []).push({
  14334. imported,
  14335. local: variable.getName(getPropertyAccess)
  14336. });
  14337. }
  14338. return importsByDependency;
  14339. }
  14340. getImportedBindingsPerDependency() {
  14341. const importSpecifiers = {};
  14342. for (const [dependency, declaration] of this.renderedDependencies) {
  14343. const specifiers = new Set();
  14344. if (declaration.imports) {
  14345. for (const { imported } of declaration.imports) {
  14346. specifiers.add(imported);
  14347. }
  14348. }
  14349. if (declaration.reexports) {
  14350. for (const { imported } of declaration.reexports) {
  14351. specifiers.add(imported);
  14352. }
  14353. }
  14354. importSpecifiers[dependency.id] = [...specifiers];
  14355. }
  14356. return importSpecifiers;
  14357. }
  14358. getReexportSpecifiers() {
  14359. const { externalLiveBindings, interop } = this.outputOptions;
  14360. const reexportSpecifiers = new Map();
  14361. for (let exportName of this.getExportNames()) {
  14362. let dependency;
  14363. let imported;
  14364. let needsLiveBinding = false;
  14365. if (exportName[0] === '*') {
  14366. const id = exportName.substring(1);
  14367. if (interop(id) === 'defaultOnly') {
  14368. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  14369. }
  14370. needsLiveBinding = externalLiveBindings;
  14371. dependency = this.modulesById.get(id);
  14372. imported = exportName = '*';
  14373. }
  14374. else {
  14375. const variable = this.exportsByName.get(exportName);
  14376. if (variable instanceof SyntheticNamedExportVariable)
  14377. continue;
  14378. const module = variable.module;
  14379. if (module instanceof Module) {
  14380. dependency = this.chunkByModule.get(module);
  14381. if (dependency === this)
  14382. continue;
  14383. imported = dependency.getVariableExportName(variable);
  14384. needsLiveBinding = variable.isReassigned;
  14385. }
  14386. else {
  14387. dependency = module;
  14388. imported = variable.name;
  14389. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  14390. return error(errUnexpectedNamedImport(module.id, imported, true));
  14391. }
  14392. needsLiveBinding =
  14393. externalLiveBindings &&
  14394. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  14395. }
  14396. }
  14397. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  14398. imported,
  14399. needsLiveBinding,
  14400. reexported: exportName
  14401. });
  14402. }
  14403. return reexportSpecifiers;
  14404. }
  14405. getReferencedFiles() {
  14406. const referencedFiles = [];
  14407. for (const module of this.orderedModules) {
  14408. for (const meta of module.importMetas) {
  14409. const fileName = meta.getReferencedFileName(this.pluginDriver);
  14410. if (fileName) {
  14411. referencedFiles.push(fileName);
  14412. }
  14413. }
  14414. }
  14415. return referencedFiles;
  14416. }
  14417. inlineChunkDependencies(chunk) {
  14418. for (const dep of chunk.dependencies) {
  14419. if (this.dependencies.has(dep))
  14420. continue;
  14421. this.dependencies.add(dep);
  14422. if (dep instanceof Chunk) {
  14423. this.inlineChunkDependencies(dep);
  14424. }
  14425. }
  14426. }
  14427. prepareModulesForRendering(snippets) {
  14428. var _a;
  14429. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  14430. for (const module of this.orderedModules) {
  14431. for (const { node, resolution } of module.dynamicImports) {
  14432. if (node.included) {
  14433. if (resolution instanceof Module) {
  14434. const chunk = this.chunkByModule.get(resolution);
  14435. if (chunk === this) {
  14436. node.setInternalResolution(resolution.namespace);
  14437. }
  14438. else {
  14439. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14440. }
  14441. }
  14442. else {
  14443. node.setExternalResolution('external', resolution, this.outputOptions, snippets, this.pluginDriver, accessedGlobalsByScope);
  14444. }
  14445. }
  14446. }
  14447. for (const importMeta of module.importMetas) {
  14448. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  14449. }
  14450. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  14451. module.namespace.prepare(accessedGlobalsByScope);
  14452. }
  14453. }
  14454. }
  14455. setExternalRenderPaths(options, inputBase) {
  14456. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  14457. if (dependency instanceof ExternalModule) {
  14458. dependency.setRenderPath(options, inputBase);
  14459. }
  14460. }
  14461. }
  14462. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  14463. const syntheticExports = new Set();
  14464. for (const exportName of this.getExportNames()) {
  14465. const exportVariable = this.exportsByName.get(exportName);
  14466. if (format !== 'es' &&
  14467. format !== 'system' &&
  14468. exportVariable.isReassigned &&
  14469. !exportVariable.isId) {
  14470. exportVariable.setRenderNames('exports', exportName);
  14471. }
  14472. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  14473. syntheticExports.add(exportVariable);
  14474. }
  14475. else {
  14476. exportVariable.setRenderNames(null, null);
  14477. }
  14478. }
  14479. for (const module of this.orderedModules) {
  14480. if (module.needsExportShim) {
  14481. this.needsExportsShim = true;
  14482. break;
  14483. }
  14484. }
  14485. const usedNames = new Set(['Object', 'Promise']);
  14486. if (this.needsExportsShim) {
  14487. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  14488. }
  14489. if (namespaceToStringTag) {
  14490. usedNames.add('Symbol');
  14491. }
  14492. switch (format) {
  14493. case 'system':
  14494. usedNames.add('module').add('exports');
  14495. break;
  14496. case 'es':
  14497. break;
  14498. case 'cjs':
  14499. usedNames.add('module').add('require').add('__filename').add('__dirname');
  14500. // fallthrough
  14501. default:
  14502. usedNames.add('exports');
  14503. for (const helper of HELPER_NAMES) {
  14504. usedNames.add(helper);
  14505. }
  14506. }
  14507. 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);
  14508. }
  14509. setUpChunkImportsAndExportsForModule(module) {
  14510. const moduleImports = new Set(module.includedImports);
  14511. // when we are not preserving modules, we need to make all namespace variables available for
  14512. // rendering the namespace object
  14513. if (!this.outputOptions.preserveModules) {
  14514. if (this.includedNamespaces.has(module)) {
  14515. const memberVariables = module.namespace.getMemberVariables();
  14516. for (const variable of Object.values(memberVariables)) {
  14517. moduleImports.add(variable);
  14518. }
  14519. }
  14520. }
  14521. for (let variable of moduleImports) {
  14522. if (variable instanceof ExportDefaultVariable) {
  14523. variable = variable.getOriginalVariable();
  14524. }
  14525. if (variable instanceof SyntheticNamedExportVariable) {
  14526. variable = variable.getBaseVariable();
  14527. }
  14528. const chunk = this.chunkByModule.get(variable.module);
  14529. if (chunk !== this) {
  14530. this.imports.add(variable);
  14531. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  14532. variable.module instanceof Module) {
  14533. chunk.exports.add(variable);
  14534. this.checkCircularDependencyImport(variable, module);
  14535. }
  14536. }
  14537. }
  14538. if (this.includedNamespaces.has(module) ||
  14539. (module.info.isEntry && module.preserveSignature !== false) ||
  14540. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  14541. this.ensureReexportsAreAvailableForModule(module);
  14542. }
  14543. for (const { node, resolution } of module.dynamicImports) {
  14544. if (node.included &&
  14545. resolution instanceof Module &&
  14546. this.chunkByModule.get(resolution) === this &&
  14547. !this.includedNamespaces.has(resolution)) {
  14548. this.includedNamespaces.add(resolution);
  14549. this.ensureReexportsAreAvailableForModule(resolution);
  14550. }
  14551. }
  14552. }
  14553. }
  14554. function getChunkNameFromModule(module) {
  14555. var _a, _b, _c, _d;
  14556. 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));
  14557. }
  14558. const QUERY_HASH_REGEX = /[?#]/;
  14559. function generateAssetFileName(name, source, outputOptions, bundle) {
  14560. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  14561. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  14562. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  14563. : outputOptions.assetFileNames, 'output.assetFileNames', {
  14564. ext: () => extname(emittedName).substring(1),
  14565. extname: () => extname(emittedName),
  14566. hash() {
  14567. return createHash()
  14568. .update(emittedName)
  14569. .update(':')
  14570. .update(source)
  14571. .digest('hex')
  14572. .substring(0, 8);
  14573. },
  14574. name: () => emittedName.substring(0, emittedName.length - extname(emittedName).length)
  14575. }), bundle);
  14576. }
  14577. function reserveFileNameInBundle(fileName, bundle, warn) {
  14578. if (fileName in bundle) {
  14579. warn(errFileNameConflict(fileName));
  14580. }
  14581. bundle[fileName] = FILE_PLACEHOLDER;
  14582. }
  14583. const FILE_PLACEHOLDER = {
  14584. type: 'placeholder'
  14585. };
  14586. function hasValidType(emittedFile) {
  14587. return Boolean(emittedFile &&
  14588. (emittedFile.type === 'asset' ||
  14589. emittedFile.type === 'chunk'));
  14590. }
  14591. function hasValidName(emittedFile) {
  14592. const validatedName = emittedFile.fileName || emittedFile.name;
  14593. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  14594. }
  14595. function getValidSource(source, emittedFile, fileReferenceId) {
  14596. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  14597. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  14598. 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.`));
  14599. }
  14600. return source;
  14601. }
  14602. function getAssetFileName(file, referenceId) {
  14603. if (typeof file.fileName !== 'string') {
  14604. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  14605. }
  14606. return file.fileName;
  14607. }
  14608. function getChunkFileName(file, facadeChunkByModule) {
  14609. var _a;
  14610. 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));
  14611. if (!fileName)
  14612. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  14613. return fileName;
  14614. }
  14615. class FileEmitter {
  14616. constructor(graph, options, baseFileEmitter) {
  14617. this.graph = graph;
  14618. this.options = options;
  14619. this.bundle = null;
  14620. this.facadeChunkByModule = null;
  14621. this.outputOptions = null;
  14622. this.assertAssetsFinalized = () => {
  14623. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  14624. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  14625. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  14626. }
  14627. };
  14628. this.emitFile = (emittedFile) => {
  14629. if (!hasValidType(emittedFile)) {
  14630. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  14631. }
  14632. if (!hasValidName(emittedFile)) {
  14633. 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}".`));
  14634. }
  14635. if (emittedFile.type === 'chunk') {
  14636. return this.emitChunk(emittedFile);
  14637. }
  14638. return this.emitAsset(emittedFile);
  14639. };
  14640. this.getFileName = (fileReferenceId) => {
  14641. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  14642. if (!emittedFile)
  14643. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  14644. if (emittedFile.type === 'chunk') {
  14645. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  14646. }
  14647. return getAssetFileName(emittedFile, fileReferenceId);
  14648. };
  14649. this.setAssetSource = (referenceId, requestedSource) => {
  14650. const consumedFile = this.filesByReferenceId.get(referenceId);
  14651. if (!consumedFile)
  14652. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  14653. if (consumedFile.type !== 'asset') {
  14654. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  14655. }
  14656. if (consumedFile.source !== undefined) {
  14657. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  14658. }
  14659. const source = getValidSource(requestedSource, consumedFile, referenceId);
  14660. if (this.bundle) {
  14661. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  14662. }
  14663. else {
  14664. consumedFile.source = source;
  14665. }
  14666. };
  14667. this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
  14668. this.outputOptions = outputOptions;
  14669. this.bundle = outputBundle;
  14670. this.facadeChunkByModule = facadeChunkByModule;
  14671. for (const emittedFile of this.filesByReferenceId.values()) {
  14672. if (emittedFile.fileName) {
  14673. reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
  14674. }
  14675. }
  14676. for (const [referenceId, consumedFile] of this.filesByReferenceId) {
  14677. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  14678. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
  14679. }
  14680. }
  14681. };
  14682. this.filesByReferenceId = baseFileEmitter
  14683. ? new Map(baseFileEmitter.filesByReferenceId)
  14684. : new Map();
  14685. }
  14686. assignReferenceId(file, idBase) {
  14687. let referenceId;
  14688. do {
  14689. referenceId = createHash()
  14690. .update(referenceId || idBase)
  14691. .digest('hex')
  14692. .substring(0, 8);
  14693. } while (this.filesByReferenceId.has(referenceId));
  14694. this.filesByReferenceId.set(referenceId, file);
  14695. return referenceId;
  14696. }
  14697. emitAsset(emittedAsset) {
  14698. const source = typeof emittedAsset.source !== 'undefined'
  14699. ? getValidSource(emittedAsset.source, emittedAsset, null)
  14700. : undefined;
  14701. const consumedAsset = {
  14702. fileName: emittedAsset.fileName,
  14703. name: emittedAsset.name,
  14704. source,
  14705. type: 'asset'
  14706. };
  14707. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  14708. if (this.bundle) {
  14709. if (emittedAsset.fileName) {
  14710. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  14711. }
  14712. if (source !== undefined) {
  14713. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  14714. }
  14715. }
  14716. return referenceId;
  14717. }
  14718. emitChunk(emittedChunk) {
  14719. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  14720. return error(errInvalidRollupPhaseForChunkEmission());
  14721. }
  14722. if (typeof emittedChunk.id !== 'string') {
  14723. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  14724. }
  14725. const consumedChunk = {
  14726. fileName: emittedChunk.fileName,
  14727. module: null,
  14728. name: emittedChunk.name || emittedChunk.id,
  14729. type: 'chunk'
  14730. };
  14731. this.graph.moduleLoader
  14732. .emitChunk(emittedChunk)
  14733. .then(module => (consumedChunk.module = module))
  14734. .catch(() => {
  14735. // Avoid unhandled Promise rejection as the error will be thrown later
  14736. // once module loading has finished
  14737. });
  14738. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  14739. }
  14740. finalizeAsset(consumedFile, source, referenceId, bundle) {
  14741. const fileName = consumedFile.fileName ||
  14742. findExistingAssetFileNameWithSource(bundle, source) ||
  14743. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  14744. // We must not modify the original assets to avoid interaction between outputs
  14745. const assetWithFileName = { ...consumedFile, fileName, source };
  14746. this.filesByReferenceId.set(referenceId, assetWithFileName);
  14747. const { options } = this;
  14748. bundle[fileName] = {
  14749. fileName,
  14750. get isAsset() {
  14751. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  14752. return true;
  14753. },
  14754. name: consumedFile.name,
  14755. source,
  14756. type: 'asset'
  14757. };
  14758. }
  14759. }
  14760. function findExistingAssetFileNameWithSource(bundle, source) {
  14761. for (const [fileName, outputFile] of Object.entries(bundle)) {
  14762. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  14763. return fileName;
  14764. }
  14765. return null;
  14766. }
  14767. function areSourcesEqual(sourceA, sourceB) {
  14768. if (typeof sourceA === 'string') {
  14769. return sourceA === sourceB;
  14770. }
  14771. if (typeof sourceB === 'string') {
  14772. return false;
  14773. }
  14774. if ('equals' in sourceA) {
  14775. return sourceA.equals(sourceB);
  14776. }
  14777. if (sourceA.length !== sourceB.length) {
  14778. return false;
  14779. }
  14780. for (let index = 0; index < sourceA.length; index++) {
  14781. if (sourceA[index] !== sourceB[index]) {
  14782. return false;
  14783. }
  14784. }
  14785. return true;
  14786. }
  14787. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  14788. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  14789. async function createAddons(options, outputPluginDriver) {
  14790. try {
  14791. let [banner, footer, intro, outro] = await Promise.all([
  14792. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  14793. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  14794. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  14795. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  14796. ]);
  14797. if (intro)
  14798. intro += '\n\n';
  14799. if (outro)
  14800. outro = `\n\n${outro}`;
  14801. if (banner.length)
  14802. banner += '\n';
  14803. if (footer.length)
  14804. footer = '\n' + footer;
  14805. return { banner, footer, intro, outro };
  14806. }
  14807. catch (err) {
  14808. return error({
  14809. code: 'ADDON_ERROR',
  14810. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  14811. \tError Message: ${err.message}`
  14812. });
  14813. }
  14814. }
  14815. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  14816. const chunkDefinitions = [];
  14817. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  14818. const manualChunkModulesByAlias = Object.create(null);
  14819. for (const [entry, alias] of manualChunkAliasByEntry) {
  14820. const chunkModules = (manualChunkModulesByAlias[alias] =
  14821. manualChunkModulesByAlias[alias] || []);
  14822. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  14823. }
  14824. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  14825. chunkDefinitions.push({ alias, modules });
  14826. }
  14827. const assignedEntryPointsByModule = new Map();
  14828. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  14829. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  14830. const staticEntries = new Set(entryModules);
  14831. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  14832. const modulesToHandle = new Set([entry]);
  14833. for (const module of modulesToHandle) {
  14834. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  14835. if (dynamicDependentEntryPoints &&
  14836. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  14837. continue;
  14838. }
  14839. else {
  14840. assignedEntryPoints.add(entry);
  14841. }
  14842. for (const dependency of module.getDependenciesToBeIncluded()) {
  14843. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14844. modulesToHandle.add(dependency);
  14845. }
  14846. }
  14847. }
  14848. }
  14849. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  14850. const entriesToCheck = new Set(entryPoints);
  14851. for (const entry of entriesToCheck) {
  14852. if (!containedIn.has(entry)) {
  14853. if (staticEntries.has(entry))
  14854. return false;
  14855. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  14856. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  14857. entriesToCheck.add(dependentEntry);
  14858. }
  14859. }
  14860. }
  14861. return true;
  14862. }
  14863. for (const entry of entryModules) {
  14864. if (!modulesInManualChunks.has(entry)) {
  14865. assignEntryToStaticDependencies(entry, null);
  14866. }
  14867. }
  14868. for (const entry of dynamicEntryModules) {
  14869. if (!modulesInManualChunks.has(entry)) {
  14870. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  14871. }
  14872. }
  14873. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  14874. return chunkDefinitions;
  14875. }
  14876. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  14877. const modulesToHandle = new Set([entry]);
  14878. for (const module of modulesToHandle) {
  14879. modulesInManualChunks.add(module);
  14880. manualChunkModules.push(module);
  14881. for (const dependency of module.dependencies) {
  14882. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  14883. modulesToHandle.add(dependency);
  14884. }
  14885. }
  14886. }
  14887. }
  14888. function analyzeModuleGraph(entryModules) {
  14889. const dynamicEntryModules = new Set();
  14890. const dependentEntryPointsByModule = new Map();
  14891. const entriesToHandle = new Set(entryModules);
  14892. for (const currentEntry of entriesToHandle) {
  14893. const modulesToHandle = new Set([currentEntry]);
  14894. for (const module of modulesToHandle) {
  14895. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  14896. for (const dependency of module.getDependenciesToBeIncluded()) {
  14897. if (!(dependency instanceof ExternalModule)) {
  14898. modulesToHandle.add(dependency);
  14899. }
  14900. }
  14901. for (const { resolution } of module.dynamicImports) {
  14902. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  14903. dynamicEntryModules.add(resolution);
  14904. entriesToHandle.add(resolution);
  14905. }
  14906. }
  14907. for (const dependency of module.implicitlyLoadedBefore) {
  14908. dynamicEntryModules.add(dependency);
  14909. entriesToHandle.add(dependency);
  14910. }
  14911. }
  14912. }
  14913. return { dependentEntryPointsByModule, dynamicEntryModules };
  14914. }
  14915. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  14916. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  14917. for (const dynamicEntry of dynamicEntryModules) {
  14918. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  14919. for (const importer of [
  14920. ...dynamicEntry.includedDynamicImporters,
  14921. ...dynamicEntry.implicitlyLoadedAfter
  14922. ]) {
  14923. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  14924. dynamicDependentEntryPoints.add(entryPoint);
  14925. }
  14926. }
  14927. }
  14928. return dynamicallyDependentEntryPointsByDynamicEntry;
  14929. }
  14930. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  14931. const chunkModules = Object.create(null);
  14932. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  14933. let chunkSignature = '';
  14934. for (const entry of allEntryPoints) {
  14935. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  14936. }
  14937. const chunk = chunkModules[chunkSignature];
  14938. if (chunk) {
  14939. chunk.push(module);
  14940. }
  14941. else {
  14942. chunkModules[chunkSignature] = [module];
  14943. }
  14944. }
  14945. return Object.values(chunkModules).map(modules => ({
  14946. alias: null,
  14947. modules
  14948. }));
  14949. }
  14950. // ported from https://github.com/substack/node-commondir
  14951. function commondir(files) {
  14952. if (files.length === 0)
  14953. return '/';
  14954. if (files.length === 1)
  14955. return dirname(files[0]);
  14956. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  14957. const pathSegements = file.split(/\/+|\\+/);
  14958. let i;
  14959. for (i = 0; commonSegments[i] === pathSegements[i] &&
  14960. i < Math.min(commonSegments.length, pathSegements.length); i++)
  14961. ;
  14962. return commonSegments.slice(0, i);
  14963. }, files[0].split(/\/+|\\+/));
  14964. // Windows correctly handles paths with forward-slashes
  14965. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  14966. }
  14967. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  14968. function sortByExecutionOrder(units) {
  14969. units.sort(compareExecIndex);
  14970. }
  14971. function analyseModuleExecution(entryModules) {
  14972. let nextExecIndex = 0;
  14973. const cyclePaths = [];
  14974. const analysedModules = new Set();
  14975. const dynamicImports = new Set();
  14976. const parents = new Map();
  14977. const orderedModules = [];
  14978. const analyseModule = (module) => {
  14979. if (module instanceof Module) {
  14980. for (const dependency of module.dependencies) {
  14981. if (parents.has(dependency)) {
  14982. if (!analysedModules.has(dependency)) {
  14983. cyclePaths.push(getCyclePath(dependency, module, parents));
  14984. }
  14985. continue;
  14986. }
  14987. parents.set(dependency, module);
  14988. analyseModule(dependency);
  14989. }
  14990. for (const dependency of module.implicitlyLoadedBefore) {
  14991. dynamicImports.add(dependency);
  14992. }
  14993. for (const { resolution } of module.dynamicImports) {
  14994. if (resolution instanceof Module) {
  14995. dynamicImports.add(resolution);
  14996. }
  14997. }
  14998. orderedModules.push(module);
  14999. }
  15000. module.execIndex = nextExecIndex++;
  15001. analysedModules.add(module);
  15002. };
  15003. for (const curEntry of entryModules) {
  15004. if (!parents.has(curEntry)) {
  15005. parents.set(curEntry, null);
  15006. analyseModule(curEntry);
  15007. }
  15008. }
  15009. for (const curEntry of dynamicImports) {
  15010. if (!parents.has(curEntry)) {
  15011. parents.set(curEntry, null);
  15012. analyseModule(curEntry);
  15013. }
  15014. }
  15015. return { cyclePaths, orderedModules };
  15016. }
  15017. function getCyclePath(module, parent, parents) {
  15018. const cycleSymbol = Symbol(module.id);
  15019. const path = [relativeId(module.id)];
  15020. let nextModule = parent;
  15021. module.cycles.add(cycleSymbol);
  15022. while (nextModule !== module) {
  15023. nextModule.cycles.add(cycleSymbol);
  15024. path.push(relativeId(nextModule.id));
  15025. nextModule = parents.get(nextModule);
  15026. }
  15027. path.push(path[0]);
  15028. path.reverse();
  15029. return path;
  15030. }
  15031. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  15032. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  15033. const cnst = constBindings ? 'const' : 'var';
  15034. const getNonArrowFunctionIntro = (params, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${params.join(`,${_}`)})${_}`;
  15035. const getFunctionIntro = arrowFunctions
  15036. ? (params, { isAsync, name }) => {
  15037. const singleParam = params.length === 1;
  15038. const asyncString = isAsync ? `async${singleParam ? ' ' : _}` : '';
  15039. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParam ? params[0] : `(${params.join(`,${_}`)})`}${_}=>${_}`;
  15040. }
  15041. : getNonArrowFunctionIntro;
  15042. const getDirectReturnFunction = (params, { functionReturn, lineBreakIndent, name }) => [
  15043. `${getFunctionIntro(params, {
  15044. isAsync: false,
  15045. name
  15046. })}${arrowFunctions
  15047. ? lineBreakIndent
  15048. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  15049. : ''
  15050. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  15051. arrowFunctions
  15052. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  15053. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  15054. ];
  15055. const isValidPropName = reservedNamesAsProps
  15056. ? (name) => validPropName.test(name)
  15057. : (name) => !RESERVED_NAMES$1.has(name) && validPropName.test(name);
  15058. return {
  15059. _,
  15060. cnst,
  15061. getDirectReturnFunction,
  15062. getDirectReturnIifeLeft: (params, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  15063. const [left, right] = getDirectReturnFunction(params, {
  15064. functionReturn: true,
  15065. lineBreakIndent: null,
  15066. name: null
  15067. });
  15068. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  15069. },
  15070. getFunctionIntro,
  15071. getNonArrowFunctionIntro,
  15072. getObject(fields, { lineBreakIndent }) {
  15073. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  15074. return `{${fields
  15075. .map(([key, value]) => {
  15076. if (key === null)
  15077. return `${prefix}${value}`;
  15078. const needsQuotes = !isValidPropName(key);
  15079. return key === value && objectShorthand && !needsQuotes
  15080. ? prefix + key
  15081. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  15082. })
  15083. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  15084. },
  15085. getPropertyAccess: (name) => isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  15086. n,
  15087. s
  15088. };
  15089. }
  15090. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  15091. const validPropName = /^(?!\d)[\w$]+$/;
  15092. class Bundle {
  15093. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  15094. this.outputOptions = outputOptions;
  15095. this.unsetOptions = unsetOptions;
  15096. this.inputOptions = inputOptions;
  15097. this.pluginDriver = pluginDriver;
  15098. this.graph = graph;
  15099. this.facadeChunkByModule = new Map();
  15100. this.includedNamespaces = new Set();
  15101. }
  15102. async generate(isWrite) {
  15103. timeStart('GENERATE', 1);
  15104. const outputBundle = Object.create(null);
  15105. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  15106. try {
  15107. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  15108. timeStart('generate chunks', 2);
  15109. const chunks = await this.generateChunks();
  15110. if (chunks.length > 1) {
  15111. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  15112. }
  15113. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  15114. timeEnd('generate chunks', 2);
  15115. timeStart('render modules', 2);
  15116. // We need to create addons before prerender because at the moment, there
  15117. // can be no async code between prerender and render due to internal state
  15118. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  15119. const snippets = getGenerateCodeSnippets(this.outputOptions);
  15120. this.prerenderChunks(chunks, inputBase, snippets);
  15121. timeEnd('render modules', 2);
  15122. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets);
  15123. }
  15124. catch (err) {
  15125. await this.pluginDriver.hookParallel('renderError', [err]);
  15126. throw err;
  15127. }
  15128. await this.pluginDriver.hookSeq('generateBundle', [
  15129. this.outputOptions,
  15130. outputBundle,
  15131. isWrite
  15132. ]);
  15133. this.finaliseAssets(outputBundle);
  15134. timeEnd('GENERATE', 1);
  15135. return outputBundle;
  15136. }
  15137. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle, snippets) {
  15138. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  15139. for (const chunk of chunks) {
  15140. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  15141. }
  15142. await Promise.all(chunks.map(async (chunk) => {
  15143. const outputChunk = outputBundle[chunk.id];
  15144. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk, snippets));
  15145. }));
  15146. }
  15147. async addManualChunks(manualChunks) {
  15148. const manualChunkAliasByEntry = new Map();
  15149. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  15150. alias,
  15151. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  15152. })));
  15153. for (const { alias, entries } of chunkEntries) {
  15154. for (const entry of entries) {
  15155. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  15156. }
  15157. }
  15158. return manualChunkAliasByEntry;
  15159. }
  15160. assignChunkIds(chunks, inputBase, addons, bundle) {
  15161. const entryChunks = [];
  15162. const otherChunks = [];
  15163. for (const chunk of chunks) {
  15164. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  15165. ? entryChunks
  15166. : otherChunks).push(chunk);
  15167. }
  15168. // make sure entry chunk names take precedence with regard to deconflicting
  15169. const chunksForNaming = entryChunks.concat(otherChunks);
  15170. for (const chunk of chunksForNaming) {
  15171. if (this.outputOptions.file) {
  15172. chunk.id = basename(this.outputOptions.file);
  15173. }
  15174. else if (this.outputOptions.preserveModules) {
  15175. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  15176. }
  15177. else {
  15178. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  15179. }
  15180. bundle[chunk.id] = FILE_PLACEHOLDER;
  15181. }
  15182. }
  15183. assignManualChunks(getManualChunk) {
  15184. const manualChunkAliasesWithEntry = [];
  15185. const manualChunksApi = {
  15186. getModuleIds: () => this.graph.modulesById.keys(),
  15187. getModuleInfo: this.graph.getModuleInfo
  15188. };
  15189. for (const module of this.graph.modulesById.values()) {
  15190. if (module instanceof Module) {
  15191. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  15192. if (typeof manualChunkAlias === 'string') {
  15193. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  15194. }
  15195. }
  15196. }
  15197. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  15198. const manualChunkAliasByEntry = new Map();
  15199. for (const [alias, module] of manualChunkAliasesWithEntry) {
  15200. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  15201. }
  15202. return manualChunkAliasByEntry;
  15203. }
  15204. finaliseAssets(outputBundle) {
  15205. for (const file of Object.values(outputBundle)) {
  15206. if (!file.type) {
  15207. 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);
  15208. file.type = 'asset';
  15209. }
  15210. if (this.outputOptions.validate && 'code' in file) {
  15211. try {
  15212. this.graph.contextParse(file.code, {
  15213. allowHashBang: true,
  15214. ecmaVersion: 'latest'
  15215. });
  15216. }
  15217. catch (err) {
  15218. this.inputOptions.onwarn(errChunkInvalid(file, err));
  15219. }
  15220. }
  15221. }
  15222. this.pluginDriver.finaliseAssets();
  15223. }
  15224. async generateChunks() {
  15225. const { manualChunks } = this.outputOptions;
  15226. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  15227. ? await this.addManualChunks(manualChunks)
  15228. : this.assignManualChunks(manualChunks);
  15229. const chunks = [];
  15230. const chunkByModule = new Map();
  15231. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  15232. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  15233. : this.outputOptions.preserveModules
  15234. ? getIncludedModules(this.graph.modulesById).map(module => ({
  15235. alias: null,
  15236. modules: [module]
  15237. }))
  15238. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  15239. sortByExecutionOrder(modules);
  15240. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  15241. chunks.push(chunk);
  15242. for (const module of modules) {
  15243. chunkByModule.set(module, chunk);
  15244. }
  15245. }
  15246. for (const chunk of chunks) {
  15247. chunk.link();
  15248. }
  15249. const facades = [];
  15250. for (const chunk of chunks) {
  15251. facades.push(...chunk.generateFacades());
  15252. }
  15253. return [...chunks, ...facades];
  15254. }
  15255. prerenderChunks(chunks, inputBase, snippets) {
  15256. for (const chunk of chunks) {
  15257. chunk.generateExports();
  15258. }
  15259. for (const chunk of chunks) {
  15260. chunk.preRender(this.outputOptions, inputBase, snippets);
  15261. }
  15262. }
  15263. }
  15264. function getAbsoluteEntryModulePaths(chunks) {
  15265. const absoluteEntryModulePaths = [];
  15266. for (const chunk of chunks) {
  15267. for (const entryModule of chunk.entryModules) {
  15268. if (isAbsolute(entryModule.id)) {
  15269. absoluteEntryModulePaths.push(entryModule.id);
  15270. }
  15271. }
  15272. }
  15273. return absoluteEntryModulePaths;
  15274. }
  15275. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  15276. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  15277. return error(errInvalidOption('output.format', 'outputformat', 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  15278. if (typeof outputOptions.file === 'string')
  15279. 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'));
  15280. if (outputOptions.sourcemapFile)
  15281. return error(errInvalidOption('output.sourcemapFile', 'outputsourcemapfile', '"output.sourcemapFile" is only supported for single-file builds'));
  15282. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  15283. 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'));
  15284. }
  15285. function getIncludedModules(modulesById) {
  15286. return [...modulesById.values()].filter((module) => module instanceof Module &&
  15287. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  15288. }
  15289. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  15290. const existingAlias = manualChunkAliasByEntry.get(module);
  15291. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  15292. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  15293. }
  15294. manualChunkAliasByEntry.set(module, alias);
  15295. }
  15296. // This file was generated. Do not modify manually!
  15297. 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];
  15298. // This file was generated. Do not modify manually!
  15299. 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];
  15300. // This file was generated. Do not modify manually!
  15301. 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";
  15302. // This file was generated. Do not modify manually!
  15303. 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";
  15304. // These are a run-length and offset encoded representation of the
  15305. // Reserved word lists for various dialects of the language
  15306. var reservedWords = {
  15307. 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",
  15308. 5: "class enum extends super const export import",
  15309. 6: "enum",
  15310. strict: "implements interface let package private protected public static yield",
  15311. strictBind: "eval arguments"
  15312. };
  15313. // And the keywords
  15314. 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";
  15315. var keywords$1 = {
  15316. 5: ecma5AndLessKeywords,
  15317. "5module": ecma5AndLessKeywords + " export import",
  15318. 6: ecma5AndLessKeywords + " const class extends export import super"
  15319. };
  15320. var keywordRelationalOperator = /^in(stanceof)?$/;
  15321. // ## Character categories
  15322. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  15323. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  15324. // This has a complexity linear to the value of the code. The
  15325. // assumption is that looking up astral identifier characters is
  15326. // rare.
  15327. function isInAstralSet(code, set) {
  15328. var pos = 0x10000;
  15329. for (var i = 0; i < set.length; i += 2) {
  15330. pos += set[i];
  15331. if (pos > code) { return false }
  15332. pos += set[i + 1];
  15333. if (pos >= code) { return true }
  15334. }
  15335. }
  15336. // Test whether a given character code starts an identifier.
  15337. function isIdentifierStart(code, astral) {
  15338. if (code < 65) { return code === 36 }
  15339. if (code < 91) { return true }
  15340. if (code < 97) { return code === 95 }
  15341. if (code < 123) { return true }
  15342. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  15343. if (astral === false) { return false }
  15344. return isInAstralSet(code, astralIdentifierStartCodes)
  15345. }
  15346. // Test whether a given character is part of an identifier.
  15347. function isIdentifierChar(code, astral) {
  15348. if (code < 48) { return code === 36 }
  15349. if (code < 58) { return true }
  15350. if (code < 65) { return false }
  15351. if (code < 91) { return true }
  15352. if (code < 97) { return code === 95 }
  15353. if (code < 123) { return true }
  15354. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  15355. if (astral === false) { return false }
  15356. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  15357. }
  15358. // ## Token types
  15359. // The assignment of fine-grained, information-carrying type objects
  15360. // allows the tokenizer to store the information it has about a
  15361. // token in a way that is very cheap for the parser to look up.
  15362. // All token type variables start with an underscore, to make them
  15363. // easy to recognize.
  15364. // The `beforeExpr` property is used to disambiguate between regular
  15365. // expressions and divisions. It is set on all token types that can
  15366. // be followed by an expression (thus, a slash after them would be a
  15367. // regular expression).
  15368. //
  15369. // The `startsExpr` property is used to check if the token ends a
  15370. // `yield` expression. It is set on all token types that either can
  15371. // directly start an expression (like a quotation mark) or can
  15372. // continue an expression (like the body of a string).
  15373. //
  15374. // `isLoop` marks a keyword as starting a loop, which is important
  15375. // to know when parsing a label, in order to allow or disallow
  15376. // continue jumps to that label.
  15377. var TokenType = function TokenType(label, conf) {
  15378. if ( conf === void 0 ) conf = {};
  15379. this.label = label;
  15380. this.keyword = conf.keyword;
  15381. this.beforeExpr = !!conf.beforeExpr;
  15382. this.startsExpr = !!conf.startsExpr;
  15383. this.isLoop = !!conf.isLoop;
  15384. this.isAssign = !!conf.isAssign;
  15385. this.prefix = !!conf.prefix;
  15386. this.postfix = !!conf.postfix;
  15387. this.binop = conf.binop || null;
  15388. this.updateContext = null;
  15389. };
  15390. function binop(name, prec) {
  15391. return new TokenType(name, {beforeExpr: true, binop: prec})
  15392. }
  15393. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  15394. // Map keyword names to token types.
  15395. var keywords = {};
  15396. // Succinct definitions of keyword token types
  15397. function kw(name, options) {
  15398. if ( options === void 0 ) options = {};
  15399. options.keyword = name;
  15400. return keywords[name] = new TokenType(name, options)
  15401. }
  15402. var types$1 = {
  15403. num: new TokenType("num", startsExpr),
  15404. regexp: new TokenType("regexp", startsExpr),
  15405. string: new TokenType("string", startsExpr),
  15406. name: new TokenType("name", startsExpr),
  15407. privateId: new TokenType("privateId", startsExpr),
  15408. eof: new TokenType("eof"),
  15409. // Punctuation token types.
  15410. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  15411. bracketR: new TokenType("]"),
  15412. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  15413. braceR: new TokenType("}"),
  15414. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  15415. parenR: new TokenType(")"),
  15416. comma: new TokenType(",", beforeExpr),
  15417. semi: new TokenType(";", beforeExpr),
  15418. colon: new TokenType(":", beforeExpr),
  15419. dot: new TokenType("."),
  15420. question: new TokenType("?", beforeExpr),
  15421. questionDot: new TokenType("?."),
  15422. arrow: new TokenType("=>", beforeExpr),
  15423. template: new TokenType("template"),
  15424. invalidTemplate: new TokenType("invalidTemplate"),
  15425. ellipsis: new TokenType("...", beforeExpr),
  15426. backQuote: new TokenType("`", startsExpr),
  15427. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  15428. // Operators. These carry several kinds of properties to help the
  15429. // parser use them properly (the presence of these properties is
  15430. // what categorizes them as operators).
  15431. //
  15432. // `binop`, when present, specifies that this operator is a binary
  15433. // operator, and will refer to its precedence.
  15434. //
  15435. // `prefix` and `postfix` mark the operator as a prefix or postfix
  15436. // unary operator.
  15437. //
  15438. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  15439. // binary operators with a very low precedence, that should result
  15440. // in AssignmentExpression nodes.
  15441. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  15442. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  15443. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  15444. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  15445. logicalOR: binop("||", 1),
  15446. logicalAND: binop("&&", 2),
  15447. bitwiseOR: binop("|", 3),
  15448. bitwiseXOR: binop("^", 4),
  15449. bitwiseAND: binop("&", 5),
  15450. equality: binop("==/!=/===/!==", 6),
  15451. relational: binop("</>/<=/>=", 7),
  15452. bitShift: binop("<</>>/>>>", 8),
  15453. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  15454. modulo: binop("%", 10),
  15455. star: binop("*", 10),
  15456. slash: binop("/", 10),
  15457. starstar: new TokenType("**", {beforeExpr: true}),
  15458. coalesce: binop("??", 1),
  15459. // Keyword token types.
  15460. _break: kw("break"),
  15461. _case: kw("case", beforeExpr),
  15462. _catch: kw("catch"),
  15463. _continue: kw("continue"),
  15464. _debugger: kw("debugger"),
  15465. _default: kw("default", beforeExpr),
  15466. _do: kw("do", {isLoop: true, beforeExpr: true}),
  15467. _else: kw("else", beforeExpr),
  15468. _finally: kw("finally"),
  15469. _for: kw("for", {isLoop: true}),
  15470. _function: kw("function", startsExpr),
  15471. _if: kw("if"),
  15472. _return: kw("return", beforeExpr),
  15473. _switch: kw("switch"),
  15474. _throw: kw("throw", beforeExpr),
  15475. _try: kw("try"),
  15476. _var: kw("var"),
  15477. _const: kw("const"),
  15478. _while: kw("while", {isLoop: true}),
  15479. _with: kw("with"),
  15480. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  15481. _this: kw("this", startsExpr),
  15482. _super: kw("super", startsExpr),
  15483. _class: kw("class", startsExpr),
  15484. _extends: kw("extends", beforeExpr),
  15485. _export: kw("export"),
  15486. _import: kw("import", startsExpr),
  15487. _null: kw("null", startsExpr),
  15488. _true: kw("true", startsExpr),
  15489. _false: kw("false", startsExpr),
  15490. _in: kw("in", {beforeExpr: true, binop: 7}),
  15491. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  15492. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  15493. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  15494. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  15495. };
  15496. // Matches a whole line break (where CRLF is considered a single
  15497. // line break). Used to count lines.
  15498. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  15499. var lineBreakG = new RegExp(lineBreak.source, "g");
  15500. function isNewLine(code) {
  15501. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  15502. }
  15503. function nextLineBreak(code, from, end) {
  15504. if ( end === void 0 ) end = code.length;
  15505. for (var i = from; i < end; i++) {
  15506. var next = code.charCodeAt(i);
  15507. if (isNewLine(next))
  15508. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  15509. }
  15510. return -1
  15511. }
  15512. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  15513. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  15514. var ref = Object.prototype;
  15515. var hasOwnProperty = ref.hasOwnProperty;
  15516. var toString = ref.toString;
  15517. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  15518. hasOwnProperty.call(obj, propName)
  15519. ); });
  15520. var isArray = Array.isArray || (function (obj) { return (
  15521. toString.call(obj) === "[object Array]"
  15522. ); });
  15523. function wordsRegexp(words) {
  15524. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  15525. }
  15526. function codePointToString(code) {
  15527. // UTF-16 Decoding
  15528. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  15529. code -= 0x10000;
  15530. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  15531. }
  15532. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  15533. // These are used when `options.locations` is on, for the
  15534. // `startLoc` and `endLoc` properties.
  15535. var Position = function Position(line, col) {
  15536. this.line = line;
  15537. this.column = col;
  15538. };
  15539. Position.prototype.offset = function offset (n) {
  15540. return new Position(this.line, this.column + n)
  15541. };
  15542. var SourceLocation = function SourceLocation(p, start, end) {
  15543. this.start = start;
  15544. this.end = end;
  15545. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  15546. };
  15547. // The `getLineInfo` function is mostly useful when the
  15548. // `locations` option is off (for performance reasons) and you
  15549. // want to find the line/column position for a given character
  15550. // offset. `input` should be the code string that the offset refers
  15551. // into.
  15552. function getLineInfo(input, offset) {
  15553. for (var line = 1, cur = 0;;) {
  15554. var nextBreak = nextLineBreak(input, cur, offset);
  15555. if (nextBreak < 0) { return new Position(line, offset - cur) }
  15556. ++line;
  15557. cur = nextBreak;
  15558. }
  15559. }
  15560. // A second argument must be given to configure the parser process.
  15561. // These options are recognized (only `ecmaVersion` is required):
  15562. var defaultOptions = {
  15563. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  15564. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  15565. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  15566. // latest version the library supports). This influences support
  15567. // for strict mode, the set of reserved words, and support for
  15568. // new syntax features.
  15569. ecmaVersion: null,
  15570. // `sourceType` indicates the mode the code should be parsed in.
  15571. // Can be either `"script"` or `"module"`. This influences global
  15572. // strict mode and parsing of `import` and `export` declarations.
  15573. sourceType: "script",
  15574. // `onInsertedSemicolon` can be a callback that will be called
  15575. // when a semicolon is automatically inserted. It will be passed
  15576. // the position of the comma as an offset, and if `locations` is
  15577. // enabled, it is given the location as a `{line, column}` object
  15578. // as second argument.
  15579. onInsertedSemicolon: null,
  15580. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  15581. // trailing commas.
  15582. onTrailingComma: null,
  15583. // By default, reserved words are only enforced if ecmaVersion >= 5.
  15584. // Set `allowReserved` to a boolean value to explicitly turn this on
  15585. // an off. When this option has the value "never", reserved words
  15586. // and keywords can also not be used as property names.
  15587. allowReserved: null,
  15588. // When enabled, a return at the top level is not considered an
  15589. // error.
  15590. allowReturnOutsideFunction: false,
  15591. // When enabled, import/export statements are not constrained to
  15592. // appearing at the top of the program, and an import.meta expression
  15593. // in a script isn't considered an error.
  15594. allowImportExportEverywhere: false,
  15595. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  15596. // When enabled, await identifiers are allowed to appear at the top-level scope,
  15597. // but they are still not allowed in non-async functions.
  15598. allowAwaitOutsideFunction: null,
  15599. // When enabled, super identifiers are not constrained to
  15600. // appearing in methods and do not raise an error when they appear elsewhere.
  15601. allowSuperOutsideMethod: null,
  15602. // When enabled, hashbang directive in the beginning of file
  15603. // is allowed and treated as a line comment.
  15604. allowHashBang: false,
  15605. // When `locations` is on, `loc` properties holding objects with
  15606. // `start` and `end` properties in `{line, column}` form (with
  15607. // line being 1-based and column 0-based) will be attached to the
  15608. // nodes.
  15609. locations: false,
  15610. // A function can be passed as `onToken` option, which will
  15611. // cause Acorn to call that function with object in the same
  15612. // format as tokens returned from `tokenizer().getToken()`. Note
  15613. // that you are not allowed to call the parser from the
  15614. // callback—that will corrupt its internal state.
  15615. onToken: null,
  15616. // A function can be passed as `onComment` option, which will
  15617. // cause Acorn to call that function with `(block, text, start,
  15618. // end)` parameters whenever a comment is skipped. `block` is a
  15619. // boolean indicating whether this is a block (`/* */`) comment,
  15620. // `text` is the content of the comment, and `start` and `end` are
  15621. // character offsets that denote the start and end of the comment.
  15622. // When the `locations` option is on, two more parameters are
  15623. // passed, the full `{line, column}` locations of the start and
  15624. // end of the comments. Note that you are not allowed to call the
  15625. // parser from the callback—that will corrupt its internal state.
  15626. onComment: null,
  15627. // Nodes have their start and end characters offsets recorded in
  15628. // `start` and `end` properties (directly on the node, rather than
  15629. // the `loc` object, which holds line/column data. To also add a
  15630. // [semi-standardized][range] `range` property holding a `[start,
  15631. // end]` array with the same numbers, set the `ranges` option to
  15632. // `true`.
  15633. //
  15634. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  15635. ranges: false,
  15636. // It is possible to parse multiple files into a single AST by
  15637. // passing the tree produced by parsing the first file as
  15638. // `program` option in subsequent parses. This will add the
  15639. // toplevel forms of the parsed file to the `Program` (top) node
  15640. // of an existing parse tree.
  15641. program: null,
  15642. // When `locations` is on, you can pass this to record the source
  15643. // file in every node's `loc` object.
  15644. sourceFile: null,
  15645. // This value, if given, is stored in every node, whether
  15646. // `locations` is on or off.
  15647. directSourceFile: null,
  15648. // When enabled, parenthesized expressions are represented by
  15649. // (non-standard) ParenthesizedExpression nodes
  15650. preserveParens: false
  15651. };
  15652. // Interpret and default an options object
  15653. var warnedAboutEcmaVersion = false;
  15654. function getOptions(opts) {
  15655. var options = {};
  15656. for (var opt in defaultOptions)
  15657. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  15658. if (options.ecmaVersion === "latest") {
  15659. options.ecmaVersion = 1e8;
  15660. } else if (options.ecmaVersion == null) {
  15661. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  15662. warnedAboutEcmaVersion = true;
  15663. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  15664. }
  15665. options.ecmaVersion = 11;
  15666. } else if (options.ecmaVersion >= 2015) {
  15667. options.ecmaVersion -= 2009;
  15668. }
  15669. if (options.allowReserved == null)
  15670. { options.allowReserved = options.ecmaVersion < 5; }
  15671. if (isArray(options.onToken)) {
  15672. var tokens = options.onToken;
  15673. options.onToken = function (token) { return tokens.push(token); };
  15674. }
  15675. if (isArray(options.onComment))
  15676. { options.onComment = pushComment(options, options.onComment); }
  15677. return options
  15678. }
  15679. function pushComment(options, array) {
  15680. return function(block, text, start, end, startLoc, endLoc) {
  15681. var comment = {
  15682. type: block ? "Block" : "Line",
  15683. value: text,
  15684. start: start,
  15685. end: end
  15686. };
  15687. if (options.locations)
  15688. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  15689. if (options.ranges)
  15690. { comment.range = [start, end]; }
  15691. array.push(comment);
  15692. }
  15693. }
  15694. // Each scope gets a bitset that may contain these flags
  15695. var
  15696. SCOPE_TOP = 1,
  15697. SCOPE_FUNCTION = 2,
  15698. SCOPE_ASYNC = 4,
  15699. SCOPE_GENERATOR = 8,
  15700. SCOPE_ARROW = 16,
  15701. SCOPE_SIMPLE_CATCH = 32,
  15702. SCOPE_SUPER = 64,
  15703. SCOPE_DIRECT_SUPER = 128,
  15704. SCOPE_CLASS_STATIC_BLOCK = 256,
  15705. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  15706. function functionFlags(async, generator) {
  15707. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  15708. }
  15709. // Used in checkLVal* and declareName to determine the type of a binding
  15710. var
  15711. BIND_NONE = 0, // Not a binding
  15712. BIND_VAR = 1, // Var-style binding
  15713. BIND_LEXICAL = 2, // Let- or const-style binding
  15714. BIND_FUNCTION = 3, // Function declaration
  15715. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  15716. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  15717. var Parser = function Parser(options, input, startPos) {
  15718. this.options = options = getOptions(options);
  15719. this.sourceFile = options.sourceFile;
  15720. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  15721. var reserved = "";
  15722. if (options.allowReserved !== true) {
  15723. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  15724. if (options.sourceType === "module") { reserved += " await"; }
  15725. }
  15726. this.reservedWords = wordsRegexp(reserved);
  15727. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  15728. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  15729. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  15730. this.input = String(input);
  15731. // Used to signal to callers of `readWord1` whether the word
  15732. // contained any escape sequences. This is needed because words with
  15733. // escape sequences must not be interpreted as keywords.
  15734. this.containsEsc = false;
  15735. // Set up token state
  15736. // The current position of the tokenizer in the input.
  15737. if (startPos) {
  15738. this.pos = startPos;
  15739. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  15740. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  15741. } else {
  15742. this.pos = this.lineStart = 0;
  15743. this.curLine = 1;
  15744. }
  15745. // Properties of the current token:
  15746. // Its type
  15747. this.type = types$1.eof;
  15748. // For tokens that include more information than their type, the value
  15749. this.value = null;
  15750. // Its start and end offset
  15751. this.start = this.end = this.pos;
  15752. // And, if locations are used, the {line, column} object
  15753. // corresponding to those offsets
  15754. this.startLoc = this.endLoc = this.curPosition();
  15755. // Position information for the previous token
  15756. this.lastTokEndLoc = this.lastTokStartLoc = null;
  15757. this.lastTokStart = this.lastTokEnd = this.pos;
  15758. // The context stack is used to superficially track syntactic
  15759. // context to predict whether a regular expression is allowed in a
  15760. // given position.
  15761. this.context = this.initialContext();
  15762. this.exprAllowed = true;
  15763. // Figure out if it's a module code.
  15764. this.inModule = options.sourceType === "module";
  15765. this.strict = this.inModule || this.strictDirective(this.pos);
  15766. // Used to signify the start of a potential arrow function
  15767. this.potentialArrowAt = -1;
  15768. this.potentialArrowInForAwait = false;
  15769. // Positions to delayed-check that yield/await does not exist in default parameters.
  15770. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  15771. // Labels in scope.
  15772. this.labels = [];
  15773. // Thus-far undefined exports.
  15774. this.undefinedExports = Object.create(null);
  15775. // If enabled, skip leading hashbang line.
  15776. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  15777. { this.skipLineComment(2); }
  15778. // Scope tracking for duplicate variable names (see scope.js)
  15779. this.scopeStack = [];
  15780. this.enterScope(SCOPE_TOP);
  15781. // For RegExp validation
  15782. this.regexpState = null;
  15783. // The stack of private names.
  15784. // Each element has two properties: 'declared' and 'used'.
  15785. // When it exited from the outermost class definition, all used private names must be declared.
  15786. this.privateNameStack = [];
  15787. };
  15788. 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 } };
  15789. Parser.prototype.parse = function parse () {
  15790. var node = this.options.program || this.startNode();
  15791. this.nextToken();
  15792. return this.parseTopLevel(node)
  15793. };
  15794. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  15795. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  15796. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  15797. prototypeAccessors.canAwait.get = function () {
  15798. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  15799. var scope = this.scopeStack[i];
  15800. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  15801. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  15802. }
  15803. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  15804. };
  15805. prototypeAccessors.allowSuper.get = function () {
  15806. var ref = this.currentThisScope();
  15807. var flags = ref.flags;
  15808. var inClassFieldInit = ref.inClassFieldInit;
  15809. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  15810. };
  15811. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  15812. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  15813. prototypeAccessors.allowNewDotTarget.get = function () {
  15814. var ref = this.currentThisScope();
  15815. var flags = ref.flags;
  15816. var inClassFieldInit = ref.inClassFieldInit;
  15817. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  15818. };
  15819. prototypeAccessors.inClassStaticBlock.get = function () {
  15820. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  15821. };
  15822. Parser.extend = function extend () {
  15823. var plugins = [], len = arguments.length;
  15824. while ( len-- ) plugins[ len ] = arguments[ len ];
  15825. var cls = this;
  15826. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  15827. return cls
  15828. };
  15829. Parser.parse = function parse (input, options) {
  15830. return new this(options, input).parse()
  15831. };
  15832. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  15833. var parser = new this(options, input, pos);
  15834. parser.nextToken();
  15835. return parser.parseExpression()
  15836. };
  15837. Parser.tokenizer = function tokenizer (input, options) {
  15838. return new this(options, input)
  15839. };
  15840. Object.defineProperties( Parser.prototype, prototypeAccessors );
  15841. var pp$9 = Parser.prototype;
  15842. // ## Parser utilities
  15843. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  15844. pp$9.strictDirective = function(start) {
  15845. if (this.options.ecmaVersion < 5) { return false }
  15846. for (;;) {
  15847. // Try to find string literal.
  15848. skipWhiteSpace.lastIndex = start;
  15849. start += skipWhiteSpace.exec(this.input)[0].length;
  15850. var match = literal.exec(this.input.slice(start));
  15851. if (!match) { return false }
  15852. if ((match[1] || match[2]) === "use strict") {
  15853. skipWhiteSpace.lastIndex = start + match[0].length;
  15854. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  15855. var next = this.input.charAt(end);
  15856. return next === ";" || next === "}" ||
  15857. (lineBreak.test(spaceAfter[0]) &&
  15858. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  15859. }
  15860. start += match[0].length;
  15861. // Skip semicolon, if any.
  15862. skipWhiteSpace.lastIndex = start;
  15863. start += skipWhiteSpace.exec(this.input)[0].length;
  15864. if (this.input[start] === ";")
  15865. { start++; }
  15866. }
  15867. };
  15868. // Predicate that tests whether the next token is of the given
  15869. // type, and if yes, consumes it as a side effect.
  15870. pp$9.eat = function(type) {
  15871. if (this.type === type) {
  15872. this.next();
  15873. return true
  15874. } else {
  15875. return false
  15876. }
  15877. };
  15878. // Tests whether parsed token is a contextual keyword.
  15879. pp$9.isContextual = function(name) {
  15880. return this.type === types$1.name && this.value === name && !this.containsEsc
  15881. };
  15882. // Consumes contextual keyword if possible.
  15883. pp$9.eatContextual = function(name) {
  15884. if (!this.isContextual(name)) { return false }
  15885. this.next();
  15886. return true
  15887. };
  15888. // Asserts that following token is given contextual keyword.
  15889. pp$9.expectContextual = function(name) {
  15890. if (!this.eatContextual(name)) { this.unexpected(); }
  15891. };
  15892. // Test whether a semicolon can be inserted at the current position.
  15893. pp$9.canInsertSemicolon = function() {
  15894. return this.type === types$1.eof ||
  15895. this.type === types$1.braceR ||
  15896. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15897. };
  15898. pp$9.insertSemicolon = function() {
  15899. if (this.canInsertSemicolon()) {
  15900. if (this.options.onInsertedSemicolon)
  15901. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  15902. return true
  15903. }
  15904. };
  15905. // Consume a semicolon, or, failing that, see if we are allowed to
  15906. // pretend that there is a semicolon at this position.
  15907. pp$9.semicolon = function() {
  15908. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  15909. };
  15910. pp$9.afterTrailingComma = function(tokType, notNext) {
  15911. if (this.type === tokType) {
  15912. if (this.options.onTrailingComma)
  15913. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  15914. if (!notNext)
  15915. { this.next(); }
  15916. return true
  15917. }
  15918. };
  15919. // Expect a token of a given type. If found, consume it, otherwise,
  15920. // raise an unexpected token error.
  15921. pp$9.expect = function(type) {
  15922. this.eat(type) || this.unexpected();
  15923. };
  15924. // Raise an unexpected token error.
  15925. pp$9.unexpected = function(pos) {
  15926. this.raise(pos != null ? pos : this.start, "Unexpected token");
  15927. };
  15928. var DestructuringErrors = function DestructuringErrors() {
  15929. this.shorthandAssign =
  15930. this.trailingComma =
  15931. this.parenthesizedAssign =
  15932. this.parenthesizedBind =
  15933. this.doubleProto =
  15934. -1;
  15935. };
  15936. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  15937. if (!refDestructuringErrors) { return }
  15938. if (refDestructuringErrors.trailingComma > -1)
  15939. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  15940. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  15941. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  15942. };
  15943. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  15944. if (!refDestructuringErrors) { return false }
  15945. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  15946. var doubleProto = refDestructuringErrors.doubleProto;
  15947. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  15948. if (shorthandAssign >= 0)
  15949. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  15950. if (doubleProto >= 0)
  15951. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  15952. };
  15953. pp$9.checkYieldAwaitInDefaultParams = function() {
  15954. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  15955. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  15956. if (this.awaitPos)
  15957. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  15958. };
  15959. pp$9.isSimpleAssignTarget = function(expr) {
  15960. if (expr.type === "ParenthesizedExpression")
  15961. { return this.isSimpleAssignTarget(expr.expression) }
  15962. return expr.type === "Identifier" || expr.type === "MemberExpression"
  15963. };
  15964. var pp$8 = Parser.prototype;
  15965. // ### Statement parsing
  15966. // Parse a program. Initializes the parser, reads any number of
  15967. // statements, and wraps them in a Program node. Optionally takes a
  15968. // `program` argument. If present, the statements will be appended
  15969. // to its body instead of creating a new node.
  15970. pp$8.parseTopLevel = function(node) {
  15971. var exports = Object.create(null);
  15972. if (!node.body) { node.body = []; }
  15973. while (this.type !== types$1.eof) {
  15974. var stmt = this.parseStatement(null, true, exports);
  15975. node.body.push(stmt);
  15976. }
  15977. if (this.inModule)
  15978. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  15979. {
  15980. var name = list[i];
  15981. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  15982. } }
  15983. this.adaptDirectivePrologue(node.body);
  15984. this.next();
  15985. node.sourceType = this.options.sourceType;
  15986. return this.finishNode(node, "Program")
  15987. };
  15988. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  15989. pp$8.isLet = function(context) {
  15990. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  15991. skipWhiteSpace.lastIndex = this.pos;
  15992. var skip = skipWhiteSpace.exec(this.input);
  15993. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  15994. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  15995. // Statement) is allowed here. If context is not empty then only a Statement
  15996. // is allowed. However, `let [` is an explicit negative lookahead for
  15997. // ExpressionStatement, so special-case it first.
  15998. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  15999. if (context) { return false }
  16000. if (nextCh === 123) { return true } // '{'
  16001. if (isIdentifierStart(nextCh, true)) {
  16002. var pos = next + 1;
  16003. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  16004. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  16005. var ident = this.input.slice(next, pos);
  16006. if (!keywordRelationalOperator.test(ident)) { return true }
  16007. }
  16008. return false
  16009. };
  16010. // check 'async [no LineTerminator here] function'
  16011. // - 'async /*foo*/ function' is OK.
  16012. // - 'async /*\n*/ function' is invalid.
  16013. pp$8.isAsyncFunction = function() {
  16014. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  16015. { return false }
  16016. skipWhiteSpace.lastIndex = this.pos;
  16017. var skip = skipWhiteSpace.exec(this.input);
  16018. var next = this.pos + skip[0].length, after;
  16019. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  16020. this.input.slice(next, next + 8) === "function" &&
  16021. (next + 8 === this.input.length ||
  16022. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  16023. };
  16024. // Parse a single statement.
  16025. //
  16026. // If expecting a statement and finding a slash operator, parse a
  16027. // regular expression literal. This is to handle cases like
  16028. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  16029. // does not help.
  16030. pp$8.parseStatement = function(context, topLevel, exports) {
  16031. var starttype = this.type, node = this.startNode(), kind;
  16032. if (this.isLet(context)) {
  16033. starttype = types$1._var;
  16034. kind = "let";
  16035. }
  16036. // Most types of statements are recognized by the keyword they
  16037. // start with. Many are trivial to parse, some require a bit of
  16038. // complexity.
  16039. switch (starttype) {
  16040. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  16041. case types$1._debugger: return this.parseDebuggerStatement(node)
  16042. case types$1._do: return this.parseDoStatement(node)
  16043. case types$1._for: return this.parseForStatement(node)
  16044. case types$1._function:
  16045. // Function as sole body of either an if statement or a labeled statement
  16046. // works, but not when it is part of a labeled statement that is the sole
  16047. // body of an if statement.
  16048. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  16049. return this.parseFunctionStatement(node, false, !context)
  16050. case types$1._class:
  16051. if (context) { this.unexpected(); }
  16052. return this.parseClass(node, true)
  16053. case types$1._if: return this.parseIfStatement(node)
  16054. case types$1._return: return this.parseReturnStatement(node)
  16055. case types$1._switch: return this.parseSwitchStatement(node)
  16056. case types$1._throw: return this.parseThrowStatement(node)
  16057. case types$1._try: return this.parseTryStatement(node)
  16058. case types$1._const: case types$1._var:
  16059. kind = kind || this.value;
  16060. if (context && kind !== "var") { this.unexpected(); }
  16061. return this.parseVarStatement(node, kind)
  16062. case types$1._while: return this.parseWhileStatement(node)
  16063. case types$1._with: return this.parseWithStatement(node)
  16064. case types$1.braceL: return this.parseBlock(true, node)
  16065. case types$1.semi: return this.parseEmptyStatement(node)
  16066. case types$1._export:
  16067. case types$1._import:
  16068. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  16069. skipWhiteSpace.lastIndex = this.pos;
  16070. var skip = skipWhiteSpace.exec(this.input);
  16071. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  16072. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  16073. { return this.parseExpressionStatement(node, this.parseExpression()) }
  16074. }
  16075. if (!this.options.allowImportExportEverywhere) {
  16076. if (!topLevel)
  16077. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  16078. if (!this.inModule)
  16079. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  16080. }
  16081. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  16082. // If the statement does not start with a statement keyword or a
  16083. // brace, it's an ExpressionStatement or LabeledStatement. We
  16084. // simply start parsing an expression, and afterwards, if the
  16085. // next token is a colon and the expression was a simple
  16086. // Identifier node, we switch to interpreting it as a label.
  16087. default:
  16088. if (this.isAsyncFunction()) {
  16089. if (context) { this.unexpected(); }
  16090. this.next();
  16091. return this.parseFunctionStatement(node, true, !context)
  16092. }
  16093. var maybeName = this.value, expr = this.parseExpression();
  16094. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  16095. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  16096. else { return this.parseExpressionStatement(node, expr) }
  16097. }
  16098. };
  16099. pp$8.parseBreakContinueStatement = function(node, keyword) {
  16100. var isBreak = keyword === "break";
  16101. this.next();
  16102. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  16103. else if (this.type !== types$1.name) { this.unexpected(); }
  16104. else {
  16105. node.label = this.parseIdent();
  16106. this.semicolon();
  16107. }
  16108. // Verify that there is an actual destination to break or
  16109. // continue to.
  16110. var i = 0;
  16111. for (; i < this.labels.length; ++i) {
  16112. var lab = this.labels[i];
  16113. if (node.label == null || lab.name === node.label.name) {
  16114. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  16115. if (node.label && isBreak) { break }
  16116. }
  16117. }
  16118. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  16119. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  16120. };
  16121. pp$8.parseDebuggerStatement = function(node) {
  16122. this.next();
  16123. this.semicolon();
  16124. return this.finishNode(node, "DebuggerStatement")
  16125. };
  16126. pp$8.parseDoStatement = function(node) {
  16127. this.next();
  16128. this.labels.push(loopLabel);
  16129. node.body = this.parseStatement("do");
  16130. this.labels.pop();
  16131. this.expect(types$1._while);
  16132. node.test = this.parseParenExpression();
  16133. if (this.options.ecmaVersion >= 6)
  16134. { this.eat(types$1.semi); }
  16135. else
  16136. { this.semicolon(); }
  16137. return this.finishNode(node, "DoWhileStatement")
  16138. };
  16139. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  16140. // loop is non-trivial. Basically, we have to parse the init `var`
  16141. // statement or expression, disallowing the `in` operator (see
  16142. // the second parameter to `parseExpression`), and then check
  16143. // whether the next token is `in` or `of`. When there is no init
  16144. // part (semicolon immediately after the opening parenthesis), it
  16145. // is a regular `for` loop.
  16146. pp$8.parseForStatement = function(node) {
  16147. this.next();
  16148. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  16149. this.labels.push(loopLabel);
  16150. this.enterScope(0);
  16151. this.expect(types$1.parenL);
  16152. if (this.type === types$1.semi) {
  16153. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16154. return this.parseFor(node, null)
  16155. }
  16156. var isLet = this.isLet();
  16157. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  16158. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  16159. this.next();
  16160. this.parseVar(init$1, true, kind);
  16161. this.finishNode(init$1, "VariableDeclaration");
  16162. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  16163. if (this.options.ecmaVersion >= 9) {
  16164. if (this.type === types$1._in) {
  16165. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16166. } else { node.await = awaitAt > -1; }
  16167. }
  16168. return this.parseForIn(node, init$1)
  16169. }
  16170. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16171. return this.parseFor(node, init$1)
  16172. }
  16173. var startsWithLet = this.isContextual("let"), isForOf = false;
  16174. var refDestructuringErrors = new DestructuringErrors;
  16175. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  16176. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  16177. if (this.options.ecmaVersion >= 9) {
  16178. if (this.type === types$1._in) {
  16179. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16180. } else { node.await = awaitAt > -1; }
  16181. }
  16182. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  16183. this.toAssignable(init, false, refDestructuringErrors);
  16184. this.checkLValPattern(init);
  16185. return this.parseForIn(node, init)
  16186. } else {
  16187. this.checkExpressionErrors(refDestructuringErrors, true);
  16188. }
  16189. if (awaitAt > -1) { this.unexpected(awaitAt); }
  16190. return this.parseFor(node, init)
  16191. };
  16192. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  16193. this.next();
  16194. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  16195. };
  16196. pp$8.parseIfStatement = function(node) {
  16197. this.next();
  16198. node.test = this.parseParenExpression();
  16199. // allow function declarations in branches, but only in non-strict mode
  16200. node.consequent = this.parseStatement("if");
  16201. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  16202. return this.finishNode(node, "IfStatement")
  16203. };
  16204. pp$8.parseReturnStatement = function(node) {
  16205. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  16206. { this.raise(this.start, "'return' outside of function"); }
  16207. this.next();
  16208. // In `return` (and `break`/`continue`), the keywords with
  16209. // optional arguments, we eagerly look for a semicolon or the
  16210. // possibility to insert one.
  16211. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  16212. else { node.argument = this.parseExpression(); this.semicolon(); }
  16213. return this.finishNode(node, "ReturnStatement")
  16214. };
  16215. pp$8.parseSwitchStatement = function(node) {
  16216. this.next();
  16217. node.discriminant = this.parseParenExpression();
  16218. node.cases = [];
  16219. this.expect(types$1.braceL);
  16220. this.labels.push(switchLabel);
  16221. this.enterScope(0);
  16222. // Statements under must be grouped (by label) in SwitchCase
  16223. // nodes. `cur` is used to keep the node that we are currently
  16224. // adding statements to.
  16225. var cur;
  16226. for (var sawDefault = false; this.type !== types$1.braceR;) {
  16227. if (this.type === types$1._case || this.type === types$1._default) {
  16228. var isCase = this.type === types$1._case;
  16229. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16230. node.cases.push(cur = this.startNode());
  16231. cur.consequent = [];
  16232. this.next();
  16233. if (isCase) {
  16234. cur.test = this.parseExpression();
  16235. } else {
  16236. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  16237. sawDefault = true;
  16238. cur.test = null;
  16239. }
  16240. this.expect(types$1.colon);
  16241. } else {
  16242. if (!cur) { this.unexpected(); }
  16243. cur.consequent.push(this.parseStatement(null));
  16244. }
  16245. }
  16246. this.exitScope();
  16247. if (cur) { this.finishNode(cur, "SwitchCase"); }
  16248. this.next(); // Closing brace
  16249. this.labels.pop();
  16250. return this.finishNode(node, "SwitchStatement")
  16251. };
  16252. pp$8.parseThrowStatement = function(node) {
  16253. this.next();
  16254. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  16255. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  16256. node.argument = this.parseExpression();
  16257. this.semicolon();
  16258. return this.finishNode(node, "ThrowStatement")
  16259. };
  16260. // Reused empty array added for node fields that are always empty.
  16261. var empty$1 = [];
  16262. pp$8.parseTryStatement = function(node) {
  16263. this.next();
  16264. node.block = this.parseBlock();
  16265. node.handler = null;
  16266. if (this.type === types$1._catch) {
  16267. var clause = this.startNode();
  16268. this.next();
  16269. if (this.eat(types$1.parenL)) {
  16270. clause.param = this.parseBindingAtom();
  16271. var simple = clause.param.type === "Identifier";
  16272. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  16273. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  16274. this.expect(types$1.parenR);
  16275. } else {
  16276. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  16277. clause.param = null;
  16278. this.enterScope(0);
  16279. }
  16280. clause.body = this.parseBlock(false);
  16281. this.exitScope();
  16282. node.handler = this.finishNode(clause, "CatchClause");
  16283. }
  16284. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  16285. if (!node.handler && !node.finalizer)
  16286. { this.raise(node.start, "Missing catch or finally clause"); }
  16287. return this.finishNode(node, "TryStatement")
  16288. };
  16289. pp$8.parseVarStatement = function(node, kind) {
  16290. this.next();
  16291. this.parseVar(node, false, kind);
  16292. this.semicolon();
  16293. return this.finishNode(node, "VariableDeclaration")
  16294. };
  16295. pp$8.parseWhileStatement = function(node) {
  16296. this.next();
  16297. node.test = this.parseParenExpression();
  16298. this.labels.push(loopLabel);
  16299. node.body = this.parseStatement("while");
  16300. this.labels.pop();
  16301. return this.finishNode(node, "WhileStatement")
  16302. };
  16303. pp$8.parseWithStatement = function(node) {
  16304. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  16305. this.next();
  16306. node.object = this.parseParenExpression();
  16307. node.body = this.parseStatement("with");
  16308. return this.finishNode(node, "WithStatement")
  16309. };
  16310. pp$8.parseEmptyStatement = function(node) {
  16311. this.next();
  16312. return this.finishNode(node, "EmptyStatement")
  16313. };
  16314. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  16315. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  16316. {
  16317. var label = list[i$1];
  16318. if (label.name === maybeName)
  16319. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  16320. } }
  16321. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  16322. for (var i = this.labels.length - 1; i >= 0; i--) {
  16323. var label$1 = this.labels[i];
  16324. if (label$1.statementStart === node.start) {
  16325. // Update information about previous labels on this node
  16326. label$1.statementStart = this.start;
  16327. label$1.kind = kind;
  16328. } else { break }
  16329. }
  16330. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  16331. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  16332. this.labels.pop();
  16333. node.label = expr;
  16334. return this.finishNode(node, "LabeledStatement")
  16335. };
  16336. pp$8.parseExpressionStatement = function(node, expr) {
  16337. node.expression = expr;
  16338. this.semicolon();
  16339. return this.finishNode(node, "ExpressionStatement")
  16340. };
  16341. // Parse a semicolon-enclosed block of statements, handling `"use
  16342. // strict"` declarations when `allowStrict` is true (used for
  16343. // function bodies).
  16344. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  16345. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  16346. if ( node === void 0 ) node = this.startNode();
  16347. node.body = [];
  16348. this.expect(types$1.braceL);
  16349. if (createNewLexicalScope) { this.enterScope(0); }
  16350. while (this.type !== types$1.braceR) {
  16351. var stmt = this.parseStatement(null);
  16352. node.body.push(stmt);
  16353. }
  16354. if (exitStrict) { this.strict = false; }
  16355. this.next();
  16356. if (createNewLexicalScope) { this.exitScope(); }
  16357. return this.finishNode(node, "BlockStatement")
  16358. };
  16359. // Parse a regular `for` loop. The disambiguation code in
  16360. // `parseStatement` will already have parsed the init statement or
  16361. // expression.
  16362. pp$8.parseFor = function(node, init) {
  16363. node.init = init;
  16364. this.expect(types$1.semi);
  16365. node.test = this.type === types$1.semi ? null : this.parseExpression();
  16366. this.expect(types$1.semi);
  16367. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  16368. this.expect(types$1.parenR);
  16369. node.body = this.parseStatement("for");
  16370. this.exitScope();
  16371. this.labels.pop();
  16372. return this.finishNode(node, "ForStatement")
  16373. };
  16374. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  16375. // same from parser's perspective.
  16376. pp$8.parseForIn = function(node, init) {
  16377. var isForIn = this.type === types$1._in;
  16378. this.next();
  16379. if (
  16380. init.type === "VariableDeclaration" &&
  16381. init.declarations[0].init != null &&
  16382. (
  16383. !isForIn ||
  16384. this.options.ecmaVersion < 8 ||
  16385. this.strict ||
  16386. init.kind !== "var" ||
  16387. init.declarations[0].id.type !== "Identifier"
  16388. )
  16389. ) {
  16390. this.raise(
  16391. init.start,
  16392. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  16393. );
  16394. }
  16395. node.left = init;
  16396. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  16397. this.expect(types$1.parenR);
  16398. node.body = this.parseStatement("for");
  16399. this.exitScope();
  16400. this.labels.pop();
  16401. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  16402. };
  16403. // Parse a list of variable declarations.
  16404. pp$8.parseVar = function(node, isFor, kind) {
  16405. node.declarations = [];
  16406. node.kind = kind;
  16407. for (;;) {
  16408. var decl = this.startNode();
  16409. this.parseVarId(decl, kind);
  16410. if (this.eat(types$1.eq)) {
  16411. decl.init = this.parseMaybeAssign(isFor);
  16412. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  16413. this.unexpected();
  16414. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  16415. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  16416. } else {
  16417. decl.init = null;
  16418. }
  16419. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  16420. if (!this.eat(types$1.comma)) { break }
  16421. }
  16422. return node
  16423. };
  16424. pp$8.parseVarId = function(decl, kind) {
  16425. decl.id = this.parseBindingAtom();
  16426. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  16427. };
  16428. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  16429. // Parse a function declaration or literal (depending on the
  16430. // `statement & FUNC_STATEMENT`).
  16431. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  16432. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  16433. this.initFunction(node);
  16434. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  16435. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  16436. { this.unexpected(); }
  16437. node.generator = this.eat(types$1.star);
  16438. }
  16439. if (this.options.ecmaVersion >= 8)
  16440. { node.async = !!isAsync; }
  16441. if (statement & FUNC_STATEMENT) {
  16442. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  16443. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  16444. // If it is a regular function declaration in sloppy mode, then it is
  16445. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  16446. // mode depends on properties of the current scope (see
  16447. // treatFunctionsAsVar).
  16448. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  16449. }
  16450. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  16451. this.yieldPos = 0;
  16452. this.awaitPos = 0;
  16453. this.awaitIdentPos = 0;
  16454. this.enterScope(functionFlags(node.async, node.generator));
  16455. if (!(statement & FUNC_STATEMENT))
  16456. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  16457. this.parseFunctionParams(node);
  16458. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  16459. this.yieldPos = oldYieldPos;
  16460. this.awaitPos = oldAwaitPos;
  16461. this.awaitIdentPos = oldAwaitIdentPos;
  16462. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  16463. };
  16464. pp$8.parseFunctionParams = function(node) {
  16465. this.expect(types$1.parenL);
  16466. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  16467. this.checkYieldAwaitInDefaultParams();
  16468. };
  16469. // Parse a class declaration or literal (depending on the
  16470. // `isStatement` parameter).
  16471. pp$8.parseClass = function(node, isStatement) {
  16472. this.next();
  16473. // ecma-262 14.6 Class Definitions
  16474. // A class definition is always strict mode code.
  16475. var oldStrict = this.strict;
  16476. this.strict = true;
  16477. this.parseClassId(node, isStatement);
  16478. this.parseClassSuper(node);
  16479. var privateNameMap = this.enterClassBody();
  16480. var classBody = this.startNode();
  16481. var hadConstructor = false;
  16482. classBody.body = [];
  16483. this.expect(types$1.braceL);
  16484. while (this.type !== types$1.braceR) {
  16485. var element = this.parseClassElement(node.superClass !== null);
  16486. if (element) {
  16487. classBody.body.push(element);
  16488. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  16489. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  16490. hadConstructor = true;
  16491. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  16492. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  16493. }
  16494. }
  16495. }
  16496. this.strict = oldStrict;
  16497. this.next();
  16498. node.body = this.finishNode(classBody, "ClassBody");
  16499. this.exitClassBody();
  16500. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  16501. };
  16502. pp$8.parseClassElement = function(constructorAllowsSuper) {
  16503. if (this.eat(types$1.semi)) { return null }
  16504. var ecmaVersion = this.options.ecmaVersion;
  16505. var node = this.startNode();
  16506. var keyName = "";
  16507. var isGenerator = false;
  16508. var isAsync = false;
  16509. var kind = "method";
  16510. var isStatic = false;
  16511. if (this.eatContextual("static")) {
  16512. // Parse static init block
  16513. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  16514. this.parseClassStaticBlock(node);
  16515. return node
  16516. }
  16517. if (this.isClassElementNameStart() || this.type === types$1.star) {
  16518. isStatic = true;
  16519. } else {
  16520. keyName = "static";
  16521. }
  16522. }
  16523. node.static = isStatic;
  16524. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  16525. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  16526. isAsync = true;
  16527. } else {
  16528. keyName = "async";
  16529. }
  16530. }
  16531. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  16532. isGenerator = true;
  16533. }
  16534. if (!keyName && !isAsync && !isGenerator) {
  16535. var lastValue = this.value;
  16536. if (this.eatContextual("get") || this.eatContextual("set")) {
  16537. if (this.isClassElementNameStart()) {
  16538. kind = lastValue;
  16539. } else {
  16540. keyName = lastValue;
  16541. }
  16542. }
  16543. }
  16544. // Parse element name
  16545. if (keyName) {
  16546. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  16547. // The last token is any of those. Make it the element name.
  16548. node.computed = false;
  16549. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  16550. node.key.name = keyName;
  16551. this.finishNode(node.key, "Identifier");
  16552. } else {
  16553. this.parseClassElementName(node);
  16554. }
  16555. // Parse element value
  16556. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  16557. var isConstructor = !node.static && checkKeyName(node, "constructor");
  16558. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  16559. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  16560. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  16561. node.kind = isConstructor ? "constructor" : kind;
  16562. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  16563. } else {
  16564. this.parseClassField(node);
  16565. }
  16566. return node
  16567. };
  16568. pp$8.isClassElementNameStart = function() {
  16569. return (
  16570. this.type === types$1.name ||
  16571. this.type === types$1.privateId ||
  16572. this.type === types$1.num ||
  16573. this.type === types$1.string ||
  16574. this.type === types$1.bracketL ||
  16575. this.type.keyword
  16576. )
  16577. };
  16578. pp$8.parseClassElementName = function(element) {
  16579. if (this.type === types$1.privateId) {
  16580. if (this.value === "constructor") {
  16581. this.raise(this.start, "Classes can't have an element named '#constructor'");
  16582. }
  16583. element.computed = false;
  16584. element.key = this.parsePrivateIdent();
  16585. } else {
  16586. this.parsePropertyName(element);
  16587. }
  16588. };
  16589. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  16590. // Check key and flags
  16591. var key = method.key;
  16592. if (method.kind === "constructor") {
  16593. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  16594. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  16595. } else if (method.static && checkKeyName(method, "prototype")) {
  16596. this.raise(key.start, "Classes may not have a static property named prototype");
  16597. }
  16598. // Parse value
  16599. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  16600. // Check value
  16601. if (method.kind === "get" && value.params.length !== 0)
  16602. { this.raiseRecoverable(value.start, "getter should have no params"); }
  16603. if (method.kind === "set" && value.params.length !== 1)
  16604. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  16605. if (method.kind === "set" && value.params[0].type === "RestElement")
  16606. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  16607. return this.finishNode(method, "MethodDefinition")
  16608. };
  16609. pp$8.parseClassField = function(field) {
  16610. if (checkKeyName(field, "constructor")) {
  16611. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  16612. } else if (field.static && checkKeyName(field, "prototype")) {
  16613. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  16614. }
  16615. if (this.eat(types$1.eq)) {
  16616. // To raise SyntaxError if 'arguments' exists in the initializer.
  16617. var scope = this.currentThisScope();
  16618. var inClassFieldInit = scope.inClassFieldInit;
  16619. scope.inClassFieldInit = true;
  16620. field.value = this.parseMaybeAssign();
  16621. scope.inClassFieldInit = inClassFieldInit;
  16622. } else {
  16623. field.value = null;
  16624. }
  16625. this.semicolon();
  16626. return this.finishNode(field, "PropertyDefinition")
  16627. };
  16628. pp$8.parseClassStaticBlock = function(node) {
  16629. node.body = [];
  16630. var oldLabels = this.labels;
  16631. this.labels = [];
  16632. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  16633. while (this.type !== types$1.braceR) {
  16634. var stmt = this.parseStatement(null);
  16635. node.body.push(stmt);
  16636. }
  16637. this.next();
  16638. this.exitScope();
  16639. this.labels = oldLabels;
  16640. return this.finishNode(node, "StaticBlock")
  16641. };
  16642. pp$8.parseClassId = function(node, isStatement) {
  16643. if (this.type === types$1.name) {
  16644. node.id = this.parseIdent();
  16645. if (isStatement)
  16646. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  16647. } else {
  16648. if (isStatement === true)
  16649. { this.unexpected(); }
  16650. node.id = null;
  16651. }
  16652. };
  16653. pp$8.parseClassSuper = function(node) {
  16654. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  16655. };
  16656. pp$8.enterClassBody = function() {
  16657. var element = {declared: Object.create(null), used: []};
  16658. this.privateNameStack.push(element);
  16659. return element.declared
  16660. };
  16661. pp$8.exitClassBody = function() {
  16662. var ref = this.privateNameStack.pop();
  16663. var declared = ref.declared;
  16664. var used = ref.used;
  16665. var len = this.privateNameStack.length;
  16666. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  16667. for (var i = 0; i < used.length; ++i) {
  16668. var id = used[i];
  16669. if (!hasOwn(declared, id.name)) {
  16670. if (parent) {
  16671. parent.used.push(id);
  16672. } else {
  16673. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  16674. }
  16675. }
  16676. }
  16677. };
  16678. function isPrivateNameConflicted(privateNameMap, element) {
  16679. var name = element.key.name;
  16680. var curr = privateNameMap[name];
  16681. var next = "true";
  16682. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  16683. next = (element.static ? "s" : "i") + element.kind;
  16684. }
  16685. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  16686. if (
  16687. curr === "iget" && next === "iset" ||
  16688. curr === "iset" && next === "iget" ||
  16689. curr === "sget" && next === "sset" ||
  16690. curr === "sset" && next === "sget"
  16691. ) {
  16692. privateNameMap[name] = "true";
  16693. return false
  16694. } else if (!curr) {
  16695. privateNameMap[name] = next;
  16696. return false
  16697. } else {
  16698. return true
  16699. }
  16700. }
  16701. function checkKeyName(node, name) {
  16702. var computed = node.computed;
  16703. var key = node.key;
  16704. return !computed && (
  16705. key.type === "Identifier" && key.name === name ||
  16706. key.type === "Literal" && key.value === name
  16707. )
  16708. }
  16709. // Parses module export declaration.
  16710. pp$8.parseExport = function(node, exports) {
  16711. this.next();
  16712. // export * from '...'
  16713. if (this.eat(types$1.star)) {
  16714. if (this.options.ecmaVersion >= 11) {
  16715. if (this.eatContextual("as")) {
  16716. node.exported = this.parseModuleExportName();
  16717. this.checkExport(exports, node.exported, this.lastTokStart);
  16718. } else {
  16719. node.exported = null;
  16720. }
  16721. }
  16722. this.expectContextual("from");
  16723. if (this.type !== types$1.string) { this.unexpected(); }
  16724. node.source = this.parseExprAtom();
  16725. this.semicolon();
  16726. return this.finishNode(node, "ExportAllDeclaration")
  16727. }
  16728. if (this.eat(types$1._default)) { // export default ...
  16729. this.checkExport(exports, "default", this.lastTokStart);
  16730. var isAsync;
  16731. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  16732. var fNode = this.startNode();
  16733. this.next();
  16734. if (isAsync) { this.next(); }
  16735. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  16736. } else if (this.type === types$1._class) {
  16737. var cNode = this.startNode();
  16738. node.declaration = this.parseClass(cNode, "nullableID");
  16739. } else {
  16740. node.declaration = this.parseMaybeAssign();
  16741. this.semicolon();
  16742. }
  16743. return this.finishNode(node, "ExportDefaultDeclaration")
  16744. }
  16745. // export var|const|let|function|class ...
  16746. if (this.shouldParseExportStatement()) {
  16747. node.declaration = this.parseStatement(null);
  16748. if (node.declaration.type === "VariableDeclaration")
  16749. { this.checkVariableExport(exports, node.declaration.declarations); }
  16750. else
  16751. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  16752. node.specifiers = [];
  16753. node.source = null;
  16754. } else { // export { x, y as z } [from '...']
  16755. node.declaration = null;
  16756. node.specifiers = this.parseExportSpecifiers(exports);
  16757. if (this.eatContextual("from")) {
  16758. if (this.type !== types$1.string) { this.unexpected(); }
  16759. node.source = this.parseExprAtom();
  16760. } else {
  16761. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  16762. // check for keywords used as local names
  16763. var spec = list[i];
  16764. this.checkUnreserved(spec.local);
  16765. // check if export is defined
  16766. this.checkLocalExport(spec.local);
  16767. if (spec.local.type === "Literal") {
  16768. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  16769. }
  16770. }
  16771. node.source = null;
  16772. }
  16773. this.semicolon();
  16774. }
  16775. return this.finishNode(node, "ExportNamedDeclaration")
  16776. };
  16777. pp$8.checkExport = function(exports, name, pos) {
  16778. if (!exports) { return }
  16779. if (typeof name !== "string")
  16780. { name = name.type === "Identifier" ? name.name : name.value; }
  16781. if (hasOwn(exports, name))
  16782. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  16783. exports[name] = true;
  16784. };
  16785. pp$8.checkPatternExport = function(exports, pat) {
  16786. var type = pat.type;
  16787. if (type === "Identifier")
  16788. { this.checkExport(exports, pat, pat.start); }
  16789. else if (type === "ObjectPattern")
  16790. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  16791. {
  16792. var prop = list[i];
  16793. this.checkPatternExport(exports, prop);
  16794. } }
  16795. else if (type === "ArrayPattern")
  16796. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  16797. var elt = list$1[i$1];
  16798. if (elt) { this.checkPatternExport(exports, elt); }
  16799. } }
  16800. else if (type === "Property")
  16801. { this.checkPatternExport(exports, pat.value); }
  16802. else if (type === "AssignmentPattern")
  16803. { this.checkPatternExport(exports, pat.left); }
  16804. else if (type === "RestElement")
  16805. { this.checkPatternExport(exports, pat.argument); }
  16806. else if (type === "ParenthesizedExpression")
  16807. { this.checkPatternExport(exports, pat.expression); }
  16808. };
  16809. pp$8.checkVariableExport = function(exports, decls) {
  16810. if (!exports) { return }
  16811. for (var i = 0, list = decls; i < list.length; i += 1)
  16812. {
  16813. var decl = list[i];
  16814. this.checkPatternExport(exports, decl.id);
  16815. }
  16816. };
  16817. pp$8.shouldParseExportStatement = function() {
  16818. return this.type.keyword === "var" ||
  16819. this.type.keyword === "const" ||
  16820. this.type.keyword === "class" ||
  16821. this.type.keyword === "function" ||
  16822. this.isLet() ||
  16823. this.isAsyncFunction()
  16824. };
  16825. // Parses a comma-separated list of module exports.
  16826. pp$8.parseExportSpecifiers = function(exports) {
  16827. var nodes = [], first = true;
  16828. // export { x, y as z } [from '...']
  16829. this.expect(types$1.braceL);
  16830. while (!this.eat(types$1.braceR)) {
  16831. if (!first) {
  16832. this.expect(types$1.comma);
  16833. if (this.afterTrailingComma(types$1.braceR)) { break }
  16834. } else { first = false; }
  16835. var node = this.startNode();
  16836. node.local = this.parseModuleExportName();
  16837. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  16838. this.checkExport(
  16839. exports,
  16840. node.exported,
  16841. node.exported.start
  16842. );
  16843. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16844. }
  16845. return nodes
  16846. };
  16847. // Parses import declaration.
  16848. pp$8.parseImport = function(node) {
  16849. this.next();
  16850. // import '...'
  16851. if (this.type === types$1.string) {
  16852. node.specifiers = empty$1;
  16853. node.source = this.parseExprAtom();
  16854. } else {
  16855. node.specifiers = this.parseImportSpecifiers();
  16856. this.expectContextual("from");
  16857. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  16858. }
  16859. this.semicolon();
  16860. return this.finishNode(node, "ImportDeclaration")
  16861. };
  16862. // Parses a comma-separated list of module imports.
  16863. pp$8.parseImportSpecifiers = function() {
  16864. var nodes = [], first = true;
  16865. if (this.type === types$1.name) {
  16866. // import defaultObj, { x, y as z } from '...'
  16867. var node = this.startNode();
  16868. node.local = this.parseIdent();
  16869. this.checkLValSimple(node.local, BIND_LEXICAL);
  16870. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  16871. if (!this.eat(types$1.comma)) { return nodes }
  16872. }
  16873. if (this.type === types$1.star) {
  16874. var node$1 = this.startNode();
  16875. this.next();
  16876. this.expectContextual("as");
  16877. node$1.local = this.parseIdent();
  16878. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  16879. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  16880. return nodes
  16881. }
  16882. this.expect(types$1.braceL);
  16883. while (!this.eat(types$1.braceR)) {
  16884. if (!first) {
  16885. this.expect(types$1.comma);
  16886. if (this.afterTrailingComma(types$1.braceR)) { break }
  16887. } else { first = false; }
  16888. var node$2 = this.startNode();
  16889. node$2.imported = this.parseModuleExportName();
  16890. if (this.eatContextual("as")) {
  16891. node$2.local = this.parseIdent();
  16892. } else {
  16893. this.checkUnreserved(node$2.imported);
  16894. node$2.local = node$2.imported;
  16895. }
  16896. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  16897. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  16898. }
  16899. return nodes
  16900. };
  16901. pp$8.parseModuleExportName = function() {
  16902. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  16903. var stringLiteral = this.parseLiteral(this.value);
  16904. if (loneSurrogate.test(stringLiteral.value)) {
  16905. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  16906. }
  16907. return stringLiteral
  16908. }
  16909. return this.parseIdent(true)
  16910. };
  16911. // Set `ExpressionStatement#directive` property for directive prologues.
  16912. pp$8.adaptDirectivePrologue = function(statements) {
  16913. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  16914. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  16915. }
  16916. };
  16917. pp$8.isDirectiveCandidate = function(statement) {
  16918. return (
  16919. statement.type === "ExpressionStatement" &&
  16920. statement.expression.type === "Literal" &&
  16921. typeof statement.expression.value === "string" &&
  16922. // Reject parenthesized strings.
  16923. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  16924. )
  16925. };
  16926. var pp$7 = Parser.prototype;
  16927. // Convert existing expression atom to assignable pattern
  16928. // if possible.
  16929. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  16930. if (this.options.ecmaVersion >= 6 && node) {
  16931. switch (node.type) {
  16932. case "Identifier":
  16933. if (this.inAsync && node.name === "await")
  16934. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  16935. break
  16936. case "ObjectPattern":
  16937. case "ArrayPattern":
  16938. case "AssignmentPattern":
  16939. case "RestElement":
  16940. break
  16941. case "ObjectExpression":
  16942. node.type = "ObjectPattern";
  16943. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16944. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  16945. var prop = list[i];
  16946. this.toAssignable(prop, isBinding);
  16947. // Early error:
  16948. // AssignmentRestProperty[Yield, Await] :
  16949. // `...` DestructuringAssignmentTarget[Yield, Await]
  16950. //
  16951. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  16952. if (
  16953. prop.type === "RestElement" &&
  16954. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  16955. ) {
  16956. this.raise(prop.argument.start, "Unexpected token");
  16957. }
  16958. }
  16959. break
  16960. case "Property":
  16961. // AssignmentProperty has type === "Property"
  16962. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  16963. this.toAssignable(node.value, isBinding);
  16964. break
  16965. case "ArrayExpression":
  16966. node.type = "ArrayPattern";
  16967. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16968. this.toAssignableList(node.elements, isBinding);
  16969. break
  16970. case "SpreadElement":
  16971. node.type = "RestElement";
  16972. this.toAssignable(node.argument, isBinding);
  16973. if (node.argument.type === "AssignmentPattern")
  16974. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  16975. break
  16976. case "AssignmentExpression":
  16977. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  16978. node.type = "AssignmentPattern";
  16979. delete node.operator;
  16980. this.toAssignable(node.left, isBinding);
  16981. break
  16982. case "ParenthesizedExpression":
  16983. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  16984. break
  16985. case "ChainExpression":
  16986. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  16987. break
  16988. case "MemberExpression":
  16989. if (!isBinding) { break }
  16990. default:
  16991. this.raise(node.start, "Assigning to rvalue");
  16992. }
  16993. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  16994. return node
  16995. };
  16996. // Convert list of expression atoms to binding list.
  16997. pp$7.toAssignableList = function(exprList, isBinding) {
  16998. var end = exprList.length;
  16999. for (var i = 0; i < end; i++) {
  17000. var elt = exprList[i];
  17001. if (elt) { this.toAssignable(elt, isBinding); }
  17002. }
  17003. if (end) {
  17004. var last = exprList[end - 1];
  17005. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  17006. { this.unexpected(last.argument.start); }
  17007. }
  17008. return exprList
  17009. };
  17010. // Parses spread element.
  17011. pp$7.parseSpread = function(refDestructuringErrors) {
  17012. var node = this.startNode();
  17013. this.next();
  17014. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  17015. return this.finishNode(node, "SpreadElement")
  17016. };
  17017. pp$7.parseRestBinding = function() {
  17018. var node = this.startNode();
  17019. this.next();
  17020. // RestElement inside of a function parameter must be an identifier
  17021. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  17022. { this.unexpected(); }
  17023. node.argument = this.parseBindingAtom();
  17024. return this.finishNode(node, "RestElement")
  17025. };
  17026. // Parses lvalue (assignable) atom.
  17027. pp$7.parseBindingAtom = function() {
  17028. if (this.options.ecmaVersion >= 6) {
  17029. switch (this.type) {
  17030. case types$1.bracketL:
  17031. var node = this.startNode();
  17032. this.next();
  17033. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  17034. return this.finishNode(node, "ArrayPattern")
  17035. case types$1.braceL:
  17036. return this.parseObj(true)
  17037. }
  17038. }
  17039. return this.parseIdent()
  17040. };
  17041. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  17042. var elts = [], first = true;
  17043. while (!this.eat(close)) {
  17044. if (first) { first = false; }
  17045. else { this.expect(types$1.comma); }
  17046. if (allowEmpty && this.type === types$1.comma) {
  17047. elts.push(null);
  17048. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  17049. break
  17050. } else if (this.type === types$1.ellipsis) {
  17051. var rest = this.parseRestBinding();
  17052. this.parseBindingListItem(rest);
  17053. elts.push(rest);
  17054. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17055. this.expect(close);
  17056. break
  17057. } else {
  17058. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  17059. this.parseBindingListItem(elem);
  17060. elts.push(elem);
  17061. }
  17062. }
  17063. return elts
  17064. };
  17065. pp$7.parseBindingListItem = function(param) {
  17066. return param
  17067. };
  17068. // Parses assignment pattern around given atom if possible.
  17069. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  17070. left = left || this.parseBindingAtom();
  17071. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  17072. var node = this.startNodeAt(startPos, startLoc);
  17073. node.left = left;
  17074. node.right = this.parseMaybeAssign();
  17075. return this.finishNode(node, "AssignmentPattern")
  17076. };
  17077. // The following three functions all verify that a node is an lvalue —
  17078. // something that can be bound, or assigned to. In order to do so, they perform
  17079. // a variety of checks:
  17080. //
  17081. // - Check that none of the bound/assigned-to identifiers are reserved words.
  17082. // - Record name declarations for bindings in the appropriate scope.
  17083. // - Check duplicate argument names, if checkClashes is set.
  17084. //
  17085. // If a complex binding pattern is encountered (e.g., object and array
  17086. // destructuring), the entire pattern is recursively checked.
  17087. //
  17088. // There are three versions of checkLVal*() appropriate for different
  17089. // circumstances:
  17090. //
  17091. // - checkLValSimple() shall be used if the syntactic construct supports
  17092. // nothing other than identifiers and member expressions. Parenthesized
  17093. // expressions are also correctly handled. This is generally appropriate for
  17094. // constructs for which the spec says
  17095. //
  17096. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  17097. // > simple.
  17098. //
  17099. // It is also appropriate for checking if an identifier is valid and not
  17100. // defined elsewhere, like import declarations or function/class identifiers.
  17101. //
  17102. // Examples where this is used include:
  17103. // a += …;
  17104. // import a from '…';
  17105. // where a is the node to be checked.
  17106. //
  17107. // - checkLValPattern() shall be used if the syntactic construct supports
  17108. // anything checkLValSimple() supports, as well as object and array
  17109. // destructuring patterns. This is generally appropriate for constructs for
  17110. // which the spec says
  17111. //
  17112. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  17113. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  17114. // > simple.
  17115. //
  17116. // Examples where this is used include:
  17117. // (a = …);
  17118. // const a = …;
  17119. // try { … } catch (a) { … }
  17120. // where a is the node to be checked.
  17121. //
  17122. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  17123. // anything checkLValPattern() supports, as well as default assignment
  17124. // patterns, rest elements, and other constructs that may appear within an
  17125. // object or array destructuring pattern.
  17126. //
  17127. // As a special case, function parameters also use checkLValInnerPattern(),
  17128. // as they also support defaults and rest constructs.
  17129. //
  17130. // These functions deliberately support both assignment and binding constructs,
  17131. // as the logic for both is exceedingly similar. If the node is the target of
  17132. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  17133. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  17134. // BIND_LEXICAL.
  17135. //
  17136. // If the function is called with a non-BIND_NONE bindingType, then
  17137. // additionally a checkClashes object may be specified to allow checking for
  17138. // duplicate argument names. checkClashes is ignored if the provided construct
  17139. // is an assignment (i.e., bindingType is BIND_NONE).
  17140. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  17141. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17142. var isBind = bindingType !== BIND_NONE;
  17143. switch (expr.type) {
  17144. case "Identifier":
  17145. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  17146. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  17147. if (isBind) {
  17148. if (bindingType === BIND_LEXICAL && expr.name === "let")
  17149. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  17150. if (checkClashes) {
  17151. if (hasOwn(checkClashes, expr.name))
  17152. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  17153. checkClashes[expr.name] = true;
  17154. }
  17155. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  17156. }
  17157. break
  17158. case "ChainExpression":
  17159. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  17160. break
  17161. case "MemberExpression":
  17162. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  17163. break
  17164. case "ParenthesizedExpression":
  17165. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  17166. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  17167. default:
  17168. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  17169. }
  17170. };
  17171. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  17172. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17173. switch (expr.type) {
  17174. case "ObjectPattern":
  17175. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  17176. var prop = list[i];
  17177. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  17178. }
  17179. break
  17180. case "ArrayPattern":
  17181. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  17182. var elem = list$1[i$1];
  17183. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  17184. }
  17185. break
  17186. default:
  17187. this.checkLValSimple(expr, bindingType, checkClashes);
  17188. }
  17189. };
  17190. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  17191. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  17192. switch (expr.type) {
  17193. case "Property":
  17194. // AssignmentProperty has type === "Property"
  17195. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  17196. break
  17197. case "AssignmentPattern":
  17198. this.checkLValPattern(expr.left, bindingType, checkClashes);
  17199. break
  17200. case "RestElement":
  17201. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  17202. break
  17203. default:
  17204. this.checkLValPattern(expr, bindingType, checkClashes);
  17205. }
  17206. };
  17207. // The algorithm used to determine whether a regexp can appear at a
  17208. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  17209. this.token = token;
  17210. this.isExpr = !!isExpr;
  17211. this.preserveSpace = !!preserveSpace;
  17212. this.override = override;
  17213. this.generator = !!generator;
  17214. };
  17215. var types = {
  17216. b_stat: new TokContext("{", false),
  17217. b_expr: new TokContext("{", true),
  17218. b_tmpl: new TokContext("${", false),
  17219. p_stat: new TokContext("(", false),
  17220. p_expr: new TokContext("(", true),
  17221. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  17222. f_stat: new TokContext("function", false),
  17223. f_expr: new TokContext("function", true),
  17224. f_expr_gen: new TokContext("function", true, false, null, true),
  17225. f_gen: new TokContext("function", false, false, null, true)
  17226. };
  17227. var pp$6 = Parser.prototype;
  17228. pp$6.initialContext = function() {
  17229. return [types.b_stat]
  17230. };
  17231. pp$6.curContext = function() {
  17232. return this.context[this.context.length - 1]
  17233. };
  17234. pp$6.braceIsBlock = function(prevType) {
  17235. var parent = this.curContext();
  17236. if (parent === types.f_expr || parent === types.f_stat)
  17237. { return true }
  17238. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  17239. { return !parent.isExpr }
  17240. // The check for `tt.name && exprAllowed` detects whether we are
  17241. // after a `yield` or `of` construct. See the `updateContext` for
  17242. // `tt.name`.
  17243. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  17244. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  17245. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  17246. { return true }
  17247. if (prevType === types$1.braceL)
  17248. { return parent === types.b_stat }
  17249. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  17250. { return false }
  17251. return !this.exprAllowed
  17252. };
  17253. pp$6.inGeneratorContext = function() {
  17254. for (var i = this.context.length - 1; i >= 1; i--) {
  17255. var context = this.context[i];
  17256. if (context.token === "function")
  17257. { return context.generator }
  17258. }
  17259. return false
  17260. };
  17261. pp$6.updateContext = function(prevType) {
  17262. var update, type = this.type;
  17263. if (type.keyword && prevType === types$1.dot)
  17264. { this.exprAllowed = false; }
  17265. else if (update = type.updateContext)
  17266. { update.call(this, prevType); }
  17267. else
  17268. { this.exprAllowed = type.beforeExpr; }
  17269. };
  17270. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  17271. pp$6.overrideContext = function(tokenCtx) {
  17272. if (this.curContext() !== tokenCtx) {
  17273. this.context[this.context.length - 1] = tokenCtx;
  17274. }
  17275. };
  17276. // Token-specific context update code
  17277. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  17278. if (this.context.length === 1) {
  17279. this.exprAllowed = true;
  17280. return
  17281. }
  17282. var out = this.context.pop();
  17283. if (out === types.b_stat && this.curContext().token === "function") {
  17284. out = this.context.pop();
  17285. }
  17286. this.exprAllowed = !out.isExpr;
  17287. };
  17288. types$1.braceL.updateContext = function(prevType) {
  17289. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  17290. this.exprAllowed = true;
  17291. };
  17292. types$1.dollarBraceL.updateContext = function() {
  17293. this.context.push(types.b_tmpl);
  17294. this.exprAllowed = true;
  17295. };
  17296. types$1.parenL.updateContext = function(prevType) {
  17297. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  17298. this.context.push(statementParens ? types.p_stat : types.p_expr);
  17299. this.exprAllowed = true;
  17300. };
  17301. types$1.incDec.updateContext = function() {
  17302. // tokExprAllowed stays unchanged
  17303. };
  17304. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  17305. if (prevType.beforeExpr && prevType !== types$1._else &&
  17306. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  17307. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  17308. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  17309. { this.context.push(types.f_expr); }
  17310. else
  17311. { this.context.push(types.f_stat); }
  17312. this.exprAllowed = false;
  17313. };
  17314. types$1.backQuote.updateContext = function() {
  17315. if (this.curContext() === types.q_tmpl)
  17316. { this.context.pop(); }
  17317. else
  17318. { this.context.push(types.q_tmpl); }
  17319. this.exprAllowed = false;
  17320. };
  17321. types$1.star.updateContext = function(prevType) {
  17322. if (prevType === types$1._function) {
  17323. var index = this.context.length - 1;
  17324. if (this.context[index] === types.f_expr)
  17325. { this.context[index] = types.f_expr_gen; }
  17326. else
  17327. { this.context[index] = types.f_gen; }
  17328. }
  17329. this.exprAllowed = true;
  17330. };
  17331. types$1.name.updateContext = function(prevType) {
  17332. var allowed = false;
  17333. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  17334. if (this.value === "of" && !this.exprAllowed ||
  17335. this.value === "yield" && this.inGeneratorContext())
  17336. { allowed = true; }
  17337. }
  17338. this.exprAllowed = allowed;
  17339. };
  17340. // A recursive descent parser operates by defining functions for all
  17341. var pp$5 = Parser.prototype;
  17342. // Check if property name clashes with already added.
  17343. // Object/class getters and setters are not allowed to clash —
  17344. // either with each other or with an init property — and in
  17345. // strict mode, init properties are also not allowed to be repeated.
  17346. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  17347. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  17348. { return }
  17349. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  17350. { return }
  17351. var key = prop.key;
  17352. var name;
  17353. switch (key.type) {
  17354. case "Identifier": name = key.name; break
  17355. case "Literal": name = String(key.value); break
  17356. default: return
  17357. }
  17358. var kind = prop.kind;
  17359. if (this.options.ecmaVersion >= 6) {
  17360. if (name === "__proto__" && kind === "init") {
  17361. if (propHash.proto) {
  17362. if (refDestructuringErrors) {
  17363. if (refDestructuringErrors.doubleProto < 0) {
  17364. refDestructuringErrors.doubleProto = key.start;
  17365. }
  17366. } else {
  17367. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  17368. }
  17369. }
  17370. propHash.proto = true;
  17371. }
  17372. return
  17373. }
  17374. name = "$" + name;
  17375. var other = propHash[name];
  17376. if (other) {
  17377. var redefinition;
  17378. if (kind === "init") {
  17379. redefinition = this.strict && other.init || other.get || other.set;
  17380. } else {
  17381. redefinition = other.init || other[kind];
  17382. }
  17383. if (redefinition)
  17384. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  17385. } else {
  17386. other = propHash[name] = {
  17387. init: false,
  17388. get: false,
  17389. set: false
  17390. };
  17391. }
  17392. other[kind] = true;
  17393. };
  17394. // ### Expression parsing
  17395. // These nest, from the most general expression type at the top to
  17396. // 'atomic', nondivisible expression types at the bottom. Most of
  17397. // the functions will simply let the function(s) below them parse,
  17398. // and, *if* the syntactic construct they handle is present, wrap
  17399. // the AST node that the inner parser gave them in another node.
  17400. // Parse a full expression. The optional arguments are used to
  17401. // forbid the `in` operator (in for loops initalization expressions)
  17402. // and provide reference for storing '=' operator inside shorthand
  17403. // property assignment in contexts where both object expression
  17404. // and object pattern might appear (so it's possible to raise
  17405. // delayed syntax error at correct position).
  17406. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  17407. var startPos = this.start, startLoc = this.startLoc;
  17408. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  17409. if (this.type === types$1.comma) {
  17410. var node = this.startNodeAt(startPos, startLoc);
  17411. node.expressions = [expr];
  17412. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  17413. return this.finishNode(node, "SequenceExpression")
  17414. }
  17415. return expr
  17416. };
  17417. // Parse an assignment expression. This includes applications of
  17418. // operators like `+=`.
  17419. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  17420. if (this.isContextual("yield")) {
  17421. if (this.inGenerator) { return this.parseYield(forInit) }
  17422. // The tokenizer will assume an expression is allowed after
  17423. // `yield`, but this isn't that kind of yield
  17424. else { this.exprAllowed = false; }
  17425. }
  17426. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  17427. if (refDestructuringErrors) {
  17428. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  17429. oldTrailingComma = refDestructuringErrors.trailingComma;
  17430. oldDoubleProto = refDestructuringErrors.doubleProto;
  17431. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  17432. } else {
  17433. refDestructuringErrors = new DestructuringErrors;
  17434. ownDestructuringErrors = true;
  17435. }
  17436. var startPos = this.start, startLoc = this.startLoc;
  17437. if (this.type === types$1.parenL || this.type === types$1.name) {
  17438. this.potentialArrowAt = this.start;
  17439. this.potentialArrowInForAwait = forInit === "await";
  17440. }
  17441. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  17442. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  17443. if (this.type.isAssign) {
  17444. var node = this.startNodeAt(startPos, startLoc);
  17445. node.operator = this.value;
  17446. if (this.type === types$1.eq)
  17447. { left = this.toAssignable(left, false, refDestructuringErrors); }
  17448. if (!ownDestructuringErrors) {
  17449. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  17450. }
  17451. if (refDestructuringErrors.shorthandAssign >= left.start)
  17452. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  17453. if (this.type === types$1.eq)
  17454. { this.checkLValPattern(left); }
  17455. else
  17456. { this.checkLValSimple(left); }
  17457. node.left = left;
  17458. this.next();
  17459. node.right = this.parseMaybeAssign(forInit);
  17460. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  17461. return this.finishNode(node, "AssignmentExpression")
  17462. } else {
  17463. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  17464. }
  17465. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  17466. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  17467. return left
  17468. };
  17469. // Parse a ternary conditional (`?:`) operator.
  17470. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  17471. var startPos = this.start, startLoc = this.startLoc;
  17472. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  17473. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17474. if (this.eat(types$1.question)) {
  17475. var node = this.startNodeAt(startPos, startLoc);
  17476. node.test = expr;
  17477. node.consequent = this.parseMaybeAssign();
  17478. this.expect(types$1.colon);
  17479. node.alternate = this.parseMaybeAssign(forInit);
  17480. return this.finishNode(node, "ConditionalExpression")
  17481. }
  17482. return expr
  17483. };
  17484. // Start the precedence parser.
  17485. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  17486. var startPos = this.start, startLoc = this.startLoc;
  17487. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  17488. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17489. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  17490. };
  17491. // Parse binary operators with the operator precedence parsing
  17492. // algorithm. `left` is the left-hand side of the operator.
  17493. // `minPrec` provides context that allows the function to stop and
  17494. // defer further parser to one of its callers when it encounters an
  17495. // operator that has a lower precedence than the set it is parsing.
  17496. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  17497. var prec = this.type.binop;
  17498. if (prec != null && (!forInit || this.type !== types$1._in)) {
  17499. if (prec > minPrec) {
  17500. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  17501. var coalesce = this.type === types$1.coalesce;
  17502. if (coalesce) {
  17503. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  17504. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  17505. prec = types$1.logicalAND.binop;
  17506. }
  17507. var op = this.value;
  17508. this.next();
  17509. var startPos = this.start, startLoc = this.startLoc;
  17510. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  17511. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  17512. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  17513. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  17514. }
  17515. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  17516. }
  17517. }
  17518. return left
  17519. };
  17520. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  17521. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  17522. var node = this.startNodeAt(startPos, startLoc);
  17523. node.left = left;
  17524. node.operator = op;
  17525. node.right = right;
  17526. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  17527. };
  17528. // Parse unary operators, both prefix and postfix.
  17529. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  17530. var startPos = this.start, startLoc = this.startLoc, expr;
  17531. if (this.isContextual("await") && this.canAwait) {
  17532. expr = this.parseAwait(forInit);
  17533. sawUnary = true;
  17534. } else if (this.type.prefix) {
  17535. var node = this.startNode(), update = this.type === types$1.incDec;
  17536. node.operator = this.value;
  17537. node.prefix = true;
  17538. this.next();
  17539. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  17540. this.checkExpressionErrors(refDestructuringErrors, true);
  17541. if (update) { this.checkLValSimple(node.argument); }
  17542. else if (this.strict && node.operator === "delete" &&
  17543. node.argument.type === "Identifier")
  17544. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  17545. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  17546. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  17547. else { sawUnary = true; }
  17548. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  17549. } else if (!sawUnary && this.type === types$1.privateId) {
  17550. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  17551. expr = this.parsePrivateIdent();
  17552. // only could be private fields in 'in', such as #x in obj
  17553. if (this.type !== types$1._in) { this.unexpected(); }
  17554. } else {
  17555. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  17556. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  17557. while (this.type.postfix && !this.canInsertSemicolon()) {
  17558. var node$1 = this.startNodeAt(startPos, startLoc);
  17559. node$1.operator = this.value;
  17560. node$1.prefix = false;
  17561. node$1.argument = expr;
  17562. this.checkLValSimple(expr);
  17563. this.next();
  17564. expr = this.finishNode(node$1, "UpdateExpression");
  17565. }
  17566. }
  17567. if (!incDec && this.eat(types$1.starstar)) {
  17568. if (sawUnary)
  17569. { this.unexpected(this.lastTokStart); }
  17570. else
  17571. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  17572. } else {
  17573. return expr
  17574. }
  17575. };
  17576. function isPrivateFieldAccess(node) {
  17577. return (
  17578. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  17579. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  17580. )
  17581. }
  17582. // Parse call, dot, and `[]`-subscript expressions.
  17583. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  17584. var startPos = this.start, startLoc = this.startLoc;
  17585. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  17586. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  17587. { return expr }
  17588. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  17589. if (refDestructuringErrors && result.type === "MemberExpression") {
  17590. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  17591. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  17592. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  17593. }
  17594. return result
  17595. };
  17596. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  17597. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  17598. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  17599. this.potentialArrowAt === base.start;
  17600. var optionalChained = false;
  17601. while (true) {
  17602. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  17603. if (element.optional) { optionalChained = true; }
  17604. if (element === base || element.type === "ArrowFunctionExpression") {
  17605. if (optionalChained) {
  17606. var chainNode = this.startNodeAt(startPos, startLoc);
  17607. chainNode.expression = element;
  17608. element = this.finishNode(chainNode, "ChainExpression");
  17609. }
  17610. return element
  17611. }
  17612. base = element;
  17613. }
  17614. };
  17615. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  17616. var optionalSupported = this.options.ecmaVersion >= 11;
  17617. var optional = optionalSupported && this.eat(types$1.questionDot);
  17618. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  17619. var computed = this.eat(types$1.bracketL);
  17620. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  17621. var node = this.startNodeAt(startPos, startLoc);
  17622. node.object = base;
  17623. if (computed) {
  17624. node.property = this.parseExpression();
  17625. this.expect(types$1.bracketR);
  17626. } else if (this.type === types$1.privateId && base.type !== "Super") {
  17627. node.property = this.parsePrivateIdent();
  17628. } else {
  17629. node.property = this.parseIdent(this.options.allowReserved !== "never");
  17630. }
  17631. node.computed = !!computed;
  17632. if (optionalSupported) {
  17633. node.optional = optional;
  17634. }
  17635. base = this.finishNode(node, "MemberExpression");
  17636. } else if (!noCalls && this.eat(types$1.parenL)) {
  17637. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  17638. this.yieldPos = 0;
  17639. this.awaitPos = 0;
  17640. this.awaitIdentPos = 0;
  17641. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  17642. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17643. this.checkPatternErrors(refDestructuringErrors, false);
  17644. this.checkYieldAwaitInDefaultParams();
  17645. if (this.awaitIdentPos > 0)
  17646. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  17647. this.yieldPos = oldYieldPos;
  17648. this.awaitPos = oldAwaitPos;
  17649. this.awaitIdentPos = oldAwaitIdentPos;
  17650. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  17651. }
  17652. this.checkExpressionErrors(refDestructuringErrors, true);
  17653. this.yieldPos = oldYieldPos || this.yieldPos;
  17654. this.awaitPos = oldAwaitPos || this.awaitPos;
  17655. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  17656. var node$1 = this.startNodeAt(startPos, startLoc);
  17657. node$1.callee = base;
  17658. node$1.arguments = exprList;
  17659. if (optionalSupported) {
  17660. node$1.optional = optional;
  17661. }
  17662. base = this.finishNode(node$1, "CallExpression");
  17663. } else if (this.type === types$1.backQuote) {
  17664. if (optional || optionalChained) {
  17665. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  17666. }
  17667. var node$2 = this.startNodeAt(startPos, startLoc);
  17668. node$2.tag = base;
  17669. node$2.quasi = this.parseTemplate({isTagged: true});
  17670. base = this.finishNode(node$2, "TaggedTemplateExpression");
  17671. }
  17672. return base
  17673. };
  17674. // Parse an atomic expression — either a single token that is an
  17675. // expression, an expression started by a keyword like `function` or
  17676. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  17677. // or `{}`.
  17678. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  17679. // If a division operator appears in an expression position, the
  17680. // tokenizer got confused, and we force it to read a regexp instead.
  17681. if (this.type === types$1.slash) { this.readRegexp(); }
  17682. var node, canBeArrow = this.potentialArrowAt === this.start;
  17683. switch (this.type) {
  17684. case types$1._super:
  17685. if (!this.allowSuper)
  17686. { this.raise(this.start, "'super' keyword outside a method"); }
  17687. node = this.startNode();
  17688. this.next();
  17689. if (this.type === types$1.parenL && !this.allowDirectSuper)
  17690. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  17691. // The `super` keyword can appear at below:
  17692. // SuperProperty:
  17693. // super [ Expression ]
  17694. // super . IdentifierName
  17695. // SuperCall:
  17696. // super ( Arguments )
  17697. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  17698. { this.unexpected(); }
  17699. return this.finishNode(node, "Super")
  17700. case types$1._this:
  17701. node = this.startNode();
  17702. this.next();
  17703. return this.finishNode(node, "ThisExpression")
  17704. case types$1.name:
  17705. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  17706. var id = this.parseIdent(false);
  17707. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  17708. this.overrideContext(types.f_expr);
  17709. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  17710. }
  17711. if (canBeArrow && !this.canInsertSemicolon()) {
  17712. if (this.eat(types$1.arrow))
  17713. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  17714. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  17715. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  17716. id = this.parseIdent(false);
  17717. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  17718. { this.unexpected(); }
  17719. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  17720. }
  17721. }
  17722. return id
  17723. case types$1.regexp:
  17724. var value = this.value;
  17725. node = this.parseLiteral(value.value);
  17726. node.regex = {pattern: value.pattern, flags: value.flags};
  17727. return node
  17728. case types$1.num: case types$1.string:
  17729. return this.parseLiteral(this.value)
  17730. case types$1._null: case types$1._true: case types$1._false:
  17731. node = this.startNode();
  17732. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  17733. node.raw = this.type.keyword;
  17734. this.next();
  17735. return this.finishNode(node, "Literal")
  17736. case types$1.parenL:
  17737. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  17738. if (refDestructuringErrors) {
  17739. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  17740. { refDestructuringErrors.parenthesizedAssign = start; }
  17741. if (refDestructuringErrors.parenthesizedBind < 0)
  17742. { refDestructuringErrors.parenthesizedBind = start; }
  17743. }
  17744. return expr
  17745. case types$1.bracketL:
  17746. node = this.startNode();
  17747. this.next();
  17748. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  17749. return this.finishNode(node, "ArrayExpression")
  17750. case types$1.braceL:
  17751. this.overrideContext(types.b_expr);
  17752. return this.parseObj(false, refDestructuringErrors)
  17753. case types$1._function:
  17754. node = this.startNode();
  17755. this.next();
  17756. return this.parseFunction(node, 0)
  17757. case types$1._class:
  17758. return this.parseClass(this.startNode(), false)
  17759. case types$1._new:
  17760. return this.parseNew()
  17761. case types$1.backQuote:
  17762. return this.parseTemplate()
  17763. case types$1._import:
  17764. if (this.options.ecmaVersion >= 11) {
  17765. return this.parseExprImport()
  17766. } else {
  17767. return this.unexpected()
  17768. }
  17769. default:
  17770. this.unexpected();
  17771. }
  17772. };
  17773. pp$5.parseExprImport = function() {
  17774. var node = this.startNode();
  17775. // Consume `import` as an identifier for `import.meta`.
  17776. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  17777. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  17778. var meta = this.parseIdent(true);
  17779. switch (this.type) {
  17780. case types$1.parenL:
  17781. return this.parseDynamicImport(node)
  17782. case types$1.dot:
  17783. node.meta = meta;
  17784. return this.parseImportMeta(node)
  17785. default:
  17786. this.unexpected();
  17787. }
  17788. };
  17789. pp$5.parseDynamicImport = function(node) {
  17790. this.next(); // skip `(`
  17791. // Parse node.source.
  17792. node.source = this.parseMaybeAssign();
  17793. // Verify ending.
  17794. if (!this.eat(types$1.parenR)) {
  17795. var errorPos = this.start;
  17796. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  17797. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  17798. } else {
  17799. this.unexpected(errorPos);
  17800. }
  17801. }
  17802. return this.finishNode(node, "ImportExpression")
  17803. };
  17804. pp$5.parseImportMeta = function(node) {
  17805. this.next(); // skip `.`
  17806. var containsEsc = this.containsEsc;
  17807. node.property = this.parseIdent(true);
  17808. if (node.property.name !== "meta")
  17809. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  17810. if (containsEsc)
  17811. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  17812. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  17813. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  17814. return this.finishNode(node, "MetaProperty")
  17815. };
  17816. pp$5.parseLiteral = function(value) {
  17817. var node = this.startNode();
  17818. node.value = value;
  17819. node.raw = this.input.slice(this.start, this.end);
  17820. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  17821. this.next();
  17822. return this.finishNode(node, "Literal")
  17823. };
  17824. pp$5.parseParenExpression = function() {
  17825. this.expect(types$1.parenL);
  17826. var val = this.parseExpression();
  17827. this.expect(types$1.parenR);
  17828. return val
  17829. };
  17830. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  17831. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  17832. if (this.options.ecmaVersion >= 6) {
  17833. this.next();
  17834. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  17835. var exprList = [], first = true, lastIsComma = false;
  17836. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  17837. this.yieldPos = 0;
  17838. this.awaitPos = 0;
  17839. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  17840. while (this.type !== types$1.parenR) {
  17841. first ? first = false : this.expect(types$1.comma);
  17842. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  17843. lastIsComma = true;
  17844. break
  17845. } else if (this.type === types$1.ellipsis) {
  17846. spreadStart = this.start;
  17847. exprList.push(this.parseParenItem(this.parseRestBinding()));
  17848. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  17849. break
  17850. } else {
  17851. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  17852. }
  17853. }
  17854. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  17855. this.expect(types$1.parenR);
  17856. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  17857. this.checkPatternErrors(refDestructuringErrors, false);
  17858. this.checkYieldAwaitInDefaultParams();
  17859. this.yieldPos = oldYieldPos;
  17860. this.awaitPos = oldAwaitPos;
  17861. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  17862. }
  17863. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  17864. if (spreadStart) { this.unexpected(spreadStart); }
  17865. this.checkExpressionErrors(refDestructuringErrors, true);
  17866. this.yieldPos = oldYieldPos || this.yieldPos;
  17867. this.awaitPos = oldAwaitPos || this.awaitPos;
  17868. if (exprList.length > 1) {
  17869. val = this.startNodeAt(innerStartPos, innerStartLoc);
  17870. val.expressions = exprList;
  17871. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  17872. } else {
  17873. val = exprList[0];
  17874. }
  17875. } else {
  17876. val = this.parseParenExpression();
  17877. }
  17878. if (this.options.preserveParens) {
  17879. var par = this.startNodeAt(startPos, startLoc);
  17880. par.expression = val;
  17881. return this.finishNode(par, "ParenthesizedExpression")
  17882. } else {
  17883. return val
  17884. }
  17885. };
  17886. pp$5.parseParenItem = function(item) {
  17887. return item
  17888. };
  17889. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  17890. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  17891. };
  17892. // New's precedence is slightly tricky. It must allow its argument to
  17893. // be a `[]` or dot subscript expression, but not a call — at least,
  17894. // not without wrapping it in parentheses. Thus, it uses the noCalls
  17895. // argument to parseSubscripts to prevent it from consuming the
  17896. // argument list.
  17897. var empty = [];
  17898. pp$5.parseNew = function() {
  17899. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  17900. var node = this.startNode();
  17901. var meta = this.parseIdent(true);
  17902. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  17903. node.meta = meta;
  17904. var containsEsc = this.containsEsc;
  17905. node.property = this.parseIdent(true);
  17906. if (node.property.name !== "target")
  17907. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  17908. if (containsEsc)
  17909. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  17910. if (!this.allowNewDotTarget)
  17911. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  17912. return this.finishNode(node, "MetaProperty")
  17913. }
  17914. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  17915. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  17916. if (isImport && node.callee.type === "ImportExpression") {
  17917. this.raise(startPos, "Cannot use new with import()");
  17918. }
  17919. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  17920. else { node.arguments = empty; }
  17921. return this.finishNode(node, "NewExpression")
  17922. };
  17923. // Parse template expression.
  17924. pp$5.parseTemplateElement = function(ref) {
  17925. var isTagged = ref.isTagged;
  17926. var elem = this.startNode();
  17927. if (this.type === types$1.invalidTemplate) {
  17928. if (!isTagged) {
  17929. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  17930. }
  17931. elem.value = {
  17932. raw: this.value,
  17933. cooked: null
  17934. };
  17935. } else {
  17936. elem.value = {
  17937. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  17938. cooked: this.value
  17939. };
  17940. }
  17941. this.next();
  17942. elem.tail = this.type === types$1.backQuote;
  17943. return this.finishNode(elem, "TemplateElement")
  17944. };
  17945. pp$5.parseTemplate = function(ref) {
  17946. if ( ref === void 0 ) ref = {};
  17947. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  17948. var node = this.startNode();
  17949. this.next();
  17950. node.expressions = [];
  17951. var curElt = this.parseTemplateElement({isTagged: isTagged});
  17952. node.quasis = [curElt];
  17953. while (!curElt.tail) {
  17954. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  17955. this.expect(types$1.dollarBraceL);
  17956. node.expressions.push(this.parseExpression());
  17957. this.expect(types$1.braceR);
  17958. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  17959. }
  17960. this.next();
  17961. return this.finishNode(node, "TemplateLiteral")
  17962. };
  17963. pp$5.isAsyncProp = function(prop) {
  17964. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  17965. (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)) &&
  17966. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17967. };
  17968. // Parse an object literal or binding pattern.
  17969. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  17970. var node = this.startNode(), first = true, propHash = {};
  17971. node.properties = [];
  17972. this.next();
  17973. while (!this.eat(types$1.braceR)) {
  17974. if (!first) {
  17975. this.expect(types$1.comma);
  17976. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  17977. } else { first = false; }
  17978. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  17979. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  17980. node.properties.push(prop);
  17981. }
  17982. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  17983. };
  17984. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  17985. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  17986. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  17987. if (isPattern) {
  17988. prop.argument = this.parseIdent(false);
  17989. if (this.type === types$1.comma) {
  17990. this.raise(this.start, "Comma is not permitted after the rest element");
  17991. }
  17992. return this.finishNode(prop, "RestElement")
  17993. }
  17994. // To disallow parenthesized identifier via `this.toAssignable()`.
  17995. if (this.type === types$1.parenL && refDestructuringErrors) {
  17996. if (refDestructuringErrors.parenthesizedAssign < 0) {
  17997. refDestructuringErrors.parenthesizedAssign = this.start;
  17998. }
  17999. if (refDestructuringErrors.parenthesizedBind < 0) {
  18000. refDestructuringErrors.parenthesizedBind = this.start;
  18001. }
  18002. }
  18003. // Parse argument.
  18004. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  18005. // To disallow trailing comma via `this.toAssignable()`.
  18006. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  18007. refDestructuringErrors.trailingComma = this.start;
  18008. }
  18009. // Finish
  18010. return this.finishNode(prop, "SpreadElement")
  18011. }
  18012. if (this.options.ecmaVersion >= 6) {
  18013. prop.method = false;
  18014. prop.shorthand = false;
  18015. if (isPattern || refDestructuringErrors) {
  18016. startPos = this.start;
  18017. startLoc = this.startLoc;
  18018. }
  18019. if (!isPattern)
  18020. { isGenerator = this.eat(types$1.star); }
  18021. }
  18022. var containsEsc = this.containsEsc;
  18023. this.parsePropertyName(prop);
  18024. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  18025. isAsync = true;
  18026. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  18027. this.parsePropertyName(prop, refDestructuringErrors);
  18028. } else {
  18029. isAsync = false;
  18030. }
  18031. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  18032. return this.finishNode(prop, "Property")
  18033. };
  18034. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  18035. if ((isGenerator || isAsync) && this.type === types$1.colon)
  18036. { this.unexpected(); }
  18037. if (this.eat(types$1.colon)) {
  18038. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  18039. prop.kind = "init";
  18040. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  18041. if (isPattern) { this.unexpected(); }
  18042. prop.kind = "init";
  18043. prop.method = true;
  18044. prop.value = this.parseMethod(isGenerator, isAsync);
  18045. } else if (!isPattern && !containsEsc &&
  18046. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  18047. (prop.key.name === "get" || prop.key.name === "set") &&
  18048. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  18049. if (isGenerator || isAsync) { this.unexpected(); }
  18050. prop.kind = prop.key.name;
  18051. this.parsePropertyName(prop);
  18052. prop.value = this.parseMethod(false);
  18053. var paramCount = prop.kind === "get" ? 0 : 1;
  18054. if (prop.value.params.length !== paramCount) {
  18055. var start = prop.value.start;
  18056. if (prop.kind === "get")
  18057. { this.raiseRecoverable(start, "getter should have no params"); }
  18058. else
  18059. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  18060. } else {
  18061. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  18062. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  18063. }
  18064. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  18065. if (isGenerator || isAsync) { this.unexpected(); }
  18066. this.checkUnreserved(prop.key);
  18067. if (prop.key.name === "await" && !this.awaitIdentPos)
  18068. { this.awaitIdentPos = startPos; }
  18069. prop.kind = "init";
  18070. if (isPattern) {
  18071. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18072. } else if (this.type === types$1.eq && refDestructuringErrors) {
  18073. if (refDestructuringErrors.shorthandAssign < 0)
  18074. { refDestructuringErrors.shorthandAssign = this.start; }
  18075. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  18076. } else {
  18077. prop.value = this.copyNode(prop.key);
  18078. }
  18079. prop.shorthand = true;
  18080. } else { this.unexpected(); }
  18081. };
  18082. pp$5.parsePropertyName = function(prop) {
  18083. if (this.options.ecmaVersion >= 6) {
  18084. if (this.eat(types$1.bracketL)) {
  18085. prop.computed = true;
  18086. prop.key = this.parseMaybeAssign();
  18087. this.expect(types$1.bracketR);
  18088. return prop.key
  18089. } else {
  18090. prop.computed = false;
  18091. }
  18092. }
  18093. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  18094. };
  18095. // Initialize empty function node.
  18096. pp$5.initFunction = function(node) {
  18097. node.id = null;
  18098. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  18099. if (this.options.ecmaVersion >= 8) { node.async = false; }
  18100. };
  18101. // Parse object or class method.
  18102. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  18103. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18104. this.initFunction(node);
  18105. if (this.options.ecmaVersion >= 6)
  18106. { node.generator = isGenerator; }
  18107. if (this.options.ecmaVersion >= 8)
  18108. { node.async = !!isAsync; }
  18109. this.yieldPos = 0;
  18110. this.awaitPos = 0;
  18111. this.awaitIdentPos = 0;
  18112. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  18113. this.expect(types$1.parenL);
  18114. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18115. this.checkYieldAwaitInDefaultParams();
  18116. this.parseFunctionBody(node, false, true, false);
  18117. this.yieldPos = oldYieldPos;
  18118. this.awaitPos = oldAwaitPos;
  18119. this.awaitIdentPos = oldAwaitIdentPos;
  18120. return this.finishNode(node, "FunctionExpression")
  18121. };
  18122. // Parse arrow function expression with given parameters.
  18123. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  18124. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18125. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  18126. this.initFunction(node);
  18127. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  18128. this.yieldPos = 0;
  18129. this.awaitPos = 0;
  18130. this.awaitIdentPos = 0;
  18131. node.params = this.toAssignableList(params, true);
  18132. this.parseFunctionBody(node, true, false, forInit);
  18133. this.yieldPos = oldYieldPos;
  18134. this.awaitPos = oldAwaitPos;
  18135. this.awaitIdentPos = oldAwaitIdentPos;
  18136. return this.finishNode(node, "ArrowFunctionExpression")
  18137. };
  18138. // Parse function body and check parameters.
  18139. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  18140. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  18141. var oldStrict = this.strict, useStrict = false;
  18142. if (isExpression) {
  18143. node.body = this.parseMaybeAssign(forInit);
  18144. node.expression = true;
  18145. this.checkParams(node, false);
  18146. } else {
  18147. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  18148. if (!oldStrict || nonSimple) {
  18149. useStrict = this.strictDirective(this.end);
  18150. // If this is a strict mode function, verify that argument names
  18151. // are not repeated, and it does not try to bind the words `eval`
  18152. // or `arguments`.
  18153. if (useStrict && nonSimple)
  18154. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  18155. }
  18156. // Start a new scope with regard to labels and the `inFunction`
  18157. // flag (restore them to their old value afterwards).
  18158. var oldLabels = this.labels;
  18159. this.labels = [];
  18160. if (useStrict) { this.strict = true; }
  18161. // Add the params to varDeclaredNames to ensure that an error is thrown
  18162. // if a let/const declaration in the function clashes with one of the params.
  18163. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  18164. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  18165. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  18166. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  18167. node.expression = false;
  18168. this.adaptDirectivePrologue(node.body.body);
  18169. this.labels = oldLabels;
  18170. }
  18171. this.exitScope();
  18172. };
  18173. pp$5.isSimpleParamList = function(params) {
  18174. for (var i = 0, list = params; i < list.length; i += 1)
  18175. {
  18176. var param = list[i];
  18177. if (param.type !== "Identifier") { return false
  18178. } }
  18179. return true
  18180. };
  18181. // Checks function params for various disallowed patterns such as using "eval"
  18182. // or "arguments" and duplicate parameters.
  18183. pp$5.checkParams = function(node, allowDuplicates) {
  18184. var nameHash = Object.create(null);
  18185. for (var i = 0, list = node.params; i < list.length; i += 1)
  18186. {
  18187. var param = list[i];
  18188. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  18189. }
  18190. };
  18191. // Parses a comma-separated list of expressions, and returns them as
  18192. // an array. `close` is the token type that ends the list, and
  18193. // `allowEmpty` can be turned on to allow subsequent commas with
  18194. // nothing in between them to be parsed as `null` (which is needed
  18195. // for array literals).
  18196. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  18197. var elts = [], first = true;
  18198. while (!this.eat(close)) {
  18199. if (!first) {
  18200. this.expect(types$1.comma);
  18201. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  18202. } else { first = false; }
  18203. var elt = (void 0);
  18204. if (allowEmpty && this.type === types$1.comma)
  18205. { elt = null; }
  18206. else if (this.type === types$1.ellipsis) {
  18207. elt = this.parseSpread(refDestructuringErrors);
  18208. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  18209. { refDestructuringErrors.trailingComma = this.start; }
  18210. } else {
  18211. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  18212. }
  18213. elts.push(elt);
  18214. }
  18215. return elts
  18216. };
  18217. pp$5.checkUnreserved = function(ref) {
  18218. var start = ref.start;
  18219. var end = ref.end;
  18220. var name = ref.name;
  18221. if (this.inGenerator && name === "yield")
  18222. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  18223. if (this.inAsync && name === "await")
  18224. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  18225. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  18226. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  18227. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  18228. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  18229. if (this.keywords.test(name))
  18230. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  18231. if (this.options.ecmaVersion < 6 &&
  18232. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  18233. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  18234. if (re.test(name)) {
  18235. if (!this.inAsync && name === "await")
  18236. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  18237. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  18238. }
  18239. };
  18240. // Parse the next token as an identifier. If `liberal` is true (used
  18241. // when parsing properties), it will also convert keywords into
  18242. // identifiers.
  18243. pp$5.parseIdent = function(liberal, isBinding) {
  18244. var node = this.startNode();
  18245. if (this.type === types$1.name) {
  18246. node.name = this.value;
  18247. } else if (this.type.keyword) {
  18248. node.name = this.type.keyword;
  18249. // To fix https://github.com/acornjs/acorn/issues/575
  18250. // `class` and `function` keywords push new context into this.context.
  18251. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  18252. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  18253. if ((node.name === "class" || node.name === "function") &&
  18254. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  18255. this.context.pop();
  18256. }
  18257. } else {
  18258. this.unexpected();
  18259. }
  18260. this.next(!!liberal);
  18261. this.finishNode(node, "Identifier");
  18262. if (!liberal) {
  18263. this.checkUnreserved(node);
  18264. if (node.name === "await" && !this.awaitIdentPos)
  18265. { this.awaitIdentPos = node.start; }
  18266. }
  18267. return node
  18268. };
  18269. pp$5.parsePrivateIdent = function() {
  18270. var node = this.startNode();
  18271. if (this.type === types$1.privateId) {
  18272. node.name = this.value;
  18273. } else {
  18274. this.unexpected();
  18275. }
  18276. this.next();
  18277. this.finishNode(node, "PrivateIdentifier");
  18278. // For validating existence
  18279. if (this.privateNameStack.length === 0) {
  18280. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  18281. } else {
  18282. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  18283. }
  18284. return node
  18285. };
  18286. // Parses yield expression inside generator.
  18287. pp$5.parseYield = function(forInit) {
  18288. if (!this.yieldPos) { this.yieldPos = this.start; }
  18289. var node = this.startNode();
  18290. this.next();
  18291. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  18292. node.delegate = false;
  18293. node.argument = null;
  18294. } else {
  18295. node.delegate = this.eat(types$1.star);
  18296. node.argument = this.parseMaybeAssign(forInit);
  18297. }
  18298. return this.finishNode(node, "YieldExpression")
  18299. };
  18300. pp$5.parseAwait = function(forInit) {
  18301. if (!this.awaitPos) { this.awaitPos = this.start; }
  18302. var node = this.startNode();
  18303. this.next();
  18304. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  18305. return this.finishNode(node, "AwaitExpression")
  18306. };
  18307. var pp$4 = Parser.prototype;
  18308. // This function is used to raise exceptions on parse errors. It
  18309. // takes an offset integer (into the current `input`) to indicate
  18310. // the location of the error, attaches the position to the end
  18311. // of the error message, and then raises a `SyntaxError` with that
  18312. // message.
  18313. pp$4.raise = function(pos, message) {
  18314. var loc = getLineInfo(this.input, pos);
  18315. message += " (" + loc.line + ":" + loc.column + ")";
  18316. var err = new SyntaxError(message);
  18317. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  18318. throw err
  18319. };
  18320. pp$4.raiseRecoverable = pp$4.raise;
  18321. pp$4.curPosition = function() {
  18322. if (this.options.locations) {
  18323. return new Position(this.curLine, this.pos - this.lineStart)
  18324. }
  18325. };
  18326. var pp$3 = Parser.prototype;
  18327. var Scope = function Scope(flags) {
  18328. this.flags = flags;
  18329. // A list of var-declared names in the current lexical scope
  18330. this.var = [];
  18331. // A list of lexically-declared names in the current lexical scope
  18332. this.lexical = [];
  18333. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  18334. this.functions = [];
  18335. // A switch to disallow the identifier reference 'arguments'
  18336. this.inClassFieldInit = false;
  18337. };
  18338. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  18339. pp$3.enterScope = function(flags) {
  18340. this.scopeStack.push(new Scope(flags));
  18341. };
  18342. pp$3.exitScope = function() {
  18343. this.scopeStack.pop();
  18344. };
  18345. // The spec says:
  18346. // > At the top level of a function, or script, function declarations are
  18347. // > treated like var declarations rather than like lexical declarations.
  18348. pp$3.treatFunctionsAsVarInScope = function(scope) {
  18349. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  18350. };
  18351. pp$3.declareName = function(name, bindingType, pos) {
  18352. var redeclared = false;
  18353. if (bindingType === BIND_LEXICAL) {
  18354. var scope = this.currentScope();
  18355. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  18356. scope.lexical.push(name);
  18357. if (this.inModule && (scope.flags & SCOPE_TOP))
  18358. { delete this.undefinedExports[name]; }
  18359. } else if (bindingType === BIND_SIMPLE_CATCH) {
  18360. var scope$1 = this.currentScope();
  18361. scope$1.lexical.push(name);
  18362. } else if (bindingType === BIND_FUNCTION) {
  18363. var scope$2 = this.currentScope();
  18364. if (this.treatFunctionsAsVar)
  18365. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  18366. else
  18367. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  18368. scope$2.functions.push(name);
  18369. } else {
  18370. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  18371. var scope$3 = this.scopeStack[i];
  18372. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  18373. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  18374. redeclared = true;
  18375. break
  18376. }
  18377. scope$3.var.push(name);
  18378. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  18379. { delete this.undefinedExports[name]; }
  18380. if (scope$3.flags & SCOPE_VAR) { break }
  18381. }
  18382. }
  18383. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  18384. };
  18385. pp$3.checkLocalExport = function(id) {
  18386. // scope.functions must be empty as Module code is always strict.
  18387. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  18388. this.scopeStack[0].var.indexOf(id.name) === -1) {
  18389. this.undefinedExports[id.name] = id;
  18390. }
  18391. };
  18392. pp$3.currentScope = function() {
  18393. return this.scopeStack[this.scopeStack.length - 1]
  18394. };
  18395. pp$3.currentVarScope = function() {
  18396. for (var i = this.scopeStack.length - 1;; i--) {
  18397. var scope = this.scopeStack[i];
  18398. if (scope.flags & SCOPE_VAR) { return scope }
  18399. }
  18400. };
  18401. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  18402. pp$3.currentThisScope = function() {
  18403. for (var i = this.scopeStack.length - 1;; i--) {
  18404. var scope = this.scopeStack[i];
  18405. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  18406. }
  18407. };
  18408. var Node = function Node(parser, pos, loc) {
  18409. this.type = "";
  18410. this.start = pos;
  18411. this.end = 0;
  18412. if (parser.options.locations)
  18413. { this.loc = new SourceLocation(parser, loc); }
  18414. if (parser.options.directSourceFile)
  18415. { this.sourceFile = parser.options.directSourceFile; }
  18416. if (parser.options.ranges)
  18417. { this.range = [pos, 0]; }
  18418. };
  18419. // Start an AST node, attaching a start offset.
  18420. var pp$2 = Parser.prototype;
  18421. pp$2.startNode = function() {
  18422. return new Node(this, this.start, this.startLoc)
  18423. };
  18424. pp$2.startNodeAt = function(pos, loc) {
  18425. return new Node(this, pos, loc)
  18426. };
  18427. // Finish an AST node, adding `type` and `end` properties.
  18428. function finishNodeAt(node, type, pos, loc) {
  18429. node.type = type;
  18430. node.end = pos;
  18431. if (this.options.locations)
  18432. { node.loc.end = loc; }
  18433. if (this.options.ranges)
  18434. { node.range[1] = pos; }
  18435. return node
  18436. }
  18437. pp$2.finishNode = function(node, type) {
  18438. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  18439. };
  18440. // Finish node at given position
  18441. pp$2.finishNodeAt = function(node, type, pos, loc) {
  18442. return finishNodeAt.call(this, node, type, pos, loc)
  18443. };
  18444. pp$2.copyNode = function(node) {
  18445. var newNode = new Node(this, node.start, this.startLoc);
  18446. for (var prop in node) { newNode[prop] = node[prop]; }
  18447. return newNode
  18448. };
  18449. // This file contains Unicode properties extracted from the ECMAScript
  18450. // specification. The lists are extracted like so:
  18451. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  18452. // #table-binary-unicode-properties
  18453. 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";
  18454. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  18455. var ecma11BinaryProperties = ecma10BinaryProperties;
  18456. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  18457. var ecma13BinaryProperties = ecma12BinaryProperties;
  18458. var unicodeBinaryProperties = {
  18459. 9: ecma9BinaryProperties,
  18460. 10: ecma10BinaryProperties,
  18461. 11: ecma11BinaryProperties,
  18462. 12: ecma12BinaryProperties,
  18463. 13: ecma13BinaryProperties
  18464. };
  18465. // #table-unicode-general-category-values
  18466. 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";
  18467. // #table-unicode-script-values
  18468. 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";
  18469. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  18470. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  18471. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  18472. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  18473. var unicodeScriptValues = {
  18474. 9: ecma9ScriptValues,
  18475. 10: ecma10ScriptValues,
  18476. 11: ecma11ScriptValues,
  18477. 12: ecma12ScriptValues,
  18478. 13: ecma13ScriptValues
  18479. };
  18480. var data = {};
  18481. function buildUnicodeData(ecmaVersion) {
  18482. var d = data[ecmaVersion] = {
  18483. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  18484. nonBinary: {
  18485. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  18486. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  18487. }
  18488. };
  18489. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  18490. d.nonBinary.gc = d.nonBinary.General_Category;
  18491. d.nonBinary.sc = d.nonBinary.Script;
  18492. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  18493. }
  18494. for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) {
  18495. var ecmaVersion = list[i];
  18496. buildUnicodeData(ecmaVersion);
  18497. }
  18498. var pp$1 = Parser.prototype;
  18499. var RegExpValidationState = function RegExpValidationState(parser) {
  18500. this.parser = parser;
  18501. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  18502. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  18503. this.source = "";
  18504. this.flags = "";
  18505. this.start = 0;
  18506. this.switchU = false;
  18507. this.switchN = false;
  18508. this.pos = 0;
  18509. this.lastIntValue = 0;
  18510. this.lastStringValue = "";
  18511. this.lastAssertionIsQuantifiable = false;
  18512. this.numCapturingParens = 0;
  18513. this.maxBackReference = 0;
  18514. this.groupNames = [];
  18515. this.backReferenceNames = [];
  18516. };
  18517. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  18518. var unicode = flags.indexOf("u") !== -1;
  18519. this.start = start | 0;
  18520. this.source = pattern + "";
  18521. this.flags = flags;
  18522. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  18523. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  18524. };
  18525. RegExpValidationState.prototype.raise = function raise (message) {
  18526. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  18527. };
  18528. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  18529. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  18530. RegExpValidationState.prototype.at = function at (i, forceU) {
  18531. if ( forceU === void 0 ) forceU = false;
  18532. var s = this.source;
  18533. var l = s.length;
  18534. if (i >= l) {
  18535. return -1
  18536. }
  18537. var c = s.charCodeAt(i);
  18538. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  18539. return c
  18540. }
  18541. var next = s.charCodeAt(i + 1);
  18542. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  18543. };
  18544. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  18545. if ( forceU === void 0 ) forceU = false;
  18546. var s = this.source;
  18547. var l = s.length;
  18548. if (i >= l) {
  18549. return l
  18550. }
  18551. var c = s.charCodeAt(i), next;
  18552. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  18553. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  18554. return i + 1
  18555. }
  18556. return i + 2
  18557. };
  18558. RegExpValidationState.prototype.current = function current (forceU) {
  18559. if ( forceU === void 0 ) forceU = false;
  18560. return this.at(this.pos, forceU)
  18561. };
  18562. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  18563. if ( forceU === void 0 ) forceU = false;
  18564. return this.at(this.nextIndex(this.pos, forceU), forceU)
  18565. };
  18566. RegExpValidationState.prototype.advance = function advance (forceU) {
  18567. if ( forceU === void 0 ) forceU = false;
  18568. this.pos = this.nextIndex(this.pos, forceU);
  18569. };
  18570. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  18571. if ( forceU === void 0 ) forceU = false;
  18572. if (this.current(forceU) === ch) {
  18573. this.advance(forceU);
  18574. return true
  18575. }
  18576. return false
  18577. };
  18578. /**
  18579. * Validate the flags part of a given RegExpLiteral.
  18580. *
  18581. * @param {RegExpValidationState} state The state to validate RegExp.
  18582. * @returns {void}
  18583. */
  18584. pp$1.validateRegExpFlags = function(state) {
  18585. var validFlags = state.validFlags;
  18586. var flags = state.flags;
  18587. for (var i = 0; i < flags.length; i++) {
  18588. var flag = flags.charAt(i);
  18589. if (validFlags.indexOf(flag) === -1) {
  18590. this.raise(state.start, "Invalid regular expression flag");
  18591. }
  18592. if (flags.indexOf(flag, i + 1) > -1) {
  18593. this.raise(state.start, "Duplicate regular expression flag");
  18594. }
  18595. }
  18596. };
  18597. /**
  18598. * Validate the pattern part of a given RegExpLiteral.
  18599. *
  18600. * @param {RegExpValidationState} state The state to validate RegExp.
  18601. * @returns {void}
  18602. */
  18603. pp$1.validateRegExpPattern = function(state) {
  18604. this.regexp_pattern(state);
  18605. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  18606. // parsing contains a |GroupName|, reparse with the goal symbol
  18607. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  18608. // exception if _P_ did not conform to the grammar, if any elements of _P_
  18609. // were not matched by the parse, or if any Early Error conditions exist.
  18610. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  18611. state.switchN = true;
  18612. this.regexp_pattern(state);
  18613. }
  18614. };
  18615. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  18616. pp$1.regexp_pattern = function(state) {
  18617. state.pos = 0;
  18618. state.lastIntValue = 0;
  18619. state.lastStringValue = "";
  18620. state.lastAssertionIsQuantifiable = false;
  18621. state.numCapturingParens = 0;
  18622. state.maxBackReference = 0;
  18623. state.groupNames.length = 0;
  18624. state.backReferenceNames.length = 0;
  18625. this.regexp_disjunction(state);
  18626. if (state.pos !== state.source.length) {
  18627. // Make the same messages as V8.
  18628. if (state.eat(0x29 /* ) */)) {
  18629. state.raise("Unmatched ')'");
  18630. }
  18631. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  18632. state.raise("Lone quantifier brackets");
  18633. }
  18634. }
  18635. if (state.maxBackReference > state.numCapturingParens) {
  18636. state.raise("Invalid escape");
  18637. }
  18638. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  18639. var name = list[i];
  18640. if (state.groupNames.indexOf(name) === -1) {
  18641. state.raise("Invalid named capture referenced");
  18642. }
  18643. }
  18644. };
  18645. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  18646. pp$1.regexp_disjunction = function(state) {
  18647. this.regexp_alternative(state);
  18648. while (state.eat(0x7C /* | */)) {
  18649. this.regexp_alternative(state);
  18650. }
  18651. // Make the same message as V8.
  18652. if (this.regexp_eatQuantifier(state, true)) {
  18653. state.raise("Nothing to repeat");
  18654. }
  18655. if (state.eat(0x7B /* { */)) {
  18656. state.raise("Lone quantifier brackets");
  18657. }
  18658. };
  18659. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  18660. pp$1.regexp_alternative = function(state) {
  18661. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  18662. { }
  18663. };
  18664. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  18665. pp$1.regexp_eatTerm = function(state) {
  18666. if (this.regexp_eatAssertion(state)) {
  18667. // Handle `QuantifiableAssertion Quantifier` alternative.
  18668. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  18669. // is a QuantifiableAssertion.
  18670. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  18671. // Make the same message as V8.
  18672. if (state.switchU) {
  18673. state.raise("Invalid quantifier");
  18674. }
  18675. }
  18676. return true
  18677. }
  18678. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  18679. this.regexp_eatQuantifier(state);
  18680. return true
  18681. }
  18682. return false
  18683. };
  18684. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  18685. pp$1.regexp_eatAssertion = function(state) {
  18686. var start = state.pos;
  18687. state.lastAssertionIsQuantifiable = false;
  18688. // ^, $
  18689. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  18690. return true
  18691. }
  18692. // \b \B
  18693. if (state.eat(0x5C /* \ */)) {
  18694. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  18695. return true
  18696. }
  18697. state.pos = start;
  18698. }
  18699. // Lookahead / Lookbehind
  18700. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  18701. var lookbehind = false;
  18702. if (this.options.ecmaVersion >= 9) {
  18703. lookbehind = state.eat(0x3C /* < */);
  18704. }
  18705. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  18706. this.regexp_disjunction(state);
  18707. if (!state.eat(0x29 /* ) */)) {
  18708. state.raise("Unterminated group");
  18709. }
  18710. state.lastAssertionIsQuantifiable = !lookbehind;
  18711. return true
  18712. }
  18713. }
  18714. state.pos = start;
  18715. return false
  18716. };
  18717. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  18718. pp$1.regexp_eatQuantifier = function(state, noError) {
  18719. if ( noError === void 0 ) noError = false;
  18720. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  18721. state.eat(0x3F /* ? */);
  18722. return true
  18723. }
  18724. return false
  18725. };
  18726. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  18727. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  18728. return (
  18729. state.eat(0x2A /* * */) ||
  18730. state.eat(0x2B /* + */) ||
  18731. state.eat(0x3F /* ? */) ||
  18732. this.regexp_eatBracedQuantifier(state, noError)
  18733. )
  18734. };
  18735. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  18736. var start = state.pos;
  18737. if (state.eat(0x7B /* { */)) {
  18738. var min = 0, max = -1;
  18739. if (this.regexp_eatDecimalDigits(state)) {
  18740. min = state.lastIntValue;
  18741. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  18742. max = state.lastIntValue;
  18743. }
  18744. if (state.eat(0x7D /* } */)) {
  18745. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  18746. if (max !== -1 && max < min && !noError) {
  18747. state.raise("numbers out of order in {} quantifier");
  18748. }
  18749. return true
  18750. }
  18751. }
  18752. if (state.switchU && !noError) {
  18753. state.raise("Incomplete quantifier");
  18754. }
  18755. state.pos = start;
  18756. }
  18757. return false
  18758. };
  18759. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  18760. pp$1.regexp_eatAtom = function(state) {
  18761. return (
  18762. this.regexp_eatPatternCharacters(state) ||
  18763. state.eat(0x2E /* . */) ||
  18764. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18765. this.regexp_eatCharacterClass(state) ||
  18766. this.regexp_eatUncapturingGroup(state) ||
  18767. this.regexp_eatCapturingGroup(state)
  18768. )
  18769. };
  18770. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  18771. var start = state.pos;
  18772. if (state.eat(0x5C /* \ */)) {
  18773. if (this.regexp_eatAtomEscape(state)) {
  18774. return true
  18775. }
  18776. state.pos = start;
  18777. }
  18778. return false
  18779. };
  18780. pp$1.regexp_eatUncapturingGroup = function(state) {
  18781. var start = state.pos;
  18782. if (state.eat(0x28 /* ( */)) {
  18783. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  18784. this.regexp_disjunction(state);
  18785. if (state.eat(0x29 /* ) */)) {
  18786. return true
  18787. }
  18788. state.raise("Unterminated group");
  18789. }
  18790. state.pos = start;
  18791. }
  18792. return false
  18793. };
  18794. pp$1.regexp_eatCapturingGroup = function(state) {
  18795. if (state.eat(0x28 /* ( */)) {
  18796. if (this.options.ecmaVersion >= 9) {
  18797. this.regexp_groupSpecifier(state);
  18798. } else if (state.current() === 0x3F /* ? */) {
  18799. state.raise("Invalid group");
  18800. }
  18801. this.regexp_disjunction(state);
  18802. if (state.eat(0x29 /* ) */)) {
  18803. state.numCapturingParens += 1;
  18804. return true
  18805. }
  18806. state.raise("Unterminated group");
  18807. }
  18808. return false
  18809. };
  18810. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  18811. pp$1.regexp_eatExtendedAtom = function(state) {
  18812. return (
  18813. state.eat(0x2E /* . */) ||
  18814. this.regexp_eatReverseSolidusAtomEscape(state) ||
  18815. this.regexp_eatCharacterClass(state) ||
  18816. this.regexp_eatUncapturingGroup(state) ||
  18817. this.regexp_eatCapturingGroup(state) ||
  18818. this.regexp_eatInvalidBracedQuantifier(state) ||
  18819. this.regexp_eatExtendedPatternCharacter(state)
  18820. )
  18821. };
  18822. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  18823. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  18824. if (this.regexp_eatBracedQuantifier(state, true)) {
  18825. state.raise("Nothing to repeat");
  18826. }
  18827. return false
  18828. };
  18829. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  18830. pp$1.regexp_eatSyntaxCharacter = function(state) {
  18831. var ch = state.current();
  18832. if (isSyntaxCharacter(ch)) {
  18833. state.lastIntValue = ch;
  18834. state.advance();
  18835. return true
  18836. }
  18837. return false
  18838. };
  18839. function isSyntaxCharacter(ch) {
  18840. return (
  18841. ch === 0x24 /* $ */ ||
  18842. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  18843. ch === 0x2E /* . */ ||
  18844. ch === 0x3F /* ? */ ||
  18845. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  18846. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  18847. )
  18848. }
  18849. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  18850. // But eat eager.
  18851. pp$1.regexp_eatPatternCharacters = function(state) {
  18852. var start = state.pos;
  18853. var ch = 0;
  18854. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  18855. state.advance();
  18856. }
  18857. return state.pos !== start
  18858. };
  18859. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  18860. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  18861. var ch = state.current();
  18862. if (
  18863. ch !== -1 &&
  18864. ch !== 0x24 /* $ */ &&
  18865. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  18866. ch !== 0x2E /* . */ &&
  18867. ch !== 0x3F /* ? */ &&
  18868. ch !== 0x5B /* [ */ &&
  18869. ch !== 0x5E /* ^ */ &&
  18870. ch !== 0x7C /* | */
  18871. ) {
  18872. state.advance();
  18873. return true
  18874. }
  18875. return false
  18876. };
  18877. // GroupSpecifier ::
  18878. // [empty]
  18879. // `?` GroupName
  18880. pp$1.regexp_groupSpecifier = function(state) {
  18881. if (state.eat(0x3F /* ? */)) {
  18882. if (this.regexp_eatGroupName(state)) {
  18883. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  18884. state.raise("Duplicate capture group name");
  18885. }
  18886. state.groupNames.push(state.lastStringValue);
  18887. return
  18888. }
  18889. state.raise("Invalid group");
  18890. }
  18891. };
  18892. // GroupName ::
  18893. // `<` RegExpIdentifierName `>`
  18894. // Note: this updates `state.lastStringValue` property with the eaten name.
  18895. pp$1.regexp_eatGroupName = function(state) {
  18896. state.lastStringValue = "";
  18897. if (state.eat(0x3C /* < */)) {
  18898. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  18899. return true
  18900. }
  18901. state.raise("Invalid capture group name");
  18902. }
  18903. return false
  18904. };
  18905. // RegExpIdentifierName ::
  18906. // RegExpIdentifierStart
  18907. // RegExpIdentifierName RegExpIdentifierPart
  18908. // Note: this updates `state.lastStringValue` property with the eaten name.
  18909. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  18910. state.lastStringValue = "";
  18911. if (this.regexp_eatRegExpIdentifierStart(state)) {
  18912. state.lastStringValue += codePointToString(state.lastIntValue);
  18913. while (this.regexp_eatRegExpIdentifierPart(state)) {
  18914. state.lastStringValue += codePointToString(state.lastIntValue);
  18915. }
  18916. return true
  18917. }
  18918. return false
  18919. };
  18920. // RegExpIdentifierStart ::
  18921. // UnicodeIDStart
  18922. // `$`
  18923. // `_`
  18924. // `\` RegExpUnicodeEscapeSequence[+U]
  18925. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  18926. var start = state.pos;
  18927. var forceU = this.options.ecmaVersion >= 11;
  18928. var ch = state.current(forceU);
  18929. state.advance(forceU);
  18930. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18931. ch = state.lastIntValue;
  18932. }
  18933. if (isRegExpIdentifierStart(ch)) {
  18934. state.lastIntValue = ch;
  18935. return true
  18936. }
  18937. state.pos = start;
  18938. return false
  18939. };
  18940. function isRegExpIdentifierStart(ch) {
  18941. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  18942. }
  18943. // RegExpIdentifierPart ::
  18944. // UnicodeIDContinue
  18945. // `$`
  18946. // `_`
  18947. // `\` RegExpUnicodeEscapeSequence[+U]
  18948. // <ZWNJ>
  18949. // <ZWJ>
  18950. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  18951. var start = state.pos;
  18952. var forceU = this.options.ecmaVersion >= 11;
  18953. var ch = state.current(forceU);
  18954. state.advance(forceU);
  18955. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  18956. ch = state.lastIntValue;
  18957. }
  18958. if (isRegExpIdentifierPart(ch)) {
  18959. state.lastIntValue = ch;
  18960. return true
  18961. }
  18962. state.pos = start;
  18963. return false
  18964. };
  18965. function isRegExpIdentifierPart(ch) {
  18966. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  18967. }
  18968. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  18969. pp$1.regexp_eatAtomEscape = function(state) {
  18970. if (
  18971. this.regexp_eatBackReference(state) ||
  18972. this.regexp_eatCharacterClassEscape(state) ||
  18973. this.regexp_eatCharacterEscape(state) ||
  18974. (state.switchN && this.regexp_eatKGroupName(state))
  18975. ) {
  18976. return true
  18977. }
  18978. if (state.switchU) {
  18979. // Make the same message as V8.
  18980. if (state.current() === 0x63 /* c */) {
  18981. state.raise("Invalid unicode escape");
  18982. }
  18983. state.raise("Invalid escape");
  18984. }
  18985. return false
  18986. };
  18987. pp$1.regexp_eatBackReference = function(state) {
  18988. var start = state.pos;
  18989. if (this.regexp_eatDecimalEscape(state)) {
  18990. var n = state.lastIntValue;
  18991. if (state.switchU) {
  18992. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  18993. if (n > state.maxBackReference) {
  18994. state.maxBackReference = n;
  18995. }
  18996. return true
  18997. }
  18998. if (n <= state.numCapturingParens) {
  18999. return true
  19000. }
  19001. state.pos = start;
  19002. }
  19003. return false
  19004. };
  19005. pp$1.regexp_eatKGroupName = function(state) {
  19006. if (state.eat(0x6B /* k */)) {
  19007. if (this.regexp_eatGroupName(state)) {
  19008. state.backReferenceNames.push(state.lastStringValue);
  19009. return true
  19010. }
  19011. state.raise("Invalid named reference");
  19012. }
  19013. return false
  19014. };
  19015. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  19016. pp$1.regexp_eatCharacterEscape = function(state) {
  19017. return (
  19018. this.regexp_eatControlEscape(state) ||
  19019. this.regexp_eatCControlLetter(state) ||
  19020. this.regexp_eatZero(state) ||
  19021. this.regexp_eatHexEscapeSequence(state) ||
  19022. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  19023. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  19024. this.regexp_eatIdentityEscape(state)
  19025. )
  19026. };
  19027. pp$1.regexp_eatCControlLetter = function(state) {
  19028. var start = state.pos;
  19029. if (state.eat(0x63 /* c */)) {
  19030. if (this.regexp_eatControlLetter(state)) {
  19031. return true
  19032. }
  19033. state.pos = start;
  19034. }
  19035. return false
  19036. };
  19037. pp$1.regexp_eatZero = function(state) {
  19038. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  19039. state.lastIntValue = 0;
  19040. state.advance();
  19041. return true
  19042. }
  19043. return false
  19044. };
  19045. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  19046. pp$1.regexp_eatControlEscape = function(state) {
  19047. var ch = state.current();
  19048. if (ch === 0x74 /* t */) {
  19049. state.lastIntValue = 0x09; /* \t */
  19050. state.advance();
  19051. return true
  19052. }
  19053. if (ch === 0x6E /* n */) {
  19054. state.lastIntValue = 0x0A; /* \n */
  19055. state.advance();
  19056. return true
  19057. }
  19058. if (ch === 0x76 /* v */) {
  19059. state.lastIntValue = 0x0B; /* \v */
  19060. state.advance();
  19061. return true
  19062. }
  19063. if (ch === 0x66 /* f */) {
  19064. state.lastIntValue = 0x0C; /* \f */
  19065. state.advance();
  19066. return true
  19067. }
  19068. if (ch === 0x72 /* r */) {
  19069. state.lastIntValue = 0x0D; /* \r */
  19070. state.advance();
  19071. return true
  19072. }
  19073. return false
  19074. };
  19075. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  19076. pp$1.regexp_eatControlLetter = function(state) {
  19077. var ch = state.current();
  19078. if (isControlLetter(ch)) {
  19079. state.lastIntValue = ch % 0x20;
  19080. state.advance();
  19081. return true
  19082. }
  19083. return false
  19084. };
  19085. function isControlLetter(ch) {
  19086. return (
  19087. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  19088. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  19089. )
  19090. }
  19091. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  19092. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  19093. if ( forceU === void 0 ) forceU = false;
  19094. var start = state.pos;
  19095. var switchU = forceU || state.switchU;
  19096. if (state.eat(0x75 /* u */)) {
  19097. if (this.regexp_eatFixedHexDigits(state, 4)) {
  19098. var lead = state.lastIntValue;
  19099. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  19100. var leadSurrogateEnd = state.pos;
  19101. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  19102. var trail = state.lastIntValue;
  19103. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  19104. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  19105. return true
  19106. }
  19107. }
  19108. state.pos = leadSurrogateEnd;
  19109. state.lastIntValue = lead;
  19110. }
  19111. return true
  19112. }
  19113. if (
  19114. switchU &&
  19115. state.eat(0x7B /* { */) &&
  19116. this.regexp_eatHexDigits(state) &&
  19117. state.eat(0x7D /* } */) &&
  19118. isValidUnicode(state.lastIntValue)
  19119. ) {
  19120. return true
  19121. }
  19122. if (switchU) {
  19123. state.raise("Invalid unicode escape");
  19124. }
  19125. state.pos = start;
  19126. }
  19127. return false
  19128. };
  19129. function isValidUnicode(ch) {
  19130. return ch >= 0 && ch <= 0x10FFFF
  19131. }
  19132. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  19133. pp$1.regexp_eatIdentityEscape = function(state) {
  19134. if (state.switchU) {
  19135. if (this.regexp_eatSyntaxCharacter(state)) {
  19136. return true
  19137. }
  19138. if (state.eat(0x2F /* / */)) {
  19139. state.lastIntValue = 0x2F; /* / */
  19140. return true
  19141. }
  19142. return false
  19143. }
  19144. var ch = state.current();
  19145. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  19146. state.lastIntValue = ch;
  19147. state.advance();
  19148. return true
  19149. }
  19150. return false
  19151. };
  19152. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  19153. pp$1.regexp_eatDecimalEscape = function(state) {
  19154. state.lastIntValue = 0;
  19155. var ch = state.current();
  19156. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  19157. do {
  19158. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19159. state.advance();
  19160. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  19161. return true
  19162. }
  19163. return false
  19164. };
  19165. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  19166. pp$1.regexp_eatCharacterClassEscape = function(state) {
  19167. var ch = state.current();
  19168. if (isCharacterClassEscape(ch)) {
  19169. state.lastIntValue = -1;
  19170. state.advance();
  19171. return true
  19172. }
  19173. if (
  19174. state.switchU &&
  19175. this.options.ecmaVersion >= 9 &&
  19176. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  19177. ) {
  19178. state.lastIntValue = -1;
  19179. state.advance();
  19180. if (
  19181. state.eat(0x7B /* { */) &&
  19182. this.regexp_eatUnicodePropertyValueExpression(state) &&
  19183. state.eat(0x7D /* } */)
  19184. ) {
  19185. return true
  19186. }
  19187. state.raise("Invalid property name");
  19188. }
  19189. return false
  19190. };
  19191. function isCharacterClassEscape(ch) {
  19192. return (
  19193. ch === 0x64 /* d */ ||
  19194. ch === 0x44 /* D */ ||
  19195. ch === 0x73 /* s */ ||
  19196. ch === 0x53 /* S */ ||
  19197. ch === 0x77 /* w */ ||
  19198. ch === 0x57 /* W */
  19199. )
  19200. }
  19201. // UnicodePropertyValueExpression ::
  19202. // UnicodePropertyName `=` UnicodePropertyValue
  19203. // LoneUnicodePropertyNameOrValue
  19204. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  19205. var start = state.pos;
  19206. // UnicodePropertyName `=` UnicodePropertyValue
  19207. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  19208. var name = state.lastStringValue;
  19209. if (this.regexp_eatUnicodePropertyValue(state)) {
  19210. var value = state.lastStringValue;
  19211. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  19212. return true
  19213. }
  19214. }
  19215. state.pos = start;
  19216. // LoneUnicodePropertyNameOrValue
  19217. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  19218. var nameOrValue = state.lastStringValue;
  19219. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  19220. return true
  19221. }
  19222. return false
  19223. };
  19224. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  19225. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  19226. { state.raise("Invalid property name"); }
  19227. if (!state.unicodeProperties.nonBinary[name].test(value))
  19228. { state.raise("Invalid property value"); }
  19229. };
  19230. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  19231. if (!state.unicodeProperties.binary.test(nameOrValue))
  19232. { state.raise("Invalid property name"); }
  19233. };
  19234. // UnicodePropertyName ::
  19235. // UnicodePropertyNameCharacters
  19236. pp$1.regexp_eatUnicodePropertyName = function(state) {
  19237. var ch = 0;
  19238. state.lastStringValue = "";
  19239. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  19240. state.lastStringValue += codePointToString(ch);
  19241. state.advance();
  19242. }
  19243. return state.lastStringValue !== ""
  19244. };
  19245. function isUnicodePropertyNameCharacter(ch) {
  19246. return isControlLetter(ch) || ch === 0x5F /* _ */
  19247. }
  19248. // UnicodePropertyValue ::
  19249. // UnicodePropertyValueCharacters
  19250. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  19251. var ch = 0;
  19252. state.lastStringValue = "";
  19253. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  19254. state.lastStringValue += codePointToString(ch);
  19255. state.advance();
  19256. }
  19257. return state.lastStringValue !== ""
  19258. };
  19259. function isUnicodePropertyValueCharacter(ch) {
  19260. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  19261. }
  19262. // LoneUnicodePropertyNameOrValue ::
  19263. // UnicodePropertyValueCharacters
  19264. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  19265. return this.regexp_eatUnicodePropertyValue(state)
  19266. };
  19267. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  19268. pp$1.regexp_eatCharacterClass = function(state) {
  19269. if (state.eat(0x5B /* [ */)) {
  19270. state.eat(0x5E /* ^ */);
  19271. this.regexp_classRanges(state);
  19272. if (state.eat(0x5D /* ] */)) {
  19273. return true
  19274. }
  19275. // Unreachable since it threw "unterminated regular expression" error before.
  19276. state.raise("Unterminated character class");
  19277. }
  19278. return false
  19279. };
  19280. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  19281. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  19282. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  19283. pp$1.regexp_classRanges = function(state) {
  19284. while (this.regexp_eatClassAtom(state)) {
  19285. var left = state.lastIntValue;
  19286. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  19287. var right = state.lastIntValue;
  19288. if (state.switchU && (left === -1 || right === -1)) {
  19289. state.raise("Invalid character class");
  19290. }
  19291. if (left !== -1 && right !== -1 && left > right) {
  19292. state.raise("Range out of order in character class");
  19293. }
  19294. }
  19295. }
  19296. };
  19297. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  19298. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  19299. pp$1.regexp_eatClassAtom = function(state) {
  19300. var start = state.pos;
  19301. if (state.eat(0x5C /* \ */)) {
  19302. if (this.regexp_eatClassEscape(state)) {
  19303. return true
  19304. }
  19305. if (state.switchU) {
  19306. // Make the same message as V8.
  19307. var ch$1 = state.current();
  19308. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  19309. state.raise("Invalid class escape");
  19310. }
  19311. state.raise("Invalid escape");
  19312. }
  19313. state.pos = start;
  19314. }
  19315. var ch = state.current();
  19316. if (ch !== 0x5D /* ] */) {
  19317. state.lastIntValue = ch;
  19318. state.advance();
  19319. return true
  19320. }
  19321. return false
  19322. };
  19323. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  19324. pp$1.regexp_eatClassEscape = function(state) {
  19325. var start = state.pos;
  19326. if (state.eat(0x62 /* b */)) {
  19327. state.lastIntValue = 0x08; /* <BS> */
  19328. return true
  19329. }
  19330. if (state.switchU && state.eat(0x2D /* - */)) {
  19331. state.lastIntValue = 0x2D; /* - */
  19332. return true
  19333. }
  19334. if (!state.switchU && state.eat(0x63 /* c */)) {
  19335. if (this.regexp_eatClassControlLetter(state)) {
  19336. return true
  19337. }
  19338. state.pos = start;
  19339. }
  19340. return (
  19341. this.regexp_eatCharacterClassEscape(state) ||
  19342. this.regexp_eatCharacterEscape(state)
  19343. )
  19344. };
  19345. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  19346. pp$1.regexp_eatClassControlLetter = function(state) {
  19347. var ch = state.current();
  19348. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  19349. state.lastIntValue = ch % 0x20;
  19350. state.advance();
  19351. return true
  19352. }
  19353. return false
  19354. };
  19355. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19356. pp$1.regexp_eatHexEscapeSequence = function(state) {
  19357. var start = state.pos;
  19358. if (state.eat(0x78 /* x */)) {
  19359. if (this.regexp_eatFixedHexDigits(state, 2)) {
  19360. return true
  19361. }
  19362. if (state.switchU) {
  19363. state.raise("Invalid escape");
  19364. }
  19365. state.pos = start;
  19366. }
  19367. return false
  19368. };
  19369. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  19370. pp$1.regexp_eatDecimalDigits = function(state) {
  19371. var start = state.pos;
  19372. var ch = 0;
  19373. state.lastIntValue = 0;
  19374. while (isDecimalDigit(ch = state.current())) {
  19375. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  19376. state.advance();
  19377. }
  19378. return state.pos !== start
  19379. };
  19380. function isDecimalDigit(ch) {
  19381. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  19382. }
  19383. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  19384. pp$1.regexp_eatHexDigits = function(state) {
  19385. var start = state.pos;
  19386. var ch = 0;
  19387. state.lastIntValue = 0;
  19388. while (isHexDigit(ch = state.current())) {
  19389. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19390. state.advance();
  19391. }
  19392. return state.pos !== start
  19393. };
  19394. function isHexDigit(ch) {
  19395. return (
  19396. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  19397. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  19398. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  19399. )
  19400. }
  19401. function hexToInt(ch) {
  19402. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  19403. return 10 + (ch - 0x41 /* A */)
  19404. }
  19405. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  19406. return 10 + (ch - 0x61 /* a */)
  19407. }
  19408. return ch - 0x30 /* 0 */
  19409. }
  19410. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  19411. // Allows only 0-377(octal) i.e. 0-255(decimal).
  19412. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  19413. if (this.regexp_eatOctalDigit(state)) {
  19414. var n1 = state.lastIntValue;
  19415. if (this.regexp_eatOctalDigit(state)) {
  19416. var n2 = state.lastIntValue;
  19417. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  19418. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  19419. } else {
  19420. state.lastIntValue = n1 * 8 + n2;
  19421. }
  19422. } else {
  19423. state.lastIntValue = n1;
  19424. }
  19425. return true
  19426. }
  19427. return false
  19428. };
  19429. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  19430. pp$1.regexp_eatOctalDigit = function(state) {
  19431. var ch = state.current();
  19432. if (isOctalDigit(ch)) {
  19433. state.lastIntValue = ch - 0x30; /* 0 */
  19434. state.advance();
  19435. return true
  19436. }
  19437. state.lastIntValue = 0;
  19438. return false
  19439. };
  19440. function isOctalDigit(ch) {
  19441. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  19442. }
  19443. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  19444. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  19445. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  19446. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  19447. var start = state.pos;
  19448. state.lastIntValue = 0;
  19449. for (var i = 0; i < length; ++i) {
  19450. var ch = state.current();
  19451. if (!isHexDigit(ch)) {
  19452. state.pos = start;
  19453. return false
  19454. }
  19455. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  19456. state.advance();
  19457. }
  19458. return true
  19459. };
  19460. // Object type used to represent tokens. Note that normally, tokens
  19461. // simply exist as properties on the parser object. This is only
  19462. // used for the onToken callback and the external tokenizer.
  19463. var Token = function Token(p) {
  19464. this.type = p.type;
  19465. this.value = p.value;
  19466. this.start = p.start;
  19467. this.end = p.end;
  19468. if (p.options.locations)
  19469. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  19470. if (p.options.ranges)
  19471. { this.range = [p.start, p.end]; }
  19472. };
  19473. // ## Tokenizer
  19474. var pp = Parser.prototype;
  19475. // Move to the next token
  19476. pp.next = function(ignoreEscapeSequenceInKeyword) {
  19477. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  19478. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  19479. if (this.options.onToken)
  19480. { this.options.onToken(new Token(this)); }
  19481. this.lastTokEnd = this.end;
  19482. this.lastTokStart = this.start;
  19483. this.lastTokEndLoc = this.endLoc;
  19484. this.lastTokStartLoc = this.startLoc;
  19485. this.nextToken();
  19486. };
  19487. pp.getToken = function() {
  19488. this.next();
  19489. return new Token(this)
  19490. };
  19491. // If we're in an ES6 environment, make parsers iterable
  19492. if (typeof Symbol !== "undefined")
  19493. { pp[Symbol.iterator] = function() {
  19494. var this$1$1 = this;
  19495. return {
  19496. next: function () {
  19497. var token = this$1$1.getToken();
  19498. return {
  19499. done: token.type === types$1.eof,
  19500. value: token
  19501. }
  19502. }
  19503. }
  19504. }; }
  19505. // Toggle strict mode. Re-reads the next number or string to please
  19506. // pedantic tests (`"use strict"; 010;` should fail).
  19507. // Read a single token, updating the parser object's token-related
  19508. // properties.
  19509. pp.nextToken = function() {
  19510. var curContext = this.curContext();
  19511. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  19512. this.start = this.pos;
  19513. if (this.options.locations) { this.startLoc = this.curPosition(); }
  19514. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  19515. if (curContext.override) { return curContext.override(this) }
  19516. else { this.readToken(this.fullCharCodeAtPos()); }
  19517. };
  19518. pp.readToken = function(code) {
  19519. // Identifier or keyword. '\uXXXX' sequences are allowed in
  19520. // identifiers, so '\' also dispatches to that.
  19521. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  19522. { return this.readWord() }
  19523. return this.getTokenFromCode(code)
  19524. };
  19525. pp.fullCharCodeAtPos = function() {
  19526. var code = this.input.charCodeAt(this.pos);
  19527. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  19528. var next = this.input.charCodeAt(this.pos + 1);
  19529. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  19530. };
  19531. pp.skipBlockComment = function() {
  19532. var startLoc = this.options.onComment && this.curPosition();
  19533. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  19534. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  19535. this.pos = end + 2;
  19536. if (this.options.locations) {
  19537. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  19538. ++this.curLine;
  19539. pos = this.lineStart = nextBreak;
  19540. }
  19541. }
  19542. if (this.options.onComment)
  19543. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  19544. startLoc, this.curPosition()); }
  19545. };
  19546. pp.skipLineComment = function(startSkip) {
  19547. var start = this.pos;
  19548. var startLoc = this.options.onComment && this.curPosition();
  19549. var ch = this.input.charCodeAt(this.pos += startSkip);
  19550. while (this.pos < this.input.length && !isNewLine(ch)) {
  19551. ch = this.input.charCodeAt(++this.pos);
  19552. }
  19553. if (this.options.onComment)
  19554. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  19555. startLoc, this.curPosition()); }
  19556. };
  19557. // Called at the start of the parse and after every token. Skips
  19558. // whitespace and comments, and.
  19559. pp.skipSpace = function() {
  19560. loop: while (this.pos < this.input.length) {
  19561. var ch = this.input.charCodeAt(this.pos);
  19562. switch (ch) {
  19563. case 32: case 160: // ' '
  19564. ++this.pos;
  19565. break
  19566. case 13:
  19567. if (this.input.charCodeAt(this.pos + 1) === 10) {
  19568. ++this.pos;
  19569. }
  19570. case 10: case 8232: case 8233:
  19571. ++this.pos;
  19572. if (this.options.locations) {
  19573. ++this.curLine;
  19574. this.lineStart = this.pos;
  19575. }
  19576. break
  19577. case 47: // '/'
  19578. switch (this.input.charCodeAt(this.pos + 1)) {
  19579. case 42: // '*'
  19580. this.skipBlockComment();
  19581. break
  19582. case 47:
  19583. this.skipLineComment(2);
  19584. break
  19585. default:
  19586. break loop
  19587. }
  19588. break
  19589. default:
  19590. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  19591. ++this.pos;
  19592. } else {
  19593. break loop
  19594. }
  19595. }
  19596. }
  19597. };
  19598. // Called at the end of every token. Sets `end`, `val`, and
  19599. // maintains `context` and `exprAllowed`, and skips the space after
  19600. // the token, so that the next one's `start` will point at the
  19601. // right position.
  19602. pp.finishToken = function(type, val) {
  19603. this.end = this.pos;
  19604. if (this.options.locations) { this.endLoc = this.curPosition(); }
  19605. var prevType = this.type;
  19606. this.type = type;
  19607. this.value = val;
  19608. this.updateContext(prevType);
  19609. };
  19610. // ### Token reading
  19611. // This is the function that is called to fetch the next token. It
  19612. // is somewhat obscure, because it works in character codes rather
  19613. // than characters, and because operator parsing has been inlined
  19614. // into it.
  19615. //
  19616. // All in the name of speed.
  19617. //
  19618. pp.readToken_dot = function() {
  19619. var next = this.input.charCodeAt(this.pos + 1);
  19620. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  19621. var next2 = this.input.charCodeAt(this.pos + 2);
  19622. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  19623. this.pos += 3;
  19624. return this.finishToken(types$1.ellipsis)
  19625. } else {
  19626. ++this.pos;
  19627. return this.finishToken(types$1.dot)
  19628. }
  19629. };
  19630. pp.readToken_slash = function() { // '/'
  19631. var next = this.input.charCodeAt(this.pos + 1);
  19632. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  19633. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19634. return this.finishOp(types$1.slash, 1)
  19635. };
  19636. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  19637. var next = this.input.charCodeAt(this.pos + 1);
  19638. var size = 1;
  19639. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  19640. // exponentiation operator ** and **=
  19641. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  19642. ++size;
  19643. tokentype = types$1.starstar;
  19644. next = this.input.charCodeAt(this.pos + 2);
  19645. }
  19646. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  19647. return this.finishOp(tokentype, size)
  19648. };
  19649. pp.readToken_pipe_amp = function(code) { // '|&'
  19650. var next = this.input.charCodeAt(this.pos + 1);
  19651. if (next === code) {
  19652. if (this.options.ecmaVersion >= 12) {
  19653. var next2 = this.input.charCodeAt(this.pos + 2);
  19654. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  19655. }
  19656. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  19657. }
  19658. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19659. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  19660. };
  19661. pp.readToken_caret = function() { // '^'
  19662. var next = this.input.charCodeAt(this.pos + 1);
  19663. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19664. return this.finishOp(types$1.bitwiseXOR, 1)
  19665. };
  19666. pp.readToken_plus_min = function(code) { // '+-'
  19667. var next = this.input.charCodeAt(this.pos + 1);
  19668. if (next === code) {
  19669. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  19670. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  19671. // A `-->` line comment
  19672. this.skipLineComment(3);
  19673. this.skipSpace();
  19674. return this.nextToken()
  19675. }
  19676. return this.finishOp(types$1.incDec, 2)
  19677. }
  19678. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  19679. return this.finishOp(types$1.plusMin, 1)
  19680. };
  19681. pp.readToken_lt_gt = function(code) { // '<>'
  19682. var next = this.input.charCodeAt(this.pos + 1);
  19683. var size = 1;
  19684. if (next === code) {
  19685. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  19686. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  19687. return this.finishOp(types$1.bitShift, size)
  19688. }
  19689. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  19690. this.input.charCodeAt(this.pos + 3) === 45) {
  19691. // `<!--`, an XML-style comment that should be interpreted as a line comment
  19692. this.skipLineComment(4);
  19693. this.skipSpace();
  19694. return this.nextToken()
  19695. }
  19696. if (next === 61) { size = 2; }
  19697. return this.finishOp(types$1.relational, size)
  19698. };
  19699. pp.readToken_eq_excl = function(code) { // '=!'
  19700. var next = this.input.charCodeAt(this.pos + 1);
  19701. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  19702. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  19703. this.pos += 2;
  19704. return this.finishToken(types$1.arrow)
  19705. }
  19706. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  19707. };
  19708. pp.readToken_question = function() { // '?'
  19709. var ecmaVersion = this.options.ecmaVersion;
  19710. if (ecmaVersion >= 11) {
  19711. var next = this.input.charCodeAt(this.pos + 1);
  19712. if (next === 46) {
  19713. var next2 = this.input.charCodeAt(this.pos + 2);
  19714. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  19715. }
  19716. if (next === 63) {
  19717. if (ecmaVersion >= 12) {
  19718. var next2$1 = this.input.charCodeAt(this.pos + 2);
  19719. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  19720. }
  19721. return this.finishOp(types$1.coalesce, 2)
  19722. }
  19723. }
  19724. return this.finishOp(types$1.question, 1)
  19725. };
  19726. pp.readToken_numberSign = function() { // '#'
  19727. var ecmaVersion = this.options.ecmaVersion;
  19728. var code = 35; // '#'
  19729. if (ecmaVersion >= 13) {
  19730. ++this.pos;
  19731. code = this.fullCharCodeAtPos();
  19732. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  19733. return this.finishToken(types$1.privateId, this.readWord1())
  19734. }
  19735. }
  19736. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19737. };
  19738. pp.getTokenFromCode = function(code) {
  19739. switch (code) {
  19740. // The interpretation of a dot depends on whether it is followed
  19741. // by a digit or another two dots.
  19742. case 46: // '.'
  19743. return this.readToken_dot()
  19744. // Punctuation tokens.
  19745. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  19746. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  19747. case 59: ++this.pos; return this.finishToken(types$1.semi)
  19748. case 44: ++this.pos; return this.finishToken(types$1.comma)
  19749. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  19750. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  19751. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  19752. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  19753. case 58: ++this.pos; return this.finishToken(types$1.colon)
  19754. case 96: // '`'
  19755. if (this.options.ecmaVersion < 6) { break }
  19756. ++this.pos;
  19757. return this.finishToken(types$1.backQuote)
  19758. case 48: // '0'
  19759. var next = this.input.charCodeAt(this.pos + 1);
  19760. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  19761. if (this.options.ecmaVersion >= 6) {
  19762. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  19763. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  19764. }
  19765. // Anything else beginning with a digit is an integer, octal
  19766. // number, or float.
  19767. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  19768. return this.readNumber(false)
  19769. // Quotes produce strings.
  19770. case 34: case 39: // '"', "'"
  19771. return this.readString(code)
  19772. // Operators are parsed inline in tiny state machines. '=' (61) is
  19773. // often referred to. `finishOp` simply skips the amount of
  19774. // characters it is given as second argument, and returns a token
  19775. // of the type given by its first argument.
  19776. case 47: // '/'
  19777. return this.readToken_slash()
  19778. case 37: case 42: // '%*'
  19779. return this.readToken_mult_modulo_exp(code)
  19780. case 124: case 38: // '|&'
  19781. return this.readToken_pipe_amp(code)
  19782. case 94: // '^'
  19783. return this.readToken_caret()
  19784. case 43: case 45: // '+-'
  19785. return this.readToken_plus_min(code)
  19786. case 60: case 62: // '<>'
  19787. return this.readToken_lt_gt(code)
  19788. case 61: case 33: // '=!'
  19789. return this.readToken_eq_excl(code)
  19790. case 63: // '?'
  19791. return this.readToken_question()
  19792. case 126: // '~'
  19793. return this.finishOp(types$1.prefix, 1)
  19794. case 35: // '#'
  19795. return this.readToken_numberSign()
  19796. }
  19797. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  19798. };
  19799. pp.finishOp = function(type, size) {
  19800. var str = this.input.slice(this.pos, this.pos + size);
  19801. this.pos += size;
  19802. return this.finishToken(type, str)
  19803. };
  19804. pp.readRegexp = function() {
  19805. var escaped, inClass, start = this.pos;
  19806. for (;;) {
  19807. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  19808. var ch = this.input.charAt(this.pos);
  19809. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  19810. if (!escaped) {
  19811. if (ch === "[") { inClass = true; }
  19812. else if (ch === "]" && inClass) { inClass = false; }
  19813. else if (ch === "/" && !inClass) { break }
  19814. escaped = ch === "\\";
  19815. } else { escaped = false; }
  19816. ++this.pos;
  19817. }
  19818. var pattern = this.input.slice(start, this.pos);
  19819. ++this.pos;
  19820. var flagsStart = this.pos;
  19821. var flags = this.readWord1();
  19822. if (this.containsEsc) { this.unexpected(flagsStart); }
  19823. // Validate pattern
  19824. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  19825. state.reset(start, pattern, flags);
  19826. this.validateRegExpFlags(state);
  19827. this.validateRegExpPattern(state);
  19828. // Create Literal#value property value.
  19829. var value = null;
  19830. try {
  19831. value = new RegExp(pattern, flags);
  19832. } catch (e) {
  19833. // ESTree requires null if it failed to instantiate RegExp object.
  19834. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  19835. }
  19836. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  19837. };
  19838. // Read an integer in the given radix. Return null if zero digits
  19839. // were read, the integer value otherwise. When `len` is given, this
  19840. // will return `null` unless the integer has exactly `len` digits.
  19841. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  19842. // `len` is used for character escape sequences. In that case, disallow separators.
  19843. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  19844. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  19845. // and isn't fraction part nor exponent part. In that case, if the first digit
  19846. // is zero then disallow separators.
  19847. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  19848. var start = this.pos, total = 0, lastCode = 0;
  19849. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  19850. var code = this.input.charCodeAt(this.pos), val = (void 0);
  19851. if (allowSeparators && code === 95) {
  19852. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  19853. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  19854. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  19855. lastCode = code;
  19856. continue
  19857. }
  19858. if (code >= 97) { val = code - 97 + 10; } // a
  19859. else if (code >= 65) { val = code - 65 + 10; } // A
  19860. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  19861. else { val = Infinity; }
  19862. if (val >= radix) { break }
  19863. lastCode = code;
  19864. total = total * radix + val;
  19865. }
  19866. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  19867. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  19868. return total
  19869. };
  19870. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  19871. if (isLegacyOctalNumericLiteral) {
  19872. return parseInt(str, 8)
  19873. }
  19874. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  19875. return parseFloat(str.replace(/_/g, ""))
  19876. }
  19877. function stringToBigInt(str) {
  19878. if (typeof BigInt !== "function") {
  19879. return null
  19880. }
  19881. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  19882. return BigInt(str.replace(/_/g, ""))
  19883. }
  19884. pp.readRadixNumber = function(radix) {
  19885. var start = this.pos;
  19886. this.pos += 2; // 0x
  19887. var val = this.readInt(radix);
  19888. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  19889. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  19890. val = stringToBigInt(this.input.slice(start, this.pos));
  19891. ++this.pos;
  19892. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19893. return this.finishToken(types$1.num, val)
  19894. };
  19895. // Read an integer, octal integer, or floating-point number.
  19896. pp.readNumber = function(startsWithDot) {
  19897. var start = this.pos;
  19898. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  19899. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  19900. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  19901. var next = this.input.charCodeAt(this.pos);
  19902. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  19903. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  19904. ++this.pos;
  19905. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19906. return this.finishToken(types$1.num, val$1)
  19907. }
  19908. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  19909. if (next === 46 && !octal) { // '.'
  19910. ++this.pos;
  19911. this.readInt(10);
  19912. next = this.input.charCodeAt(this.pos);
  19913. }
  19914. if ((next === 69 || next === 101) && !octal) { // 'eE'
  19915. next = this.input.charCodeAt(++this.pos);
  19916. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  19917. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  19918. }
  19919. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  19920. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  19921. return this.finishToken(types$1.num, val)
  19922. };
  19923. // Read a string value, interpreting backslash-escapes.
  19924. pp.readCodePoint = function() {
  19925. var ch = this.input.charCodeAt(this.pos), code;
  19926. if (ch === 123) { // '{'
  19927. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  19928. var codePos = ++this.pos;
  19929. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  19930. ++this.pos;
  19931. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  19932. } else {
  19933. code = this.readHexChar(4);
  19934. }
  19935. return code
  19936. };
  19937. pp.readString = function(quote) {
  19938. var out = "", chunkStart = ++this.pos;
  19939. for (;;) {
  19940. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  19941. var ch = this.input.charCodeAt(this.pos);
  19942. if (ch === quote) { break }
  19943. if (ch === 92) { // '\'
  19944. out += this.input.slice(chunkStart, this.pos);
  19945. out += this.readEscapedChar(false);
  19946. chunkStart = this.pos;
  19947. } else if (ch === 0x2028 || ch === 0x2029) {
  19948. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  19949. ++this.pos;
  19950. if (this.options.locations) {
  19951. this.curLine++;
  19952. this.lineStart = this.pos;
  19953. }
  19954. } else {
  19955. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  19956. ++this.pos;
  19957. }
  19958. }
  19959. out += this.input.slice(chunkStart, this.pos++);
  19960. return this.finishToken(types$1.string, out)
  19961. };
  19962. // Reads template string tokens.
  19963. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  19964. pp.tryReadTemplateToken = function() {
  19965. this.inTemplateElement = true;
  19966. try {
  19967. this.readTmplToken();
  19968. } catch (err) {
  19969. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  19970. this.readInvalidTemplateToken();
  19971. } else {
  19972. throw err
  19973. }
  19974. }
  19975. this.inTemplateElement = false;
  19976. };
  19977. pp.invalidStringToken = function(position, message) {
  19978. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  19979. throw INVALID_TEMPLATE_ESCAPE_ERROR
  19980. } else {
  19981. this.raise(position, message);
  19982. }
  19983. };
  19984. pp.readTmplToken = function() {
  19985. var out = "", chunkStart = this.pos;
  19986. for (;;) {
  19987. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  19988. var ch = this.input.charCodeAt(this.pos);
  19989. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  19990. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  19991. if (ch === 36) {
  19992. this.pos += 2;
  19993. return this.finishToken(types$1.dollarBraceL)
  19994. } else {
  19995. ++this.pos;
  19996. return this.finishToken(types$1.backQuote)
  19997. }
  19998. }
  19999. out += this.input.slice(chunkStart, this.pos);
  20000. return this.finishToken(types$1.template, out)
  20001. }
  20002. if (ch === 92) { // '\'
  20003. out += this.input.slice(chunkStart, this.pos);
  20004. out += this.readEscapedChar(true);
  20005. chunkStart = this.pos;
  20006. } else if (isNewLine(ch)) {
  20007. out += this.input.slice(chunkStart, this.pos);
  20008. ++this.pos;
  20009. switch (ch) {
  20010. case 13:
  20011. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  20012. case 10:
  20013. out += "\n";
  20014. break
  20015. default:
  20016. out += String.fromCharCode(ch);
  20017. break
  20018. }
  20019. if (this.options.locations) {
  20020. ++this.curLine;
  20021. this.lineStart = this.pos;
  20022. }
  20023. chunkStart = this.pos;
  20024. } else {
  20025. ++this.pos;
  20026. }
  20027. }
  20028. };
  20029. // Reads a template token to search for the end, without validating any escape sequences
  20030. pp.readInvalidTemplateToken = function() {
  20031. for (; this.pos < this.input.length; this.pos++) {
  20032. switch (this.input[this.pos]) {
  20033. case "\\":
  20034. ++this.pos;
  20035. break
  20036. case "$":
  20037. if (this.input[this.pos + 1] !== "{") {
  20038. break
  20039. }
  20040. // falls through
  20041. case "`":
  20042. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  20043. // no default
  20044. }
  20045. }
  20046. this.raise(this.start, "Unterminated template");
  20047. };
  20048. // Used to read escaped characters
  20049. pp.readEscapedChar = function(inTemplate) {
  20050. var ch = this.input.charCodeAt(++this.pos);
  20051. ++this.pos;
  20052. switch (ch) {
  20053. case 110: return "\n" // 'n' -> '\n'
  20054. case 114: return "\r" // 'r' -> '\r'
  20055. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  20056. case 117: return codePointToString(this.readCodePoint()) // 'u'
  20057. case 116: return "\t" // 't' -> '\t'
  20058. case 98: return "\b" // 'b' -> '\b'
  20059. case 118: return "\u000b" // 'v' -> '\u000b'
  20060. case 102: return "\f" // 'f' -> '\f'
  20061. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  20062. case 10: // ' \n'
  20063. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  20064. return ""
  20065. case 56:
  20066. case 57:
  20067. if (this.strict) {
  20068. this.invalidStringToken(
  20069. this.pos - 1,
  20070. "Invalid escape sequence"
  20071. );
  20072. }
  20073. if (inTemplate) {
  20074. var codePos = this.pos - 1;
  20075. this.invalidStringToken(
  20076. codePos,
  20077. "Invalid escape sequence in template string"
  20078. );
  20079. return null
  20080. }
  20081. default:
  20082. if (ch >= 48 && ch <= 55) {
  20083. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  20084. var octal = parseInt(octalStr, 8);
  20085. if (octal > 255) {
  20086. octalStr = octalStr.slice(0, -1);
  20087. octal = parseInt(octalStr, 8);
  20088. }
  20089. this.pos += octalStr.length - 1;
  20090. ch = this.input.charCodeAt(this.pos);
  20091. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  20092. this.invalidStringToken(
  20093. this.pos - 1 - octalStr.length,
  20094. inTemplate
  20095. ? "Octal literal in template string"
  20096. : "Octal literal in strict mode"
  20097. );
  20098. }
  20099. return String.fromCharCode(octal)
  20100. }
  20101. if (isNewLine(ch)) {
  20102. // Unicode new line characters after \ get removed from output in both
  20103. // template literals and strings
  20104. return ""
  20105. }
  20106. return String.fromCharCode(ch)
  20107. }
  20108. };
  20109. // Used to read character escape sequences ('\x', '\u', '\U').
  20110. pp.readHexChar = function(len) {
  20111. var codePos = this.pos;
  20112. var n = this.readInt(16, len);
  20113. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  20114. return n
  20115. };
  20116. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  20117. // to whether the word contained a '\u' escape.
  20118. //
  20119. // Incrementally adds only escaped chars, adding other chunks as-is
  20120. // as a micro-optimization.
  20121. pp.readWord1 = function() {
  20122. this.containsEsc = false;
  20123. var word = "", first = true, chunkStart = this.pos;
  20124. var astral = this.options.ecmaVersion >= 6;
  20125. while (this.pos < this.input.length) {
  20126. var ch = this.fullCharCodeAtPos();
  20127. if (isIdentifierChar(ch, astral)) {
  20128. this.pos += ch <= 0xffff ? 1 : 2;
  20129. } else if (ch === 92) { // "\"
  20130. this.containsEsc = true;
  20131. word += this.input.slice(chunkStart, this.pos);
  20132. var escStart = this.pos;
  20133. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  20134. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  20135. ++this.pos;
  20136. var esc = this.readCodePoint();
  20137. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  20138. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  20139. word += codePointToString(esc);
  20140. chunkStart = this.pos;
  20141. } else {
  20142. break
  20143. }
  20144. first = false;
  20145. }
  20146. return word + this.input.slice(chunkStart, this.pos)
  20147. };
  20148. // Read an identifier or keyword token. Will check for reserved
  20149. // words when necessary.
  20150. pp.readWord = function() {
  20151. var word = this.readWord1();
  20152. var type = types$1.name;
  20153. if (this.keywords.test(word)) {
  20154. type = keywords[word];
  20155. }
  20156. return this.finishToken(type, word)
  20157. };
  20158. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  20159. var version = "8.7.1";
  20160. Parser.acorn = {
  20161. Parser: Parser,
  20162. version: version,
  20163. defaultOptions: defaultOptions,
  20164. Position: Position,
  20165. SourceLocation: SourceLocation,
  20166. getLineInfo: getLineInfo,
  20167. Node: Node,
  20168. TokenType: TokenType,
  20169. tokTypes: types$1,
  20170. keywordTypes: keywords,
  20171. TokContext: TokContext,
  20172. tokContexts: types,
  20173. isIdentifierChar: isIdentifierChar,
  20174. isIdentifierStart: isIdentifierStart,
  20175. Token: Token,
  20176. isNewLine: isNewLine,
  20177. lineBreak: lineBreak,
  20178. lineBreakG: lineBreakG,
  20179. nonASCIIwhitespace: nonASCIIwhitespace
  20180. };
  20181. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20182. let skipped = null;
  20183. let replaceContext = null;
  20184. if (skip) {
  20185. skipped = new Set();
  20186. for (const skippedCall of skip) {
  20187. if (source === skippedCall.source && importer === skippedCall.importer) {
  20188. skipped.add(skippedCall.plugin);
  20189. }
  20190. }
  20191. replaceContext = (pluginContext, plugin) => ({
  20192. ...pluginContext,
  20193. resolve: (source, importer, { custom, isEntry, skipSelf } = BLANK) => {
  20194. return moduleLoaderResolveId(source, importer, custom, isEntry, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20195. }
  20196. });
  20197. }
  20198. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions, isEntry }], replaceContext, skipped);
  20199. }
  20200. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry) {
  20201. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry);
  20202. if (pluginResult != null)
  20203. return pluginResult;
  20204. // external modules (non-entry modules that start with neither '.' or '/')
  20205. // are skipped at this stage.
  20206. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  20207. return null;
  20208. // `resolve` processes paths from right to left, prepending them until an
  20209. // absolute path is created. Absolute importees therefore shortcircuit the
  20210. // resolve call and require no special handing on our part.
  20211. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20212. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  20213. }
  20214. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  20215. var _a, _b;
  20216. 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)));
  20217. }
  20218. async function findFile(file, preserveSymlinks) {
  20219. try {
  20220. const stats = await promises.lstat(file);
  20221. if (!preserveSymlinks && stats.isSymbolicLink())
  20222. return await findFile(await promises.realpath(file), preserveSymlinks);
  20223. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20224. // check case
  20225. const name = basename(file);
  20226. const files = await promises.readdir(dirname(file));
  20227. if (files.includes(name))
  20228. return file;
  20229. }
  20230. }
  20231. catch (_a) {
  20232. // suppress
  20233. }
  20234. }
  20235. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20236. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20237. function throwPluginError(err, plugin, { hook, id } = {}) {
  20238. if (typeof err === 'string')
  20239. err = { message: err };
  20240. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  20241. err.pluginCode = err.code;
  20242. }
  20243. err.code = Errors.PLUGIN_ERROR;
  20244. err.plugin = plugin;
  20245. if (hook) {
  20246. err.hook = hook;
  20247. }
  20248. if (id) {
  20249. err.id = id;
  20250. }
  20251. return error(err);
  20252. }
  20253. const deprecatedHooks = [
  20254. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  20255. ];
  20256. function warnDeprecatedHooks(plugins, options) {
  20257. for (const { active, deprecated, replacement } of deprecatedHooks) {
  20258. for (const plugin of plugins) {
  20259. if (deprecated in plugin) {
  20260. warnDeprecation({
  20261. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  20262. plugin: plugin.name
  20263. }, active, options);
  20264. }
  20265. }
  20266. }
  20267. }
  20268. function createPluginCache(cache) {
  20269. return {
  20270. delete(id) {
  20271. return delete cache[id];
  20272. },
  20273. get(id) {
  20274. const item = cache[id];
  20275. if (!item)
  20276. return undefined;
  20277. item[0] = 0;
  20278. return item[1];
  20279. },
  20280. has(id) {
  20281. const item = cache[id];
  20282. if (!item)
  20283. return false;
  20284. item[0] = 0;
  20285. return true;
  20286. },
  20287. set(id, value) {
  20288. cache[id] = [0, value];
  20289. }
  20290. };
  20291. }
  20292. function getTrackedPluginCache(pluginCache, onUse) {
  20293. return {
  20294. delete(id) {
  20295. onUse();
  20296. return pluginCache.delete(id);
  20297. },
  20298. get(id) {
  20299. onUse();
  20300. return pluginCache.get(id);
  20301. },
  20302. has(id) {
  20303. onUse();
  20304. return pluginCache.has(id);
  20305. },
  20306. set(id, value) {
  20307. onUse();
  20308. return pluginCache.set(id, value);
  20309. }
  20310. };
  20311. }
  20312. const NO_CACHE = {
  20313. delete() {
  20314. return false;
  20315. },
  20316. get() {
  20317. return undefined;
  20318. },
  20319. has() {
  20320. return false;
  20321. },
  20322. set() { }
  20323. };
  20324. function uncacheablePluginError(pluginName) {
  20325. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20326. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20327. return error({
  20328. code: 'ANONYMOUS_PLUGIN_CACHE',
  20329. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  20330. });
  20331. }
  20332. return error({
  20333. code: 'DUPLICATE_PLUGIN_NAME',
  20334. 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).`
  20335. });
  20336. }
  20337. function getCacheForUncacheablePlugin(pluginName) {
  20338. return {
  20339. delete() {
  20340. return uncacheablePluginError(pluginName);
  20341. },
  20342. get() {
  20343. return uncacheablePluginError(pluginName);
  20344. },
  20345. has() {
  20346. return uncacheablePluginError(pluginName);
  20347. },
  20348. set() {
  20349. return uncacheablePluginError(pluginName);
  20350. }
  20351. };
  20352. }
  20353. async function transform(source, module, pluginDriver, warn) {
  20354. const id = module.id;
  20355. const sourcemapChain = [];
  20356. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20357. const originalCode = source.code;
  20358. let ast = source.ast;
  20359. const transformDependencies = [];
  20360. const emittedFiles = [];
  20361. let customTransformCache = false;
  20362. const useCustomTransformCache = () => (customTransformCache = true);
  20363. let pluginName = '';
  20364. const curSource = source.code;
  20365. function transformReducer(previousCode, result, plugin) {
  20366. let code;
  20367. let map;
  20368. if (typeof result === 'string') {
  20369. code = result;
  20370. }
  20371. else if (result && typeof result === 'object') {
  20372. module.updateOptions(result);
  20373. if (result.code == null) {
  20374. if (result.map || result.ast) {
  20375. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  20376. }
  20377. return previousCode;
  20378. }
  20379. ({ code, map, ast } = result);
  20380. }
  20381. else {
  20382. return previousCode;
  20383. }
  20384. // strict null check allows 'null' maps to not be pushed to the chain,
  20385. // while 'undefined' gets the missing map warning
  20386. if (map !== null) {
  20387. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20388. missing: true,
  20389. plugin: plugin.name
  20390. });
  20391. }
  20392. return code;
  20393. }
  20394. let code;
  20395. try {
  20396. code = await pluginDriver.hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  20397. pluginName = plugin.name;
  20398. return {
  20399. ...pluginContext,
  20400. addWatchFile(id) {
  20401. transformDependencies.push(id);
  20402. pluginContext.addWatchFile(id);
  20403. },
  20404. cache: customTransformCache
  20405. ? pluginContext.cache
  20406. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20407. emitAsset(name, source) {
  20408. emittedFiles.push({ name, source, type: 'asset' });
  20409. return pluginContext.emitAsset(name, source);
  20410. },
  20411. emitChunk(id, options) {
  20412. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  20413. return pluginContext.emitChunk(id, options);
  20414. },
  20415. emitFile(emittedFile) {
  20416. emittedFiles.push(emittedFile);
  20417. return pluginDriver.emitFile(emittedFile);
  20418. },
  20419. error(err, pos) {
  20420. if (typeof err === 'string')
  20421. err = { message: err };
  20422. if (pos)
  20423. augmentCodeLocation(err, pos, curSource, id);
  20424. err.id = id;
  20425. err.hook = 'transform';
  20426. return pluginContext.error(err);
  20427. },
  20428. getCombinedSourcemap() {
  20429. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  20430. if (!combinedMap) {
  20431. const magicString = new MagicString(originalCode);
  20432. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20433. }
  20434. if (originalSourcemap !== combinedMap) {
  20435. originalSourcemap = combinedMap;
  20436. sourcemapChain.length = 0;
  20437. }
  20438. return new SourceMap({
  20439. ...combinedMap,
  20440. file: null,
  20441. sourcesContent: combinedMap.sourcesContent
  20442. });
  20443. },
  20444. setAssetSource() {
  20445. return this.error({
  20446. code: 'INVALID_SETASSETSOURCE',
  20447. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  20448. });
  20449. },
  20450. warn(warning, pos) {
  20451. if (typeof warning === 'string')
  20452. warning = { message: warning };
  20453. if (pos)
  20454. augmentCodeLocation(warning, pos, curSource, id);
  20455. warning.id = id;
  20456. warning.hook = 'transform';
  20457. pluginContext.warn(warning);
  20458. }
  20459. };
  20460. });
  20461. }
  20462. catch (err) {
  20463. throwPluginError(err, pluginName, { hook: 'transform', id });
  20464. }
  20465. if (!customTransformCache) {
  20466. // files emitted by a transform hook need to be emitted again if the hook is skipped
  20467. if (emittedFiles.length)
  20468. module.transformFiles = emittedFiles;
  20469. }
  20470. return {
  20471. ast,
  20472. code,
  20473. customTransformCache,
  20474. originalCode,
  20475. originalSourcemap,
  20476. sourcemapChain,
  20477. transformDependencies
  20478. };
  20479. }
  20480. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20481. class ModuleLoader {
  20482. constructor(graph, modulesById, options, pluginDriver) {
  20483. this.graph = graph;
  20484. this.modulesById = modulesById;
  20485. this.options = options;
  20486. this.pluginDriver = pluginDriver;
  20487. this.implicitEntryModules = new Set();
  20488. this.indexedEntryModules = [];
  20489. this.latestLoadModulesPromise = Promise.resolve();
  20490. this.moduleLoadPromises = new Map();
  20491. this.modulesWithLoadedDependencies = new Set();
  20492. this.nextChunkNamePriority = 0;
  20493. this.nextEntryModuleIndex = 0;
  20494. this.resolveId = async (source, importer, customOptions, isEntry, skip = null) => {
  20495. return this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20496. ? false
  20497. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer), importer, source));
  20498. };
  20499. this.hasModuleSideEffects = options.treeshake
  20500. ? options.treeshake.moduleSideEffects
  20501. : () => true;
  20502. }
  20503. async addAdditionalModules(unresolvedModules) {
  20504. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  20505. await this.awaitLoadModulesPromise();
  20506. return result;
  20507. }
  20508. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20509. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20510. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20511. const firstChunkNamePriority = this.nextChunkNamePriority;
  20512. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20513. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  20514. for (let index = 0; index < entryModules.length; index++) {
  20515. const entryModule = entryModules[index];
  20516. entryModule.isUserDefinedEntryPoint =
  20517. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20518. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20519. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20520. if (!existingIndexedModule) {
  20521. this.indexedEntryModules.push({
  20522. index: firstEntryModuleIndex + index,
  20523. module: entryModule
  20524. });
  20525. }
  20526. else {
  20527. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20528. }
  20529. }
  20530. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20531. return entryModules;
  20532. }));
  20533. await this.awaitLoadModulesPromise();
  20534. return {
  20535. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20536. implicitEntryModules: [...this.implicitEntryModules],
  20537. newEntryModules
  20538. };
  20539. }
  20540. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20541. const unresolvedModule = {
  20542. fileName: fileName || null,
  20543. id,
  20544. importer,
  20545. name: name || null
  20546. };
  20547. const module = implicitlyLoadedAfterOneOf
  20548. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20549. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20550. if (preserveSignature != null) {
  20551. module.preserveSignature = preserveSignature;
  20552. }
  20553. return module;
  20554. }
  20555. async preloadModule(resolvedId) {
  20556. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20557. return module.info;
  20558. }
  20559. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20560. const chunkNamePriority = this.nextChunkNamePriority++;
  20561. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  20562. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20563. if (!entryModule.info.isEntry) {
  20564. this.implicitEntryModules.add(entryModule);
  20565. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  20566. for (const module of implicitlyLoadedAfterModules) {
  20567. entryModule.implicitlyLoadedAfter.add(module);
  20568. }
  20569. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20570. dependant.implicitlyLoadedBefore.add(entryModule);
  20571. }
  20572. }
  20573. return entryModule;
  20574. }));
  20575. }
  20576. async addModuleSource(id, importer, module) {
  20577. timeStart('load modules', 3);
  20578. let source;
  20579. try {
  20580. source = await this.graph.fileOperationQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await promises.readFile(id, 'utf8')); });
  20581. }
  20582. catch (err) {
  20583. timeEnd('load modules', 3);
  20584. let msg = `Could not load ${id}`;
  20585. if (importer)
  20586. msg += ` (imported by ${relativeId(importer)})`;
  20587. msg += `: ${err.message}`;
  20588. err.message = msg;
  20589. throw err;
  20590. }
  20591. timeEnd('load modules', 3);
  20592. const sourceDescription = typeof source === 'string'
  20593. ? { code: source }
  20594. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20595. ? source
  20596. : error(errBadLoader(id));
  20597. const cachedModule = this.graph.cachedModules.get(id);
  20598. if (cachedModule &&
  20599. !cachedModule.customTransformCache &&
  20600. cachedModule.originalCode === sourceDescription.code &&
  20601. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20602. {
  20603. ast: cachedModule.ast,
  20604. code: cachedModule.code,
  20605. id: cachedModule.id,
  20606. meta: cachedModule.meta,
  20607. moduleSideEffects: cachedModule.moduleSideEffects,
  20608. resolvedSources: cachedModule.resolvedIds,
  20609. syntheticNamedExports: cachedModule.syntheticNamedExports
  20610. }
  20611. ]))) {
  20612. if (cachedModule.transformFiles) {
  20613. for (const emittedFile of cachedModule.transformFiles)
  20614. this.pluginDriver.emitFile(emittedFile);
  20615. }
  20616. module.setSource(cachedModule);
  20617. }
  20618. else {
  20619. module.updateOptions(sourceDescription);
  20620. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  20621. }
  20622. }
  20623. async awaitLoadModulesPromise() {
  20624. let startingPromise;
  20625. do {
  20626. startingPromise = this.latestLoadModulesPromise;
  20627. await startingPromise;
  20628. } while (startingPromise !== this.latestLoadModulesPromise);
  20629. }
  20630. extendLoadModulesPromise(loadNewModulesPromise) {
  20631. this.latestLoadModulesPromise = Promise.all([
  20632. loadNewModulesPromise,
  20633. this.latestLoadModulesPromise
  20634. ]);
  20635. this.latestLoadModulesPromise.catch(() => {
  20636. /* Avoid unhandled Promise rejections */
  20637. });
  20638. return loadNewModulesPromise;
  20639. }
  20640. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20641. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  20642. if (resolvedId === null)
  20643. return null;
  20644. if (typeof resolvedId === 'string') {
  20645. dynamicImport.resolution = resolvedId;
  20646. return null;
  20647. }
  20648. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20649. })));
  20650. for (const dependency of dependencies) {
  20651. if (dependency) {
  20652. module.dynamicDependencies.add(dependency);
  20653. dependency.dynamicImporters.push(module.id);
  20654. }
  20655. }
  20656. }
  20657. // If this is a preload, then this method always waits for the dependencies of the module to be resolved.
  20658. // Otherwise if the module does not exist, it waits for the module and all its dependencies to be loaded.
  20659. // Otherwise it returns immediately.
  20660. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20661. const existingModule = this.modulesById.get(id);
  20662. if (existingModule instanceof Module) {
  20663. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20664. return existingModule;
  20665. }
  20666. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  20667. this.modulesById.set(id, module);
  20668. this.graph.watchFiles[id] = true;
  20669. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20670. this.getResolveStaticDependencyPromises(module),
  20671. this.getResolveDynamicImportPromises(module),
  20672. loadAndResolveDependenciesPromise
  20673. ]);
  20674. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20675. loadAndResolveDependenciesPromise.catch(() => {
  20676. /* avoid unhandled promise rejections */
  20677. });
  20678. this.moduleLoadPromises.set(module, loadPromise);
  20679. const resolveDependencyPromises = await loadPromise;
  20680. if (!isPreload) {
  20681. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20682. }
  20683. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20684. await loadAndResolveDependenciesPromise;
  20685. }
  20686. return module;
  20687. }
  20688. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20689. if (this.modulesWithLoadedDependencies.has(module)) {
  20690. return;
  20691. }
  20692. this.modulesWithLoadedDependencies.add(module);
  20693. await Promise.all([
  20694. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20695. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20696. ]);
  20697. module.linkImports();
  20698. // To handle errors when resolving dependencies or in moduleParsed
  20699. await loadAndResolveDependenciesPromise;
  20700. }
  20701. fetchResolvedDependency(source, importer, resolvedId) {
  20702. if (resolvedId.external) {
  20703. const { external, id, moduleSideEffects, meta } = resolvedId;
  20704. if (!this.modulesById.has(id)) {
  20705. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  20706. }
  20707. const externalModule = this.modulesById.get(id);
  20708. if (!(externalModule instanceof ExternalModule)) {
  20709. return error(errInternalIdCannotBeExternal(source, importer));
  20710. }
  20711. return Promise.resolve(externalModule);
  20712. }
  20713. return this.fetchModule(resolvedId, importer, false, false);
  20714. }
  20715. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20716. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  20717. module.dependencies.add(dependency);
  20718. dependency.importers.push(module.id);
  20719. }
  20720. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20721. for (const dependency of module.dependencies) {
  20722. if (dependency instanceof Module) {
  20723. dependency.importedFromNotTreeshaken = true;
  20724. }
  20725. }
  20726. }
  20727. }
  20728. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  20729. const { makeAbsoluteExternalsRelative } = this.options;
  20730. if (resolveIdResult) {
  20731. if (typeof resolveIdResult === 'object') {
  20732. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  20733. return {
  20734. ...resolveIdResult,
  20735. external: external &&
  20736. (external === 'relative' ||
  20737. !isAbsolute(resolveIdResult.id) ||
  20738. (external === true &&
  20739. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  20740. 'absolute')
  20741. };
  20742. }
  20743. const external = this.options.external(resolveIdResult, importer, true);
  20744. return {
  20745. external: external &&
  20746. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  20747. 'absolute'),
  20748. id: external && makeAbsoluteExternalsRelative
  20749. ? normalizeRelativeExternalId(resolveIdResult, importer)
  20750. : resolveIdResult
  20751. };
  20752. }
  20753. const id = makeAbsoluteExternalsRelative
  20754. ? normalizeRelativeExternalId(source, importer)
  20755. : source;
  20756. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  20757. return null;
  20758. }
  20759. return {
  20760. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  20761. id
  20762. };
  20763. }
  20764. getResolveDynamicImportPromises(module) {
  20765. return module.dynamicImports.map(async (dynamicImport) => {
  20766. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  20767. ? dynamicImport.argument
  20768. : dynamicImport.argument.esTreeNode, module.id);
  20769. if (resolvedId && typeof resolvedId === 'object') {
  20770. dynamicImport.id = resolvedId.id;
  20771. }
  20772. return [dynamicImport, resolvedId];
  20773. });
  20774. }
  20775. getResolveStaticDependencyPromises(module) {
  20776. return Array.from(module.sources, async (source) => [
  20777. source,
  20778. (module.resolvedIds[source] =
  20779. module.resolvedIds[source] ||
  20780. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT, false), source, module.id))
  20781. ]);
  20782. }
  20783. getResolvedIdWithDefaults(resolvedId) {
  20784. var _a, _b;
  20785. if (!resolvedId) {
  20786. return null;
  20787. }
  20788. const external = resolvedId.external || false;
  20789. return {
  20790. external,
  20791. id: resolvedId.id,
  20792. meta: resolvedId.meta || {},
  20793. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  20794. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  20795. };
  20796. }
  20797. async handleExistingModule(module, isEntry, isPreload) {
  20798. const loadPromise = this.moduleLoadPromises.get(module);
  20799. if (isPreload) {
  20800. return isPreload === RESOLVE_DEPENDENCIES
  20801. ? waitForDependencyResolution(loadPromise)
  20802. : loadPromise;
  20803. }
  20804. if (isEntry) {
  20805. module.info.isEntry = true;
  20806. this.implicitEntryModules.delete(module);
  20807. for (const dependant of module.implicitlyLoadedAfter) {
  20808. dependant.implicitlyLoadedBefore.delete(module);
  20809. }
  20810. module.implicitlyLoadedAfter.clear();
  20811. }
  20812. return this.fetchModuleDependencies(module, ...(await loadPromise));
  20813. }
  20814. handleResolveId(resolvedId, source, importer) {
  20815. if (resolvedId === null) {
  20816. if (isRelative(source)) {
  20817. return error(errUnresolvedImport(source, importer));
  20818. }
  20819. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  20820. return {
  20821. external: true,
  20822. id: source,
  20823. meta: {},
  20824. moduleSideEffects: this.hasModuleSideEffects(source, true),
  20825. syntheticNamedExports: false
  20826. };
  20827. }
  20828. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  20829. this.options.onwarn(errExternalSyntheticExports(source, importer));
  20830. }
  20831. return resolvedId;
  20832. }
  20833. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  20834. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true);
  20835. if (resolveIdResult == null) {
  20836. return error(implicitlyLoadedBefore === null
  20837. ? errUnresolvedEntry(unresolvedId)
  20838. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  20839. }
  20840. if (resolveIdResult === false ||
  20841. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  20842. return error(implicitlyLoadedBefore === null
  20843. ? errEntryCannotBeExternal(unresolvedId)
  20844. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  20845. }
  20846. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  20847. ? resolveIdResult
  20848. : { id: resolveIdResult }), undefined, isEntry, false);
  20849. }
  20850. async resolveDynamicImport(module, specifier, importer) {
  20851. var _a;
  20852. var _b;
  20853. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  20854. specifier,
  20855. importer
  20856. ]);
  20857. if (typeof specifier !== 'string') {
  20858. if (typeof resolution === 'string') {
  20859. return resolution;
  20860. }
  20861. if (!resolution) {
  20862. return null;
  20863. }
  20864. return {
  20865. external: false,
  20866. moduleSideEffects: true,
  20867. ...resolution
  20868. };
  20869. }
  20870. if (resolution == null) {
  20871. 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)));
  20872. }
  20873. return this.handleResolveId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  20874. }
  20875. }
  20876. function normalizeRelativeExternalId(source, importer) {
  20877. return isRelative(source)
  20878. ? importer
  20879. ? resolve(importer, '..', source)
  20880. : resolve(source)
  20881. : source;
  20882. }
  20883. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  20884. var _a;
  20885. if (fileName !== null) {
  20886. module.chunkFileNames.add(fileName);
  20887. }
  20888. else if (name !== null) {
  20889. // Always keep chunkNames sorted by priority
  20890. let namePosition = 0;
  20891. while (((_a = module.chunkNames[namePosition]) === null || _a === void 0 ? void 0 : _a.priority) < priority)
  20892. namePosition++;
  20893. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  20894. }
  20895. }
  20896. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  20897. return (makeAbsoluteExternalsRelative === true ||
  20898. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  20899. !isAbsolute(id));
  20900. }
  20901. async function waitForDependencyResolution(loadPromise) {
  20902. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  20903. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  20904. }
  20905. class GlobalScope extends Scope$1 {
  20906. constructor() {
  20907. super();
  20908. this.parent = null;
  20909. this.variables.set('undefined', new UndefinedVariable());
  20910. }
  20911. findVariable(name) {
  20912. let variable = this.variables.get(name);
  20913. if (!variable) {
  20914. variable = new GlobalVariable(name);
  20915. this.variables.set(name, variable);
  20916. }
  20917. return variable;
  20918. }
  20919. }
  20920. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  20921. let deprecationWarningShown = false;
  20922. return ((...args) => {
  20923. if (!deprecationWarningShown) {
  20924. deprecationWarningShown = true;
  20925. warnDeprecation({
  20926. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  20927. plugin: pluginName
  20928. }, activeDeprecation, options);
  20929. }
  20930. return handler(...args);
  20931. });
  20932. }
  20933. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  20934. let cacheable = true;
  20935. if (typeof plugin.cacheKey !== 'string') {
  20936. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20937. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  20938. existingPluginNames.has(plugin.name)) {
  20939. cacheable = false;
  20940. }
  20941. else {
  20942. existingPluginNames.add(plugin.name);
  20943. }
  20944. }
  20945. let cacheInstance;
  20946. if (!pluginCache) {
  20947. cacheInstance = NO_CACHE;
  20948. }
  20949. else if (cacheable) {
  20950. const cacheKey = plugin.cacheKey || plugin.name;
  20951. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  20952. }
  20953. else {
  20954. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  20955. }
  20956. return {
  20957. addWatchFile(id) {
  20958. if (graph.phase >= BuildPhase.GENERATE) {
  20959. return this.error(errInvalidRollupPhaseForAddWatchFile());
  20960. }
  20961. graph.watchFiles[id] = true;
  20962. },
  20963. cache: cacheInstance,
  20964. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  20965. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  20966. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  20967. error(err) {
  20968. return throwPluginError(err, plugin.name);
  20969. },
  20970. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  20971. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  20972. getFileName: fileEmitter.getFileName,
  20973. getModuleIds: () => graph.modulesById.keys(),
  20974. getModuleInfo: graph.getModuleInfo,
  20975. getWatchFiles: () => Object.keys(graph.watchFiles),
  20976. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  20977. load(resolvedId) {
  20978. return graph.moduleLoader.preloadModule(resolvedId);
  20979. },
  20980. meta: {
  20981. rollupVersion: version$1,
  20982. watchMode: graph.watchMode
  20983. },
  20984. get moduleIds() {
  20985. function* wrappedModuleIds() {
  20986. // We are wrapping this in a generator to only show the message once we are actually iterating
  20987. warnDeprecation({
  20988. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  20989. plugin: plugin.name
  20990. }, false, options);
  20991. yield* moduleIds;
  20992. }
  20993. const moduleIds = graph.modulesById.keys();
  20994. return wrappedModuleIds();
  20995. },
  20996. parse: graph.contextParse.bind(graph),
  20997. resolve(source, importer, { custom, isEntry, skipSelf } = BLANK) {
  20998. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, skipSelf ? [{ importer, plugin, source }] : null);
  20999. },
  21000. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  21001. .resolveId(source, importer, BLANK, undefined)
  21002. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  21003. setAssetSource: fileEmitter.setAssetSource,
  21004. warn(warning) {
  21005. if (typeof warning === 'string')
  21006. warning = { message: warning };
  21007. if (warning.code)
  21008. warning.pluginCode = warning.code;
  21009. warning.code = 'PLUGIN_WARNING';
  21010. warning.plugin = plugin.name;
  21011. options.onwarn(warning);
  21012. }
  21013. };
  21014. }
  21015. // This will make sure no input hook is omitted
  21016. const inputHookNames = {
  21017. buildEnd: 1,
  21018. buildStart: 1,
  21019. closeBundle: 1,
  21020. closeWatcher: 1,
  21021. load: 1,
  21022. moduleParsed: 1,
  21023. options: 1,
  21024. resolveDynamicImport: 1,
  21025. resolveId: 1,
  21026. shouldTransformCachedModule: 1,
  21027. transform: 1,
  21028. watchChange: 1
  21029. };
  21030. const inputHooks = Object.keys(inputHookNames);
  21031. class PluginDriver {
  21032. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21033. this.graph = graph;
  21034. this.options = options;
  21035. this.pluginCache = pluginCache;
  21036. this.sortedPlugins = new Map();
  21037. this.unfulfilledActions = new Set();
  21038. warnDeprecatedHooks(userPlugins, options);
  21039. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21040. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21041. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21042. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  21043. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21044. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  21045. const existingPluginNames = new Set();
  21046. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21047. plugin,
  21048. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21049. ]));
  21050. if (basePluginDriver) {
  21051. for (const plugin of userPlugins) {
  21052. for (const hook of inputHooks) {
  21053. if (hook in plugin) {
  21054. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  21055. }
  21056. }
  21057. }
  21058. }
  21059. }
  21060. createOutputPluginDriver(plugins) {
  21061. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21062. }
  21063. getUnfulfilledHookActions() {
  21064. return this.unfulfilledActions;
  21065. }
  21066. // chains, first non-null result stops and returns
  21067. hookFirst(hookName, args, replaceContext, skipped) {
  21068. let promise = Promise.resolve(null);
  21069. for (const plugin of this.getSortedPlugins(hookName)) {
  21070. if (skipped && skipped.has(plugin))
  21071. continue;
  21072. promise = promise.then(result => {
  21073. if (result != null)
  21074. return result;
  21075. return this.runHook(hookName, args, plugin, replaceContext);
  21076. });
  21077. }
  21078. return promise;
  21079. }
  21080. // chains synchronously, first non-null result stops and returns
  21081. hookFirstSync(hookName, args, replaceContext) {
  21082. for (const plugin of this.getSortedPlugins(hookName)) {
  21083. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21084. if (result != null)
  21085. return result;
  21086. }
  21087. return null;
  21088. }
  21089. // parallel, ignores returns
  21090. async hookParallel(hookName, args, replaceContext) {
  21091. const parallelPromises = [];
  21092. for (const plugin of this.getSortedPlugins(hookName)) {
  21093. if (plugin[hookName].sequential) {
  21094. await Promise.all(parallelPromises);
  21095. parallelPromises.length = 0;
  21096. await this.runHook(hookName, args, plugin, replaceContext);
  21097. }
  21098. else {
  21099. parallelPromises.push(this.runHook(hookName, args, plugin, replaceContext));
  21100. }
  21101. }
  21102. await Promise.all(parallelPromises);
  21103. }
  21104. // chains, reduces returned value, handling the reduced value as the first hook argument
  21105. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  21106. let promise = Promise.resolve(arg0);
  21107. for (const plugin of this.getSortedPlugins(hookName)) {
  21108. promise = promise.then(arg0 => this.runHook(hookName, [arg0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin)));
  21109. }
  21110. return promise;
  21111. }
  21112. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21113. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  21114. for (const plugin of this.getSortedPlugins(hookName)) {
  21115. const args = [arg0, ...rest];
  21116. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21117. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  21118. }
  21119. return arg0;
  21120. }
  21121. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21122. async hookReduceValue(hookName, initialValue, args, reducer) {
  21123. const results = [];
  21124. const parallelResults = [];
  21125. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21126. if (plugin[hookName].sequential) {
  21127. results.push(...(await Promise.all(parallelResults)));
  21128. parallelResults.length = 0;
  21129. results.push(await this.runHook(hookName, args, plugin));
  21130. }
  21131. else {
  21132. parallelResults.push(this.runHook(hookName, args, plugin));
  21133. }
  21134. }
  21135. results.push(...(await Promise.all(parallelResults)));
  21136. return results.reduce(reducer, await initialValue);
  21137. }
  21138. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21139. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  21140. let acc = initialValue;
  21141. for (const plugin of this.getSortedPlugins(hookName)) {
  21142. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  21143. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  21144. }
  21145. return acc;
  21146. }
  21147. // chains, ignores returns
  21148. hookSeq(hookName, args, replaceContext) {
  21149. let promise = Promise.resolve();
  21150. for (const plugin of this.getSortedPlugins(hookName)) {
  21151. promise = promise.then(() => this.runHook(hookName, args, plugin, replaceContext));
  21152. }
  21153. return promise.then(noReturn);
  21154. }
  21155. getSortedPlugins(hookName, validateHandler) {
  21156. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21157. }
  21158. // Implementation signature
  21159. runHook(hookName, args, plugin, replaceContext) {
  21160. // We always filter for plugins that support the hook before running it
  21161. const hook = plugin[hookName];
  21162. const handler = typeof hook === 'object' ? hook.handler : hook;
  21163. let context = this.pluginContexts.get(plugin);
  21164. if (replaceContext) {
  21165. context = replaceContext(context, plugin);
  21166. }
  21167. let action = null;
  21168. return Promise.resolve()
  21169. .then(() => {
  21170. if (typeof handler !== 'function') {
  21171. return handler;
  21172. }
  21173. // eslint-disable-next-line @typescript-eslint/ban-types
  21174. const hookResult = handler.apply(context, args);
  21175. if (!(hookResult === null || hookResult === void 0 ? void 0 : hookResult.then)) {
  21176. // short circuit for non-thenables and non-Promises
  21177. return hookResult;
  21178. }
  21179. // Track pending hook actions to properly error out when
  21180. // unfulfilled promises cause rollup to abruptly and confusingly
  21181. // exit with a successful 0 return code but without producing any
  21182. // output, errors or warnings.
  21183. action = [plugin.name, hookName, args];
  21184. this.unfulfilledActions.add(action);
  21185. // Although it would be more elegant to just return hookResult here
  21186. // and put the .then() handler just above the .catch() handler below,
  21187. // doing so would subtly change the defacto async event dispatch order
  21188. // which at least one test and some plugins in the wild may depend on.
  21189. return Promise.resolve(hookResult).then(result => {
  21190. // action was fulfilled
  21191. this.unfulfilledActions.delete(action);
  21192. return result;
  21193. });
  21194. })
  21195. .catch(err => {
  21196. if (action !== null) {
  21197. // action considered to be fulfilled since error being handled
  21198. this.unfulfilledActions.delete(action);
  21199. }
  21200. return throwPluginError(err, plugin.name, { hook: hookName });
  21201. });
  21202. }
  21203. /**
  21204. * Run a sync plugin hook and return the result.
  21205. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21206. * @param args Arguments passed to the plugin hook.
  21207. * @param plugin The acutal plugin
  21208. * @param replaceContext When passed, the plugin context can be overridden.
  21209. */
  21210. runHookSync(hookName, args, plugin, replaceContext) {
  21211. const hook = plugin[hookName];
  21212. const handler = typeof hook === 'object' ? hook.handler : hook;
  21213. let context = this.pluginContexts.get(plugin);
  21214. if (replaceContext) {
  21215. context = replaceContext(context, plugin);
  21216. }
  21217. try {
  21218. // eslint-disable-next-line @typescript-eslint/ban-types
  21219. return handler.apply(context, args);
  21220. }
  21221. catch (err) {
  21222. return throwPluginError(err, plugin.name, { hook: hookName });
  21223. }
  21224. }
  21225. }
  21226. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  21227. const pre = [];
  21228. const normal = [];
  21229. const post = [];
  21230. for (const plugin of plugins) {
  21231. const hook = plugin[hookName];
  21232. if (hook) {
  21233. if (typeof hook === 'object') {
  21234. validateHandler(hook.handler, hookName, plugin);
  21235. if (hook.order === 'pre') {
  21236. pre.push(plugin);
  21237. continue;
  21238. }
  21239. if (hook.order === 'post') {
  21240. post.push(plugin);
  21241. continue;
  21242. }
  21243. }
  21244. else {
  21245. validateHandler(hook, hookName, plugin);
  21246. }
  21247. normal.push(plugin);
  21248. }
  21249. }
  21250. return [...pre, ...normal, ...post];
  21251. }
  21252. function validateFunctionPluginHandler(handler, hookName, plugin) {
  21253. if (typeof handler !== 'function') {
  21254. error(errInvalidFunctionPluginHook(hookName, plugin.name));
  21255. }
  21256. }
  21257. function validateAddonPluginHandler(handler, hookName, plugin) {
  21258. if (typeof handler !== 'string' && typeof handler !== 'function') {
  21259. return error(errInvalidAddonPluginHook(hookName, plugin.name));
  21260. }
  21261. }
  21262. function noReturn() { }
  21263. class Queue {
  21264. constructor(maxParallel) {
  21265. this.maxParallel = maxParallel;
  21266. this.queue = [];
  21267. this.workerCount = 0;
  21268. }
  21269. run(task) {
  21270. return new Promise((resolve, reject) => {
  21271. this.queue.push({ reject, resolve, task });
  21272. this.work();
  21273. });
  21274. }
  21275. async work() {
  21276. if (this.workerCount >= this.maxParallel)
  21277. return;
  21278. this.workerCount++;
  21279. let entry;
  21280. while ((entry = this.queue.shift())) {
  21281. const { reject, resolve, task } = entry;
  21282. try {
  21283. const result = await task();
  21284. resolve(result);
  21285. }
  21286. catch (err) {
  21287. reject(err);
  21288. }
  21289. }
  21290. this.workerCount--;
  21291. }
  21292. }
  21293. function normalizeEntryModules(entryModules) {
  21294. if (Array.isArray(entryModules)) {
  21295. return entryModules.map(id => ({
  21296. fileName: null,
  21297. id,
  21298. implicitlyLoadedAfter: [],
  21299. importer: undefined,
  21300. name: null
  21301. }));
  21302. }
  21303. return Object.entries(entryModules).map(([name, id]) => ({
  21304. fileName: null,
  21305. id,
  21306. implicitlyLoadedAfter: [],
  21307. importer: undefined,
  21308. name
  21309. }));
  21310. }
  21311. class Graph {
  21312. constructor(options, watcher) {
  21313. var _a, _b;
  21314. this.options = options;
  21315. this.cachedModules = new Map();
  21316. this.deoptimizationTracker = new PathTracker();
  21317. this.entryModules = [];
  21318. this.modulesById = new Map();
  21319. this.needsTreeshakingPass = false;
  21320. this.phase = BuildPhase.LOAD_AND_PARSE;
  21321. this.scope = new GlobalScope();
  21322. this.watchFiles = Object.create(null);
  21323. this.watchMode = false;
  21324. this.externalModules = [];
  21325. this.implicitEntryModules = [];
  21326. this.modules = [];
  21327. this.getModuleInfo = (moduleId) => {
  21328. const foundModule = this.modulesById.get(moduleId);
  21329. if (!foundModule)
  21330. return null;
  21331. return foundModule.info;
  21332. };
  21333. if (options.cache !== false) {
  21334. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  21335. for (const module of options.cache.modules)
  21336. this.cachedModules.set(module.id, module);
  21337. }
  21338. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  21339. // increment access counter
  21340. for (const name in this.pluginCache) {
  21341. const cache = this.pluginCache[name];
  21342. for (const value of Object.values(cache))
  21343. value[0]++;
  21344. }
  21345. }
  21346. if (watcher) {
  21347. this.watchMode = true;
  21348. const handleChange = (...args) => this.pluginDriver.hookParallel('watchChange', args);
  21349. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  21350. watcher.onCurrentAwaited('change', handleChange);
  21351. watcher.onCurrentAwaited('close', handleClose);
  21352. }
  21353. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  21354. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  21355. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  21356. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  21357. }
  21358. async build() {
  21359. timeStart('generate module graph', 2);
  21360. await this.generateModuleGraph();
  21361. timeEnd('generate module graph', 2);
  21362. timeStart('sort modules', 2);
  21363. this.phase = BuildPhase.ANALYSE;
  21364. this.sortModules();
  21365. timeEnd('sort modules', 2);
  21366. timeStart('mark included statements', 2);
  21367. this.includeStatements();
  21368. timeEnd('mark included statements', 2);
  21369. this.phase = BuildPhase.GENERATE;
  21370. }
  21371. contextParse(code, options = {}) {
  21372. const onCommentOrig = options.onComment;
  21373. const comments = [];
  21374. if (onCommentOrig && typeof onCommentOrig == 'function') {
  21375. options.onComment = (block, text, start, end, ...args) => {
  21376. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  21377. return onCommentOrig.call(options, block, text, start, end, ...args);
  21378. };
  21379. }
  21380. else {
  21381. options.onComment = comments;
  21382. }
  21383. const ast = this.acornParser.parse(code, {
  21384. ...this.options.acorn,
  21385. ...options
  21386. });
  21387. if (typeof onCommentOrig == 'object') {
  21388. onCommentOrig.push(...comments);
  21389. }
  21390. options.onComment = onCommentOrig;
  21391. addAnnotations(comments, ast, code);
  21392. return ast;
  21393. }
  21394. getCache() {
  21395. // handle plugin cache eviction
  21396. for (const name in this.pluginCache) {
  21397. const cache = this.pluginCache[name];
  21398. let allDeleted = true;
  21399. for (const [key, value] of Object.entries(cache)) {
  21400. if (value[0] >= this.options.experimentalCacheExpiry)
  21401. delete cache[key];
  21402. else
  21403. allDeleted = false;
  21404. }
  21405. if (allDeleted)
  21406. delete this.pluginCache[name];
  21407. }
  21408. return {
  21409. modules: this.modules.map(module => module.toJSON()),
  21410. plugins: this.pluginCache
  21411. };
  21412. }
  21413. async generateModuleGraph() {
  21414. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  21415. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  21416. if (this.entryModules.length === 0) {
  21417. throw new Error('You must supply options.input to rollup');
  21418. }
  21419. for (const module of this.modulesById.values()) {
  21420. if (module instanceof Module) {
  21421. this.modules.push(module);
  21422. }
  21423. else {
  21424. this.externalModules.push(module);
  21425. }
  21426. }
  21427. }
  21428. includeStatements() {
  21429. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21430. markModuleAndImpureDependenciesAsExecuted(module);
  21431. }
  21432. if (this.options.treeshake) {
  21433. let treeshakingPass = 1;
  21434. do {
  21435. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  21436. this.needsTreeshakingPass = false;
  21437. for (const module of this.modules) {
  21438. if (module.isExecuted) {
  21439. if (module.info.moduleSideEffects === 'no-treeshake') {
  21440. module.includeAllInBundle();
  21441. }
  21442. else {
  21443. module.include();
  21444. }
  21445. }
  21446. }
  21447. if (treeshakingPass === 1) {
  21448. // We only include exports after the first pass to avoid issues with
  21449. // the TDZ detection logic
  21450. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  21451. if (module.preserveSignature !== false) {
  21452. module.includeAllExports(false);
  21453. this.needsTreeshakingPass = true;
  21454. }
  21455. }
  21456. }
  21457. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  21458. } while (this.needsTreeshakingPass);
  21459. }
  21460. else {
  21461. for (const module of this.modules)
  21462. module.includeAllInBundle();
  21463. }
  21464. for (const externalModule of this.externalModules)
  21465. externalModule.warnUnusedImports();
  21466. for (const module of this.implicitEntryModules) {
  21467. for (const dependant of module.implicitlyLoadedAfter) {
  21468. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  21469. error(errImplicitDependantIsNotIncluded(dependant));
  21470. }
  21471. }
  21472. }
  21473. }
  21474. sortModules() {
  21475. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  21476. for (const cyclePath of cyclePaths) {
  21477. this.options.onwarn({
  21478. code: 'CIRCULAR_DEPENDENCY',
  21479. cycle: cyclePath,
  21480. importer: cyclePath[0],
  21481. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  21482. });
  21483. }
  21484. this.modules = orderedModules;
  21485. for (const module of this.modules) {
  21486. module.bindReferences();
  21487. }
  21488. this.warnForMissingExports();
  21489. }
  21490. warnForMissingExports() {
  21491. for (const module of this.modules) {
  21492. for (const importDescription of module.importDescriptions.values()) {
  21493. if (importDescription.name !== '*' &&
  21494. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  21495. module.warn({
  21496. code: 'NON_EXISTENT_EXPORT',
  21497. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  21498. name: importDescription.name,
  21499. source: importDescription.module.id
  21500. }, importDescription.start);
  21501. }
  21502. }
  21503. }
  21504. }
  21505. }
  21506. function ensureArray(items) {
  21507. if (Array.isArray(items)) {
  21508. return items.filter(Boolean);
  21509. }
  21510. if (items) {
  21511. return [items];
  21512. }
  21513. return [];
  21514. }
  21515. function formatAction([pluginName, hookName, args]) {
  21516. const action = `(${pluginName}) ${hookName}`;
  21517. const s = JSON.stringify;
  21518. switch (hookName) {
  21519. case 'resolveId':
  21520. return `${action} ${s(args[0])} ${s(args[1])}`;
  21521. case 'load':
  21522. return `${action} ${s(args[0])}`;
  21523. case 'transform':
  21524. return `${action} ${s(args[1])}`;
  21525. case 'shouldTransformCachedModule':
  21526. return `${action} ${s(args[0].id)}`;
  21527. case 'moduleParsed':
  21528. return `${action} ${s(args[0].id)}`;
  21529. }
  21530. return action;
  21531. }
  21532. // We do not directly listen on process to avoid max listeners warnings for
  21533. // complicated build processes
  21534. const beforeExitEvent = 'beforeExit';
  21535. const beforeExitEmitter = new EventEmitter();
  21536. beforeExitEmitter.setMaxListeners(0);
  21537. process$1.on(beforeExitEvent, () => beforeExitEmitter.emit(beforeExitEvent));
  21538. async function catchUnfinishedHookActions(pluginDriver, callback) {
  21539. let handleEmptyEventLoop;
  21540. const emptyEventLoopPromise = new Promise((_, reject) => {
  21541. handleEmptyEventLoop = () => {
  21542. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  21543. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  21544. [...unfulfilledActions].map(formatAction).join('\n')));
  21545. };
  21546. beforeExitEmitter.once(beforeExitEvent, handleEmptyEventLoop);
  21547. });
  21548. const result = await Promise.race([callback(), emptyEventLoopPromise]);
  21549. beforeExitEmitter.off(beforeExitEvent, handleEmptyEventLoop);
  21550. return result;
  21551. }
  21552. const defaultOnWarn = warning => console.warn(warning.message || warning);
  21553. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  21554. const validOptionSet = new Set(validOptions);
  21555. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  21556. if (unknownOptions.length > 0) {
  21557. warn({
  21558. code: 'UNKNOWN_OPTION',
  21559. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  21560. ...validOptionSet
  21561. ]
  21562. .sort()
  21563. .join(', ')}`
  21564. });
  21565. }
  21566. }
  21567. const treeshakePresets = {
  21568. recommended: {
  21569. annotations: true,
  21570. correctVarValueBeforeDeclaration: false,
  21571. moduleSideEffects: () => true,
  21572. propertyReadSideEffects: true,
  21573. tryCatchDeoptimization: true,
  21574. unknownGlobalSideEffects: false
  21575. },
  21576. safest: {
  21577. annotations: true,
  21578. correctVarValueBeforeDeclaration: true,
  21579. moduleSideEffects: () => true,
  21580. propertyReadSideEffects: true,
  21581. tryCatchDeoptimization: true,
  21582. unknownGlobalSideEffects: true
  21583. },
  21584. smallest: {
  21585. annotations: true,
  21586. correctVarValueBeforeDeclaration: false,
  21587. moduleSideEffects: () => false,
  21588. propertyReadSideEffects: false,
  21589. tryCatchDeoptimization: false,
  21590. unknownGlobalSideEffects: false
  21591. }
  21592. };
  21593. const generatedCodePresets = {
  21594. es2015: {
  21595. arrowFunctions: true,
  21596. constBindings: true,
  21597. objectShorthand: true,
  21598. reservedNamesAsProps: true,
  21599. symbols: true
  21600. },
  21601. es5: {
  21602. arrowFunctions: false,
  21603. constBindings: false,
  21604. objectShorthand: false,
  21605. reservedNamesAsProps: true,
  21606. symbols: false
  21607. }
  21608. };
  21609. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  21610. const objectifyOptionWithPresets = (presets, optionName, additionalValues) => (value) => {
  21611. if (typeof value === 'string') {
  21612. const preset = presets[value];
  21613. if (preset) {
  21614. return preset;
  21615. }
  21616. 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));
  21617. }
  21618. return objectifyOption(value);
  21619. };
  21620. const getOptionWithPreset = (value, presets, optionName, additionalValues) => {
  21621. const presetName = value === null || value === void 0 ? void 0 : value.preset;
  21622. if (presetName) {
  21623. const preset = presets[presetName];
  21624. if (preset) {
  21625. return { ...preset, ...value };
  21626. }
  21627. else {
  21628. error(errInvalidOption(`${optionName}.preset`, getHashFromObjectOption(optionName), `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  21629. }
  21630. }
  21631. return objectifyOptionWithPresets(presets, optionName, additionalValues)(value);
  21632. };
  21633. const getHashFromObjectOption = (optionName) => optionName.split('.').join('').toLowerCase();
  21634. function normalizeInputOptions(config) {
  21635. var _a, _b, _c;
  21636. // These are options that may trigger special warnings or behaviour later
  21637. // if the user did not select an explicit value
  21638. const unsetOptions = new Set();
  21639. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  21640. const onwarn = getOnwarn(config);
  21641. const strictDeprecations = config.strictDeprecations || false;
  21642. const maxParallelFileOps = getmaxParallelFileOps(config, onwarn, strictDeprecations);
  21643. const options = {
  21644. acorn: getAcorn(config),
  21645. acornInjectPlugins: getAcornInjectPlugins(config),
  21646. cache: getCache(config),
  21647. context,
  21648. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  21649. external: getIdMatcher(config.external),
  21650. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  21651. input: getInput(config),
  21652. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  21653. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  21654. maxParallelFileOps,
  21655. maxParallelFileReads: maxParallelFileOps,
  21656. moduleContext: getModuleContext(config, context),
  21657. onwarn,
  21658. perf: config.perf || false,
  21659. plugins: ensureArray(config.plugins),
  21660. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  21661. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  21662. preserveSymlinks: config.preserveSymlinks || false,
  21663. shimMissingExports: config.shimMissingExports || false,
  21664. strictDeprecations,
  21665. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  21666. };
  21667. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  21668. return { options, unsetOptions };
  21669. }
  21670. const getOnwarn = (config) => {
  21671. const { onwarn } = config;
  21672. return onwarn
  21673. ? warning => {
  21674. warning.toString = () => {
  21675. let str = '';
  21676. if (warning.plugin)
  21677. str += `(${warning.plugin} plugin) `;
  21678. if (warning.loc)
  21679. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  21680. str += warning.message;
  21681. return str;
  21682. };
  21683. onwarn(warning, defaultOnWarn);
  21684. }
  21685. : defaultOnWarn;
  21686. };
  21687. const getAcorn = (config) => ({
  21688. allowAwaitOutsideFunction: true,
  21689. ecmaVersion: 'latest',
  21690. preserveParens: false,
  21691. sourceType: 'module',
  21692. ...config.acorn
  21693. });
  21694. const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
  21695. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  21696. const getIdMatcher = (option) => {
  21697. if (option === true) {
  21698. return () => true;
  21699. }
  21700. if (typeof option === 'function') {
  21701. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  21702. }
  21703. if (option) {
  21704. const ids = new Set();
  21705. const matchers = [];
  21706. for (const value of ensureArray(option)) {
  21707. if (value instanceof RegExp) {
  21708. matchers.push(value);
  21709. }
  21710. else {
  21711. ids.add(value);
  21712. }
  21713. }
  21714. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  21715. }
  21716. return () => false;
  21717. };
  21718. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  21719. const configInlineDynamicImports = config.inlineDynamicImports;
  21720. if (configInlineDynamicImports) {
  21721. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  21722. }
  21723. return configInlineDynamicImports;
  21724. };
  21725. const getInput = (config) => {
  21726. const configInput = config.input;
  21727. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  21728. };
  21729. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  21730. const configManualChunks = config.manualChunks;
  21731. if (configManualChunks) {
  21732. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  21733. }
  21734. return configManualChunks;
  21735. };
  21736. const getmaxParallelFileOps = (config, warn, strictDeprecations) => {
  21737. var _a;
  21738. const maxParallelFileReads = config.maxParallelFileReads;
  21739. if (typeof maxParallelFileReads === 'number') {
  21740. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', false, warn, strictDeprecations);
  21741. }
  21742. const maxParallelFileOps = (_a = config.maxParallelFileOps) !== null && _a !== void 0 ? _a : maxParallelFileReads;
  21743. if (typeof maxParallelFileOps === 'number') {
  21744. if (maxParallelFileOps <= 0)
  21745. return Infinity;
  21746. return maxParallelFileOps;
  21747. }
  21748. return 20;
  21749. };
  21750. const getModuleContext = (config, context) => {
  21751. const configModuleContext = config.moduleContext;
  21752. if (typeof configModuleContext === 'function') {
  21753. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  21754. }
  21755. if (configModuleContext) {
  21756. const contextByModuleId = Object.create(null);
  21757. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  21758. contextByModuleId[resolve(key)] = moduleContext;
  21759. }
  21760. return id => contextByModuleId[id] || context;
  21761. }
  21762. return () => context;
  21763. };
  21764. const getPreserveEntrySignatures = (config, unsetOptions) => {
  21765. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  21766. if (configPreserveEntrySignatures == null) {
  21767. unsetOptions.add('preserveEntrySignatures');
  21768. }
  21769. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  21770. };
  21771. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  21772. const configPreserveModules = config.preserveModules;
  21773. if (configPreserveModules) {
  21774. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  21775. }
  21776. return configPreserveModules;
  21777. };
  21778. const getTreeshake = (config, warn, strictDeprecations) => {
  21779. const configTreeshake = config.treeshake;
  21780. if (configTreeshake === false) {
  21781. return false;
  21782. }
  21783. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', 'false, true, ');
  21784. if (typeof configWithPreset.pureExternalModules !== 'undefined') {
  21785. 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);
  21786. }
  21787. return {
  21788. annotations: configWithPreset.annotations !== false,
  21789. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  21790. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  21791. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  21792. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  21793. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  21794. ? 'always'
  21795. : configWithPreset.propertyReadSideEffects !== false,
  21796. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  21797. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  21798. };
  21799. };
  21800. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  21801. if (typeof moduleSideEffectsOption === 'boolean') {
  21802. return () => moduleSideEffectsOption;
  21803. }
  21804. if (moduleSideEffectsOption === 'no-external') {
  21805. return (_id, external) => !external;
  21806. }
  21807. if (typeof moduleSideEffectsOption === 'function') {
  21808. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  21809. }
  21810. if (Array.isArray(moduleSideEffectsOption)) {
  21811. const ids = new Set(moduleSideEffectsOption);
  21812. return id => ids.has(id);
  21813. }
  21814. if (moduleSideEffectsOption) {
  21815. error(errInvalidOption('treeshake.moduleSideEffects', 'treeshake', 'please use one of false, "no-external", a function or an array'));
  21816. }
  21817. const isPureExternalModule = getIdMatcher(pureExternalModules);
  21818. return (id, external) => !(external && isPureExternalModule(id));
  21819. };
  21820. // https://datatracker.ietf.org/doc/html/rfc2396
  21821. // eslint-disable-next-line no-control-regex
  21822. const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
  21823. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  21824. function sanitizeFileName(name) {
  21825. const match = DRIVE_LETTER_REGEX.exec(name);
  21826. const driveLetter = match ? match[0] : '';
  21827. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  21828. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  21829. return driveLetter + name.substr(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  21830. }
  21831. function isValidUrl(url) {
  21832. try {
  21833. new URL(url);
  21834. }
  21835. catch (_) {
  21836. return false;
  21837. }
  21838. return true;
  21839. }
  21840. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  21841. var _a, _b, _c, _d, _e, _f, _g;
  21842. // These are options that may trigger special warnings or behaviour later
  21843. // if the user did not select an explicit value
  21844. const unsetOptions = new Set(unsetInputOptions);
  21845. const compact = config.compact || false;
  21846. const format = getFormat(config);
  21847. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  21848. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  21849. const file = getFile(config, preserveModules, inputOptions);
  21850. const preferConst = getPreferConst(config, inputOptions);
  21851. const generatedCode = getGeneratedCode(config, preferConst);
  21852. const outputOptions = {
  21853. amd: getAmd(config),
  21854. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  21855. banner: getAddon(config, 'banner'),
  21856. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  21857. compact,
  21858. dir: getDir(config, file),
  21859. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  21860. entryFileNames: getEntryFileNames(config, unsetOptions),
  21861. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  21862. exports: getExports(config, unsetOptions),
  21863. extend: config.extend || false,
  21864. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  21865. file,
  21866. footer: getAddon(config, 'footer'),
  21867. format,
  21868. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  21869. generatedCode,
  21870. globals: config.globals || {},
  21871. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  21872. indent: getIndent(config, compact),
  21873. inlineDynamicImports,
  21874. interop: getInterop(config, inputOptions),
  21875. intro: getAddon(config, 'intro'),
  21876. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  21877. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  21878. name: config.name,
  21879. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  21880. noConflict: config.noConflict || false,
  21881. outro: getAddon(config, 'outro'),
  21882. paths: config.paths || {},
  21883. plugins: ensureArray(config.plugins),
  21884. preferConst,
  21885. preserveModules,
  21886. preserveModulesRoot: getPreserveModulesRoot(config),
  21887. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  21888. ? config.sanitizeFileName
  21889. : config.sanitizeFileName === false
  21890. ? id => id
  21891. : sanitizeFileName,
  21892. sourcemap: config.sourcemap || false,
  21893. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  21894. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  21895. sourcemapFile: config.sourcemapFile,
  21896. sourcemapPathTransform: config.sourcemapPathTransform,
  21897. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  21898. systemNullSetters: config.systemNullSetters || false,
  21899. validate: config.validate || false
  21900. };
  21901. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  21902. return { options: outputOptions, unsetOptions };
  21903. }
  21904. const getFile = (config, preserveModules, inputOptions) => {
  21905. const { file } = config;
  21906. if (typeof file === 'string') {
  21907. if (preserveModules) {
  21908. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  21909. }
  21910. if (!Array.isArray(inputOptions.input))
  21911. return error(errInvalidOption('output.file', 'outputdir', 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  21912. }
  21913. return file;
  21914. };
  21915. const getFormat = (config) => {
  21916. const configFormat = config.format;
  21917. switch (configFormat) {
  21918. case undefined:
  21919. case 'es':
  21920. case 'esm':
  21921. case 'module':
  21922. return 'es';
  21923. case 'cjs':
  21924. case 'commonjs':
  21925. return 'cjs';
  21926. case 'system':
  21927. case 'systemjs':
  21928. return 'system';
  21929. case 'amd':
  21930. case 'iife':
  21931. case 'umd':
  21932. return configFormat;
  21933. default:
  21934. return error({
  21935. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  21936. url: `https://rollupjs.org/guide/en/#outputformat`
  21937. });
  21938. }
  21939. };
  21940. const getInlineDynamicImports = (config, inputOptions) => {
  21941. var _a;
  21942. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  21943. const { input } = inputOptions;
  21944. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  21945. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  21946. }
  21947. return inlineDynamicImports;
  21948. };
  21949. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  21950. var _a;
  21951. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  21952. if (preserveModules) {
  21953. if (inlineDynamicImports) {
  21954. return error(errInvalidOption('output.inlineDynamicImports', 'outputinlinedynamicimports', `this option is not supported for "output.preserveModules"`));
  21955. }
  21956. if (inputOptions.preserveEntrySignatures === false) {
  21957. return error(errInvalidOption('preserveEntrySignatures', 'preserveentrysignatures', 'setting this option to false is not supported for "output.preserveModules"'));
  21958. }
  21959. }
  21960. return preserveModules;
  21961. };
  21962. const getPreferConst = (config, inputOptions) => {
  21963. const configPreferConst = config.preferConst;
  21964. if (configPreferConst != null) {
  21965. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, false, inputOptions);
  21966. }
  21967. return !!configPreferConst;
  21968. };
  21969. const getPreserveModulesRoot = (config) => {
  21970. const { preserveModulesRoot } = config;
  21971. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  21972. return undefined;
  21973. }
  21974. return resolve(preserveModulesRoot);
  21975. };
  21976. const getAmd = (config) => {
  21977. const mergedOption = {
  21978. autoId: false,
  21979. basePath: '',
  21980. define: 'define',
  21981. ...config.amd
  21982. };
  21983. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  21984. return error(errInvalidOption('output.amd.id', 'outputamd', 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  21985. }
  21986. if (mergedOption.basePath && !mergedOption.autoId) {
  21987. return error(errInvalidOption('output.amd.basePath', 'outputamd', 'this option only works with "output.amd.autoId"'));
  21988. }
  21989. let normalized;
  21990. if (mergedOption.autoId) {
  21991. normalized = {
  21992. autoId: true,
  21993. basePath: mergedOption.basePath,
  21994. define: mergedOption.define
  21995. };
  21996. }
  21997. else {
  21998. normalized = {
  21999. autoId: false,
  22000. define: mergedOption.define,
  22001. id: mergedOption.id
  22002. };
  22003. }
  22004. return normalized;
  22005. };
  22006. const getAddon = (config, name) => {
  22007. const configAddon = config[name];
  22008. if (typeof configAddon === 'function') {
  22009. return configAddon;
  22010. }
  22011. return () => configAddon || '';
  22012. };
  22013. const getDir = (config, file) => {
  22014. const { dir } = config;
  22015. if (typeof dir === 'string' && typeof file === 'string') {
  22016. return error(errInvalidOption('output.dir', 'outputdir', 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  22017. }
  22018. return dir;
  22019. };
  22020. const getDynamicImportFunction = (config, inputOptions) => {
  22021. const configDynamicImportFunction = config.dynamicImportFunction;
  22022. if (configDynamicImportFunction) {
  22023. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  22024. }
  22025. return configDynamicImportFunction;
  22026. };
  22027. const getEntryFileNames = (config, unsetOptions) => {
  22028. const configEntryFileNames = config.entryFileNames;
  22029. if (configEntryFileNames == null) {
  22030. unsetOptions.add('entryFileNames');
  22031. }
  22032. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  22033. };
  22034. function getExports(config, unsetOptions) {
  22035. const configExports = config.exports;
  22036. if (configExports == null) {
  22037. unsetOptions.add('exports');
  22038. }
  22039. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22040. return error(errInvalidExportOptionValue(configExports));
  22041. }
  22042. return configExports || 'auto';
  22043. }
  22044. const getGeneratedCode = (config, preferConst) => {
  22045. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', '');
  22046. return {
  22047. arrowFunctions: configWithPreset.arrowFunctions === true,
  22048. constBindings: configWithPreset.constBindings === true || preferConst,
  22049. objectShorthand: configWithPreset.objectShorthand === true,
  22050. reservedNamesAsProps: configWithPreset.reservedNamesAsProps === true,
  22051. symbols: configWithPreset.symbols === true
  22052. };
  22053. };
  22054. const getIndent = (config, compact) => {
  22055. if (compact) {
  22056. return '';
  22057. }
  22058. const configIndent = config.indent;
  22059. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  22060. };
  22061. const ALLOWED_INTEROP_TYPES = new Set([
  22062. 'auto',
  22063. 'esModule',
  22064. 'default',
  22065. 'defaultOnly',
  22066. true,
  22067. false
  22068. ]);
  22069. const getInterop = (config, inputOptions) => {
  22070. const configInterop = config.interop;
  22071. const validatedInteropTypes = new Set();
  22072. const validateInterop = (interop) => {
  22073. if (!validatedInteropTypes.has(interop)) {
  22074. validatedInteropTypes.add(interop);
  22075. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22076. return error(errInvalidOption('output.interop', 'outputinterop', `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22077. }
  22078. if (typeof interop === 'boolean') {
  22079. warnDeprecation({
  22080. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  22081. url: 'https://rollupjs.org/guide/en/#outputinterop'
  22082. }, false, inputOptions);
  22083. }
  22084. }
  22085. return interop;
  22086. };
  22087. if (typeof configInterop === 'function') {
  22088. const interopPerId = Object.create(null);
  22089. let defaultInterop = null;
  22090. return id => id === null
  22091. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22092. : id in interopPerId
  22093. ? interopPerId[id]
  22094. : validateInterop((interopPerId[id] = configInterop(id)));
  22095. }
  22096. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  22097. };
  22098. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  22099. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  22100. if (configManualChunks) {
  22101. if (inlineDynamicImports) {
  22102. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.inlineDynamicImports"'));
  22103. }
  22104. if (preserveModules) {
  22105. return error(errInvalidOption('output.manualChunks', 'outputmanualchunks', 'this option is not supported for "output.preserveModules"'));
  22106. }
  22107. }
  22108. return configManualChunks || {};
  22109. };
  22110. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  22111. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  22112. const configNamespaceToStringTag = config.namespaceToStringTag;
  22113. if (configNamespaceToStringTag != null) {
  22114. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, false, inputOptions);
  22115. return configNamespaceToStringTag;
  22116. }
  22117. return generatedCode.symbols || false;
  22118. };
  22119. const getSourcemapBaseUrl = (config) => {
  22120. const { sourcemapBaseUrl } = config;
  22121. if (sourcemapBaseUrl) {
  22122. if (isValidUrl(sourcemapBaseUrl)) {
  22123. return sourcemapBaseUrl;
  22124. }
  22125. return error(errInvalidOption('output.sourcemapBaseUrl', 'outputsourcemapbaseurl', `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22126. }
  22127. };
  22128. function rollup(rawInputOptions) {
  22129. return rollupInternal(rawInputOptions, null);
  22130. }
  22131. async function rollupInternal(rawInputOptions, watcher) {
  22132. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22133. initialiseTimers(inputOptions);
  22134. const graph = new Graph(inputOptions, watcher);
  22135. // remove the cache option from the memory after graph creation (cache is not used anymore)
  22136. const useCache = rawInputOptions.cache !== false;
  22137. delete inputOptions.cache;
  22138. delete rawInputOptions.cache;
  22139. timeStart('BUILD', 1);
  22140. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22141. try {
  22142. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22143. await graph.build();
  22144. }
  22145. catch (err) {
  22146. const watchFiles = Object.keys(graph.watchFiles);
  22147. if (watchFiles.length > 0) {
  22148. err.watchFiles = watchFiles;
  22149. }
  22150. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  22151. await graph.pluginDriver.hookParallel('closeBundle', []);
  22152. throw err;
  22153. }
  22154. await graph.pluginDriver.hookParallel('buildEnd', []);
  22155. });
  22156. timeEnd('BUILD', 1);
  22157. const result = {
  22158. cache: useCache ? graph.getCache() : undefined,
  22159. async close() {
  22160. if (result.closed)
  22161. return;
  22162. result.closed = true;
  22163. await graph.pluginDriver.hookParallel('closeBundle', []);
  22164. },
  22165. closed: false,
  22166. async generate(rawOutputOptions) {
  22167. if (result.closed)
  22168. return error(errAlreadyClosed());
  22169. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22170. },
  22171. watchFiles: Object.keys(graph.watchFiles),
  22172. async write(rawOutputOptions) {
  22173. if (result.closed)
  22174. return error(errAlreadyClosed());
  22175. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22176. }
  22177. };
  22178. if (inputOptions.perf)
  22179. result.getTimings = getTimings;
  22180. return result;
  22181. }
  22182. async function getInputOptions(rawInputOptions, watchMode) {
  22183. if (!rawInputOptions) {
  22184. throw new Error('You must supply an options object to rollup');
  22185. }
  22186. const rawPlugins = getSortedValidatedPlugins('options', ensureArray(rawInputOptions.plugins));
  22187. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  22188. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22189. return { options, unsetOptions };
  22190. }
  22191. function applyOptionHook(watchMode) {
  22192. return async (inputOptions, plugin) => {
  22193. const handler = 'handler' in plugin.options ? plugin.options.handler : plugin.options;
  22194. return ((await handler.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  22195. };
  22196. }
  22197. function normalizePlugins(plugins, anonymousPrefix) {
  22198. plugins.forEach((plugin, index) => {
  22199. if (!plugin.name) {
  22200. plugin.name = `${anonymousPrefix}${index + 1}`;
  22201. }
  22202. });
  22203. }
  22204. function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22205. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22206. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22207. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22208. const generated = await bundle.generate(isWrite);
  22209. if (isWrite) {
  22210. if (!outputOptions.dir && !outputOptions.file) {
  22211. return error({
  22212. code: 'MISSING_OPTION',
  22213. message: 'You must specify "output.file" or "output.dir" for the build.'
  22214. });
  22215. }
  22216. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  22217. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22218. }
  22219. return createOutput(generated);
  22220. });
  22221. }
  22222. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22223. if (!rawOutputOptions) {
  22224. throw new Error('You must supply an options object');
  22225. }
  22226. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  22227. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22228. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22229. return {
  22230. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  22231. outputPluginDriver
  22232. };
  22233. }
  22234. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22235. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22236. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  22237. return {
  22238. ...pluginContext,
  22239. emitFile: emitError,
  22240. setAssetSource: emitError
  22241. };
  22242. }), inputOptions, unsetInputOptions);
  22243. }
  22244. function createOutput(outputBundle) {
  22245. return {
  22246. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  22247. const fileTypeA = getSortingFileType(outputFileA);
  22248. const fileTypeB = getSortingFileType(outputFileB);
  22249. if (fileTypeA === fileTypeB)
  22250. return 0;
  22251. return fileTypeA < fileTypeB ? -1 : 1;
  22252. })
  22253. };
  22254. }
  22255. var SortingFileType;
  22256. (function (SortingFileType) {
  22257. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22258. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22259. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22260. })(SortingFileType || (SortingFileType = {}));
  22261. function getSortingFileType(file) {
  22262. if (file.type === 'asset') {
  22263. return SortingFileType.ASSET;
  22264. }
  22265. if (file.isEntry) {
  22266. return SortingFileType.ENTRY_CHUNK;
  22267. }
  22268. return SortingFileType.SECONDARY_CHUNK;
  22269. }
  22270. async function writeOutputFile(outputFile, outputOptions) {
  22271. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22272. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22273. await promises.mkdir(dirname(fileName), { recursive: true });
  22274. let writeSourceMapPromise;
  22275. let source;
  22276. if (outputFile.type === 'asset') {
  22277. source = outputFile.source;
  22278. }
  22279. else {
  22280. source = outputFile.code;
  22281. if (outputOptions.sourcemap && outputFile.map) {
  22282. let url;
  22283. if (outputOptions.sourcemap === 'inline') {
  22284. url = outputFile.map.toUrl();
  22285. }
  22286. else {
  22287. const { sourcemapBaseUrl } = outputOptions;
  22288. const sourcemapFileName = `${basename(outputFile.fileName)}.map`;
  22289. url = sourcemapBaseUrl
  22290. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  22291. : sourcemapFileName;
  22292. writeSourceMapPromise = promises.writeFile(`${fileName}.map`, outputFile.map.toString());
  22293. }
  22294. if (outputOptions.sourcemap !== 'hidden') {
  22295. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  22296. }
  22297. }
  22298. }
  22299. return Promise.all([promises.writeFile(fileName, source), writeSourceMapPromise]);
  22300. }
  22301. /**
  22302. * Auxiliary function for defining rollup configuration
  22303. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  22304. * @param options
  22305. */
  22306. function defineConfig(options) {
  22307. return options;
  22308. }
  22309. class WatchEmitter extends EventEmitter {
  22310. constructor() {
  22311. super();
  22312. this.awaitedHandlers = Object.create(null);
  22313. // Allows more than 10 bundles to be watched without
  22314. // showing the `MaxListenersExceededWarning` to the user.
  22315. this.setMaxListeners(Infinity);
  22316. }
  22317. // Will be overwritten by Rollup
  22318. async close() { }
  22319. emitAndAwait(event, ...args) {
  22320. this.emit(event, ...args);
  22321. return Promise.all(this.getHandlers(event).map(handler => handler(...args)));
  22322. }
  22323. onCurrentAwaited(event, listener) {
  22324. this.getHandlers(event).push(listener);
  22325. return this;
  22326. }
  22327. removeAwaited() {
  22328. this.awaitedHandlers = {};
  22329. return this;
  22330. }
  22331. getHandlers(event) {
  22332. return this.awaitedHandlers[event] || (this.awaitedHandlers[event] = []);
  22333. }
  22334. }
  22335. let fsEvents;
  22336. let fsEventsImportError;
  22337. async function loadFsEvents() {
  22338. try {
  22339. ({ default: fsEvents } = await import('fsevents'));
  22340. }
  22341. catch (err) {
  22342. fsEventsImportError = err;
  22343. }
  22344. }
  22345. // A call to this function will be injected into the chokidar code
  22346. function getFsEvents() {
  22347. if (fsEventsImportError)
  22348. throw fsEventsImportError;
  22349. return fsEvents;
  22350. }
  22351. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  22352. __proto__: null,
  22353. loadFsEvents,
  22354. getFsEvents
  22355. }, Symbol.toStringTag, { value: 'Module' });
  22356. function watch(configs) {
  22357. const emitter = new WatchEmitter();
  22358. const configArray = ensureArray(configs);
  22359. const watchConfigs = configArray.filter(config => config.watch !== false);
  22360. if (watchConfigs.length === 0) {
  22361. return error(errInvalidOption('watch', 'watch', 'there must be at least one config where "watch" is not set to "false"'));
  22362. }
  22363. loadFsEvents()
  22364. .then(() => import('./watch.js'))
  22365. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  22366. return emitter;
  22367. }
  22368. export { createFilter, defaultOnWarn, defineConfig, ensureArray, fseventsImporter, generatedCodePresets, getAugmentedNamespace, objectifyOption, objectifyOptionWithPresets, picomatch$1 as picomatch, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };