rollup.js 740 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251
  1. /*
  2. @license
  3. Rollup.js v2.40.0
  4. Fri, 26 Feb 2021 14:39:44 GMT - commit 0a0958ff926554abe9916178f56762ba71301ddd
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. var path = require('path');
  10. var crypto = require('crypto');
  11. var fs = require('fs');
  12. var require$$0 = require('events');
  13. function _interopNamespaceDefaultOnly(e) {
  14. return {__proto__: null, 'default': e};
  15. }
  16. var version$1 = "2.40.0";
  17. function ensureArray(items) {
  18. if (Array.isArray(items)) {
  19. return items.filter(Boolean);
  20. }
  21. if (items) {
  22. return [items];
  23. }
  24. return [];
  25. }
  26. const defaultOnWarn = warning => console.warn(warning.message || warning);
  27. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  28. const validOptionSet = new Set(validOptions);
  29. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  30. if (unknownOptions.length > 0) {
  31. warn({
  32. code: 'UNKNOWN_OPTION',
  33. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  34. ...validOptionSet
  35. ]
  36. .sort()
  37. .join(', ')}`
  38. });
  39. }
  40. }
  41. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  42. const relativePath = /^\.?\.\//;
  43. function isAbsolute(path) {
  44. return absolutePath.test(path);
  45. }
  46. function isRelative(path) {
  47. return relativePath.test(path);
  48. }
  49. function normalize(path) {
  50. if (path.indexOf('\\') == -1)
  51. return path;
  52. return path.replace(/\\/g, '/');
  53. }
  54. function sanitizeFileName(name) {
  55. const match = /^[a-z]:/i.exec(name);
  56. const driveLetter = match ? match[0] : "";
  57. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  58. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  59. return driveLetter + name.substr(driveLetter.length).replace(/[\0?*:]/g, '_');
  60. }
  61. function getAliasName(id) {
  62. const base = path.basename(id);
  63. return base.substr(0, base.length - path.extname(id).length);
  64. }
  65. function relativeId(id) {
  66. if (!isAbsolute(id))
  67. return id;
  68. return path.relative(path.resolve(), id);
  69. }
  70. function isPlainPathFragment(name) {
  71. // not starting with "/", "./", "../"
  72. return (name[0] !== '/' &&
  73. !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
  74. sanitizeFileName(name) === name &&
  75. !isAbsolute(name));
  76. }
  77. let fsEvents;
  78. let fsEventsImportError;
  79. function loadFsEvents() {
  80. return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespaceDefaultOnly(require('fsevents')); })
  81. .then(namespace => {
  82. fsEvents = namespace.default;
  83. })
  84. .catch(err => {
  85. fsEventsImportError = err;
  86. });
  87. }
  88. // A call to this function will be injected into the chokidar code
  89. function getFsEvents() {
  90. if (fsEventsImportError)
  91. throw fsEventsImportError;
  92. return fsEvents;
  93. }
  94. var fseventsImporter = {
  95. __proto__: null,
  96. loadFsEvents: loadFsEvents,
  97. getFsEvents: getFsEvents
  98. };
  99. function getAugmentedNamespace(n) {
  100. if (n.__esModule) return n;
  101. var a = Object.defineProperty({}, '__esModule', {value: true});
  102. Object.keys(n).forEach(function (k) {
  103. var d = Object.getOwnPropertyDescriptor(n, k);
  104. Object.defineProperty(a, k, d.get ? d : {
  105. enumerable: true,
  106. get: function () {
  107. return n[k];
  108. }
  109. });
  110. });
  111. return a;
  112. }
  113. var charToInteger = {};
  114. var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  115. for (var i = 0; i < chars$1.length; i++) {
  116. charToInteger[chars$1.charCodeAt(i)] = i;
  117. }
  118. function decode(mappings) {
  119. var decoded = [];
  120. var line = [];
  121. var segment = [
  122. 0,
  123. 0,
  124. 0,
  125. 0,
  126. 0,
  127. ];
  128. var j = 0;
  129. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  130. var c = mappings.charCodeAt(i);
  131. if (c === 44) { // ","
  132. segmentify(line, segment, j);
  133. j = 0;
  134. }
  135. else if (c === 59) { // ";"
  136. segmentify(line, segment, j);
  137. j = 0;
  138. decoded.push(line);
  139. line = [];
  140. segment[0] = 0;
  141. }
  142. else {
  143. var integer = charToInteger[c];
  144. if (integer === undefined) {
  145. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  146. }
  147. var hasContinuationBit = integer & 32;
  148. integer &= 31;
  149. value += integer << shift;
  150. if (hasContinuationBit) {
  151. shift += 5;
  152. }
  153. else {
  154. var shouldNegate = value & 1;
  155. value >>>= 1;
  156. if (shouldNegate) {
  157. value = value === 0 ? -0x80000000 : -value;
  158. }
  159. segment[j] += value;
  160. j++;
  161. value = shift = 0; // reset
  162. }
  163. }
  164. }
  165. segmentify(line, segment, j);
  166. decoded.push(line);
  167. return decoded;
  168. }
  169. function segmentify(line, segment, j) {
  170. // This looks ugly, but we're creating specialized arrays with a specific
  171. // length. This is much faster than creating a new array (which v8 expands to
  172. // a capacity of 17 after pushing the first item), or slicing out a subarray
  173. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  174. // length 5 (since not everything will have an associated name), followed by
  175. // length 1 (it's probably rare for a source substring to not have an
  176. // associated segment data).
  177. if (j === 4)
  178. line.push([segment[0], segment[1], segment[2], segment[3]]);
  179. else if (j === 5)
  180. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  181. else if (j === 1)
  182. line.push([segment[0]]);
  183. }
  184. function encode(decoded) {
  185. var sourceFileIndex = 0; // second field
  186. var sourceCodeLine = 0; // third field
  187. var sourceCodeColumn = 0; // fourth field
  188. var nameIndex = 0; // fifth field
  189. var mappings = '';
  190. for (var i = 0; i < decoded.length; i++) {
  191. var line = decoded[i];
  192. if (i > 0)
  193. mappings += ';';
  194. if (line.length === 0)
  195. continue;
  196. var generatedCodeColumn = 0; // first field
  197. var lineMappings = [];
  198. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  199. var segment = line_1[_i];
  200. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  201. generatedCodeColumn = segment[0];
  202. if (segment.length > 1) {
  203. segmentMappings +=
  204. encodeInteger(segment[1] - sourceFileIndex) +
  205. encodeInteger(segment[2] - sourceCodeLine) +
  206. encodeInteger(segment[3] - sourceCodeColumn);
  207. sourceFileIndex = segment[1];
  208. sourceCodeLine = segment[2];
  209. sourceCodeColumn = segment[3];
  210. }
  211. if (segment.length === 5) {
  212. segmentMappings += encodeInteger(segment[4] - nameIndex);
  213. nameIndex = segment[4];
  214. }
  215. lineMappings.push(segmentMappings);
  216. }
  217. mappings += lineMappings.join(',');
  218. }
  219. return mappings;
  220. }
  221. function encodeInteger(num) {
  222. var result = '';
  223. num = num < 0 ? (-num << 1) | 1 : num << 1;
  224. do {
  225. var clamped = num & 31;
  226. num >>>= 5;
  227. if (num > 0) {
  228. clamped |= 32;
  229. }
  230. result += chars$1[clamped];
  231. } while (num > 0);
  232. return result;
  233. }
  234. var BitSet = function BitSet(arg) {
  235. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  236. };
  237. BitSet.prototype.add = function add (n) {
  238. this.bits[n >> 5] |= 1 << (n & 31);
  239. };
  240. BitSet.prototype.has = function has (n) {
  241. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  242. };
  243. var Chunk$1 = function Chunk(start, end, content) {
  244. this.start = start;
  245. this.end = end;
  246. this.original = content;
  247. this.intro = '';
  248. this.outro = '';
  249. this.content = content;
  250. this.storeName = false;
  251. this.edited = false;
  252. // we make these non-enumerable, for sanity while debugging
  253. Object.defineProperties(this, {
  254. previous: { writable: true, value: null },
  255. next: { writable: true, value: null }
  256. });
  257. };
  258. Chunk$1.prototype.appendLeft = function appendLeft (content) {
  259. this.outro += content;
  260. };
  261. Chunk$1.prototype.appendRight = function appendRight (content) {
  262. this.intro = this.intro + content;
  263. };
  264. Chunk$1.prototype.clone = function clone () {
  265. var chunk = new Chunk$1(this.start, this.end, this.original);
  266. chunk.intro = this.intro;
  267. chunk.outro = this.outro;
  268. chunk.content = this.content;
  269. chunk.storeName = this.storeName;
  270. chunk.edited = this.edited;
  271. return chunk;
  272. };
  273. Chunk$1.prototype.contains = function contains (index) {
  274. return this.start < index && index < this.end;
  275. };
  276. Chunk$1.prototype.eachNext = function eachNext (fn) {
  277. var chunk = this;
  278. while (chunk) {
  279. fn(chunk);
  280. chunk = chunk.next;
  281. }
  282. };
  283. Chunk$1.prototype.eachPrevious = function eachPrevious (fn) {
  284. var chunk = this;
  285. while (chunk) {
  286. fn(chunk);
  287. chunk = chunk.previous;
  288. }
  289. };
  290. Chunk$1.prototype.edit = function edit (content, storeName, contentOnly) {
  291. this.content = content;
  292. if (!contentOnly) {
  293. this.intro = '';
  294. this.outro = '';
  295. }
  296. this.storeName = storeName;
  297. this.edited = true;
  298. return this;
  299. };
  300. Chunk$1.prototype.prependLeft = function prependLeft (content) {
  301. this.outro = content + this.outro;
  302. };
  303. Chunk$1.prototype.prependRight = function prependRight (content) {
  304. this.intro = content + this.intro;
  305. };
  306. Chunk$1.prototype.split = function split (index) {
  307. var sliceIndex = index - this.start;
  308. var originalBefore = this.original.slice(0, sliceIndex);
  309. var originalAfter = this.original.slice(sliceIndex);
  310. this.original = originalBefore;
  311. var newChunk = new Chunk$1(index, this.end, originalAfter);
  312. newChunk.outro = this.outro;
  313. this.outro = '';
  314. this.end = index;
  315. if (this.edited) {
  316. // TODO is this block necessary?...
  317. newChunk.edit('', false);
  318. this.content = '';
  319. } else {
  320. this.content = originalBefore;
  321. }
  322. newChunk.next = this.next;
  323. if (newChunk.next) { newChunk.next.previous = newChunk; }
  324. newChunk.previous = this;
  325. this.next = newChunk;
  326. return newChunk;
  327. };
  328. Chunk$1.prototype.toString = function toString () {
  329. return this.intro + this.content + this.outro;
  330. };
  331. Chunk$1.prototype.trimEnd = function trimEnd (rx) {
  332. this.outro = this.outro.replace(rx, '');
  333. if (this.outro.length) { return true; }
  334. var trimmed = this.content.replace(rx, '');
  335. if (trimmed.length) {
  336. if (trimmed !== this.content) {
  337. this.split(this.start + trimmed.length).edit('', undefined, true);
  338. }
  339. return true;
  340. } else {
  341. this.edit('', undefined, true);
  342. this.intro = this.intro.replace(rx, '');
  343. if (this.intro.length) { return true; }
  344. }
  345. };
  346. Chunk$1.prototype.trimStart = function trimStart (rx) {
  347. this.intro = this.intro.replace(rx, '');
  348. if (this.intro.length) { return true; }
  349. var trimmed = this.content.replace(rx, '');
  350. if (trimmed.length) {
  351. if (trimmed !== this.content) {
  352. this.split(this.end - trimmed.length);
  353. this.edit('', undefined, true);
  354. }
  355. return true;
  356. } else {
  357. this.edit('', undefined, true);
  358. this.outro = this.outro.replace(rx, '');
  359. if (this.outro.length) { return true; }
  360. }
  361. };
  362. var btoa = function () {
  363. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  364. };
  365. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  366. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  367. } else if (typeof Buffer === 'function') {
  368. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  369. }
  370. var SourceMap = function SourceMap(properties) {
  371. this.version = 3;
  372. this.file = properties.file;
  373. this.sources = properties.sources;
  374. this.sourcesContent = properties.sourcesContent;
  375. this.names = properties.names;
  376. this.mappings = encode(properties.mappings);
  377. };
  378. SourceMap.prototype.toString = function toString () {
  379. return JSON.stringify(this);
  380. };
  381. SourceMap.prototype.toUrl = function toUrl () {
  382. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  383. };
  384. function guessIndent(code) {
  385. var lines = code.split('\n');
  386. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  387. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  388. if (tabbed.length === 0 && spaced.length === 0) {
  389. return null;
  390. }
  391. // More lines tabbed than spaced? Assume tabs, and
  392. // default to tabs in the case of a tie (or nothing
  393. // to go on)
  394. if (tabbed.length >= spaced.length) {
  395. return '\t';
  396. }
  397. // Otherwise, we need to guess the multiple
  398. var min = spaced.reduce(function (previous, current) {
  399. var numSpaces = /^ +/.exec(current)[0].length;
  400. return Math.min(numSpaces, previous);
  401. }, Infinity);
  402. return new Array(min + 1).join(' ');
  403. }
  404. function getRelativePath(from, to) {
  405. var fromParts = from.split(/[/\\]/);
  406. var toParts = to.split(/[/\\]/);
  407. fromParts.pop(); // get dirname
  408. while (fromParts[0] === toParts[0]) {
  409. fromParts.shift();
  410. toParts.shift();
  411. }
  412. if (fromParts.length) {
  413. var i = fromParts.length;
  414. while (i--) { fromParts[i] = '..'; }
  415. }
  416. return fromParts.concat(toParts).join('/');
  417. }
  418. var toString$1 = Object.prototype.toString;
  419. function isObject(thing) {
  420. return toString$1.call(thing) === '[object Object]';
  421. }
  422. function getLocator$1(source) {
  423. var originalLines = source.split('\n');
  424. var lineOffsets = [];
  425. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  426. lineOffsets.push(pos);
  427. pos += originalLines[i].length + 1;
  428. }
  429. return function locate(index) {
  430. var i = 0;
  431. var j = lineOffsets.length;
  432. while (i < j) {
  433. var m = (i + j) >> 1;
  434. if (index < lineOffsets[m]) {
  435. j = m;
  436. } else {
  437. i = m + 1;
  438. }
  439. }
  440. var line = i - 1;
  441. var column = index - lineOffsets[line];
  442. return { line: line, column: column };
  443. };
  444. }
  445. var Mappings = function Mappings(hires) {
  446. this.hires = hires;
  447. this.generatedCodeLine = 0;
  448. this.generatedCodeColumn = 0;
  449. this.raw = [];
  450. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  451. this.pending = null;
  452. };
  453. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  454. if (content.length) {
  455. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  456. if (nameIndex >= 0) {
  457. segment.push(nameIndex);
  458. }
  459. this.rawSegments.push(segment);
  460. } else if (this.pending) {
  461. this.rawSegments.push(this.pending);
  462. }
  463. this.advance(content);
  464. this.pending = null;
  465. };
  466. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  467. var originalCharIndex = chunk.start;
  468. var first = true;
  469. while (originalCharIndex < chunk.end) {
  470. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  471. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  472. }
  473. if (original[originalCharIndex] === '\n') {
  474. loc.line += 1;
  475. loc.column = 0;
  476. this.generatedCodeLine += 1;
  477. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  478. this.generatedCodeColumn = 0;
  479. first = true;
  480. } else {
  481. loc.column += 1;
  482. this.generatedCodeColumn += 1;
  483. first = false;
  484. }
  485. originalCharIndex += 1;
  486. }
  487. this.pending = null;
  488. };
  489. Mappings.prototype.advance = function advance (str) {
  490. if (!str) { return; }
  491. var lines = str.split('\n');
  492. if (lines.length > 1) {
  493. for (var i = 0; i < lines.length - 1; i++) {
  494. this.generatedCodeLine++;
  495. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  496. }
  497. this.generatedCodeColumn = 0;
  498. }
  499. this.generatedCodeColumn += lines[lines.length - 1].length;
  500. };
  501. var n = '\n';
  502. var warned = {
  503. insertLeft: false,
  504. insertRight: false,
  505. storeName: false
  506. };
  507. var MagicString = function MagicString(string, options) {
  508. if ( options === void 0 ) options = {};
  509. var chunk = new Chunk$1(0, string.length, string);
  510. Object.defineProperties(this, {
  511. original: { writable: true, value: string },
  512. outro: { writable: true, value: '' },
  513. intro: { writable: true, value: '' },
  514. firstChunk: { writable: true, value: chunk },
  515. lastChunk: { writable: true, value: chunk },
  516. lastSearchedChunk: { writable: true, value: chunk },
  517. byStart: { writable: true, value: {} },
  518. byEnd: { writable: true, value: {} },
  519. filename: { writable: true, value: options.filename },
  520. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  521. sourcemapLocations: { writable: true, value: new BitSet() },
  522. storedNames: { writable: true, value: {} },
  523. indentStr: { writable: true, value: guessIndent(string) }
  524. });
  525. this.byStart[0] = chunk;
  526. this.byEnd[string.length] = chunk;
  527. };
  528. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  529. this.sourcemapLocations.add(char);
  530. };
  531. MagicString.prototype.append = function append (content) {
  532. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  533. this.outro += content;
  534. return this;
  535. };
  536. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  537. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  538. this._split(index);
  539. var chunk = this.byEnd[index];
  540. if (chunk) {
  541. chunk.appendLeft(content);
  542. } else {
  543. this.intro += content;
  544. }
  545. return this;
  546. };
  547. MagicString.prototype.appendRight = function appendRight (index, content) {
  548. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  549. this._split(index);
  550. var chunk = this.byStart[index];
  551. if (chunk) {
  552. chunk.appendRight(content);
  553. } else {
  554. this.outro += content;
  555. }
  556. return this;
  557. };
  558. MagicString.prototype.clone = function clone () {
  559. var cloned = new MagicString(this.original, { filename: this.filename });
  560. var originalChunk = this.firstChunk;
  561. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  562. while (originalChunk) {
  563. cloned.byStart[clonedChunk.start] = clonedChunk;
  564. cloned.byEnd[clonedChunk.end] = clonedChunk;
  565. var nextOriginalChunk = originalChunk.next;
  566. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  567. if (nextClonedChunk) {
  568. clonedChunk.next = nextClonedChunk;
  569. nextClonedChunk.previous = clonedChunk;
  570. clonedChunk = nextClonedChunk;
  571. }
  572. originalChunk = nextOriginalChunk;
  573. }
  574. cloned.lastChunk = clonedChunk;
  575. if (this.indentExclusionRanges) {
  576. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  577. }
  578. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  579. cloned.intro = this.intro;
  580. cloned.outro = this.outro;
  581. return cloned;
  582. };
  583. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  584. var this$1 = this;
  585. options = options || {};
  586. var sourceIndex = 0;
  587. var names = Object.keys(this.storedNames);
  588. var mappings = new Mappings(options.hires);
  589. var locate = getLocator$1(this.original);
  590. if (this.intro) {
  591. mappings.advance(this.intro);
  592. }
  593. this.firstChunk.eachNext(function (chunk) {
  594. var loc = locate(chunk.start);
  595. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  596. if (chunk.edited) {
  597. mappings.addEdit(
  598. sourceIndex,
  599. chunk.content,
  600. loc,
  601. chunk.storeName ? names.indexOf(chunk.original) : -1
  602. );
  603. } else {
  604. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  605. }
  606. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  607. });
  608. return {
  609. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  610. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  611. sourcesContent: options.includeContent ? [this.original] : [null],
  612. names: names,
  613. mappings: mappings.raw
  614. };
  615. };
  616. MagicString.prototype.generateMap = function generateMap (options) {
  617. return new SourceMap(this.generateDecodedMap(options));
  618. };
  619. MagicString.prototype.getIndentString = function getIndentString () {
  620. return this.indentStr === null ? '\t' : this.indentStr;
  621. };
  622. MagicString.prototype.indent = function indent (indentStr, options) {
  623. var pattern = /^[^\r\n]/gm;
  624. if (isObject(indentStr)) {
  625. options = indentStr;
  626. indentStr = undefined;
  627. }
  628. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  629. if (indentStr === '') { return this; } // noop
  630. options = options || {};
  631. // Process exclusion ranges
  632. var isExcluded = {};
  633. if (options.exclude) {
  634. var exclusions =
  635. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  636. exclusions.forEach(function (exclusion) {
  637. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  638. isExcluded[i] = true;
  639. }
  640. });
  641. }
  642. var shouldIndentNextCharacter = options.indentStart !== false;
  643. var replacer = function (match) {
  644. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  645. shouldIndentNextCharacter = true;
  646. return match;
  647. };
  648. this.intro = this.intro.replace(pattern, replacer);
  649. var charIndex = 0;
  650. var chunk = this.firstChunk;
  651. while (chunk) {
  652. var end = chunk.end;
  653. if (chunk.edited) {
  654. if (!isExcluded[charIndex]) {
  655. chunk.content = chunk.content.replace(pattern, replacer);
  656. if (chunk.content.length) {
  657. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  658. }
  659. }
  660. } else {
  661. charIndex = chunk.start;
  662. while (charIndex < end) {
  663. if (!isExcluded[charIndex]) {
  664. var char = this.original[charIndex];
  665. if (char === '\n') {
  666. shouldIndentNextCharacter = true;
  667. } else if (char !== '\r' && shouldIndentNextCharacter) {
  668. shouldIndentNextCharacter = false;
  669. if (charIndex === chunk.start) {
  670. chunk.prependRight(indentStr);
  671. } else {
  672. this._splitChunk(chunk, charIndex);
  673. chunk = chunk.next;
  674. chunk.prependRight(indentStr);
  675. }
  676. }
  677. }
  678. charIndex += 1;
  679. }
  680. }
  681. charIndex = chunk.end;
  682. chunk = chunk.next;
  683. }
  684. this.outro = this.outro.replace(pattern, replacer);
  685. return this;
  686. };
  687. MagicString.prototype.insert = function insert () {
  688. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  689. };
  690. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  691. if (!warned.insertLeft) {
  692. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  693. warned.insertLeft = true;
  694. }
  695. return this.appendLeft(index, content);
  696. };
  697. MagicString.prototype.insertRight = function insertRight (index, content) {
  698. if (!warned.insertRight) {
  699. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  700. warned.insertRight = true;
  701. }
  702. return this.prependRight(index, content);
  703. };
  704. MagicString.prototype.move = function move (start, end, index) {
  705. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  706. this._split(start);
  707. this._split(end);
  708. this._split(index);
  709. var first = this.byStart[start];
  710. var last = this.byEnd[end];
  711. var oldLeft = first.previous;
  712. var oldRight = last.next;
  713. var newRight = this.byStart[index];
  714. if (!newRight && last === this.lastChunk) { return this; }
  715. var newLeft = newRight ? newRight.previous : this.lastChunk;
  716. if (oldLeft) { oldLeft.next = oldRight; }
  717. if (oldRight) { oldRight.previous = oldLeft; }
  718. if (newLeft) { newLeft.next = first; }
  719. if (newRight) { newRight.previous = last; }
  720. if (!first.previous) { this.firstChunk = last.next; }
  721. if (!last.next) {
  722. this.lastChunk = first.previous;
  723. this.lastChunk.next = null;
  724. }
  725. first.previous = newLeft;
  726. last.next = newRight || null;
  727. if (!newLeft) { this.firstChunk = first; }
  728. if (!newRight) { this.lastChunk = last; }
  729. return this;
  730. };
  731. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  732. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  733. while (start < 0) { start += this.original.length; }
  734. while (end < 0) { end += this.original.length; }
  735. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  736. if (start === end)
  737. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  738. this._split(start);
  739. this._split(end);
  740. if (options === true) {
  741. if (!warned.storeName) {
  742. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  743. warned.storeName = true;
  744. }
  745. options = { storeName: true };
  746. }
  747. var storeName = options !== undefined ? options.storeName : false;
  748. var contentOnly = options !== undefined ? options.contentOnly : false;
  749. if (storeName) {
  750. var original = this.original.slice(start, end);
  751. this.storedNames[original] = true;
  752. }
  753. var first = this.byStart[start];
  754. var last = this.byEnd[end];
  755. if (first) {
  756. if (end > first.end && first.next !== this.byStart[first.end]) {
  757. throw new Error('Cannot overwrite across a split point');
  758. }
  759. first.edit(content, storeName, contentOnly);
  760. if (first !== last) {
  761. var chunk = first.next;
  762. while (chunk !== last) {
  763. chunk.edit('', false);
  764. chunk = chunk.next;
  765. }
  766. chunk.edit('', false);
  767. }
  768. } else {
  769. // must be inserting at the end
  770. var newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  771. // TODO last chunk in the array may not be the last chunk, if it's moved...
  772. last.next = newChunk;
  773. newChunk.previous = last;
  774. }
  775. return this;
  776. };
  777. MagicString.prototype.prepend = function prepend (content) {
  778. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  779. this.intro = content + this.intro;
  780. return this;
  781. };
  782. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  783. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  784. this._split(index);
  785. var chunk = this.byEnd[index];
  786. if (chunk) {
  787. chunk.prependLeft(content);
  788. } else {
  789. this.intro = content + this.intro;
  790. }
  791. return this;
  792. };
  793. MagicString.prototype.prependRight = function prependRight (index, content) {
  794. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  795. this._split(index);
  796. var chunk = this.byStart[index];
  797. if (chunk) {
  798. chunk.prependRight(content);
  799. } else {
  800. this.outro = content + this.outro;
  801. }
  802. return this;
  803. };
  804. MagicString.prototype.remove = function remove (start, end) {
  805. while (start < 0) { start += this.original.length; }
  806. while (end < 0) { end += this.original.length; }
  807. if (start === end) { return this; }
  808. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  809. if (start > end) { throw new Error('end must be greater than start'); }
  810. this._split(start);
  811. this._split(end);
  812. var chunk = this.byStart[start];
  813. while (chunk) {
  814. chunk.intro = '';
  815. chunk.outro = '';
  816. chunk.edit('');
  817. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  818. }
  819. return this;
  820. };
  821. MagicString.prototype.lastChar = function lastChar () {
  822. if (this.outro.length)
  823. { return this.outro[this.outro.length - 1]; }
  824. var chunk = this.lastChunk;
  825. do {
  826. if (chunk.outro.length)
  827. { return chunk.outro[chunk.outro.length - 1]; }
  828. if (chunk.content.length)
  829. { return chunk.content[chunk.content.length - 1]; }
  830. if (chunk.intro.length)
  831. { return chunk.intro[chunk.intro.length - 1]; }
  832. } while (chunk = chunk.previous);
  833. if (this.intro.length)
  834. { return this.intro[this.intro.length - 1]; }
  835. return '';
  836. };
  837. MagicString.prototype.lastLine = function lastLine () {
  838. var lineIndex = this.outro.lastIndexOf(n);
  839. if (lineIndex !== -1)
  840. { return this.outro.substr(lineIndex + 1); }
  841. var lineStr = this.outro;
  842. var chunk = this.lastChunk;
  843. do {
  844. if (chunk.outro.length > 0) {
  845. lineIndex = chunk.outro.lastIndexOf(n);
  846. if (lineIndex !== -1)
  847. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  848. lineStr = chunk.outro + lineStr;
  849. }
  850. if (chunk.content.length > 0) {
  851. lineIndex = chunk.content.lastIndexOf(n);
  852. if (lineIndex !== -1)
  853. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  854. lineStr = chunk.content + lineStr;
  855. }
  856. if (chunk.intro.length > 0) {
  857. lineIndex = chunk.intro.lastIndexOf(n);
  858. if (lineIndex !== -1)
  859. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  860. lineStr = chunk.intro + lineStr;
  861. }
  862. } while (chunk = chunk.previous);
  863. lineIndex = this.intro.lastIndexOf(n);
  864. if (lineIndex !== -1)
  865. { return this.intro.substr(lineIndex + 1) + lineStr; }
  866. return this.intro + lineStr;
  867. };
  868. MagicString.prototype.slice = function slice (start, end) {
  869. if ( start === void 0 ) start = 0;
  870. if ( end === void 0 ) end = this.original.length;
  871. while (start < 0) { start += this.original.length; }
  872. while (end < 0) { end += this.original.length; }
  873. var result = '';
  874. // find start chunk
  875. var chunk = this.firstChunk;
  876. while (chunk && (chunk.start > start || chunk.end <= start)) {
  877. // found end chunk before start
  878. if (chunk.start < end && chunk.end >= end) {
  879. return result;
  880. }
  881. chunk = chunk.next;
  882. }
  883. if (chunk && chunk.edited && chunk.start !== start)
  884. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  885. var startChunk = chunk;
  886. while (chunk) {
  887. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  888. result += chunk.intro;
  889. }
  890. var containsEnd = chunk.start < end && chunk.end >= end;
  891. if (containsEnd && chunk.edited && chunk.end !== end)
  892. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  893. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  894. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  895. result += chunk.content.slice(sliceStart, sliceEnd);
  896. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  897. result += chunk.outro;
  898. }
  899. if (containsEnd) {
  900. break;
  901. }
  902. chunk = chunk.next;
  903. }
  904. return result;
  905. };
  906. // TODO deprecate this? not really very useful
  907. MagicString.prototype.snip = function snip (start, end) {
  908. var clone = this.clone();
  909. clone.remove(0, start);
  910. clone.remove(end, clone.original.length);
  911. return clone;
  912. };
  913. MagicString.prototype._split = function _split (index) {
  914. if (this.byStart[index] || this.byEnd[index]) { return; }
  915. var chunk = this.lastSearchedChunk;
  916. var searchForward = index > chunk.end;
  917. while (chunk) {
  918. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  919. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  920. }
  921. };
  922. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  923. if (chunk.edited && chunk.content.length) {
  924. // zero-length edited chunks are a special case (overlapping replacements)
  925. var loc = getLocator$1(this.original)(index);
  926. throw new Error(
  927. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  928. );
  929. }
  930. var newChunk = chunk.split(index);
  931. this.byEnd[index] = chunk;
  932. this.byStart[index] = newChunk;
  933. this.byEnd[newChunk.end] = newChunk;
  934. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  935. this.lastSearchedChunk = chunk;
  936. return true;
  937. };
  938. MagicString.prototype.toString = function toString () {
  939. var str = this.intro;
  940. var chunk = this.firstChunk;
  941. while (chunk) {
  942. str += chunk.toString();
  943. chunk = chunk.next;
  944. }
  945. return str + this.outro;
  946. };
  947. MagicString.prototype.isEmpty = function isEmpty () {
  948. var chunk = this.firstChunk;
  949. do {
  950. if (chunk.intro.length && chunk.intro.trim() ||
  951. chunk.content.length && chunk.content.trim() ||
  952. chunk.outro.length && chunk.outro.trim())
  953. { return false; }
  954. } while (chunk = chunk.next);
  955. return true;
  956. };
  957. MagicString.prototype.length = function length () {
  958. var chunk = this.firstChunk;
  959. var length = 0;
  960. do {
  961. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  962. } while (chunk = chunk.next);
  963. return length;
  964. };
  965. MagicString.prototype.trimLines = function trimLines () {
  966. return this.trim('[\\r\\n]');
  967. };
  968. MagicString.prototype.trim = function trim (charType) {
  969. return this.trimStart(charType).trimEnd(charType);
  970. };
  971. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  972. var rx = new RegExp((charType || '\\s') + '+$');
  973. this.outro = this.outro.replace(rx, '');
  974. if (this.outro.length) { return true; }
  975. var chunk = this.lastChunk;
  976. do {
  977. var end = chunk.end;
  978. var aborted = chunk.trimEnd(rx);
  979. // if chunk was trimmed, we have a new lastChunk
  980. if (chunk.end !== end) {
  981. if (this.lastChunk === chunk) {
  982. this.lastChunk = chunk.next;
  983. }
  984. this.byEnd[chunk.end] = chunk;
  985. this.byStart[chunk.next.start] = chunk.next;
  986. this.byEnd[chunk.next.end] = chunk.next;
  987. }
  988. if (aborted) { return true; }
  989. chunk = chunk.previous;
  990. } while (chunk);
  991. return false;
  992. };
  993. MagicString.prototype.trimEnd = function trimEnd (charType) {
  994. this.trimEndAborted(charType);
  995. return this;
  996. };
  997. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  998. var rx = new RegExp('^' + (charType || '\\s') + '+');
  999. this.intro = this.intro.replace(rx, '');
  1000. if (this.intro.length) { return true; }
  1001. var chunk = this.firstChunk;
  1002. do {
  1003. var end = chunk.end;
  1004. var aborted = chunk.trimStart(rx);
  1005. if (chunk.end !== end) {
  1006. // special case...
  1007. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  1008. this.byEnd[chunk.end] = chunk;
  1009. this.byStart[chunk.next.start] = chunk.next;
  1010. this.byEnd[chunk.next.end] = chunk.next;
  1011. }
  1012. if (aborted) { return true; }
  1013. chunk = chunk.next;
  1014. } while (chunk);
  1015. return false;
  1016. };
  1017. MagicString.prototype.trimStart = function trimStart (charType) {
  1018. this.trimStartAborted(charType);
  1019. return this;
  1020. };
  1021. var hasOwnProp = Object.prototype.hasOwnProperty;
  1022. var Bundle$1 = function Bundle(options) {
  1023. if ( options === void 0 ) options = {};
  1024. this.intro = options.intro || '';
  1025. this.separator = options.separator !== undefined ? options.separator : '\n';
  1026. this.sources = [];
  1027. this.uniqueSources = [];
  1028. this.uniqueSourceIndexByFilename = {};
  1029. };
  1030. Bundle$1.prototype.addSource = function addSource (source) {
  1031. if (source instanceof MagicString) {
  1032. return this.addSource({
  1033. content: source,
  1034. filename: source.filename,
  1035. separator: this.separator
  1036. });
  1037. }
  1038. if (!isObject(source) || !source.content) {
  1039. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  1040. }
  1041. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  1042. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  1043. });
  1044. if (source.separator === undefined) {
  1045. // TODO there's a bunch of this sort of thing, needs cleaning up
  1046. source.separator = this.separator;
  1047. }
  1048. if (source.filename) {
  1049. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1050. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1051. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1052. } else {
  1053. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1054. if (source.content.original !== uniqueSource.content) {
  1055. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  1056. }
  1057. }
  1058. }
  1059. this.sources.push(source);
  1060. return this;
  1061. };
  1062. Bundle$1.prototype.append = function append (str, options) {
  1063. this.addSource({
  1064. content: new MagicString(str),
  1065. separator: (options && options.separator) || ''
  1066. });
  1067. return this;
  1068. };
  1069. Bundle$1.prototype.clone = function clone () {
  1070. var bundle = new Bundle$1({
  1071. intro: this.intro,
  1072. separator: this.separator
  1073. });
  1074. this.sources.forEach(function (source) {
  1075. bundle.addSource({
  1076. filename: source.filename,
  1077. content: source.content.clone(),
  1078. separator: source.separator
  1079. });
  1080. });
  1081. return bundle;
  1082. };
  1083. Bundle$1.prototype.generateDecodedMap = function generateDecodedMap (options) {
  1084. var this$1 = this;
  1085. if ( options === void 0 ) options = {};
  1086. var names = [];
  1087. this.sources.forEach(function (source) {
  1088. Object.keys(source.content.storedNames).forEach(function (name) {
  1089. if (!~names.indexOf(name)) { names.push(name); }
  1090. });
  1091. });
  1092. var mappings = new Mappings(options.hires);
  1093. if (this.intro) {
  1094. mappings.advance(this.intro);
  1095. }
  1096. this.sources.forEach(function (source, i) {
  1097. if (i > 0) {
  1098. mappings.advance(this$1.separator);
  1099. }
  1100. var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
  1101. var magicString = source.content;
  1102. var locate = getLocator$1(magicString.original);
  1103. if (magicString.intro) {
  1104. mappings.advance(magicString.intro);
  1105. }
  1106. magicString.firstChunk.eachNext(function (chunk) {
  1107. var loc = locate(chunk.start);
  1108. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  1109. if (source.filename) {
  1110. if (chunk.edited) {
  1111. mappings.addEdit(
  1112. sourceIndex,
  1113. chunk.content,
  1114. loc,
  1115. chunk.storeName ? names.indexOf(chunk.original) : -1
  1116. );
  1117. } else {
  1118. mappings.addUneditedChunk(
  1119. sourceIndex,
  1120. chunk,
  1121. magicString.original,
  1122. loc,
  1123. magicString.sourcemapLocations
  1124. );
  1125. }
  1126. } else {
  1127. mappings.advance(chunk.content);
  1128. }
  1129. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  1130. });
  1131. if (magicString.outro) {
  1132. mappings.advance(magicString.outro);
  1133. }
  1134. });
  1135. return {
  1136. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1137. sources: this.uniqueSources.map(function (source) {
  1138. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1139. }),
  1140. sourcesContent: this.uniqueSources.map(function (source) {
  1141. return options.includeContent ? source.content : null;
  1142. }),
  1143. names: names,
  1144. mappings: mappings.raw
  1145. };
  1146. };
  1147. Bundle$1.prototype.generateMap = function generateMap (options) {
  1148. return new SourceMap(this.generateDecodedMap(options));
  1149. };
  1150. Bundle$1.prototype.getIndentString = function getIndentString () {
  1151. var indentStringCounts = {};
  1152. this.sources.forEach(function (source) {
  1153. var indentStr = source.content.indentStr;
  1154. if (indentStr === null) { return; }
  1155. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  1156. indentStringCounts[indentStr] += 1;
  1157. });
  1158. return (
  1159. Object.keys(indentStringCounts).sort(function (a, b) {
  1160. return indentStringCounts[a] - indentStringCounts[b];
  1161. })[0] || '\t'
  1162. );
  1163. };
  1164. Bundle$1.prototype.indent = function indent (indentStr) {
  1165. var this$1 = this;
  1166. if (!arguments.length) {
  1167. indentStr = this.getIndentString();
  1168. }
  1169. if (indentStr === '') { return this; } // noop
  1170. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1171. this.sources.forEach(function (source, i) {
  1172. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1173. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1174. source.content.indent(indentStr, {
  1175. exclude: source.indentExclusionRanges,
  1176. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1177. });
  1178. trailingNewline = source.content.lastChar() === '\n';
  1179. });
  1180. if (this.intro) {
  1181. this.intro =
  1182. indentStr +
  1183. this.intro.replace(/^[^\n]/gm, function (match, index) {
  1184. return index > 0 ? indentStr + match : match;
  1185. });
  1186. }
  1187. return this;
  1188. };
  1189. Bundle$1.prototype.prepend = function prepend (str) {
  1190. this.intro = str + this.intro;
  1191. return this;
  1192. };
  1193. Bundle$1.prototype.toString = function toString () {
  1194. var this$1 = this;
  1195. var body = this.sources
  1196. .map(function (source, i) {
  1197. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1198. var str = (i > 0 ? separator : '') + source.content.toString();
  1199. return str;
  1200. })
  1201. .join('');
  1202. return this.intro + body;
  1203. };
  1204. Bundle$1.prototype.isEmpty = function isEmpty () {
  1205. if (this.intro.length && this.intro.trim())
  1206. { return false; }
  1207. if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
  1208. { return false; }
  1209. return true;
  1210. };
  1211. Bundle$1.prototype.length = function length () {
  1212. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  1213. };
  1214. Bundle$1.prototype.trimLines = function trimLines () {
  1215. return this.trim('[\\r\\n]');
  1216. };
  1217. Bundle$1.prototype.trim = function trim (charType) {
  1218. return this.trimStart(charType).trimEnd(charType);
  1219. };
  1220. Bundle$1.prototype.trimStart = function trimStart (charType) {
  1221. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1222. this.intro = this.intro.replace(rx, '');
  1223. if (!this.intro) {
  1224. var source;
  1225. var i = 0;
  1226. do {
  1227. source = this.sources[i++];
  1228. if (!source) {
  1229. break;
  1230. }
  1231. } while (!source.content.trimStartAborted(charType));
  1232. }
  1233. return this;
  1234. };
  1235. Bundle$1.prototype.trimEnd = function trimEnd (charType) {
  1236. var rx = new RegExp((charType || '\\s') + '+$');
  1237. var source;
  1238. var i = this.sources.length - 1;
  1239. do {
  1240. source = this.sources[i--];
  1241. if (!source) {
  1242. this.intro = this.intro.replace(rx, '');
  1243. break;
  1244. }
  1245. } while (!source.content.trimEndAborted(charType));
  1246. return this;
  1247. };
  1248. function relative(from, to) {
  1249. const fromParts = from.split(/[/\\]/).filter(Boolean);
  1250. const toParts = to.split(/[/\\]/).filter(Boolean);
  1251. if (fromParts[0] === '.')
  1252. fromParts.shift();
  1253. if (toParts[0] === '.')
  1254. toParts.shift();
  1255. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1256. fromParts.shift();
  1257. toParts.shift();
  1258. }
  1259. while (toParts[0] === '..' && fromParts.length > 0) {
  1260. toParts.shift();
  1261. fromParts.pop();
  1262. }
  1263. while (fromParts.pop()) {
  1264. toParts.unshift('..');
  1265. }
  1266. return toParts.join('/');
  1267. }
  1268. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  1269. const BlockStatement$1 = 'BlockStatement';
  1270. const CallExpression$1 = 'CallExpression';
  1271. const ExpressionStatement$1 = 'ExpressionStatement';
  1272. const Identifier$1 = 'Identifier';
  1273. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  1274. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  1275. const NewExpression$1 = 'NewExpression';
  1276. const Program$1 = 'Program';
  1277. const Property$1 = 'Property';
  1278. const ReturnStatement$1 = 'ReturnStatement';
  1279. function treeshakeNode(node, code, start, end) {
  1280. code.remove(start, end);
  1281. if (node.annotations) {
  1282. for (const annotation of node.annotations) {
  1283. if (annotation.start < start) {
  1284. code.remove(annotation.start, annotation.end);
  1285. }
  1286. else {
  1287. return;
  1288. }
  1289. }
  1290. }
  1291. }
  1292. function removeAnnotations(node, code) {
  1293. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  1294. node = node.parent;
  1295. }
  1296. if (node.annotations) {
  1297. for (const annotation of node.annotations) {
  1298. code.remove(annotation.start, annotation.end);
  1299. }
  1300. }
  1301. }
  1302. const NO_SEMICOLON = { isNoStatement: true };
  1303. // This assumes there are only white-space and comments between start and the string we are looking for
  1304. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1305. let searchPos, charCodeAfterSlash;
  1306. searchPos = code.indexOf(searchString, start);
  1307. while (true) {
  1308. start = code.indexOf('/', start);
  1309. if (start === -1 || start >= searchPos)
  1310. return searchPos;
  1311. charCodeAfterSlash = code.charCodeAt(++start);
  1312. ++start;
  1313. // With our assumption, '/' always starts a comment. Determine comment type:
  1314. start =
  1315. charCodeAfterSlash === 47 /*"/"*/
  1316. ? code.indexOf('\n', start) + 1
  1317. : code.indexOf('*/', start) + 2;
  1318. if (start > searchPos) {
  1319. searchPos = code.indexOf(searchString, start);
  1320. }
  1321. }
  1322. }
  1323. const NON_WHITESPACE = /\S/g;
  1324. function findNonWhiteSpace(code, index) {
  1325. NON_WHITESPACE.lastIndex = index;
  1326. const result = NON_WHITESPACE.exec(code);
  1327. return result.index;
  1328. }
  1329. // This assumes "code" only contains white-space and comments
  1330. // Returns position of line-comment if applicable
  1331. function findFirstLineBreakOutsideComment(code) {
  1332. let lineBreakPos, charCodeAfterSlash, start = 0;
  1333. lineBreakPos = code.indexOf('\n', start);
  1334. while (true) {
  1335. start = code.indexOf('/', start);
  1336. if (start === -1 || start > lineBreakPos)
  1337. return [lineBreakPos, lineBreakPos + 1];
  1338. // With our assumption, '/' always starts a comment. Determine comment type:
  1339. charCodeAfterSlash = code.charCodeAt(start + 1);
  1340. if (charCodeAfterSlash === 47 /*"/"*/)
  1341. return [start, lineBreakPos + 1];
  1342. start = code.indexOf('*/', start + 3) + 2;
  1343. if (start > lineBreakPos) {
  1344. lineBreakPos = code.indexOf('\n', start);
  1345. }
  1346. }
  1347. }
  1348. function renderStatementList(statements, code, start, end, options) {
  1349. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1350. let nextNode = statements[0];
  1351. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1352. if (nextNodeNeedsBoundaries) {
  1353. nextNodeStart =
  1354. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1355. }
  1356. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1357. currentNode = nextNode;
  1358. currentNodeStart = nextNodeStart;
  1359. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1360. nextNode = statements[nextIndex];
  1361. nextNodeNeedsBoundaries =
  1362. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1363. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1364. nextNodeStart =
  1365. currentNode.end +
  1366. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1367. if (currentNode.included) {
  1368. currentNodeNeedsBoundaries
  1369. ? currentNode.render(code, options, {
  1370. end: nextNodeStart,
  1371. start: currentNodeStart
  1372. })
  1373. : currentNode.render(code, options);
  1374. }
  1375. else {
  1376. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1377. }
  1378. }
  1379. else {
  1380. currentNode.render(code, options);
  1381. }
  1382. }
  1383. }
  1384. // This assumes that the first character is not part of the first node
  1385. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1386. const splitUpNodes = [];
  1387. let node, nextNode, nextNodeStart, contentEnd, char;
  1388. let separator = start - 1;
  1389. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  1390. nextNode = nodes[nextIndex];
  1391. if (node !== undefined) {
  1392. separator =
  1393. node.end +
  1394. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1395. }
  1396. nextNodeStart = contentEnd =
  1397. separator +
  1398. 1 +
  1399. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1400. while (((char = code.original.charCodeAt(nextNodeStart)),
  1401. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1402. nextNodeStart++;
  1403. if (node !== undefined) {
  1404. splitUpNodes.push({
  1405. contentEnd,
  1406. end: nextNodeStart,
  1407. node,
  1408. separator,
  1409. start
  1410. });
  1411. }
  1412. node = nextNode;
  1413. start = nextNodeStart;
  1414. }
  1415. splitUpNodes.push({
  1416. contentEnd: end,
  1417. end,
  1418. node: node,
  1419. separator: null,
  1420. start
  1421. });
  1422. return splitUpNodes;
  1423. }
  1424. // This assumes there are only white-space and comments between start and end
  1425. function removeLineBreaks(code, start, end) {
  1426. while (true) {
  1427. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1428. if (removeStart === -1) {
  1429. break;
  1430. }
  1431. code.remove(start + removeStart, (start += removeEnd));
  1432. }
  1433. }
  1434. function getSystemExportStatement(exportedVariables, options) {
  1435. const _ = options.compact ? '' : ' ';
  1436. if (exportedVariables.length === 1 &&
  1437. options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1438. const variable = exportedVariables[0];
  1439. return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
  1440. }
  1441. else {
  1442. return `exports({${_}${exportedVariables
  1443. .map(variable => {
  1444. return options.exportNamesByVariable
  1445. .get(variable)
  1446. .map(exportName => `${exportName}:${_}${variable.getName()}`)
  1447. .join(`,${_}`);
  1448. })
  1449. .join(`,${_}`)}${_}})`;
  1450. }
  1451. }
  1452. function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
  1453. const _ = options.compact ? '' : ' ';
  1454. const s = options.compact ? '' : ';';
  1455. return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
  1456. .map(variable => {
  1457. return options.exportNamesByVariable
  1458. .get(variable)
  1459. .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
  1460. .join(`,${_}`);
  1461. })
  1462. .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
  1463. }
  1464. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  1465. const base$1 = 64;
  1466. function toBase64(num) {
  1467. let outStr = '';
  1468. do {
  1469. const curDigit = num % base$1;
  1470. num = Math.floor(num / base$1);
  1471. outStr = chars[curDigit] + outStr;
  1472. } while (num !== 0);
  1473. return outStr;
  1474. }
  1475. const RESERVED_NAMES = {
  1476. // @ts-ignore
  1477. __proto__: null,
  1478. await: true,
  1479. break: true,
  1480. case: true,
  1481. catch: true,
  1482. class: true,
  1483. const: true,
  1484. continue: true,
  1485. debugger: true,
  1486. default: true,
  1487. delete: true,
  1488. do: true,
  1489. else: true,
  1490. enum: true,
  1491. eval: true,
  1492. export: true,
  1493. extends: true,
  1494. false: true,
  1495. finally: true,
  1496. for: true,
  1497. function: true,
  1498. if: true,
  1499. implements: true,
  1500. import: true,
  1501. in: true,
  1502. instanceof: true,
  1503. interface: true,
  1504. let: true,
  1505. new: true,
  1506. null: true,
  1507. package: true,
  1508. private: true,
  1509. protected: true,
  1510. public: true,
  1511. return: true,
  1512. static: true,
  1513. super: true,
  1514. switch: true,
  1515. this: true,
  1516. throw: true,
  1517. true: true,
  1518. try: true,
  1519. typeof: true,
  1520. undefined: true,
  1521. var: true,
  1522. void: true,
  1523. while: true,
  1524. with: true,
  1525. yield: true
  1526. };
  1527. function getSafeName(baseName, usedNames) {
  1528. let safeName = baseName;
  1529. let count = 1;
  1530. while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
  1531. safeName = `${baseName}$${toBase64(count++)}`;
  1532. }
  1533. usedNames.add(safeName);
  1534. return safeName;
  1535. }
  1536. const NO_ARGS = [];
  1537. function getOrCreate(map, key, init) {
  1538. const existing = map.get(key);
  1539. if (existing) {
  1540. return existing;
  1541. }
  1542. const value = init();
  1543. map.set(key, value);
  1544. return value;
  1545. }
  1546. const UnknownKey = Symbol('Unknown Key');
  1547. const EMPTY_PATH = [];
  1548. const UNKNOWN_PATH = [UnknownKey];
  1549. const EntitiesKey = Symbol('Entities');
  1550. class PathTracker {
  1551. constructor() {
  1552. this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1553. }
  1554. getEntities(path) {
  1555. let currentPaths = this.entityPaths;
  1556. for (const pathSegment of path) {
  1557. currentPaths = currentPaths[pathSegment] =
  1558. currentPaths[pathSegment] ||
  1559. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1560. }
  1561. return currentPaths[EntitiesKey];
  1562. }
  1563. }
  1564. const SHARED_RECURSION_TRACKER = new PathTracker();
  1565. class DiscriminatedPathTracker {
  1566. constructor() {
  1567. this.entityPaths = Object.create(null, {
  1568. [EntitiesKey]: { value: new Map() }
  1569. });
  1570. }
  1571. getEntities(path, discriminator) {
  1572. let currentPaths = this.entityPaths;
  1573. for (const pathSegment of path) {
  1574. currentPaths = currentPaths[pathSegment] =
  1575. currentPaths[pathSegment] ||
  1576. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1577. }
  1578. return getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1579. }
  1580. }
  1581. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  1582. return Object.create(inheritedDescriptions, memberDescriptions);
  1583. }
  1584. const UnknownValue = Symbol('Unknown Value');
  1585. const UNKNOWN_EXPRESSION = {
  1586. deoptimizePath: () => { },
  1587. getLiteralValueAtPath: () => UnknownValue,
  1588. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  1589. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  1590. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1591. hasEffectsWhenCalledAtPath: () => true,
  1592. include: () => { },
  1593. includeCallArguments(context, args) {
  1594. for (const arg of args) {
  1595. arg.include(context, false);
  1596. }
  1597. },
  1598. included: true,
  1599. toString: () => '[[UNKNOWN]]'
  1600. };
  1601. const UNDEFINED_EXPRESSION = {
  1602. deoptimizePath: () => { },
  1603. getLiteralValueAtPath: () => undefined,
  1604. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  1605. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  1606. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1607. hasEffectsWhenCalledAtPath: () => true,
  1608. include: () => { },
  1609. includeCallArguments() { },
  1610. included: true,
  1611. toString: () => 'undefined'
  1612. };
  1613. const returnsUnknown = {
  1614. value: {
  1615. callsArgs: null,
  1616. mutatesSelf: false,
  1617. returns: null,
  1618. returnsPrimitive: UNKNOWN_EXPRESSION
  1619. }
  1620. };
  1621. const mutatesSelfReturnsUnknown = {
  1622. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
  1623. };
  1624. const callsArgReturnsUnknown = {
  1625. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
  1626. };
  1627. class UnknownArrayExpression {
  1628. constructor() {
  1629. this.included = false;
  1630. }
  1631. deoptimizePath() { }
  1632. getLiteralValueAtPath() {
  1633. return UnknownValue;
  1634. }
  1635. getReturnExpressionWhenCalledAtPath(path) {
  1636. if (path.length === 1) {
  1637. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  1638. }
  1639. return UNKNOWN_EXPRESSION;
  1640. }
  1641. hasEffectsWhenAccessedAtPath(path) {
  1642. return path.length > 1;
  1643. }
  1644. hasEffectsWhenAssignedAtPath(path) {
  1645. return path.length > 1;
  1646. }
  1647. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  1648. if (path.length === 1) {
  1649. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  1650. }
  1651. return true;
  1652. }
  1653. include() {
  1654. this.included = true;
  1655. }
  1656. includeCallArguments(context, args) {
  1657. for (const arg of args) {
  1658. arg.include(context, false);
  1659. }
  1660. }
  1661. toString() {
  1662. return '[[UNKNOWN ARRAY]]';
  1663. }
  1664. }
  1665. const returnsArray = {
  1666. value: {
  1667. callsArgs: null,
  1668. mutatesSelf: false,
  1669. returns: UnknownArrayExpression,
  1670. returnsPrimitive: null
  1671. }
  1672. };
  1673. const mutatesSelfReturnsArray = {
  1674. value: {
  1675. callsArgs: null,
  1676. mutatesSelf: true,
  1677. returns: UnknownArrayExpression,
  1678. returnsPrimitive: null
  1679. }
  1680. };
  1681. const callsArgReturnsArray = {
  1682. value: {
  1683. callsArgs: [0],
  1684. mutatesSelf: false,
  1685. returns: UnknownArrayExpression,
  1686. returnsPrimitive: null
  1687. }
  1688. };
  1689. const callsArgMutatesSelfReturnsArray = {
  1690. value: {
  1691. callsArgs: [0],
  1692. mutatesSelf: true,
  1693. returns: UnknownArrayExpression,
  1694. returnsPrimitive: null
  1695. }
  1696. };
  1697. const UNKNOWN_LITERAL_BOOLEAN = {
  1698. deoptimizePath: () => { },
  1699. getLiteralValueAtPath: () => UnknownValue,
  1700. getReturnExpressionWhenCalledAtPath: path => {
  1701. if (path.length === 1) {
  1702. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  1703. }
  1704. return UNKNOWN_EXPRESSION;
  1705. },
  1706. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1707. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1708. hasEffectsWhenCalledAtPath: path => {
  1709. if (path.length === 1) {
  1710. const subPath = path[0];
  1711. return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
  1712. }
  1713. return true;
  1714. },
  1715. include: () => { },
  1716. includeCallArguments(context, args) {
  1717. for (const arg of args) {
  1718. arg.include(context, false);
  1719. }
  1720. },
  1721. included: true,
  1722. toString: () => '[[UNKNOWN BOOLEAN]]'
  1723. };
  1724. const returnsBoolean = {
  1725. value: {
  1726. callsArgs: null,
  1727. mutatesSelf: false,
  1728. returns: null,
  1729. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  1730. }
  1731. };
  1732. const callsArgReturnsBoolean = {
  1733. value: {
  1734. callsArgs: [0],
  1735. mutatesSelf: false,
  1736. returns: null,
  1737. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  1738. }
  1739. };
  1740. const UNKNOWN_LITERAL_NUMBER = {
  1741. deoptimizePath: () => { },
  1742. getLiteralValueAtPath: () => UnknownValue,
  1743. getReturnExpressionWhenCalledAtPath: path => {
  1744. if (path.length === 1) {
  1745. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  1746. }
  1747. return UNKNOWN_EXPRESSION;
  1748. },
  1749. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1750. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1751. hasEffectsWhenCalledAtPath: path => {
  1752. if (path.length === 1) {
  1753. const subPath = path[0];
  1754. return typeof subPath !== 'string' || !literalNumberMembers[subPath];
  1755. }
  1756. return true;
  1757. },
  1758. include: () => { },
  1759. includeCallArguments(context, args) {
  1760. for (const arg of args) {
  1761. arg.include(context, false);
  1762. }
  1763. },
  1764. included: true,
  1765. toString: () => '[[UNKNOWN NUMBER]]'
  1766. };
  1767. const returnsNumber = {
  1768. value: {
  1769. callsArgs: null,
  1770. mutatesSelf: false,
  1771. returns: null,
  1772. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1773. }
  1774. };
  1775. const mutatesSelfReturnsNumber = {
  1776. value: {
  1777. callsArgs: null,
  1778. mutatesSelf: true,
  1779. returns: null,
  1780. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1781. }
  1782. };
  1783. const callsArgReturnsNumber = {
  1784. value: {
  1785. callsArgs: [0],
  1786. mutatesSelf: false,
  1787. returns: null,
  1788. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  1789. }
  1790. };
  1791. const UNKNOWN_LITERAL_STRING = {
  1792. deoptimizePath: () => { },
  1793. getLiteralValueAtPath: () => UnknownValue,
  1794. getReturnExpressionWhenCalledAtPath: path => {
  1795. if (path.length === 1) {
  1796. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  1797. }
  1798. return UNKNOWN_EXPRESSION;
  1799. },
  1800. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  1801. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  1802. hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
  1803. if (path.length === 1) {
  1804. return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
  1805. }
  1806. return true;
  1807. },
  1808. include: () => { },
  1809. includeCallArguments(context, args) {
  1810. for (const arg of args) {
  1811. arg.include(context, false);
  1812. }
  1813. },
  1814. included: true,
  1815. toString: () => '[[UNKNOWN STRING]]'
  1816. };
  1817. const returnsString = {
  1818. value: {
  1819. callsArgs: null,
  1820. mutatesSelf: false,
  1821. returns: null,
  1822. returnsPrimitive: UNKNOWN_LITERAL_STRING
  1823. }
  1824. };
  1825. class UnknownObjectExpression {
  1826. constructor() {
  1827. this.included = false;
  1828. }
  1829. deoptimizePath() { }
  1830. getLiteralValueAtPath() {
  1831. return UnknownValue;
  1832. }
  1833. getReturnExpressionWhenCalledAtPath(path) {
  1834. if (path.length === 1) {
  1835. return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
  1836. }
  1837. return UNKNOWN_EXPRESSION;
  1838. }
  1839. hasEffectsWhenAccessedAtPath(path) {
  1840. return path.length > 1;
  1841. }
  1842. hasEffectsWhenAssignedAtPath(path) {
  1843. return path.length > 1;
  1844. }
  1845. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  1846. if (path.length === 1) {
  1847. return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
  1848. }
  1849. return true;
  1850. }
  1851. include() {
  1852. this.included = true;
  1853. }
  1854. includeCallArguments(context, args) {
  1855. for (const arg of args) {
  1856. arg.include(context, false);
  1857. }
  1858. }
  1859. toString() {
  1860. return '[[UNKNOWN OBJECT]]';
  1861. }
  1862. }
  1863. const objectMembers = assembleMemberDescriptions({
  1864. hasOwnProperty: returnsBoolean,
  1865. isPrototypeOf: returnsBoolean,
  1866. propertyIsEnumerable: returnsBoolean,
  1867. toLocaleString: returnsString,
  1868. toString: returnsString,
  1869. valueOf: returnsUnknown
  1870. });
  1871. const arrayMembers = assembleMemberDescriptions({
  1872. concat: returnsArray,
  1873. copyWithin: mutatesSelfReturnsArray,
  1874. every: callsArgReturnsBoolean,
  1875. fill: mutatesSelfReturnsArray,
  1876. filter: callsArgReturnsArray,
  1877. find: callsArgReturnsUnknown,
  1878. findIndex: callsArgReturnsNumber,
  1879. forEach: callsArgReturnsUnknown,
  1880. includes: returnsBoolean,
  1881. indexOf: returnsNumber,
  1882. join: returnsString,
  1883. lastIndexOf: returnsNumber,
  1884. map: callsArgReturnsArray,
  1885. pop: mutatesSelfReturnsUnknown,
  1886. push: mutatesSelfReturnsNumber,
  1887. reduce: callsArgReturnsUnknown,
  1888. reduceRight: callsArgReturnsUnknown,
  1889. reverse: mutatesSelfReturnsArray,
  1890. shift: mutatesSelfReturnsUnknown,
  1891. slice: returnsArray,
  1892. some: callsArgReturnsBoolean,
  1893. sort: callsArgMutatesSelfReturnsArray,
  1894. splice: mutatesSelfReturnsArray,
  1895. unshift: mutatesSelfReturnsNumber
  1896. }, objectMembers);
  1897. const literalBooleanMembers = assembleMemberDescriptions({
  1898. valueOf: returnsBoolean
  1899. }, objectMembers);
  1900. const literalNumberMembers = assembleMemberDescriptions({
  1901. toExponential: returnsString,
  1902. toFixed: returnsString,
  1903. toLocaleString: returnsString,
  1904. toPrecision: returnsString,
  1905. valueOf: returnsNumber
  1906. }, objectMembers);
  1907. const literalStringMembers = assembleMemberDescriptions({
  1908. charAt: returnsString,
  1909. charCodeAt: returnsNumber,
  1910. codePointAt: returnsNumber,
  1911. concat: returnsString,
  1912. endsWith: returnsBoolean,
  1913. includes: returnsBoolean,
  1914. indexOf: returnsNumber,
  1915. lastIndexOf: returnsNumber,
  1916. localeCompare: returnsNumber,
  1917. match: returnsBoolean,
  1918. normalize: returnsString,
  1919. padEnd: returnsString,
  1920. padStart: returnsString,
  1921. repeat: returnsString,
  1922. replace: {
  1923. value: {
  1924. callsArgs: [1],
  1925. mutatesSelf: false,
  1926. returns: null,
  1927. returnsPrimitive: UNKNOWN_LITERAL_STRING
  1928. }
  1929. },
  1930. search: returnsNumber,
  1931. slice: returnsString,
  1932. split: returnsArray,
  1933. startsWith: returnsBoolean,
  1934. substr: returnsString,
  1935. substring: returnsString,
  1936. toLocaleLowerCase: returnsString,
  1937. toLocaleUpperCase: returnsString,
  1938. toLowerCase: returnsString,
  1939. toUpperCase: returnsString,
  1940. trim: returnsString,
  1941. valueOf: returnsString
  1942. }, objectMembers);
  1943. function getLiteralMembersForValue(value) {
  1944. switch (typeof value) {
  1945. case 'boolean':
  1946. return literalBooleanMembers;
  1947. case 'number':
  1948. return literalNumberMembers;
  1949. case 'string':
  1950. return literalStringMembers;
  1951. default:
  1952. return Object.create(null);
  1953. }
  1954. }
  1955. function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
  1956. if (typeof memberName !== 'string' ||
  1957. !members[memberName] ||
  1958. (members[memberName].mutatesSelf && parentIncluded))
  1959. return true;
  1960. if (!members[memberName].callsArgs)
  1961. return false;
  1962. for (const argIndex of members[memberName].callsArgs) {
  1963. if (callOptions.args[argIndex] &&
  1964. callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  1965. args: NO_ARGS,
  1966. withNew: false
  1967. }, context))
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972. function getMemberReturnExpressionWhenCalled(members, memberName) {
  1973. if (typeof memberName !== 'string' || !members[memberName])
  1974. return UNKNOWN_EXPRESSION;
  1975. return members[memberName].returnsPrimitive !== null
  1976. ? members[memberName].returnsPrimitive
  1977. : new members[memberName].returns();
  1978. }
  1979. const BROKEN_FLOW_NONE = 0;
  1980. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  1981. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  1982. function createInclusionContext() {
  1983. return {
  1984. brokenFlow: BROKEN_FLOW_NONE,
  1985. includedCallArguments: new Set(),
  1986. includedLabels: new Set()
  1987. };
  1988. }
  1989. function createHasEffectsContext() {
  1990. return {
  1991. accessed: new PathTracker(),
  1992. assigned: new PathTracker(),
  1993. brokenFlow: BROKEN_FLOW_NONE,
  1994. called: new DiscriminatedPathTracker(),
  1995. ignore: {
  1996. breaks: false,
  1997. continues: false,
  1998. labels: new Set(),
  1999. returnAwaitYield: false
  2000. },
  2001. includedLabels: new Set(),
  2002. instantiated: new DiscriminatedPathTracker(),
  2003. replacedVariableInits: new Map()
  2004. };
  2005. }
  2006. class Variable {
  2007. constructor(name) {
  2008. this.alwaysRendered = false;
  2009. this.included = false;
  2010. this.isId = false;
  2011. this.isReassigned = false;
  2012. this.renderBaseName = null;
  2013. this.renderName = null;
  2014. this.name = name;
  2015. }
  2016. /**
  2017. * Binds identifiers that reference this variable to this variable.
  2018. * Necessary to be able to change variable names.
  2019. */
  2020. addReference(_identifier) { }
  2021. deoptimizePath(_path) { }
  2022. getBaseVariableName() {
  2023. return this.renderBaseName || this.renderName || this.name;
  2024. }
  2025. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2026. return UnknownValue;
  2027. }
  2028. getName() {
  2029. const name = this.renderName || this.name;
  2030. return this.renderBaseName
  2031. ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
  2032. : name;
  2033. }
  2034. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  2035. return UNKNOWN_EXPRESSION;
  2036. }
  2037. hasEffectsWhenAccessedAtPath(path, _context) {
  2038. return path.length > 0;
  2039. }
  2040. hasEffectsWhenAssignedAtPath(_path, _context) {
  2041. return true;
  2042. }
  2043. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  2044. return true;
  2045. }
  2046. /**
  2047. * Marks this variable as being part of the bundle, which is usually the case when one of
  2048. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2049. * previously.
  2050. * Once a variable is included, it should take care all its declarations are included.
  2051. */
  2052. include() {
  2053. this.included = true;
  2054. }
  2055. includeCallArguments(context, args) {
  2056. for (const arg of args) {
  2057. arg.include(context, false);
  2058. }
  2059. }
  2060. markCalledFromTryStatement() { }
  2061. setRenderNames(baseName, name) {
  2062. this.renderBaseName = baseName;
  2063. this.renderName = name;
  2064. }
  2065. }
  2066. // To avoid infinite recursions
  2067. const MAX_PATH_DEPTH = 7;
  2068. class LocalVariable extends Variable {
  2069. constructor(name, declarator, init, context) {
  2070. super(name);
  2071. this.additionalInitializers = null;
  2072. this.calledFromTryStatement = false;
  2073. this.expressionsToBeDeoptimized = [];
  2074. this.declarations = declarator ? [declarator] : [];
  2075. this.init = init;
  2076. this.deoptimizationTracker = context.deoptimizationTracker;
  2077. this.module = context.module;
  2078. }
  2079. addDeclaration(identifier, init) {
  2080. this.declarations.push(identifier);
  2081. if (this.additionalInitializers === null) {
  2082. this.additionalInitializers = this.init === null ? [] : [this.init];
  2083. this.init = UNKNOWN_EXPRESSION;
  2084. this.isReassigned = true;
  2085. }
  2086. if (init !== null) {
  2087. this.additionalInitializers.push(init);
  2088. }
  2089. }
  2090. consolidateInitializers() {
  2091. if (this.additionalInitializers !== null) {
  2092. for (const initializer of this.additionalInitializers) {
  2093. initializer.deoptimizePath(UNKNOWN_PATH);
  2094. }
  2095. this.additionalInitializers = null;
  2096. }
  2097. }
  2098. deoptimizePath(path) {
  2099. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2100. return;
  2101. const trackedEntities = this.deoptimizationTracker.getEntities(path);
  2102. if (trackedEntities.has(this))
  2103. return;
  2104. trackedEntities.add(this);
  2105. if (path.length === 0) {
  2106. if (!this.isReassigned) {
  2107. this.isReassigned = true;
  2108. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  2109. this.expressionsToBeDeoptimized = [];
  2110. for (const expression of expressionsToBeDeoptimized) {
  2111. expression.deoptimizeCache();
  2112. }
  2113. if (this.init) {
  2114. this.init.deoptimizePath(UNKNOWN_PATH);
  2115. }
  2116. }
  2117. }
  2118. else if (this.init) {
  2119. this.init.deoptimizePath(path);
  2120. }
  2121. }
  2122. getLiteralValueAtPath(path, recursionTracker, origin) {
  2123. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2124. return UnknownValue;
  2125. }
  2126. const trackedEntities = recursionTracker.getEntities(path);
  2127. if (trackedEntities.has(this.init)) {
  2128. return UnknownValue;
  2129. }
  2130. this.expressionsToBeDeoptimized.push(origin);
  2131. trackedEntities.add(this.init);
  2132. const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  2133. trackedEntities.delete(this.init);
  2134. return value;
  2135. }
  2136. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  2137. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2138. return UNKNOWN_EXPRESSION;
  2139. }
  2140. const trackedEntities = recursionTracker.getEntities(path);
  2141. if (trackedEntities.has(this.init)) {
  2142. return UNKNOWN_EXPRESSION;
  2143. }
  2144. this.expressionsToBeDeoptimized.push(origin);
  2145. trackedEntities.add(this.init);
  2146. const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  2147. trackedEntities.delete(this.init);
  2148. return value;
  2149. }
  2150. hasEffectsWhenAccessedAtPath(path, context) {
  2151. if (path.length === 0)
  2152. return false;
  2153. if (this.isReassigned || path.length > MAX_PATH_DEPTH)
  2154. return true;
  2155. const trackedExpressions = context.accessed.getEntities(path);
  2156. if (trackedExpressions.has(this))
  2157. return false;
  2158. trackedExpressions.add(this);
  2159. return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
  2160. }
  2161. hasEffectsWhenAssignedAtPath(path, context) {
  2162. if (this.included || path.length > MAX_PATH_DEPTH)
  2163. return true;
  2164. if (path.length === 0)
  2165. return false;
  2166. if (this.isReassigned)
  2167. return true;
  2168. const trackedExpressions = context.assigned.getEntities(path);
  2169. if (trackedExpressions.has(this))
  2170. return false;
  2171. trackedExpressions.add(this);
  2172. return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
  2173. }
  2174. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2175. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2176. return true;
  2177. const trackedExpressions = (callOptions.withNew
  2178. ? context.instantiated
  2179. : context.called).getEntities(path, callOptions);
  2180. if (trackedExpressions.has(this))
  2181. return false;
  2182. trackedExpressions.add(this);
  2183. return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2184. }
  2185. include() {
  2186. if (!this.included) {
  2187. this.included = true;
  2188. for (const declaration of this.declarations) {
  2189. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  2190. if (!declaration.included)
  2191. declaration.include(createInclusionContext(), false);
  2192. let node = declaration.parent;
  2193. while (!node.included) {
  2194. // We do not want to properly include parents in case they are part of a dead branch
  2195. // in which case .include() might pull in more dead code
  2196. node.included = true;
  2197. if (node.type === Program$1)
  2198. break;
  2199. node = node.parent;
  2200. }
  2201. }
  2202. }
  2203. }
  2204. includeCallArguments(context, args) {
  2205. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  2206. for (const arg of args) {
  2207. arg.include(context, false);
  2208. }
  2209. }
  2210. else if (this.init) {
  2211. context.includedCallArguments.add(this.init);
  2212. this.init.includeCallArguments(context, args);
  2213. context.includedCallArguments.delete(this.init);
  2214. }
  2215. }
  2216. markCalledFromTryStatement() {
  2217. this.calledFromTryStatement = true;
  2218. }
  2219. }
  2220. class Scope$1 {
  2221. constructor() {
  2222. this.children = [];
  2223. this.variables = new Map();
  2224. }
  2225. addDeclaration(identifier, context, init, _isHoisted) {
  2226. const name = identifier.name;
  2227. let variable = this.variables.get(name);
  2228. if (variable) {
  2229. variable.addDeclaration(identifier, init);
  2230. }
  2231. else {
  2232. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  2233. this.variables.set(name, variable);
  2234. }
  2235. return variable;
  2236. }
  2237. contains(name) {
  2238. return this.variables.has(name);
  2239. }
  2240. findVariable(_name) {
  2241. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  2242. }
  2243. }
  2244. class ChildScope extends Scope$1 {
  2245. constructor(parent) {
  2246. super();
  2247. this.accessedOutsideVariables = new Map();
  2248. this.parent = parent;
  2249. parent.children.push(this);
  2250. }
  2251. addAccessedDynamicImport(importExpression) {
  2252. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  2253. if (this.parent instanceof ChildScope) {
  2254. this.parent.addAccessedDynamicImport(importExpression);
  2255. }
  2256. }
  2257. addAccessedGlobals(globals, accessedGlobalsByScope) {
  2258. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  2259. for (const name of globals) {
  2260. accessedGlobals.add(name);
  2261. }
  2262. accessedGlobalsByScope.set(this, accessedGlobals);
  2263. if (this.parent instanceof ChildScope) {
  2264. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  2265. }
  2266. }
  2267. addNamespaceMemberAccess(name, variable) {
  2268. this.accessedOutsideVariables.set(name, variable);
  2269. this.parent.addNamespaceMemberAccess(name, variable);
  2270. }
  2271. addReturnExpression(expression) {
  2272. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  2273. }
  2274. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  2275. for (const variable of this.accessedOutsideVariables.values()) {
  2276. if (variable.included) {
  2277. usedNames.add(variable.getBaseVariableName());
  2278. if (format === 'system' && exportNamesByVariable.has(variable)) {
  2279. usedNames.add('exports');
  2280. }
  2281. }
  2282. }
  2283. const accessedGlobals = accessedGlobalsByScope.get(this);
  2284. if (accessedGlobals) {
  2285. for (const name of accessedGlobals) {
  2286. usedNames.add(name);
  2287. }
  2288. }
  2289. }
  2290. contains(name) {
  2291. return this.variables.has(name) || this.parent.contains(name);
  2292. }
  2293. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  2294. const usedNames = new Set();
  2295. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  2296. if (this.accessedDynamicImports) {
  2297. for (const importExpression of this.accessedDynamicImports) {
  2298. if (importExpression.inlineNamespace) {
  2299. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  2300. }
  2301. }
  2302. }
  2303. for (const [name, variable] of this.variables) {
  2304. if (variable.included || variable.alwaysRendered) {
  2305. variable.setRenderNames(null, getSafeName(name, usedNames));
  2306. }
  2307. }
  2308. for (const scope of this.children) {
  2309. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  2310. }
  2311. }
  2312. findLexicalBoundary() {
  2313. return this.parent.findLexicalBoundary();
  2314. }
  2315. findVariable(name) {
  2316. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  2317. if (knownVariable) {
  2318. return knownVariable;
  2319. }
  2320. const variable = this.parent.findVariable(name);
  2321. this.accessedOutsideVariables.set(name, variable);
  2322. return variable;
  2323. }
  2324. }
  2325. function getLocator(source, options) {
  2326. if (options === void 0) { options = {}; }
  2327. var offsetLine = options.offsetLine || 0;
  2328. var offsetColumn = options.offsetColumn || 0;
  2329. var originalLines = source.split('\n');
  2330. var start = 0;
  2331. var lineRanges = originalLines.map(function (line, i) {
  2332. var end = start + line.length + 1;
  2333. var range = { start: start, end: end, line: i };
  2334. start = end;
  2335. return range;
  2336. });
  2337. var i = 0;
  2338. function rangeContains(range, index) {
  2339. return range.start <= index && index < range.end;
  2340. }
  2341. function getLocation(range, index) {
  2342. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  2343. }
  2344. function locate(search, startIndex) {
  2345. if (typeof search === 'string') {
  2346. search = source.indexOf(search, startIndex || 0);
  2347. }
  2348. var range = lineRanges[i];
  2349. var d = search >= range.end ? 1 : -1;
  2350. while (range) {
  2351. if (rangeContains(range, search))
  2352. return getLocation(range, search);
  2353. i += d;
  2354. range = lineRanges[i];
  2355. }
  2356. }
  2357. return locate;
  2358. }
  2359. function locate(source, search, options) {
  2360. if (typeof options === 'number') {
  2361. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  2362. }
  2363. return getLocator(source, options)(search, options && options.startIndex);
  2364. }
  2365. const keys = {
  2366. Literal: [],
  2367. Program: ['body']
  2368. };
  2369. function getAndCreateKeys(esTreeNode) {
  2370. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
  2371. return keys[esTreeNode.type];
  2372. }
  2373. const INCLUDE_PARAMETERS = 'variables';
  2374. class NodeBase {
  2375. constructor(esTreeNode, parent, parentScope) {
  2376. this.included = false;
  2377. this.esTreeNode = esTreeNode;
  2378. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  2379. this.parent = parent;
  2380. this.context = parent.context;
  2381. this.createScope(parentScope);
  2382. this.parseNode(esTreeNode);
  2383. this.initialise();
  2384. this.context.magicString.addSourcemapLocation(this.start);
  2385. this.context.magicString.addSourcemapLocation(this.end);
  2386. }
  2387. addExportedVariables(_variables, _exportNamesByVariable) { }
  2388. /**
  2389. * Override this to bind assignments to variables and do any initialisations that
  2390. * require the scopes to be populated with variables.
  2391. */
  2392. bind() {
  2393. for (const key of this.keys) {
  2394. const value = this[key];
  2395. if (value === null || key === 'annotations')
  2396. continue;
  2397. if (Array.isArray(value)) {
  2398. for (const child of value) {
  2399. if (child !== null)
  2400. child.bind();
  2401. }
  2402. }
  2403. else {
  2404. value.bind();
  2405. }
  2406. }
  2407. }
  2408. /**
  2409. * Override if this node should receive a different scope than the parent scope.
  2410. */
  2411. createScope(parentScope) {
  2412. this.scope = parentScope;
  2413. }
  2414. deoptimizePath(_path) { }
  2415. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2416. return UnknownValue;
  2417. }
  2418. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  2419. return UNKNOWN_EXPRESSION;
  2420. }
  2421. hasEffects(context) {
  2422. for (const key of this.keys) {
  2423. const value = this[key];
  2424. if (value === null || key === 'annotations')
  2425. continue;
  2426. if (Array.isArray(value)) {
  2427. for (const child of value) {
  2428. if (child !== null && child.hasEffects(context))
  2429. return true;
  2430. }
  2431. }
  2432. else if (value.hasEffects(context))
  2433. return true;
  2434. }
  2435. return false;
  2436. }
  2437. hasEffectsWhenAccessedAtPath(path, _context) {
  2438. return path.length > 0;
  2439. }
  2440. hasEffectsWhenAssignedAtPath(_path, _context) {
  2441. return true;
  2442. }
  2443. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  2444. return true;
  2445. }
  2446. include(context, includeChildrenRecursively) {
  2447. this.included = true;
  2448. for (const key of this.keys) {
  2449. const value = this[key];
  2450. if (value === null || key === 'annotations')
  2451. continue;
  2452. if (Array.isArray(value)) {
  2453. for (const child of value) {
  2454. if (child !== null)
  2455. child.include(context, includeChildrenRecursively);
  2456. }
  2457. }
  2458. else {
  2459. value.include(context, includeChildrenRecursively);
  2460. }
  2461. }
  2462. }
  2463. includeAsSingleStatement(context, includeChildrenRecursively) {
  2464. this.include(context, includeChildrenRecursively);
  2465. }
  2466. includeCallArguments(context, args) {
  2467. for (const arg of args) {
  2468. arg.include(context, false);
  2469. }
  2470. }
  2471. /**
  2472. * Override to perform special initialisation steps after the scope is initialised
  2473. */
  2474. initialise() { }
  2475. insertSemicolon(code) {
  2476. if (code.original[this.end - 1] !== ';') {
  2477. code.appendLeft(this.end, ';');
  2478. }
  2479. }
  2480. parseNode(esTreeNode) {
  2481. for (const key of Object.keys(esTreeNode)) {
  2482. // That way, we can override this function to add custom initialisation and then call super.parseNode
  2483. if (this.hasOwnProperty(key))
  2484. continue;
  2485. const value = esTreeNode[key];
  2486. if (typeof value !== 'object' || value === null || key === 'annotations') {
  2487. this[key] = value;
  2488. }
  2489. else if (Array.isArray(value)) {
  2490. this[key] = [];
  2491. for (const child of value) {
  2492. this[key].push(child === null
  2493. ? null
  2494. : new (this.context.nodeConstructors[child.type] ||
  2495. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  2496. }
  2497. }
  2498. else {
  2499. this[key] = new (this.context.nodeConstructors[value.type] ||
  2500. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  2501. }
  2502. }
  2503. }
  2504. render(code, options) {
  2505. for (const key of this.keys) {
  2506. const value = this[key];
  2507. if (value === null || key === 'annotations')
  2508. continue;
  2509. if (Array.isArray(value)) {
  2510. for (const child of value) {
  2511. if (child !== null)
  2512. child.render(code, options);
  2513. }
  2514. }
  2515. else {
  2516. value.render(code, options);
  2517. }
  2518. }
  2519. }
  2520. shouldBeIncluded(context) {
  2521. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2522. }
  2523. }
  2524. class ClassNode extends NodeBase {
  2525. createScope(parentScope) {
  2526. this.scope = new ChildScope(parentScope);
  2527. }
  2528. hasEffectsWhenAccessedAtPath(path) {
  2529. if (path.length <= 1)
  2530. return false;
  2531. return path.length > 2 || path[0] !== 'prototype';
  2532. }
  2533. hasEffectsWhenAssignedAtPath(path) {
  2534. if (path.length <= 1)
  2535. return false;
  2536. return path.length > 2 || path[0] !== 'prototype';
  2537. }
  2538. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2539. if (!callOptions.withNew)
  2540. return true;
  2541. return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2542. (this.superClass !== null &&
  2543. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  2544. }
  2545. initialise() {
  2546. if (this.id !== null) {
  2547. this.id.declare('class', this);
  2548. }
  2549. }
  2550. }
  2551. class ClassDeclaration extends ClassNode {
  2552. initialise() {
  2553. super.initialise();
  2554. if (this.id !== null) {
  2555. this.id.variable.isId = true;
  2556. }
  2557. }
  2558. parseNode(esTreeNode) {
  2559. if (esTreeNode.id !== null) {
  2560. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  2561. }
  2562. super.parseNode(esTreeNode);
  2563. }
  2564. render(code, options) {
  2565. if (options.format === 'system' &&
  2566. this.id &&
  2567. options.exportNamesByVariable.has(this.id.variable)) {
  2568. code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
  2569. }
  2570. super.render(code, options);
  2571. }
  2572. }
  2573. class ArgumentsVariable extends LocalVariable {
  2574. constructor(context) {
  2575. super('arguments', null, UNKNOWN_EXPRESSION, context);
  2576. }
  2577. hasEffectsWhenAccessedAtPath(path) {
  2578. return path.length > 1;
  2579. }
  2580. hasEffectsWhenAssignedAtPath() {
  2581. return true;
  2582. }
  2583. hasEffectsWhenCalledAtPath() {
  2584. return true;
  2585. }
  2586. }
  2587. class ThisVariable extends LocalVariable {
  2588. constructor(context) {
  2589. super('this', null, null, context);
  2590. }
  2591. getLiteralValueAtPath() {
  2592. return UnknownValue;
  2593. }
  2594. hasEffectsWhenAccessedAtPath(path, context) {
  2595. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  2596. super.hasEffectsWhenAccessedAtPath(path, context));
  2597. }
  2598. hasEffectsWhenAssignedAtPath(path, context) {
  2599. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  2600. super.hasEffectsWhenAssignedAtPath(path, context));
  2601. }
  2602. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2603. return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  2604. super.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2605. }
  2606. getInit(context) {
  2607. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  2608. }
  2609. }
  2610. class SpreadElement extends NodeBase {
  2611. bind() {
  2612. super.bind();
  2613. // Only properties of properties of the argument could become subject to reassignment
  2614. // This will also reassign the return values of iterators
  2615. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  2616. }
  2617. }
  2618. class ParameterScope extends ChildScope {
  2619. constructor(parent, context) {
  2620. super(parent);
  2621. this.parameters = [];
  2622. this.hasRest = false;
  2623. this.context = context;
  2624. this.hoistedBodyVarScope = new ChildScope(this);
  2625. }
  2626. /**
  2627. * Adds a parameter to this scope. Parameters must be added in the correct
  2628. * order, e.g. from left to right.
  2629. */
  2630. addParameterDeclaration(identifier) {
  2631. const name = identifier.name;
  2632. let variable = this.hoistedBodyVarScope.variables.get(name);
  2633. if (variable) {
  2634. variable.addDeclaration(identifier, null);
  2635. }
  2636. else {
  2637. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  2638. }
  2639. this.variables.set(name, variable);
  2640. return variable;
  2641. }
  2642. addParameterVariables(parameters, hasRest) {
  2643. this.parameters = parameters;
  2644. for (const parameterList of parameters) {
  2645. for (const parameter of parameterList) {
  2646. parameter.alwaysRendered = true;
  2647. }
  2648. }
  2649. this.hasRest = hasRest;
  2650. }
  2651. includeCallArguments(context, args) {
  2652. let calledFromTryStatement = false;
  2653. let argIncluded = false;
  2654. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  2655. for (const checkedArg of args) {
  2656. if (checkedArg instanceof SpreadElement) {
  2657. for (const arg of args) {
  2658. arg.include(context, false);
  2659. }
  2660. break;
  2661. }
  2662. }
  2663. for (let index = args.length - 1; index >= 0; index--) {
  2664. const paramVars = this.parameters[index] || restParam;
  2665. const arg = args[index];
  2666. if (paramVars) {
  2667. calledFromTryStatement = false;
  2668. for (const variable of paramVars) {
  2669. if (variable.included) {
  2670. argIncluded = true;
  2671. }
  2672. if (variable.calledFromTryStatement) {
  2673. calledFromTryStatement = true;
  2674. }
  2675. }
  2676. }
  2677. if (!argIncluded && arg.shouldBeIncluded(context)) {
  2678. argIncluded = true;
  2679. }
  2680. if (argIncluded) {
  2681. arg.include(context, calledFromTryStatement);
  2682. }
  2683. }
  2684. }
  2685. }
  2686. class ReturnValueScope extends ParameterScope {
  2687. constructor() {
  2688. super(...arguments);
  2689. this.returnExpression = null;
  2690. this.returnExpressions = [];
  2691. }
  2692. addReturnExpression(expression) {
  2693. this.returnExpressions.push(expression);
  2694. }
  2695. getReturnExpression() {
  2696. if (this.returnExpression === null)
  2697. this.updateReturnExpression();
  2698. return this.returnExpression;
  2699. }
  2700. updateReturnExpression() {
  2701. if (this.returnExpressions.length === 1) {
  2702. this.returnExpression = this.returnExpressions[0];
  2703. }
  2704. else {
  2705. this.returnExpression = UNKNOWN_EXPRESSION;
  2706. for (const expression of this.returnExpressions) {
  2707. expression.deoptimizePath(UNKNOWN_PATH);
  2708. }
  2709. }
  2710. }
  2711. }
  2712. class FunctionScope extends ReturnValueScope {
  2713. constructor(parent, context) {
  2714. super(parent, context);
  2715. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  2716. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  2717. }
  2718. findLexicalBoundary() {
  2719. return this;
  2720. }
  2721. includeCallArguments(context, args) {
  2722. super.includeCallArguments(context, args);
  2723. if (this.argumentsVariable.included) {
  2724. for (const arg of args) {
  2725. if (!arg.included) {
  2726. arg.include(context, false);
  2727. }
  2728. }
  2729. }
  2730. }
  2731. }
  2732. //@ts-check
  2733. /** @typedef { import('estree').Node} Node */
  2734. /** @typedef {Node | {
  2735. * type: 'PropertyDefinition';
  2736. * computed: boolean;
  2737. * value: Node
  2738. * }} NodeWithPropertyDefinition */
  2739. /**
  2740. *
  2741. * @param {NodeWithPropertyDefinition} node
  2742. * @param {NodeWithPropertyDefinition} parent
  2743. * @returns boolean
  2744. */
  2745. function is_reference (node, parent) {
  2746. if (node.type === 'MemberExpression') {
  2747. return !node.computed && is_reference(node.object, node);
  2748. }
  2749. if (node.type === 'Identifier') {
  2750. if (!parent) return true;
  2751. switch (parent.type) {
  2752. // disregard `bar` in `foo.bar`
  2753. case 'MemberExpression': return parent.computed || node === parent.object;
  2754. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  2755. case 'MethodDefinition': return parent.computed;
  2756. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  2757. case 'PropertyDefinition': return parent.computed || node === parent.value;
  2758. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  2759. case 'Property': return parent.computed || node === parent.value;
  2760. // disregard the `bar` in `export { foo as bar }` or
  2761. // the foo in `import { foo as bar }`
  2762. case 'ExportSpecifier':
  2763. case 'ImportSpecifier': return node === parent.local;
  2764. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  2765. case 'LabeledStatement':
  2766. case 'BreakStatement':
  2767. case 'ContinueStatement': return false;
  2768. default: return true;
  2769. }
  2770. }
  2771. return false;
  2772. }
  2773. const BLANK = Object.freeze(Object.create(null));
  2774. const EMPTY_OBJECT = Object.freeze({});
  2775. const EMPTY_ARRAY = Object.freeze([]);
  2776. const ValueProperties = Symbol('Value Properties');
  2777. const PURE = { pure: true };
  2778. const IMPURE = { pure: false };
  2779. // We use shortened variables to reduce file size here
  2780. /* OBJECT */
  2781. const O = {
  2782. // @ts-ignore
  2783. __proto__: null,
  2784. [ValueProperties]: IMPURE
  2785. };
  2786. /* PURE FUNCTION */
  2787. const PF = {
  2788. // @ts-ignore
  2789. __proto__: null,
  2790. [ValueProperties]: PURE
  2791. };
  2792. /* CONSTRUCTOR */
  2793. const C = {
  2794. // @ts-ignore
  2795. __proto__: null,
  2796. [ValueProperties]: IMPURE,
  2797. prototype: O
  2798. };
  2799. /* PURE CONSTRUCTOR */
  2800. const PC = {
  2801. // @ts-ignore
  2802. __proto__: null,
  2803. [ValueProperties]: PURE,
  2804. prototype: O
  2805. };
  2806. const ARRAY_TYPE = {
  2807. // @ts-ignore
  2808. __proto__: null,
  2809. [ValueProperties]: PURE,
  2810. from: PF,
  2811. of: PF,
  2812. prototype: O
  2813. };
  2814. const INTL_MEMBER = {
  2815. // @ts-ignore
  2816. __proto__: null,
  2817. [ValueProperties]: PURE,
  2818. supportedLocalesOf: PC
  2819. };
  2820. const knownGlobals = {
  2821. // Placeholders for global objects to avoid shape mutations
  2822. global: O,
  2823. globalThis: O,
  2824. self: O,
  2825. window: O,
  2826. // Common globals
  2827. // @ts-ignore
  2828. __proto__: null,
  2829. [ValueProperties]: IMPURE,
  2830. Array: {
  2831. // @ts-ignore
  2832. __proto__: null,
  2833. [ValueProperties]: IMPURE,
  2834. from: O,
  2835. isArray: PF,
  2836. of: PF,
  2837. prototype: O
  2838. },
  2839. ArrayBuffer: {
  2840. // @ts-ignore
  2841. __proto__: null,
  2842. [ValueProperties]: PURE,
  2843. isView: PF,
  2844. prototype: O
  2845. },
  2846. Atomics: O,
  2847. BigInt: C,
  2848. BigInt64Array: C,
  2849. BigUint64Array: C,
  2850. Boolean: PC,
  2851. // @ts-ignore
  2852. constructor: C,
  2853. DataView: PC,
  2854. Date: {
  2855. // @ts-ignore
  2856. __proto__: null,
  2857. [ValueProperties]: PURE,
  2858. now: PF,
  2859. parse: PF,
  2860. prototype: O,
  2861. UTC: PF
  2862. },
  2863. decodeURI: PF,
  2864. decodeURIComponent: PF,
  2865. encodeURI: PF,
  2866. encodeURIComponent: PF,
  2867. Error: PC,
  2868. escape: PF,
  2869. eval: O,
  2870. EvalError: PC,
  2871. Float32Array: ARRAY_TYPE,
  2872. Float64Array: ARRAY_TYPE,
  2873. Function: C,
  2874. // @ts-ignore
  2875. hasOwnProperty: O,
  2876. Infinity: O,
  2877. Int16Array: ARRAY_TYPE,
  2878. Int32Array: ARRAY_TYPE,
  2879. Int8Array: ARRAY_TYPE,
  2880. isFinite: PF,
  2881. isNaN: PF,
  2882. // @ts-ignore
  2883. isPrototypeOf: O,
  2884. JSON: O,
  2885. Map: PC,
  2886. Math: {
  2887. // @ts-ignore
  2888. __proto__: null,
  2889. [ValueProperties]: IMPURE,
  2890. abs: PF,
  2891. acos: PF,
  2892. acosh: PF,
  2893. asin: PF,
  2894. asinh: PF,
  2895. atan: PF,
  2896. atan2: PF,
  2897. atanh: PF,
  2898. cbrt: PF,
  2899. ceil: PF,
  2900. clz32: PF,
  2901. cos: PF,
  2902. cosh: PF,
  2903. exp: PF,
  2904. expm1: PF,
  2905. floor: PF,
  2906. fround: PF,
  2907. hypot: PF,
  2908. imul: PF,
  2909. log: PF,
  2910. log10: PF,
  2911. log1p: PF,
  2912. log2: PF,
  2913. max: PF,
  2914. min: PF,
  2915. pow: PF,
  2916. random: PF,
  2917. round: PF,
  2918. sign: PF,
  2919. sin: PF,
  2920. sinh: PF,
  2921. sqrt: PF,
  2922. tan: PF,
  2923. tanh: PF,
  2924. trunc: PF
  2925. },
  2926. NaN: O,
  2927. Number: {
  2928. // @ts-ignore
  2929. __proto__: null,
  2930. [ValueProperties]: PURE,
  2931. isFinite: PF,
  2932. isInteger: PF,
  2933. isNaN: PF,
  2934. isSafeInteger: PF,
  2935. parseFloat: PF,
  2936. parseInt: PF,
  2937. prototype: O
  2938. },
  2939. Object: {
  2940. // @ts-ignore
  2941. __proto__: null,
  2942. [ValueProperties]: PURE,
  2943. create: PF,
  2944. getNotifier: PF,
  2945. getOwn: PF,
  2946. getOwnPropertyDescriptor: PF,
  2947. getOwnPropertyNames: PF,
  2948. getOwnPropertySymbols: PF,
  2949. getPrototypeOf: PF,
  2950. is: PF,
  2951. isExtensible: PF,
  2952. isFrozen: PF,
  2953. isSealed: PF,
  2954. keys: PF,
  2955. prototype: O
  2956. },
  2957. parseFloat: PF,
  2958. parseInt: PF,
  2959. Promise: {
  2960. // @ts-ignore
  2961. __proto__: null,
  2962. [ValueProperties]: IMPURE,
  2963. all: PF,
  2964. prototype: O,
  2965. race: PF,
  2966. resolve: PF
  2967. },
  2968. // @ts-ignore
  2969. propertyIsEnumerable: O,
  2970. Proxy: O,
  2971. RangeError: PC,
  2972. ReferenceError: PC,
  2973. Reflect: O,
  2974. RegExp: PC,
  2975. Set: PC,
  2976. SharedArrayBuffer: C,
  2977. String: {
  2978. // @ts-ignore
  2979. __proto__: null,
  2980. [ValueProperties]: PURE,
  2981. fromCharCode: PF,
  2982. fromCodePoint: PF,
  2983. prototype: O,
  2984. raw: PF
  2985. },
  2986. Symbol: {
  2987. // @ts-ignore
  2988. __proto__: null,
  2989. [ValueProperties]: PURE,
  2990. for: PF,
  2991. keyFor: PF,
  2992. prototype: O
  2993. },
  2994. SyntaxError: PC,
  2995. // @ts-ignore
  2996. toLocaleString: O,
  2997. // @ts-ignore
  2998. toString: O,
  2999. TypeError: PC,
  3000. Uint16Array: ARRAY_TYPE,
  3001. Uint32Array: ARRAY_TYPE,
  3002. Uint8Array: ARRAY_TYPE,
  3003. Uint8ClampedArray: ARRAY_TYPE,
  3004. // Technically, this is a global, but it needs special handling
  3005. // undefined: ?,
  3006. unescape: PF,
  3007. URIError: PC,
  3008. // @ts-ignore
  3009. valueOf: O,
  3010. WeakMap: PC,
  3011. WeakSet: PC,
  3012. // Additional globals shared by Node and Browser that are not strictly part of the language
  3013. clearInterval: C,
  3014. clearTimeout: C,
  3015. console: O,
  3016. Intl: {
  3017. // @ts-ignore
  3018. __proto__: null,
  3019. [ValueProperties]: IMPURE,
  3020. Collator: INTL_MEMBER,
  3021. DateTimeFormat: INTL_MEMBER,
  3022. ListFormat: INTL_MEMBER,
  3023. NumberFormat: INTL_MEMBER,
  3024. PluralRules: INTL_MEMBER,
  3025. RelativeTimeFormat: INTL_MEMBER
  3026. },
  3027. setInterval: C,
  3028. setTimeout: C,
  3029. TextDecoder: C,
  3030. TextEncoder: C,
  3031. URL: C,
  3032. URLSearchParams: C,
  3033. // Browser specific globals
  3034. AbortController: C,
  3035. AbortSignal: C,
  3036. addEventListener: O,
  3037. alert: O,
  3038. AnalyserNode: C,
  3039. Animation: C,
  3040. AnimationEvent: C,
  3041. applicationCache: O,
  3042. ApplicationCache: C,
  3043. ApplicationCacheErrorEvent: C,
  3044. atob: O,
  3045. Attr: C,
  3046. Audio: C,
  3047. AudioBuffer: C,
  3048. AudioBufferSourceNode: C,
  3049. AudioContext: C,
  3050. AudioDestinationNode: C,
  3051. AudioListener: C,
  3052. AudioNode: C,
  3053. AudioParam: C,
  3054. AudioProcessingEvent: C,
  3055. AudioScheduledSourceNode: C,
  3056. AudioWorkletNode: C,
  3057. BarProp: C,
  3058. BaseAudioContext: C,
  3059. BatteryManager: C,
  3060. BeforeUnloadEvent: C,
  3061. BiquadFilterNode: C,
  3062. Blob: C,
  3063. BlobEvent: C,
  3064. blur: O,
  3065. BroadcastChannel: C,
  3066. btoa: O,
  3067. ByteLengthQueuingStrategy: C,
  3068. Cache: C,
  3069. caches: O,
  3070. CacheStorage: C,
  3071. cancelAnimationFrame: O,
  3072. cancelIdleCallback: O,
  3073. CanvasCaptureMediaStreamTrack: C,
  3074. CanvasGradient: C,
  3075. CanvasPattern: C,
  3076. CanvasRenderingContext2D: C,
  3077. ChannelMergerNode: C,
  3078. ChannelSplitterNode: C,
  3079. CharacterData: C,
  3080. clientInformation: O,
  3081. ClipboardEvent: C,
  3082. close: O,
  3083. closed: O,
  3084. CloseEvent: C,
  3085. Comment: C,
  3086. CompositionEvent: C,
  3087. confirm: O,
  3088. ConstantSourceNode: C,
  3089. ConvolverNode: C,
  3090. CountQueuingStrategy: C,
  3091. createImageBitmap: O,
  3092. Credential: C,
  3093. CredentialsContainer: C,
  3094. crypto: O,
  3095. Crypto: C,
  3096. CryptoKey: C,
  3097. CSS: C,
  3098. CSSConditionRule: C,
  3099. CSSFontFaceRule: C,
  3100. CSSGroupingRule: C,
  3101. CSSImportRule: C,
  3102. CSSKeyframeRule: C,
  3103. CSSKeyframesRule: C,
  3104. CSSMediaRule: C,
  3105. CSSNamespaceRule: C,
  3106. CSSPageRule: C,
  3107. CSSRule: C,
  3108. CSSRuleList: C,
  3109. CSSStyleDeclaration: C,
  3110. CSSStyleRule: C,
  3111. CSSStyleSheet: C,
  3112. CSSSupportsRule: C,
  3113. CustomElementRegistry: C,
  3114. customElements: O,
  3115. CustomEvent: C,
  3116. DataTransfer: C,
  3117. DataTransferItem: C,
  3118. DataTransferItemList: C,
  3119. defaultstatus: O,
  3120. defaultStatus: O,
  3121. DelayNode: C,
  3122. DeviceMotionEvent: C,
  3123. DeviceOrientationEvent: C,
  3124. devicePixelRatio: O,
  3125. dispatchEvent: O,
  3126. document: O,
  3127. Document: C,
  3128. DocumentFragment: C,
  3129. DocumentType: C,
  3130. DOMError: C,
  3131. DOMException: C,
  3132. DOMImplementation: C,
  3133. DOMMatrix: C,
  3134. DOMMatrixReadOnly: C,
  3135. DOMParser: C,
  3136. DOMPoint: C,
  3137. DOMPointReadOnly: C,
  3138. DOMQuad: C,
  3139. DOMRect: C,
  3140. DOMRectReadOnly: C,
  3141. DOMStringList: C,
  3142. DOMStringMap: C,
  3143. DOMTokenList: C,
  3144. DragEvent: C,
  3145. DynamicsCompressorNode: C,
  3146. Element: C,
  3147. ErrorEvent: C,
  3148. Event: C,
  3149. EventSource: C,
  3150. EventTarget: C,
  3151. external: O,
  3152. fetch: O,
  3153. File: C,
  3154. FileList: C,
  3155. FileReader: C,
  3156. find: O,
  3157. focus: O,
  3158. FocusEvent: C,
  3159. FontFace: C,
  3160. FontFaceSetLoadEvent: C,
  3161. FormData: C,
  3162. frames: O,
  3163. GainNode: C,
  3164. Gamepad: C,
  3165. GamepadButton: C,
  3166. GamepadEvent: C,
  3167. getComputedStyle: O,
  3168. getSelection: O,
  3169. HashChangeEvent: C,
  3170. Headers: C,
  3171. history: O,
  3172. History: C,
  3173. HTMLAllCollection: C,
  3174. HTMLAnchorElement: C,
  3175. HTMLAreaElement: C,
  3176. HTMLAudioElement: C,
  3177. HTMLBaseElement: C,
  3178. HTMLBodyElement: C,
  3179. HTMLBRElement: C,
  3180. HTMLButtonElement: C,
  3181. HTMLCanvasElement: C,
  3182. HTMLCollection: C,
  3183. HTMLContentElement: C,
  3184. HTMLDataElement: C,
  3185. HTMLDataListElement: C,
  3186. HTMLDetailsElement: C,
  3187. HTMLDialogElement: C,
  3188. HTMLDirectoryElement: C,
  3189. HTMLDivElement: C,
  3190. HTMLDListElement: C,
  3191. HTMLDocument: C,
  3192. HTMLElement: C,
  3193. HTMLEmbedElement: C,
  3194. HTMLFieldSetElement: C,
  3195. HTMLFontElement: C,
  3196. HTMLFormControlsCollection: C,
  3197. HTMLFormElement: C,
  3198. HTMLFrameElement: C,
  3199. HTMLFrameSetElement: C,
  3200. HTMLHeadElement: C,
  3201. HTMLHeadingElement: C,
  3202. HTMLHRElement: C,
  3203. HTMLHtmlElement: C,
  3204. HTMLIFrameElement: C,
  3205. HTMLImageElement: C,
  3206. HTMLInputElement: C,
  3207. HTMLLabelElement: C,
  3208. HTMLLegendElement: C,
  3209. HTMLLIElement: C,
  3210. HTMLLinkElement: C,
  3211. HTMLMapElement: C,
  3212. HTMLMarqueeElement: C,
  3213. HTMLMediaElement: C,
  3214. HTMLMenuElement: C,
  3215. HTMLMetaElement: C,
  3216. HTMLMeterElement: C,
  3217. HTMLModElement: C,
  3218. HTMLObjectElement: C,
  3219. HTMLOListElement: C,
  3220. HTMLOptGroupElement: C,
  3221. HTMLOptionElement: C,
  3222. HTMLOptionsCollection: C,
  3223. HTMLOutputElement: C,
  3224. HTMLParagraphElement: C,
  3225. HTMLParamElement: C,
  3226. HTMLPictureElement: C,
  3227. HTMLPreElement: C,
  3228. HTMLProgressElement: C,
  3229. HTMLQuoteElement: C,
  3230. HTMLScriptElement: C,
  3231. HTMLSelectElement: C,
  3232. HTMLShadowElement: C,
  3233. HTMLSlotElement: C,
  3234. HTMLSourceElement: C,
  3235. HTMLSpanElement: C,
  3236. HTMLStyleElement: C,
  3237. HTMLTableCaptionElement: C,
  3238. HTMLTableCellElement: C,
  3239. HTMLTableColElement: C,
  3240. HTMLTableElement: C,
  3241. HTMLTableRowElement: C,
  3242. HTMLTableSectionElement: C,
  3243. HTMLTemplateElement: C,
  3244. HTMLTextAreaElement: C,
  3245. HTMLTimeElement: C,
  3246. HTMLTitleElement: C,
  3247. HTMLTrackElement: C,
  3248. HTMLUListElement: C,
  3249. HTMLUnknownElement: C,
  3250. HTMLVideoElement: C,
  3251. IDBCursor: C,
  3252. IDBCursorWithValue: C,
  3253. IDBDatabase: C,
  3254. IDBFactory: C,
  3255. IDBIndex: C,
  3256. IDBKeyRange: C,
  3257. IDBObjectStore: C,
  3258. IDBOpenDBRequest: C,
  3259. IDBRequest: C,
  3260. IDBTransaction: C,
  3261. IDBVersionChangeEvent: C,
  3262. IdleDeadline: C,
  3263. IIRFilterNode: C,
  3264. Image: C,
  3265. ImageBitmap: C,
  3266. ImageBitmapRenderingContext: C,
  3267. ImageCapture: C,
  3268. ImageData: C,
  3269. indexedDB: O,
  3270. innerHeight: O,
  3271. innerWidth: O,
  3272. InputEvent: C,
  3273. IntersectionObserver: C,
  3274. IntersectionObserverEntry: C,
  3275. isSecureContext: O,
  3276. KeyboardEvent: C,
  3277. KeyframeEffect: C,
  3278. length: O,
  3279. localStorage: O,
  3280. location: O,
  3281. Location: C,
  3282. locationbar: O,
  3283. matchMedia: O,
  3284. MediaDeviceInfo: C,
  3285. MediaDevices: C,
  3286. MediaElementAudioSourceNode: C,
  3287. MediaEncryptedEvent: C,
  3288. MediaError: C,
  3289. MediaKeyMessageEvent: C,
  3290. MediaKeySession: C,
  3291. MediaKeyStatusMap: C,
  3292. MediaKeySystemAccess: C,
  3293. MediaList: C,
  3294. MediaQueryList: C,
  3295. MediaQueryListEvent: C,
  3296. MediaRecorder: C,
  3297. MediaSettingsRange: C,
  3298. MediaSource: C,
  3299. MediaStream: C,
  3300. MediaStreamAudioDestinationNode: C,
  3301. MediaStreamAudioSourceNode: C,
  3302. MediaStreamEvent: C,
  3303. MediaStreamTrack: C,
  3304. MediaStreamTrackEvent: C,
  3305. menubar: O,
  3306. MessageChannel: C,
  3307. MessageEvent: C,
  3308. MessagePort: C,
  3309. MIDIAccess: C,
  3310. MIDIConnectionEvent: C,
  3311. MIDIInput: C,
  3312. MIDIInputMap: C,
  3313. MIDIMessageEvent: C,
  3314. MIDIOutput: C,
  3315. MIDIOutputMap: C,
  3316. MIDIPort: C,
  3317. MimeType: C,
  3318. MimeTypeArray: C,
  3319. MouseEvent: C,
  3320. moveBy: O,
  3321. moveTo: O,
  3322. MutationEvent: C,
  3323. MutationObserver: C,
  3324. MutationRecord: C,
  3325. name: O,
  3326. NamedNodeMap: C,
  3327. NavigationPreloadManager: C,
  3328. navigator: O,
  3329. Navigator: C,
  3330. NetworkInformation: C,
  3331. Node: C,
  3332. NodeFilter: O,
  3333. NodeIterator: C,
  3334. NodeList: C,
  3335. Notification: C,
  3336. OfflineAudioCompletionEvent: C,
  3337. OfflineAudioContext: C,
  3338. offscreenBuffering: O,
  3339. OffscreenCanvas: C,
  3340. open: O,
  3341. openDatabase: O,
  3342. Option: C,
  3343. origin: O,
  3344. OscillatorNode: C,
  3345. outerHeight: O,
  3346. outerWidth: O,
  3347. PageTransitionEvent: C,
  3348. pageXOffset: O,
  3349. pageYOffset: O,
  3350. PannerNode: C,
  3351. parent: O,
  3352. Path2D: C,
  3353. PaymentAddress: C,
  3354. PaymentRequest: C,
  3355. PaymentRequestUpdateEvent: C,
  3356. PaymentResponse: C,
  3357. performance: O,
  3358. Performance: C,
  3359. PerformanceEntry: C,
  3360. PerformanceLongTaskTiming: C,
  3361. PerformanceMark: C,
  3362. PerformanceMeasure: C,
  3363. PerformanceNavigation: C,
  3364. PerformanceNavigationTiming: C,
  3365. PerformanceObserver: C,
  3366. PerformanceObserverEntryList: C,
  3367. PerformancePaintTiming: C,
  3368. PerformanceResourceTiming: C,
  3369. PerformanceTiming: C,
  3370. PeriodicWave: C,
  3371. Permissions: C,
  3372. PermissionStatus: C,
  3373. personalbar: O,
  3374. PhotoCapabilities: C,
  3375. Plugin: C,
  3376. PluginArray: C,
  3377. PointerEvent: C,
  3378. PopStateEvent: C,
  3379. postMessage: O,
  3380. Presentation: C,
  3381. PresentationAvailability: C,
  3382. PresentationConnection: C,
  3383. PresentationConnectionAvailableEvent: C,
  3384. PresentationConnectionCloseEvent: C,
  3385. PresentationConnectionList: C,
  3386. PresentationReceiver: C,
  3387. PresentationRequest: C,
  3388. print: O,
  3389. ProcessingInstruction: C,
  3390. ProgressEvent: C,
  3391. PromiseRejectionEvent: C,
  3392. prompt: O,
  3393. PushManager: C,
  3394. PushSubscription: C,
  3395. PushSubscriptionOptions: C,
  3396. queueMicrotask: O,
  3397. RadioNodeList: C,
  3398. Range: C,
  3399. ReadableStream: C,
  3400. RemotePlayback: C,
  3401. removeEventListener: O,
  3402. Request: C,
  3403. requestAnimationFrame: O,
  3404. requestIdleCallback: O,
  3405. resizeBy: O,
  3406. ResizeObserver: C,
  3407. ResizeObserverEntry: C,
  3408. resizeTo: O,
  3409. Response: C,
  3410. RTCCertificate: C,
  3411. RTCDataChannel: C,
  3412. RTCDataChannelEvent: C,
  3413. RTCDtlsTransport: C,
  3414. RTCIceCandidate: C,
  3415. RTCIceTransport: C,
  3416. RTCPeerConnection: C,
  3417. RTCPeerConnectionIceEvent: C,
  3418. RTCRtpReceiver: C,
  3419. RTCRtpSender: C,
  3420. RTCSctpTransport: C,
  3421. RTCSessionDescription: C,
  3422. RTCStatsReport: C,
  3423. RTCTrackEvent: C,
  3424. screen: O,
  3425. Screen: C,
  3426. screenLeft: O,
  3427. ScreenOrientation: C,
  3428. screenTop: O,
  3429. screenX: O,
  3430. screenY: O,
  3431. ScriptProcessorNode: C,
  3432. scroll: O,
  3433. scrollbars: O,
  3434. scrollBy: O,
  3435. scrollTo: O,
  3436. scrollX: O,
  3437. scrollY: O,
  3438. SecurityPolicyViolationEvent: C,
  3439. Selection: C,
  3440. ServiceWorker: C,
  3441. ServiceWorkerContainer: C,
  3442. ServiceWorkerRegistration: C,
  3443. sessionStorage: O,
  3444. ShadowRoot: C,
  3445. SharedWorker: C,
  3446. SourceBuffer: C,
  3447. SourceBufferList: C,
  3448. speechSynthesis: O,
  3449. SpeechSynthesisEvent: C,
  3450. SpeechSynthesisUtterance: C,
  3451. StaticRange: C,
  3452. status: O,
  3453. statusbar: O,
  3454. StereoPannerNode: C,
  3455. stop: O,
  3456. Storage: C,
  3457. StorageEvent: C,
  3458. StorageManager: C,
  3459. styleMedia: O,
  3460. StyleSheet: C,
  3461. StyleSheetList: C,
  3462. SubtleCrypto: C,
  3463. SVGAElement: C,
  3464. SVGAngle: C,
  3465. SVGAnimatedAngle: C,
  3466. SVGAnimatedBoolean: C,
  3467. SVGAnimatedEnumeration: C,
  3468. SVGAnimatedInteger: C,
  3469. SVGAnimatedLength: C,
  3470. SVGAnimatedLengthList: C,
  3471. SVGAnimatedNumber: C,
  3472. SVGAnimatedNumberList: C,
  3473. SVGAnimatedPreserveAspectRatio: C,
  3474. SVGAnimatedRect: C,
  3475. SVGAnimatedString: C,
  3476. SVGAnimatedTransformList: C,
  3477. SVGAnimateElement: C,
  3478. SVGAnimateMotionElement: C,
  3479. SVGAnimateTransformElement: C,
  3480. SVGAnimationElement: C,
  3481. SVGCircleElement: C,
  3482. SVGClipPathElement: C,
  3483. SVGComponentTransferFunctionElement: C,
  3484. SVGDefsElement: C,
  3485. SVGDescElement: C,
  3486. SVGDiscardElement: C,
  3487. SVGElement: C,
  3488. SVGEllipseElement: C,
  3489. SVGFEBlendElement: C,
  3490. SVGFEColorMatrixElement: C,
  3491. SVGFEComponentTransferElement: C,
  3492. SVGFECompositeElement: C,
  3493. SVGFEConvolveMatrixElement: C,
  3494. SVGFEDiffuseLightingElement: C,
  3495. SVGFEDisplacementMapElement: C,
  3496. SVGFEDistantLightElement: C,
  3497. SVGFEDropShadowElement: C,
  3498. SVGFEFloodElement: C,
  3499. SVGFEFuncAElement: C,
  3500. SVGFEFuncBElement: C,
  3501. SVGFEFuncGElement: C,
  3502. SVGFEFuncRElement: C,
  3503. SVGFEGaussianBlurElement: C,
  3504. SVGFEImageElement: C,
  3505. SVGFEMergeElement: C,
  3506. SVGFEMergeNodeElement: C,
  3507. SVGFEMorphologyElement: C,
  3508. SVGFEOffsetElement: C,
  3509. SVGFEPointLightElement: C,
  3510. SVGFESpecularLightingElement: C,
  3511. SVGFESpotLightElement: C,
  3512. SVGFETileElement: C,
  3513. SVGFETurbulenceElement: C,
  3514. SVGFilterElement: C,
  3515. SVGForeignObjectElement: C,
  3516. SVGGElement: C,
  3517. SVGGeometryElement: C,
  3518. SVGGradientElement: C,
  3519. SVGGraphicsElement: C,
  3520. SVGImageElement: C,
  3521. SVGLength: C,
  3522. SVGLengthList: C,
  3523. SVGLinearGradientElement: C,
  3524. SVGLineElement: C,
  3525. SVGMarkerElement: C,
  3526. SVGMaskElement: C,
  3527. SVGMatrix: C,
  3528. SVGMetadataElement: C,
  3529. SVGMPathElement: C,
  3530. SVGNumber: C,
  3531. SVGNumberList: C,
  3532. SVGPathElement: C,
  3533. SVGPatternElement: C,
  3534. SVGPoint: C,
  3535. SVGPointList: C,
  3536. SVGPolygonElement: C,
  3537. SVGPolylineElement: C,
  3538. SVGPreserveAspectRatio: C,
  3539. SVGRadialGradientElement: C,
  3540. SVGRect: C,
  3541. SVGRectElement: C,
  3542. SVGScriptElement: C,
  3543. SVGSetElement: C,
  3544. SVGStopElement: C,
  3545. SVGStringList: C,
  3546. SVGStyleElement: C,
  3547. SVGSVGElement: C,
  3548. SVGSwitchElement: C,
  3549. SVGSymbolElement: C,
  3550. SVGTextContentElement: C,
  3551. SVGTextElement: C,
  3552. SVGTextPathElement: C,
  3553. SVGTextPositioningElement: C,
  3554. SVGTitleElement: C,
  3555. SVGTransform: C,
  3556. SVGTransformList: C,
  3557. SVGTSpanElement: C,
  3558. SVGUnitTypes: C,
  3559. SVGUseElement: C,
  3560. SVGViewElement: C,
  3561. TaskAttributionTiming: C,
  3562. Text: C,
  3563. TextEvent: C,
  3564. TextMetrics: C,
  3565. TextTrack: C,
  3566. TextTrackCue: C,
  3567. TextTrackCueList: C,
  3568. TextTrackList: C,
  3569. TimeRanges: C,
  3570. toolbar: O,
  3571. top: O,
  3572. Touch: C,
  3573. TouchEvent: C,
  3574. TouchList: C,
  3575. TrackEvent: C,
  3576. TransitionEvent: C,
  3577. TreeWalker: C,
  3578. UIEvent: C,
  3579. ValidityState: C,
  3580. visualViewport: O,
  3581. VisualViewport: C,
  3582. VTTCue: C,
  3583. WaveShaperNode: C,
  3584. WebAssembly: O,
  3585. WebGL2RenderingContext: C,
  3586. WebGLActiveInfo: C,
  3587. WebGLBuffer: C,
  3588. WebGLContextEvent: C,
  3589. WebGLFramebuffer: C,
  3590. WebGLProgram: C,
  3591. WebGLQuery: C,
  3592. WebGLRenderbuffer: C,
  3593. WebGLRenderingContext: C,
  3594. WebGLSampler: C,
  3595. WebGLShader: C,
  3596. WebGLShaderPrecisionFormat: C,
  3597. WebGLSync: C,
  3598. WebGLTexture: C,
  3599. WebGLTransformFeedback: C,
  3600. WebGLUniformLocation: C,
  3601. WebGLVertexArrayObject: C,
  3602. WebSocket: C,
  3603. WheelEvent: C,
  3604. Window: C,
  3605. Worker: C,
  3606. WritableStream: C,
  3607. XMLDocument: C,
  3608. XMLHttpRequest: C,
  3609. XMLHttpRequestEventTarget: C,
  3610. XMLHttpRequestUpload: C,
  3611. XMLSerializer: C,
  3612. XPathEvaluator: C,
  3613. XPathExpression: C,
  3614. XPathResult: C,
  3615. XSLTProcessor: C
  3616. };
  3617. for (const global of ['window', 'global', 'self', 'globalThis']) {
  3618. knownGlobals[global] = knownGlobals;
  3619. }
  3620. function getGlobalAtPath(path) {
  3621. let currentGlobal = knownGlobals;
  3622. for (const pathSegment of path) {
  3623. if (typeof pathSegment !== 'string') {
  3624. return null;
  3625. }
  3626. currentGlobal = currentGlobal[pathSegment];
  3627. if (!currentGlobal) {
  3628. return null;
  3629. }
  3630. }
  3631. return currentGlobal[ValueProperties];
  3632. }
  3633. function isPureGlobal(path) {
  3634. const globalAtPath = getGlobalAtPath(path);
  3635. return globalAtPath !== null && globalAtPath.pure;
  3636. }
  3637. function isGlobalMember(path) {
  3638. if (path.length === 1) {
  3639. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  3640. }
  3641. return getGlobalAtPath(path.slice(0, -1)) !== null;
  3642. }
  3643. class GlobalVariable extends Variable {
  3644. constructor() {
  3645. super(...arguments);
  3646. this.isReassigned = true;
  3647. }
  3648. hasEffectsWhenAccessedAtPath(path) {
  3649. return !isGlobalMember([this.name, ...path]);
  3650. }
  3651. hasEffectsWhenCalledAtPath(path) {
  3652. return !isPureGlobal([this.name, ...path]);
  3653. }
  3654. }
  3655. class Identifier extends NodeBase {
  3656. constructor() {
  3657. super(...arguments);
  3658. this.variable = null;
  3659. this.bound = false;
  3660. }
  3661. addExportedVariables(variables, exportNamesByVariable) {
  3662. if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
  3663. variables.push(this.variable);
  3664. }
  3665. }
  3666. bind() {
  3667. if (this.bound)
  3668. return;
  3669. this.bound = true;
  3670. if (this.variable === null && is_reference(this, this.parent)) {
  3671. this.variable = this.scope.findVariable(this.name);
  3672. this.variable.addReference(this);
  3673. }
  3674. if (this.variable !== null &&
  3675. this.variable instanceof LocalVariable &&
  3676. this.variable.additionalInitializers !== null) {
  3677. this.variable.consolidateInitializers();
  3678. }
  3679. }
  3680. declare(kind, init) {
  3681. let variable;
  3682. switch (kind) {
  3683. case 'var':
  3684. variable = this.scope.addDeclaration(this, this.context, init, true);
  3685. break;
  3686. case 'function':
  3687. // in strict mode, functions are only hoisted within a scope but not across block scopes
  3688. variable = this.scope.addDeclaration(this, this.context, init, false);
  3689. break;
  3690. case 'let':
  3691. case 'const':
  3692. case 'class':
  3693. variable = this.scope.addDeclaration(this, this.context, init, false);
  3694. break;
  3695. case 'parameter':
  3696. variable = this.scope.addParameterDeclaration(this);
  3697. break;
  3698. /* istanbul ignore next */
  3699. default:
  3700. /* istanbul ignore next */
  3701. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  3702. }
  3703. return [(this.variable = variable)];
  3704. }
  3705. deoptimizePath(path) {
  3706. if (!this.bound)
  3707. this.bind();
  3708. if (path.length === 0 && !this.scope.contains(this.name)) {
  3709. this.disallowImportReassignment();
  3710. }
  3711. this.variable.deoptimizePath(path);
  3712. }
  3713. getLiteralValueAtPath(path, recursionTracker, origin) {
  3714. if (!this.bound)
  3715. this.bind();
  3716. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  3717. }
  3718. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  3719. if (!this.bound)
  3720. this.bind();
  3721. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  3722. }
  3723. hasEffects() {
  3724. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  3725. this.variable instanceof GlobalVariable &&
  3726. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  3727. }
  3728. hasEffectsWhenAccessedAtPath(path, context) {
  3729. return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  3730. }
  3731. hasEffectsWhenAssignedAtPath(path, context) {
  3732. return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
  3733. }
  3734. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3735. return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  3736. }
  3737. include() {
  3738. if (!this.included) {
  3739. this.included = true;
  3740. if (this.variable !== null) {
  3741. this.context.includeVariableInModule(this.variable);
  3742. }
  3743. }
  3744. }
  3745. includeCallArguments(context, args) {
  3746. this.variable.includeCallArguments(context, args);
  3747. }
  3748. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  3749. if (this.variable) {
  3750. const name = this.variable.getName();
  3751. if (name !== this.name) {
  3752. code.overwrite(this.start, this.end, name, {
  3753. contentOnly: true,
  3754. storeName: true
  3755. });
  3756. if (isShorthandProperty) {
  3757. code.prependRight(this.start, `${this.name}: `);
  3758. }
  3759. }
  3760. // In strict mode, any variable named "eval" must be the actual "eval" function
  3761. if (name === 'eval' &&
  3762. renderedParentType === CallExpression$1 &&
  3763. isCalleeOfRenderedParent) {
  3764. code.appendRight(this.start, '0, ');
  3765. }
  3766. }
  3767. }
  3768. disallowImportReassignment() {
  3769. return this.context.error({
  3770. code: 'ILLEGAL_REASSIGNMENT',
  3771. message: `Illegal reassignment to import '${this.name}'`
  3772. }, this.start);
  3773. }
  3774. }
  3775. class RestElement extends NodeBase {
  3776. constructor() {
  3777. super(...arguments);
  3778. this.declarationInit = null;
  3779. }
  3780. addExportedVariables(variables, exportNamesByVariable) {
  3781. this.argument.addExportedVariables(variables, exportNamesByVariable);
  3782. }
  3783. bind() {
  3784. super.bind();
  3785. if (this.declarationInit !== null) {
  3786. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  3787. }
  3788. }
  3789. declare(kind, init) {
  3790. this.declarationInit = init;
  3791. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  3792. }
  3793. deoptimizePath(path) {
  3794. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  3795. }
  3796. hasEffectsWhenAssignedAtPath(path, context) {
  3797. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  3798. }
  3799. }
  3800. class FunctionNode extends NodeBase {
  3801. constructor() {
  3802. super(...arguments);
  3803. this.isPrototypeDeoptimized = false;
  3804. }
  3805. createScope(parentScope) {
  3806. this.scope = new FunctionScope(parentScope, this.context);
  3807. }
  3808. deoptimizePath(path) {
  3809. if (path.length === 1) {
  3810. if (path[0] === 'prototype') {
  3811. this.isPrototypeDeoptimized = true;
  3812. }
  3813. else if (path[0] === UnknownKey) {
  3814. this.isPrototypeDeoptimized = true;
  3815. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  3816. // which means the return expression needs to be reassigned as well
  3817. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  3818. }
  3819. }
  3820. }
  3821. getReturnExpressionWhenCalledAtPath(path) {
  3822. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  3823. }
  3824. hasEffects() {
  3825. return this.id !== null && this.id.hasEffects();
  3826. }
  3827. hasEffectsWhenAccessedAtPath(path) {
  3828. if (path.length <= 1)
  3829. return false;
  3830. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3831. }
  3832. hasEffectsWhenAssignedAtPath(path) {
  3833. if (path.length <= 1) {
  3834. return false;
  3835. }
  3836. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  3837. }
  3838. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3839. if (path.length > 0)
  3840. return true;
  3841. for (const param of this.params) {
  3842. if (param.hasEffects(context))
  3843. return true;
  3844. }
  3845. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  3846. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
  3847. const { brokenFlow, ignore } = context;
  3848. context.ignore = {
  3849. breaks: false,
  3850. continues: false,
  3851. labels: new Set(),
  3852. returnAwaitYield: true
  3853. };
  3854. if (this.body.hasEffects(context))
  3855. return true;
  3856. context.brokenFlow = brokenFlow;
  3857. if (thisInit) {
  3858. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  3859. }
  3860. else {
  3861. context.replacedVariableInits.delete(this.scope.thisVariable);
  3862. }
  3863. context.ignore = ignore;
  3864. return false;
  3865. }
  3866. include(context, includeChildrenRecursively) {
  3867. this.included = true;
  3868. if (this.id)
  3869. this.id.include();
  3870. const hasArguments = this.scope.argumentsVariable.included;
  3871. for (const param of this.params) {
  3872. if (!(param instanceof Identifier) || hasArguments) {
  3873. param.include(context, includeChildrenRecursively);
  3874. }
  3875. }
  3876. const { brokenFlow } = context;
  3877. context.brokenFlow = BROKEN_FLOW_NONE;
  3878. this.body.include(context, includeChildrenRecursively);
  3879. context.brokenFlow = brokenFlow;
  3880. }
  3881. includeCallArguments(context, args) {
  3882. this.scope.includeCallArguments(context, args);
  3883. }
  3884. initialise() {
  3885. if (this.id !== null) {
  3886. this.id.declare('function', this);
  3887. }
  3888. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  3889. this.body.addImplicitReturnExpressionToScope();
  3890. }
  3891. parseNode(esTreeNode) {
  3892. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  3893. super.parseNode(esTreeNode);
  3894. }
  3895. }
  3896. FunctionNode.prototype.preventChildBlockScope = true;
  3897. class FunctionDeclaration extends FunctionNode {
  3898. initialise() {
  3899. super.initialise();
  3900. if (this.id !== null) {
  3901. this.id.variable.isId = true;
  3902. }
  3903. }
  3904. parseNode(esTreeNode) {
  3905. if (esTreeNode.id !== null) {
  3906. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
  3907. .parent);
  3908. }
  3909. super.parseNode(esTreeNode);
  3910. }
  3911. }
  3912. // The header ends at the first non-white-space after "default"
  3913. function getDeclarationStart(code, start) {
  3914. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  3915. }
  3916. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  3917. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  3918. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  3919. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  3920. if (generatorStarPos === -1) {
  3921. return declarationEnd;
  3922. }
  3923. return declarationEnd + generatorStarPos + 1;
  3924. }
  3925. class ExportDefaultDeclaration extends NodeBase {
  3926. include(context, includeChildrenRecursively) {
  3927. super.include(context, includeChildrenRecursively);
  3928. if (includeChildrenRecursively) {
  3929. this.context.includeVariableInModule(this.variable);
  3930. }
  3931. }
  3932. initialise() {
  3933. const declaration = this.declaration;
  3934. this.declarationName =
  3935. (declaration.id && declaration.id.name) || this.declaration.name;
  3936. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  3937. this.context.addExport(this);
  3938. }
  3939. render(code, options, nodeRenderOptions) {
  3940. const { start, end } = nodeRenderOptions;
  3941. const declarationStart = getDeclarationStart(code.original, this.start);
  3942. if (this.declaration instanceof FunctionDeclaration) {
  3943. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  3944. }
  3945. else if (this.declaration instanceof ClassDeclaration) {
  3946. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  3947. }
  3948. else if (this.variable.getOriginalVariable() !== this.variable) {
  3949. // Remove altogether to prevent re-declaring the same variable
  3950. treeshakeNode(this, code, start, end);
  3951. return;
  3952. }
  3953. else if (this.variable.included) {
  3954. this.renderVariableDeclaration(code, declarationStart, options);
  3955. }
  3956. else {
  3957. code.remove(this.start, declarationStart);
  3958. this.declaration.render(code, options, {
  3959. isCalleeOfRenderedParent: false,
  3960. renderedParentType: ExpressionStatement$1
  3961. });
  3962. if (code.original[this.end - 1] !== ';') {
  3963. code.appendLeft(this.end, ';');
  3964. }
  3965. return;
  3966. }
  3967. this.declaration.render(code, options);
  3968. }
  3969. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  3970. const name = this.variable.getName();
  3971. // Remove `export default`
  3972. code.remove(this.start, declarationStart);
  3973. if (needsId) {
  3974. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  3975. }
  3976. if (options.format === 'system' &&
  3977. this.declaration instanceof ClassDeclaration &&
  3978. options.exportNamesByVariable.has(this.variable)) {
  3979. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  3980. }
  3981. }
  3982. renderVariableDeclaration(code, declarationStart, options) {
  3983. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  3984. const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
  3985. if (systemExportNames) {
  3986. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
  3987. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  3988. }
  3989. else {
  3990. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
  3991. if (!hasTrailingSemicolon) {
  3992. code.appendLeft(this.end, ';');
  3993. }
  3994. }
  3995. }
  3996. }
  3997. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  3998. class UndefinedVariable extends Variable {
  3999. constructor() {
  4000. super('undefined');
  4001. }
  4002. getLiteralValueAtPath() {
  4003. return undefined;
  4004. }
  4005. }
  4006. class ExportDefaultVariable extends LocalVariable {
  4007. constructor(name, exportDefaultDeclaration, context) {
  4008. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  4009. this.hasId = false;
  4010. this.originalId = null;
  4011. this.originalVariable = null;
  4012. const declaration = exportDefaultDeclaration.declaration;
  4013. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  4014. declaration.id) {
  4015. this.hasId = true;
  4016. this.originalId = declaration.id;
  4017. }
  4018. else if (declaration instanceof Identifier) {
  4019. this.originalId = declaration;
  4020. }
  4021. }
  4022. addReference(identifier) {
  4023. if (!this.hasId) {
  4024. this.name = identifier.name;
  4025. }
  4026. }
  4027. getAssignedVariableName() {
  4028. return (this.originalId && this.originalId.name) || null;
  4029. }
  4030. getBaseVariableName() {
  4031. const original = this.getOriginalVariable();
  4032. if (original === this) {
  4033. return super.getBaseVariableName();
  4034. }
  4035. else {
  4036. return original.getBaseVariableName();
  4037. }
  4038. }
  4039. getDirectOriginalVariable() {
  4040. return this.originalId &&
  4041. (this.hasId ||
  4042. !(this.originalId.variable.isReassigned ||
  4043. this.originalId.variable instanceof UndefinedVariable ||
  4044. // this avoids a circular dependency
  4045. 'syntheticNamespace' in this.originalId.variable))
  4046. ? this.originalId.variable
  4047. : null;
  4048. }
  4049. getName() {
  4050. const original = this.getOriginalVariable();
  4051. if (original === this) {
  4052. return super.getName();
  4053. }
  4054. else {
  4055. return original.getName();
  4056. }
  4057. }
  4058. getOriginalVariable() {
  4059. if (this.originalVariable)
  4060. return this.originalVariable;
  4061. let original = this;
  4062. let currentVariable;
  4063. const checkedVariables = new Set();
  4064. do {
  4065. checkedVariables.add(original);
  4066. currentVariable = original;
  4067. original = currentVariable.getDirectOriginalVariable();
  4068. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  4069. return (this.originalVariable = original || currentVariable);
  4070. }
  4071. }
  4072. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  4073. class ExportShimVariable extends Variable {
  4074. constructor(module) {
  4075. super(MISSING_EXPORT_SHIM_VARIABLE);
  4076. this.module = module;
  4077. }
  4078. }
  4079. class NamespaceVariable extends Variable {
  4080. constructor(context, syntheticNamedExports) {
  4081. super(context.getModuleName());
  4082. this.memberVariables = null;
  4083. this.mergedNamespaces = [];
  4084. this.referencedEarly = false;
  4085. this.references = [];
  4086. this.context = context;
  4087. this.module = context.module;
  4088. this.syntheticNamedExports = syntheticNamedExports;
  4089. }
  4090. addReference(identifier) {
  4091. this.references.push(identifier);
  4092. this.name = identifier.name;
  4093. }
  4094. // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
  4095. // build fails due to an illegal namespace reassignment or MemberExpression already forwards
  4096. // the reassignment to the right variable. This means we lost track of this variable and thus
  4097. // need to reassign all exports.
  4098. deoptimizePath() {
  4099. const memberVariables = this.getMemberVariables();
  4100. for (const key of Object.keys(memberVariables)) {
  4101. memberVariables[key].deoptimizePath(UNKNOWN_PATH);
  4102. }
  4103. }
  4104. getMemberVariables() {
  4105. if (this.memberVariables) {
  4106. return this.memberVariables;
  4107. }
  4108. const memberVariables = Object.create(null);
  4109. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  4110. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  4111. memberVariables[name] = this.context.traceExport(name);
  4112. }
  4113. }
  4114. return (this.memberVariables = memberVariables);
  4115. }
  4116. include() {
  4117. this.included = true;
  4118. this.context.includeAllExports();
  4119. }
  4120. prepareNamespace(mergedNamespaces) {
  4121. this.mergedNamespaces = mergedNamespaces;
  4122. const moduleExecIndex = this.context.getModuleExecIndex();
  4123. for (const identifier of this.references) {
  4124. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  4125. this.referencedEarly = true;
  4126. break;
  4127. }
  4128. }
  4129. }
  4130. renderBlock(options) {
  4131. const _ = options.compact ? '' : ' ';
  4132. const n = options.compact ? '' : '\n';
  4133. const t = options.indent;
  4134. const memberVariables = this.getMemberVariables();
  4135. const members = Object.keys(memberVariables).map(name => {
  4136. const original = memberVariables[name];
  4137. if (this.referencedEarly || original.isReassigned) {
  4138. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  4139. }
  4140. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  4141. return `${t}${safeName}: ${original.getName()}`;
  4142. });
  4143. if (options.namespaceToStringTag) {
  4144. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  4145. }
  4146. const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
  4147. if (!needsObjectAssign)
  4148. members.unshift(`${t}__proto__:${_}null`);
  4149. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  4150. if (needsObjectAssign) {
  4151. const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
  4152. if (this.mergedNamespaces.length > 0) {
  4153. assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
  4154. }
  4155. if (this.syntheticNamedExports) {
  4156. assignmentArgs.push(this.module.getSyntheticNamespace().getName());
  4157. }
  4158. if (members.length > 0) {
  4159. assignmentArgs.push(output);
  4160. }
  4161. output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
  4162. }
  4163. if (options.freeze) {
  4164. output = `/*#__PURE__*/Object.freeze(${output})`;
  4165. }
  4166. const name = this.getName();
  4167. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  4168. if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
  4169. output += `${n}${getSystemExportStatement([this], options)};`;
  4170. }
  4171. return output;
  4172. }
  4173. renderFirst() {
  4174. return this.referencedEarly;
  4175. }
  4176. }
  4177. NamespaceVariable.prototype.isNamespace = true;
  4178. class SyntheticNamedExportVariable extends Variable {
  4179. constructor(context, name, syntheticNamespace) {
  4180. super(name);
  4181. this.baseVariable = null;
  4182. this.context = context;
  4183. this.module = context.module;
  4184. this.syntheticNamespace = syntheticNamespace;
  4185. }
  4186. getBaseVariable() {
  4187. if (this.baseVariable)
  4188. return this.baseVariable;
  4189. let baseVariable = this.syntheticNamespace;
  4190. while (baseVariable instanceof ExportDefaultVariable ||
  4191. baseVariable instanceof SyntheticNamedExportVariable) {
  4192. if (baseVariable instanceof ExportDefaultVariable) {
  4193. const original = baseVariable.getOriginalVariable();
  4194. if (original === baseVariable)
  4195. break;
  4196. baseVariable = original;
  4197. }
  4198. if (baseVariable instanceof SyntheticNamedExportVariable) {
  4199. baseVariable = baseVariable.syntheticNamespace;
  4200. }
  4201. }
  4202. return (this.baseVariable = baseVariable);
  4203. }
  4204. getBaseVariableName() {
  4205. return this.syntheticNamespace.getBaseVariableName();
  4206. }
  4207. getName() {
  4208. const name = this.name;
  4209. return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
  4210. }
  4211. include() {
  4212. if (!this.included) {
  4213. this.included = true;
  4214. this.context.includeVariableInModule(this.syntheticNamespace);
  4215. }
  4216. }
  4217. setRenderNames(baseName, name) {
  4218. super.setRenderNames(baseName, name);
  4219. }
  4220. }
  4221. const getPropertyAccess = (name) => {
  4222. return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
  4223. ? `.${name}`
  4224. : `[${JSON.stringify(name)}]`;
  4225. };
  4226. class ExternalVariable extends Variable {
  4227. constructor(module, name) {
  4228. super(name);
  4229. this.module = module;
  4230. this.isNamespace = name === '*';
  4231. this.referenced = false;
  4232. }
  4233. addReference(identifier) {
  4234. this.referenced = true;
  4235. if (this.name === 'default' || this.name === '*') {
  4236. this.module.suggestName(identifier.name);
  4237. }
  4238. }
  4239. include() {
  4240. if (!this.included) {
  4241. this.included = true;
  4242. this.module.used = true;
  4243. }
  4244. }
  4245. }
  4246. 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'.split(' ');
  4247. const builtins$1 = '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'.split(' ');
  4248. const blacklisted = new Set(reservedWords$1.concat(builtins$1));
  4249. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  4250. const startsWithDigit = (str) => /\d/.test(str[0]);
  4251. function isLegal(str) {
  4252. if (startsWithDigit(str) || blacklisted.has(str)) {
  4253. return false;
  4254. }
  4255. return !illegalCharacters.test(str);
  4256. }
  4257. function makeLegal(str) {
  4258. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  4259. if (startsWithDigit(str) || blacklisted.has(str))
  4260. str = `_${str}`;
  4261. return str || '_';
  4262. }
  4263. class ExternalModule {
  4264. constructor(options, id, hasModuleSideEffects, meta) {
  4265. this.options = options;
  4266. this.id = id;
  4267. this.defaultVariableName = '';
  4268. this.dynamicImporters = [];
  4269. this.importers = [];
  4270. this.mostCommonSuggestion = 0;
  4271. this.namespaceVariableName = '';
  4272. this.reexported = false;
  4273. this.renderPath = undefined;
  4274. this.renormalizeRenderPath = false;
  4275. this.used = false;
  4276. this.variableName = '';
  4277. this.execIndex = Infinity;
  4278. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  4279. this.nameSuggestions = Object.create(null);
  4280. this.declarations = Object.create(null);
  4281. this.exportedVariables = new Map();
  4282. const module = this;
  4283. this.info = {
  4284. ast: null,
  4285. code: null,
  4286. dynamicallyImportedIds: EMPTY_ARRAY,
  4287. get dynamicImporters() {
  4288. return module.dynamicImporters.sort();
  4289. },
  4290. hasModuleSideEffects,
  4291. id,
  4292. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  4293. implicitlyLoadedBefore: EMPTY_ARRAY,
  4294. importedIds: EMPTY_ARRAY,
  4295. get importers() {
  4296. return module.importers.sort();
  4297. },
  4298. isEntry: false,
  4299. isExternal: true,
  4300. meta,
  4301. syntheticNamedExports: false
  4302. };
  4303. }
  4304. getVariableForExportName(name) {
  4305. let declaration = this.declarations[name];
  4306. if (declaration)
  4307. return declaration;
  4308. this.declarations[name] = declaration = new ExternalVariable(this, name);
  4309. this.exportedVariables.set(declaration, name);
  4310. return declaration;
  4311. }
  4312. setRenderPath(options, inputBase) {
  4313. this.renderPath =
  4314. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  4315. if (!this.renderPath) {
  4316. if (!isAbsolute(this.id)) {
  4317. this.renderPath = this.id;
  4318. }
  4319. else {
  4320. this.renderPath = normalize(path.relative(inputBase, this.id));
  4321. this.renormalizeRenderPath = true;
  4322. }
  4323. }
  4324. return this.renderPath;
  4325. }
  4326. suggestName(name) {
  4327. if (!this.nameSuggestions[name])
  4328. this.nameSuggestions[name] = 0;
  4329. this.nameSuggestions[name] += 1;
  4330. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  4331. this.mostCommonSuggestion = this.nameSuggestions[name];
  4332. this.suggestedVariableName = name;
  4333. }
  4334. }
  4335. warnUnusedImports() {
  4336. const unused = Object.keys(this.declarations).filter(name => {
  4337. if (name === '*')
  4338. return false;
  4339. const declaration = this.declarations[name];
  4340. return !declaration.included && !this.reexported && !declaration.referenced;
  4341. });
  4342. if (unused.length === 0)
  4343. return;
  4344. const names = unused.length === 1
  4345. ? `'${unused[0]}' is`
  4346. : `${unused
  4347. .slice(0, -1)
  4348. .map(name => `'${name}'`)
  4349. .join(', ')} and '${unused.slice(-1)}' are`;
  4350. this.options.onwarn({
  4351. code: 'UNUSED_EXTERNAL_IMPORT',
  4352. message: `${names} imported from external module '${this.id}' but never used`,
  4353. names: unused,
  4354. source: this.id
  4355. });
  4356. }
  4357. }
  4358. function removeJsExtension(name) {
  4359. return name.endsWith('.js') ? name.slice(0, -3) : name;
  4360. }
  4361. function getCompleteAmdId(options, chunkId) {
  4362. if (!options.autoId) {
  4363. return options.id || '';
  4364. }
  4365. else {
  4366. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  4367. }
  4368. }
  4369. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  4370. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  4371. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  4372. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  4373. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  4374. const defaultInteropHelpersByInteropType = {
  4375. auto: INTEROP_DEFAULT_VARIABLE,
  4376. default: null,
  4377. defaultOnly: null,
  4378. esModule: null,
  4379. false: null,
  4380. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  4381. };
  4382. function isDefaultAProperty(interopType, externalLiveBindings) {
  4383. return (interopType === 'esModule' ||
  4384. (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
  4385. }
  4386. const namespaceInteropHelpersByInteropType = {
  4387. auto: INTEROP_NAMESPACE_VARIABLE,
  4388. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  4389. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  4390. esModule: null,
  4391. false: null,
  4392. true: INTEROP_NAMESPACE_VARIABLE
  4393. };
  4394. function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
  4395. return (isDefaultAProperty(interopType, externalLiveBindings) &&
  4396. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
  4397. }
  4398. function getDefaultOnlyHelper() {
  4399. return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
  4400. }
  4401. function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
  4402. return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
  4403. ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  4404. : '').join('');
  4405. }
  4406. const HELPER_GENERATORS = {
  4407. [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
  4408. `e${_}&&${_}e.__esModule${_}?${_}` +
  4409. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4410. [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
  4411. `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  4412. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  4413. [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  4414. (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
  4415. ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
  4416. : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  4417. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
  4418. `}${n}${n}`,
  4419. [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  4420. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
  4421. `}${n}${n}`,
  4422. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
  4423. `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
  4424. `}${n}${n}`
  4425. };
  4426. function getDefaultLiveBinding(_) {
  4427. return `e${_}:${_}{${_}'default':${_}e${_}}`;
  4428. }
  4429. function getDefaultStatic(_) {
  4430. return `e['default']${_}:${_}e`;
  4431. }
  4432. function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
  4433. return (`${i}var n${_}=${_}${namespaceToStringTag
  4434. ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
  4435. : 'Object.create(null)'};${n}` +
  4436. `${i}if${_}(e)${_}{${n}` +
  4437. `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  4438. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
  4439. `${i}${t}});${n}` +
  4440. `${i}}${n}` +
  4441. `${i}n['default']${_}=${_}e;${n}` +
  4442. `${i}return ${getFrozen('n', freeze)};${n}`);
  4443. }
  4444. function copyPropertyLiveBinding(_, n, t, i) {
  4445. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  4446. `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  4447. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  4448. `${i}${t}${t}enumerable:${_}true,${n}` +
  4449. `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
  4450. `${i}${t}${t}${t}return e[k];${n}` +
  4451. `${i}${t}${t}}${n}` +
  4452. `${i}${t}});${n}` +
  4453. `${i}}${n}`);
  4454. }
  4455. function copyPropertyStatic(_, n, _t, i) {
  4456. return `${i}n[k]${_}=${_}e[k];${n}`;
  4457. }
  4458. function getFrozen(fragment, freeze) {
  4459. return freeze ? `Object.freeze(${fragment})` : fragment;
  4460. }
  4461. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  4462. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
  4463. const _ = compact ? '' : ' ';
  4464. const n = compact ? '' : '\n';
  4465. if (!namedExportsMode) {
  4466. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
  4467. }
  4468. let exportBlock = '';
  4469. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4470. if (reexports && namedExportsMode) {
  4471. for (const specifier of reexports) {
  4472. if (specifier.reexported !== '*') {
  4473. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4474. if (exportBlock)
  4475. exportBlock += n;
  4476. exportBlock +=
  4477. specifier.imported !== '*' && specifier.needsLiveBinding
  4478. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  4479. `${t}enumerable:${_}true,${n}` +
  4480. `${t}get:${_}function${_}()${_}{${n}` +
  4481. `${t}${t}return ${importName};${n}${t}}${n}});`
  4482. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  4483. }
  4484. }
  4485. }
  4486. }
  4487. for (const chunkExport of exports) {
  4488. const lhs = `exports.${chunkExport.exported}`;
  4489. const rhs = chunkExport.local;
  4490. if (lhs !== rhs) {
  4491. if (exportBlock)
  4492. exportBlock += n;
  4493. exportBlock += `${lhs}${_}=${_}${rhs};`;
  4494. }
  4495. }
  4496. for (const { name, reexports } of dependencies) {
  4497. if (reexports && namedExportsMode) {
  4498. for (const specifier of reexports) {
  4499. if (specifier.reexported === '*') {
  4500. if (exportBlock)
  4501. exportBlock += n;
  4502. if (specifier.needsLiveBinding) {
  4503. exportBlock +=
  4504. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4505. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  4506. `${t}${t}enumerable:${_}true,${n}` +
  4507. `${t}${t}get:${_}function${_}()${_}{${n}` +
  4508. `${t}${t}${t}return ${name}[k];${n}` +
  4509. `${t}${t}}${n}${t}});${n}});`;
  4510. }
  4511. else {
  4512. exportBlock +=
  4513. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4514. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}exports[k]${_}=${_}${name}[k];${n}});`;
  4515. }
  4516. }
  4517. }
  4518. }
  4519. }
  4520. if (exportBlock) {
  4521. return `${n}${n}${exportBlock}`;
  4522. }
  4523. return '';
  4524. }
  4525. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
  4526. if (exports.length > 0) {
  4527. return exports[0].local;
  4528. }
  4529. else {
  4530. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4531. if (reexports) {
  4532. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  4533. }
  4534. }
  4535. }
  4536. }
  4537. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
  4538. if (imported === 'default') {
  4539. if (!isChunk) {
  4540. const moduleInterop = String(interop(moduleId));
  4541. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  4542. ? defaultVariableName
  4543. : moduleVariableName;
  4544. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  4545. ? `${variableName}['default']`
  4546. : variableName;
  4547. }
  4548. return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
  4549. }
  4550. if (imported === '*') {
  4551. return (isChunk
  4552. ? !depNamedExportsMode
  4553. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  4554. ? namespaceVariableName
  4555. : moduleVariableName;
  4556. }
  4557. return `${moduleVariableName}.${imported}`;
  4558. }
  4559. function getEsModuleExport(_) {
  4560. return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
  4561. }
  4562. function getNamespaceToStringExport(_) {
  4563. return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
  4564. }
  4565. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
  4566. let namespaceMarkers = '';
  4567. if (hasNamedExports) {
  4568. if (addEsModule) {
  4569. namespaceMarkers += getEsModuleExport(_);
  4570. }
  4571. if (addNamespaceToStringTag) {
  4572. if (namespaceMarkers) {
  4573. namespaceMarkers += n;
  4574. }
  4575. namespaceMarkers += getNamespaceToStringExport(_);
  4576. }
  4577. }
  4578. return namespaceMarkers;
  4579. }
  4580. function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
  4581. const neededInteropHelpers = new Set();
  4582. const interopStatements = [];
  4583. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  4584. neededInteropHelpers.add(helper);
  4585. interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  4586. };
  4587. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  4588. if (isChunk) {
  4589. for (const { imported, reexported } of [
  4590. ...(imports || []),
  4591. ...(reexports || [])
  4592. ]) {
  4593. if (imported === '*' && reexported !== '*') {
  4594. if (!namedExportsMode) {
  4595. addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
  4596. }
  4597. break;
  4598. }
  4599. }
  4600. }
  4601. else {
  4602. const moduleInterop = String(interop(id));
  4603. let hasDefault = false;
  4604. let hasNamespace = false;
  4605. for (const { imported, reexported } of [
  4606. ...(imports || []),
  4607. ...(reexports || [])
  4608. ]) {
  4609. let helper;
  4610. let variableName;
  4611. if (imported === 'default') {
  4612. if (!hasDefault) {
  4613. hasDefault = true;
  4614. if (defaultVariableName !== namespaceVariableName) {
  4615. variableName = defaultVariableName;
  4616. helper = defaultInteropHelpersByInteropType[moduleInterop];
  4617. }
  4618. }
  4619. }
  4620. else if (imported === '*' && reexported !== '*') {
  4621. if (!hasNamespace) {
  4622. hasNamespace = true;
  4623. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  4624. variableName = namespaceVariableName;
  4625. }
  4626. }
  4627. if (helper) {
  4628. addInteropStatement(variableName, helper, name);
  4629. }
  4630. }
  4631. }
  4632. }
  4633. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  4634. }
  4635. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  4636. // The assumption is that this makes sense for all relative ids:
  4637. // https://requirejs.org/docs/api.html#jsfiles
  4638. function removeExtensionFromRelativeAmdId(id) {
  4639. return id[0] === '.' ? removeJsExtension(id) : id;
  4640. }
  4641. const builtins = {
  4642. assert: true,
  4643. buffer: true,
  4644. console: true,
  4645. constants: true,
  4646. domain: true,
  4647. events: true,
  4648. http: true,
  4649. https: true,
  4650. os: true,
  4651. path: true,
  4652. process: true,
  4653. punycode: true,
  4654. querystring: true,
  4655. stream: true,
  4656. string_decoder: true,
  4657. timers: true,
  4658. tty: true,
  4659. url: true,
  4660. util: true,
  4661. vm: true,
  4662. zlib: true
  4663. };
  4664. function warnOnBuiltins(warn, dependencies) {
  4665. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  4666. if (!externalBuiltins.length)
  4667. return;
  4668. const detail = externalBuiltins.length === 1
  4669. ? `module ('${externalBuiltins[0]}')`
  4670. : `modules (${externalBuiltins
  4671. .slice(0, -1)
  4672. .map(name => `'${name}'`)
  4673. .join(', ')} and '${externalBuiltins.slice(-1)}')`;
  4674. warn({
  4675. code: 'MISSING_NODE_BUILTINS',
  4676. message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills`,
  4677. modules: externalBuiltins
  4678. });
  4679. }
  4680. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4681. warnOnBuiltins(warn, dependencies);
  4682. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  4683. const args = dependencies.map(m => m.name);
  4684. const n = compact ? '' : '\n';
  4685. const s = compact ? '' : ';';
  4686. const _ = compact ? '' : ' ';
  4687. if (namedExportsMode && hasExports) {
  4688. args.unshift(`exports`);
  4689. deps.unshift(`'exports'`);
  4690. }
  4691. if (accessedGlobals.has('require')) {
  4692. args.unshift('require');
  4693. deps.unshift(`'require'`);
  4694. }
  4695. if (accessedGlobals.has('module')) {
  4696. args.unshift('module');
  4697. deps.unshift(`'module'`);
  4698. }
  4699. const completeAmdId = getCompleteAmdId(amd, id);
  4700. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  4701. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  4702. const useStrict = strict ? `${_}'use strict';` : '';
  4703. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  4704. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  4705. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4706. if (namespaceMarkers) {
  4707. namespaceMarkers = n + n + namespaceMarkers;
  4708. }
  4709. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  4710. return magicString
  4711. .indent(t)
  4712. .prepend(`${amd.define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
  4713. .append(`${n}${n}});`);
  4714. }
  4715. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  4716. const n = compact ? '' : '\n';
  4717. const s = compact ? '' : ';';
  4718. const _ = compact ? '' : ' ';
  4719. const useStrict = strict ? `'use strict';${n}${n}` : '';
  4720. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  4721. if (namespaceMarkers) {
  4722. namespaceMarkers += n + n;
  4723. }
  4724. const importBlock = getImportBlock$1(dependencies, compact, varOrConst, n, _);
  4725. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  4726. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  4727. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
  4728. return magicString.append(`${exportBlock}${outro}`);
  4729. }
  4730. function getImportBlock$1(dependencies, compact, varOrConst, n, _) {
  4731. let importBlock = '';
  4732. let definingVariable = false;
  4733. for (const { id, name, reexports, imports } of dependencies) {
  4734. if (!reexports && !imports) {
  4735. if (importBlock) {
  4736. importBlock += !compact || definingVariable ? `;${n}` : ',';
  4737. }
  4738. definingVariable = false;
  4739. importBlock += `require('${id}')`;
  4740. }
  4741. else {
  4742. importBlock +=
  4743. compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  4744. definingVariable = true;
  4745. importBlock += `${name}${_}=${_}require('${id}')`;
  4746. }
  4747. }
  4748. if (importBlock) {
  4749. return `${importBlock};${n}${n}`;
  4750. }
  4751. return '';
  4752. }
  4753. function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
  4754. const _ = compact ? '' : ' ';
  4755. const n = compact ? '' : '\n';
  4756. const importBlock = getImportBlock(dependencies, _);
  4757. if (importBlock.length > 0)
  4758. intro += importBlock.join(n) + n + n;
  4759. if (intro)
  4760. magicString.prepend(intro);
  4761. const exportBlock = getExportBlock(exports, _, varOrConst);
  4762. if (exportBlock.length)
  4763. magicString.append(n + n + exportBlock.join(n).trim());
  4764. if (outro)
  4765. magicString.append(outro);
  4766. return magicString.trim();
  4767. }
  4768. function getImportBlock(dependencies, _) {
  4769. const importBlock = [];
  4770. for (const { id, reexports, imports, name } of dependencies) {
  4771. if (!reexports && !imports) {
  4772. importBlock.push(`import${_}'${id}';`);
  4773. continue;
  4774. }
  4775. if (imports) {
  4776. let defaultImport = null;
  4777. let starImport = null;
  4778. const importedNames = [];
  4779. for (const specifier of imports) {
  4780. if (specifier.imported === 'default') {
  4781. defaultImport = specifier;
  4782. }
  4783. else if (specifier.imported === '*') {
  4784. starImport = specifier;
  4785. }
  4786. else {
  4787. importedNames.push(specifier);
  4788. }
  4789. }
  4790. if (starImport) {
  4791. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  4792. }
  4793. if (defaultImport && importedNames.length === 0) {
  4794. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  4795. }
  4796. else if (importedNames.length > 0) {
  4797. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  4798. .map(specifier => {
  4799. if (specifier.imported === specifier.local) {
  4800. return specifier.imported;
  4801. }
  4802. else {
  4803. return `${specifier.imported} as ${specifier.local}`;
  4804. }
  4805. })
  4806. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4807. }
  4808. }
  4809. if (reexports) {
  4810. let starExport = null;
  4811. const namespaceReexports = [];
  4812. const namedReexports = [];
  4813. for (const specifier of reexports) {
  4814. if (specifier.reexported === '*') {
  4815. starExport = specifier;
  4816. }
  4817. else if (specifier.imported === '*') {
  4818. namespaceReexports.push(specifier);
  4819. }
  4820. else {
  4821. namedReexports.push(specifier);
  4822. }
  4823. }
  4824. if (starExport) {
  4825. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  4826. }
  4827. if (namespaceReexports.length > 0) {
  4828. if (!imports ||
  4829. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  4830. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  4831. }
  4832. for (const specifier of namespaceReexports) {
  4833. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  4834. }
  4835. }
  4836. if (namedReexports.length > 0) {
  4837. importBlock.push(`export${_}{${_}${namedReexports
  4838. .map(specifier => {
  4839. if (specifier.imported === specifier.reexported) {
  4840. return specifier.imported;
  4841. }
  4842. else {
  4843. return `${specifier.imported} as ${specifier.reexported}`;
  4844. }
  4845. })
  4846. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  4847. }
  4848. }
  4849. }
  4850. return importBlock;
  4851. }
  4852. function getExportBlock(exports, _, varOrConst) {
  4853. const exportBlock = [];
  4854. const exportDeclaration = [];
  4855. for (const specifier of exports) {
  4856. if (specifier.exported === 'default') {
  4857. exportBlock.push(`export default ${specifier.local};`);
  4858. }
  4859. else {
  4860. if (specifier.expression) {
  4861. exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
  4862. }
  4863. exportDeclaration.push(specifier.exported === specifier.local
  4864. ? specifier.local
  4865. : `${specifier.local} as ${specifier.exported}`);
  4866. }
  4867. }
  4868. if (exportDeclaration.length) {
  4869. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  4870. }
  4871. return exportBlock;
  4872. }
  4873. function spaces(i) {
  4874. let result = '';
  4875. while (i--)
  4876. result += ' ';
  4877. return result;
  4878. }
  4879. function tabsToSpaces(str) {
  4880. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  4881. }
  4882. function getCodeFrame(source, line, column) {
  4883. let lines = source.split('\n');
  4884. const frameStart = Math.max(0, line - 3);
  4885. let frameEnd = Math.min(line + 2, lines.length);
  4886. lines = lines.slice(frameStart, frameEnd);
  4887. while (!/\S/.test(lines[lines.length - 1])) {
  4888. lines.pop();
  4889. frameEnd -= 1;
  4890. }
  4891. const digits = String(frameEnd).length;
  4892. return lines
  4893. .map((str, i) => {
  4894. const isErrorLine = frameStart + i + 1 === line;
  4895. let lineNum = String(i + frameStart + 1);
  4896. while (lineNum.length < digits)
  4897. lineNum = ` ${lineNum}`;
  4898. if (isErrorLine) {
  4899. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  4900. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  4901. }
  4902. return `${lineNum}: ${tabsToSpaces(str)}`;
  4903. })
  4904. .join('\n');
  4905. }
  4906. function error(base) {
  4907. if (!(base instanceof Error))
  4908. base = Object.assign(new Error(base.message), base);
  4909. throw base;
  4910. }
  4911. function augmentCodeLocation(props, pos, source, id) {
  4912. if (typeof pos === 'object') {
  4913. const { line, column } = pos;
  4914. props.loc = { file: id, line, column };
  4915. }
  4916. else {
  4917. props.pos = pos;
  4918. const { line, column } = locate(source, pos, { offsetLine: 1 });
  4919. props.loc = { file: id, line, column };
  4920. }
  4921. if (props.frame === undefined) {
  4922. const { line, column } = props.loc;
  4923. props.frame = getCodeFrame(source, line, column);
  4924. }
  4925. }
  4926. var Errors;
  4927. (function (Errors) {
  4928. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  4929. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  4930. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  4931. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  4932. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  4933. Errors["BAD_LOADER"] = "BAD_LOADER";
  4934. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  4935. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  4936. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  4937. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  4938. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  4939. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  4940. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  4941. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  4942. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  4943. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  4944. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  4945. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  4946. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  4947. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  4948. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  4949. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  4950. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  4951. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  4952. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  4953. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  4954. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  4955. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  4956. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  4957. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  4958. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  4959. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  4960. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  4961. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  4962. })(Errors || (Errors = {}));
  4963. function errAssetNotFinalisedForFileName(name) {
  4964. return {
  4965. code: Errors.ASSET_NOT_FINALISED,
  4966. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  4967. };
  4968. }
  4969. function errCannotEmitFromOptionsHook() {
  4970. return {
  4971. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  4972. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  4973. };
  4974. }
  4975. function errChunkNotGeneratedForFileName(name) {
  4976. return {
  4977. code: Errors.CHUNK_NOT_GENERATED,
  4978. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  4979. };
  4980. }
  4981. function errChunkInvalid({ fileName, code }, exception) {
  4982. const errorProps = {
  4983. code: Errors.CHUNK_INVALID,
  4984. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  4985. };
  4986. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  4987. return errorProps;
  4988. }
  4989. function errCircularReexport(exportName, importedModule) {
  4990. return {
  4991. code: Errors.CIRCULAR_REEXPORT,
  4992. id: importedModule,
  4993. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  4994. };
  4995. }
  4996. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  4997. return {
  4998. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  4999. exporter,
  5000. importer,
  5001. 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.`,
  5002. reexporter
  5003. };
  5004. }
  5005. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  5006. return {
  5007. code: Errors.ASSET_NOT_FOUND,
  5008. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  5009. };
  5010. }
  5011. function errAssetSourceAlreadySet(name) {
  5012. return {
  5013. code: Errors.ASSET_SOURCE_ALREADY_SET,
  5014. message: `Unable to set the source for asset "${name}", source already set.`
  5015. };
  5016. }
  5017. function errNoAssetSourceSet(assetName) {
  5018. return {
  5019. code: Errors.ASSET_SOURCE_MISSING,
  5020. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  5021. };
  5022. }
  5023. function errBadLoader(id) {
  5024. return {
  5025. code: Errors.BAD_LOADER,
  5026. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  5027. };
  5028. }
  5029. function errDeprecation(deprecation) {
  5030. return {
  5031. code: Errors.DEPRECATED_FEATURE,
  5032. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  5033. };
  5034. }
  5035. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  5036. return {
  5037. code: Errors.FILE_NOT_FOUND,
  5038. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  5039. };
  5040. }
  5041. function errFileNameConflict(fileName) {
  5042. return {
  5043. code: Errors.FILE_NAME_CONFLICT,
  5044. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  5045. };
  5046. }
  5047. function errInputHookInOutputPlugin(pluginName, hookName) {
  5048. return {
  5049. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  5050. 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.`
  5051. };
  5052. }
  5053. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  5054. return {
  5055. code: Errors.INVALID_CHUNK,
  5056. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  5057. };
  5058. }
  5059. function errInvalidExportOptionValue(optionValue) {
  5060. return {
  5061. code: Errors.INVALID_EXPORT_OPTION,
  5062. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  5063. url: `https://rollupjs.org/guide/en/#outputexports`
  5064. };
  5065. }
  5066. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  5067. return {
  5068. code: 'INVALID_EXPORT_OPTION',
  5069. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  5070. };
  5071. }
  5072. function errInternalIdCannotBeExternal(source, importer) {
  5073. return {
  5074. code: Errors.INVALID_EXTERNAL_ID,
  5075. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  5076. };
  5077. }
  5078. function errInvalidOption(option, explanation) {
  5079. return {
  5080. code: Errors.INVALID_OPTION,
  5081. message: `Invalid value for option "${option}" - ${explanation}.`
  5082. };
  5083. }
  5084. function errInvalidRollupPhaseForAddWatchFile() {
  5085. return {
  5086. code: Errors.INVALID_ROLLUP_PHASE,
  5087. message: `Cannot call addWatchFile after the build has finished.`
  5088. };
  5089. }
  5090. function errInvalidRollupPhaseForChunkEmission() {
  5091. return {
  5092. code: Errors.INVALID_ROLLUP_PHASE,
  5093. message: `Cannot emit chunks after module loading has finished.`
  5094. };
  5095. }
  5096. function errMissingExport(exportName, importingModule, importedModule) {
  5097. return {
  5098. code: Errors.MISSING_EXPORT,
  5099. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  5100. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  5101. };
  5102. }
  5103. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  5104. return {
  5105. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5106. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  5107. };
  5108. }
  5109. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  5110. return {
  5111. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5112. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  5113. };
  5114. }
  5115. function errImplicitDependantIsNotIncluded(module) {
  5116. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  5117. return {
  5118. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  5119. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
  5120. ? implicitDependencies[0]
  5121. : `${implicitDependencies.slice(0, -1).join('", "')}" and "${implicitDependencies.slice(-1)[0]}`}" 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.`
  5122. };
  5123. }
  5124. function errMixedExport(facadeModuleId, name) {
  5125. return {
  5126. code: Errors.MIXED_EXPORTS,
  5127. id: facadeModuleId,
  5128. 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`,
  5129. url: `https://rollupjs.org/guide/en/#outputexports`
  5130. };
  5131. }
  5132. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  5133. return {
  5134. code: Errors.NAMESPACE_CONFLICT,
  5135. message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
  5136. name,
  5137. reexporter: reexportingModule.id,
  5138. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  5139. };
  5140. }
  5141. function errNoTransformMapOrAstWithoutCode(pluginName) {
  5142. return {
  5143. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  5144. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  5145. 'a "code". This will be ignored.'
  5146. };
  5147. }
  5148. function errPreferNamedExports(facadeModuleId) {
  5149. const file = relativeId(facadeModuleId);
  5150. return {
  5151. code: Errors.PREFER_NAMED_EXPORTS,
  5152. id: facadeModuleId,
  5153. 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.`,
  5154. url: `https://rollupjs.org/guide/en/#outputexports`
  5155. };
  5156. }
  5157. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  5158. return {
  5159. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  5160. id,
  5161. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  5162. ? `an export named "${syntheticNamedExportsOption}"`
  5163. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  5164. };
  5165. }
  5166. function errUnexpectedNamedImport(id, imported, isReexport) {
  5167. const importType = isReexport ? 'reexport' : 'import';
  5168. return {
  5169. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5170. id,
  5171. 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.`,
  5172. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5173. };
  5174. }
  5175. function errUnexpectedNamespaceReexport(id) {
  5176. return {
  5177. code: Errors.UNEXPECTED_NAMED_IMPORT,
  5178. id,
  5179. 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.`,
  5180. url: 'https://rollupjs.org/guide/en/#outputinterop'
  5181. };
  5182. }
  5183. function errEntryCannotBeExternal(unresolvedId) {
  5184. return {
  5185. code: Errors.UNRESOLVED_ENTRY,
  5186. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  5187. };
  5188. }
  5189. function errUnresolvedEntry(unresolvedId) {
  5190. return {
  5191. code: Errors.UNRESOLVED_ENTRY,
  5192. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  5193. };
  5194. }
  5195. function errUnresolvedImport(source, importer) {
  5196. return {
  5197. code: Errors.UNRESOLVED_IMPORT,
  5198. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  5199. };
  5200. }
  5201. function errUnresolvedImportTreatedAsExternal(source, importer) {
  5202. return {
  5203. code: Errors.UNRESOLVED_IMPORT,
  5204. importer: relativeId(importer),
  5205. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  5206. source,
  5207. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  5208. };
  5209. }
  5210. function errExternalSyntheticExports(source, importer) {
  5211. return {
  5212. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  5213. importer: relativeId(importer),
  5214. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  5215. source
  5216. };
  5217. }
  5218. function errFailedValidation(message) {
  5219. return {
  5220. code: Errors.VALIDATION_ERROR,
  5221. message
  5222. };
  5223. }
  5224. function errAlreadyClosed() {
  5225. return {
  5226. code: Errors.ALREADY_CLOSED,
  5227. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  5228. };
  5229. }
  5230. function warnDeprecation(deprecation, activeDeprecation, options) {
  5231. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  5232. }
  5233. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  5234. if (activeDeprecation || strictDeprecations) {
  5235. const warning = errDeprecation(deprecation);
  5236. if (strictDeprecations) {
  5237. return error(warning);
  5238. }
  5239. warn(warning);
  5240. }
  5241. }
  5242. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  5243. // if the property name isn't trivial
  5244. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  5245. function property(prop) {
  5246. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  5247. }
  5248. function keypath(keypath) {
  5249. return keypath
  5250. .split('.')
  5251. .map(property)
  5252. .join('');
  5253. }
  5254. function setupNamespace(name, root, globals, compact) {
  5255. const _ = compact ? '' : ' ';
  5256. const parts = name.split('.');
  5257. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5258. parts.pop();
  5259. let acc = root;
  5260. return (parts
  5261. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  5262. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  5263. }
  5264. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  5265. const _ = compact ? '' : ' ';
  5266. const parts = deepName.split('.');
  5267. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5268. const last = parts.pop();
  5269. let acc = root;
  5270. let deepAssignment = parts
  5271. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  5272. .concat(`${acc}${property(last)}`)
  5273. .join(`,${_}`)
  5274. .concat(`${_}=${_}${assignment}`);
  5275. if (parts.length > 0) {
  5276. deepAssignment = `(${deepAssignment})`;
  5277. }
  5278. return deepAssignment;
  5279. }
  5280. function trimEmptyImports(dependencies) {
  5281. let i = dependencies.length;
  5282. while (i--) {
  5283. const { imports, reexports } = dependencies[i];
  5284. if (imports || reexports) {
  5285. return dependencies.slice(0, i + 1);
  5286. }
  5287. }
  5288. return [];
  5289. }
  5290. const thisProp = (name) => `this${keypath(name)}`;
  5291. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  5292. const _ = compact ? '' : ' ';
  5293. const s = compact ? '' : ';';
  5294. const n = compact ? '' : '\n';
  5295. const isNamespaced = name && name.indexOf('.') !== -1;
  5296. const useVariableAssignment = !extend && !isNamespaced;
  5297. if (name && useVariableAssignment && !isLegal(name)) {
  5298. return error({
  5299. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  5300. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  5301. });
  5302. }
  5303. warnOnBuiltins(warn, dependencies);
  5304. const external = trimEmptyImports(dependencies);
  5305. const deps = external.map(dep => dep.globalName || 'null');
  5306. const args = external.map(m => m.name);
  5307. if (hasExports && !name) {
  5308. warn({
  5309. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5310. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  5311. });
  5312. }
  5313. if (namedExportsMode && hasExports) {
  5314. if (extend) {
  5315. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  5316. args.unshift('exports');
  5317. }
  5318. else {
  5319. deps.unshift('{}');
  5320. args.unshift('exports');
  5321. }
  5322. }
  5323. const useStrict = strict ? `${t}'use strict';${n}` : '';
  5324. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  5325. magicString.prepend(`${intro}${interopBlock}`);
  5326. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
  5327. if (hasExports) {
  5328. if (name && !(extend && namedExportsMode)) {
  5329. wrapperIntro =
  5330. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  5331. `${_}=${_}${wrapperIntro}`;
  5332. }
  5333. if (isNamespaced) {
  5334. wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
  5335. }
  5336. }
  5337. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  5338. if (hasExports && !extend && namedExportsMode) {
  5339. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  5340. }
  5341. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5342. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5343. if (namespaceMarkers) {
  5344. namespaceMarkers = n + n + namespaceMarkers;
  5345. }
  5346. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5347. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  5348. }
  5349. function getStarExcludes({ dependencies, exports }) {
  5350. const starExcludes = new Set(exports.map(expt => expt.exported));
  5351. if (!starExcludes.has('default'))
  5352. starExcludes.add('default');
  5353. // also include reexport names
  5354. for (const { reexports } of dependencies) {
  5355. if (reexports) {
  5356. for (const reexport of reexports) {
  5357. if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
  5358. starExcludes.add(reexport.reexported);
  5359. }
  5360. }
  5361. }
  5362. return starExcludes;
  5363. }
  5364. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  5365. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
  5366. .map(prop => `${prop}:${_}1`)
  5367. .join(`,${_}`)}${_}};`
  5368. : '';
  5369. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  5370. function getExportsBlock(exports, _, t, n) {
  5371. if (exports.length === 0) {
  5372. return '';
  5373. }
  5374. if (exports.length === 1) {
  5375. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  5376. }
  5377. return (`${t}${t}${t}exports({${n}` +
  5378. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  5379. `${n}${t}${t}${t}});${n}${n}`);
  5380. }
  5381. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5382. .filter(expt => expt.hoisted || expt.uninitialized)
  5383. .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
  5384. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5385. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  5386. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  5387. const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5388. .filter(expt => expt.expression)
  5389. .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  5390. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  5391. const n = options.compact ? '' : '\n';
  5392. const _ = options.compact ? '' : ' ';
  5393. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  5394. const importBindings = [];
  5395. let starExcludes;
  5396. const setters = [];
  5397. for (const { imports, reexports } of dependencies) {
  5398. const setter = [];
  5399. if (imports) {
  5400. for (const specifier of imports) {
  5401. importBindings.push(specifier.local);
  5402. if (specifier.imported === '*') {
  5403. setter.push(`${specifier.local}${_}=${_}module;`);
  5404. }
  5405. else {
  5406. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  5407. }
  5408. }
  5409. }
  5410. if (reexports) {
  5411. let createdSetter = false;
  5412. // bulk-reexport form
  5413. if (reexports.length > 1 ||
  5414. (reexports.length === 1 &&
  5415. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  5416. // star reexports
  5417. for (const specifier of reexports) {
  5418. if (specifier.reexported !== '*')
  5419. continue;
  5420. // need own exports list for deduping in star export case
  5421. if (!starExcludes) {
  5422. starExcludes = getStarExcludes({ dependencies, exports });
  5423. }
  5424. if (!createdSetter) {
  5425. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5426. createdSetter = true;
  5427. }
  5428. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  5429. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  5430. setter.push('}');
  5431. }
  5432. // star import reexport
  5433. for (const specifier of reexports) {
  5434. if (specifier.imported !== '*' || specifier.reexported === '*')
  5435. continue;
  5436. setter.push(`exports('${specifier.reexported}',${_}module);`);
  5437. }
  5438. // reexports
  5439. for (const specifier of reexports) {
  5440. if (specifier.reexported === '*' || specifier.imported === '*')
  5441. continue;
  5442. if (!createdSetter) {
  5443. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5444. createdSetter = true;
  5445. }
  5446. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  5447. }
  5448. if (createdSetter) {
  5449. setter.push('exports(_setter);');
  5450. }
  5451. }
  5452. else {
  5453. // single reexport
  5454. for (const specifier of reexports) {
  5455. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  5456. }
  5457. }
  5458. }
  5459. setters.push(setter.join(`${n}${t}${t}${t}`));
  5460. }
  5461. const registeredName = options.name ? `'${options.name}',${_}` : '';
  5462. const wrapperParams = accessedGlobals.has('module')
  5463. ? `exports,${_}module`
  5464. : hasExports
  5465. ? 'exports'
  5466. : '';
  5467. let wrapperStart = `System.register(${registeredName}[` +
  5468. dependencyIds.join(`,${_}`) +
  5469. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  5470. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  5471. getImportBindingsBlock(importBindings, _, t, n) +
  5472. `${n}${t}return${_}{${setters.length
  5473. ? `${n}${t}${t}setters:${_}[${setters
  5474. .map(s => s
  5475. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  5476. : options.systemNullSetters
  5477. ? `null`
  5478. : `function${_}()${_}{}`)
  5479. .join(`,${_}`)}],`
  5480. : ''}${n}`;
  5481. wrapperStart +=
  5482. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  5483. getHoistedExportsBlock(exports, _, t, n);
  5484. const wrapperEnd = `${n}${n}` +
  5485. getSyntheticExportsBlock(exports, _, t, n) +
  5486. getMissingExportsBlock(exports, _, t, n) +
  5487. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  5488. if (intro)
  5489. magicString.prepend(intro);
  5490. if (outro)
  5491. magicString.append(outro);
  5492. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  5493. }
  5494. function globalProp(name, globalVar) {
  5495. if (!name)
  5496. return 'null';
  5497. return `${globalVar}${keypath(name)}`;
  5498. }
  5499. function safeAccess(name, globalVar, _) {
  5500. const parts = name.split('.');
  5501. let acc = globalVar;
  5502. return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
  5503. }
  5504. function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, id, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  5505. const _ = compact ? '' : ' ';
  5506. const n = compact ? '' : '\n';
  5507. const s = compact ? '' : ';';
  5508. const factoryVar = compact ? 'f' : 'factory';
  5509. const globalVar = compact ? 'g' : 'global';
  5510. if (hasExports && !name) {
  5511. return error({
  5512. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5513. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  5514. });
  5515. }
  5516. warnOnBuiltins(warn, dependencies);
  5517. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  5518. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  5519. const trimmedImports = trimEmptyImports(dependencies);
  5520. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  5521. const factoryArgs = trimmedImports.map(m => m.name);
  5522. if (namedExportsMode && (hasExports || noConflict)) {
  5523. amdDeps.unshift(`'exports'`);
  5524. cjsDeps.unshift(`exports`);
  5525. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
  5526. factoryArgs.unshift('exports');
  5527. }
  5528. const completeAmdId = getCompleteAmdId(amd, id);
  5529. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  5530. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  5531. const define = amd.define;
  5532. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  5533. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  5534. let iifeExport;
  5535. if (noConflict) {
  5536. const noConflictExportsVar = compact ? 'e' : 'exports';
  5537. let factory;
  5538. if (!namedExportsMode && hasExports) {
  5539. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  5540. }
  5541. else {
  5542. const module = globalDeps.shift();
  5543. factory =
  5544. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  5545. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  5546. }
  5547. iifeExport =
  5548. `(function${_}()${_}{${n}` +
  5549. `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
  5550. `${t}${t}${factory}${n}` +
  5551. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  5552. `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
  5553. `${t}}())`;
  5554. }
  5555. else {
  5556. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  5557. if (!namedExportsMode && hasExports) {
  5558. iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
  5559. }
  5560. }
  5561. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  5562. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  5563. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  5564. const iifeStart = iifeNeedsGlobal
  5565. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  5566. : '';
  5567. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  5568. const cjsIntro = iifeNeedsGlobal
  5569. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  5570. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  5571. : '';
  5572. // factory function should be wrapped by parentheses to avoid lazy parsing
  5573. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  5574. cjsIntro +
  5575. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  5576. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  5577. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  5578. const wrapperOutro = n + n + '})));';
  5579. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  5580. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  5581. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  5582. if (namespaceMarkers) {
  5583. namespaceMarkers = n + n + namespaceMarkers;
  5584. }
  5585. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  5586. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  5587. }
  5588. var finalisers = { system, amd, cjs, es, iife, umd };
  5589. const extractors = {
  5590. ArrayPattern(names, param) {
  5591. for (const element of param.elements) {
  5592. if (element)
  5593. extractors[element.type](names, element);
  5594. }
  5595. },
  5596. AssignmentPattern(names, param) {
  5597. extractors[param.left.type](names, param.left);
  5598. },
  5599. Identifier(names, param) {
  5600. names.push(param.name);
  5601. },
  5602. MemberExpression() { },
  5603. ObjectPattern(names, param) {
  5604. for (const prop of param.properties) {
  5605. if (prop.type === 'RestElement') {
  5606. extractors.RestElement(names, prop);
  5607. }
  5608. else {
  5609. extractors[prop.value.type](names, prop.value);
  5610. }
  5611. }
  5612. },
  5613. RestElement(names, param) {
  5614. extractors[param.argument.type](names, param.argument);
  5615. }
  5616. };
  5617. const extractAssignedNames = function extractAssignedNames(param) {
  5618. const names = [];
  5619. extractors[param.type](names, param);
  5620. return names;
  5621. };
  5622. class ExportAllDeclaration extends NodeBase {
  5623. hasEffects() {
  5624. return false;
  5625. }
  5626. initialise() {
  5627. this.context.addExport(this);
  5628. }
  5629. render(code, _options, nodeRenderOptions) {
  5630. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  5631. }
  5632. }
  5633. ExportAllDeclaration.prototype.needsBoundaries = true;
  5634. class ArrayExpression extends NodeBase {
  5635. bind() {
  5636. super.bind();
  5637. for (const element of this.elements) {
  5638. if (element !== null)
  5639. element.deoptimizePath(UNKNOWN_PATH);
  5640. }
  5641. }
  5642. getReturnExpressionWhenCalledAtPath(path) {
  5643. if (path.length !== 1)
  5644. return UNKNOWN_EXPRESSION;
  5645. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  5646. }
  5647. hasEffectsWhenAccessedAtPath(path) {
  5648. return path.length > 1;
  5649. }
  5650. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5651. if (path.length === 1) {
  5652. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  5653. }
  5654. return true;
  5655. }
  5656. }
  5657. class ArrayPattern extends NodeBase {
  5658. addExportedVariables(variables, exportNamesByVariable) {
  5659. for (const element of this.elements) {
  5660. if (element !== null) {
  5661. element.addExportedVariables(variables, exportNamesByVariable);
  5662. }
  5663. }
  5664. }
  5665. declare(kind) {
  5666. const variables = [];
  5667. for (const element of this.elements) {
  5668. if (element !== null) {
  5669. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5670. }
  5671. }
  5672. return variables;
  5673. }
  5674. deoptimizePath(path) {
  5675. if (path.length === 0) {
  5676. for (const element of this.elements) {
  5677. if (element !== null) {
  5678. element.deoptimizePath(path);
  5679. }
  5680. }
  5681. }
  5682. }
  5683. hasEffectsWhenAssignedAtPath(path, context) {
  5684. if (path.length > 0)
  5685. return true;
  5686. for (const element of this.elements) {
  5687. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5688. return true;
  5689. }
  5690. return false;
  5691. }
  5692. }
  5693. class BlockScope extends ChildScope {
  5694. addDeclaration(identifier, context, init, isHoisted) {
  5695. if (isHoisted) {
  5696. return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
  5697. }
  5698. else {
  5699. return super.addDeclaration(identifier, context, init, false);
  5700. }
  5701. }
  5702. }
  5703. class ExpressionStatement extends NodeBase {
  5704. initialise() {
  5705. if (this.directive &&
  5706. this.directive !== 'use strict' &&
  5707. this.parent.type === Program$1) {
  5708. this.context.warn(
  5709. // This is necessary, because either way (deleting or not) can lead to errors.
  5710. {
  5711. code: 'MODULE_LEVEL_DIRECTIVE',
  5712. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  5713. }, this.start);
  5714. }
  5715. }
  5716. render(code, options) {
  5717. super.render(code, options);
  5718. if (this.included)
  5719. this.insertSemicolon(code);
  5720. }
  5721. shouldBeIncluded(context) {
  5722. if (this.directive && this.directive !== 'use strict')
  5723. return this.parent.type !== Program$1;
  5724. return super.shouldBeIncluded(context);
  5725. }
  5726. }
  5727. class BlockStatement extends NodeBase {
  5728. constructor() {
  5729. super(...arguments);
  5730. this.directlyIncluded = false;
  5731. }
  5732. addImplicitReturnExpressionToScope() {
  5733. const lastStatement = this.body[this.body.length - 1];
  5734. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  5735. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  5736. }
  5737. }
  5738. createScope(parentScope) {
  5739. this.scope = this.parent.preventChildBlockScope
  5740. ? parentScope
  5741. : new BlockScope(parentScope);
  5742. }
  5743. hasEffects(context) {
  5744. if (this.deoptimizeBody)
  5745. return true;
  5746. for (const node of this.body) {
  5747. if (node.hasEffects(context))
  5748. return true;
  5749. if (context.brokenFlow)
  5750. break;
  5751. }
  5752. return false;
  5753. }
  5754. include(context, includeChildrenRecursively) {
  5755. if (!this.deoptimizeBody || !this.directlyIncluded) {
  5756. this.included = true;
  5757. this.directlyIncluded = true;
  5758. if (this.deoptimizeBody)
  5759. includeChildrenRecursively = true;
  5760. for (const node of this.body) {
  5761. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5762. node.include(context, includeChildrenRecursively);
  5763. }
  5764. }
  5765. }
  5766. initialise() {
  5767. const firstBodyStatement = this.body[0];
  5768. this.deoptimizeBody =
  5769. firstBodyStatement instanceof ExpressionStatement &&
  5770. firstBodyStatement.directive === 'use asm';
  5771. }
  5772. render(code, options) {
  5773. if (this.body.length) {
  5774. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  5775. }
  5776. else {
  5777. super.render(code, options);
  5778. }
  5779. }
  5780. }
  5781. class ArrowFunctionExpression extends NodeBase {
  5782. createScope(parentScope) {
  5783. this.scope = new ReturnValueScope(parentScope, this.context);
  5784. }
  5785. deoptimizePath(path) {
  5786. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5787. // which means the return expression needs to be reassigned
  5788. if (path.length === 1 && path[0] === UnknownKey) {
  5789. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5790. }
  5791. }
  5792. getReturnExpressionWhenCalledAtPath(path) {
  5793. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  5794. }
  5795. hasEffects() {
  5796. return false;
  5797. }
  5798. hasEffectsWhenAccessedAtPath(path) {
  5799. return path.length > 1;
  5800. }
  5801. hasEffectsWhenAssignedAtPath(path) {
  5802. return path.length > 1;
  5803. }
  5804. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  5805. if (path.length > 0)
  5806. return true;
  5807. for (const param of this.params) {
  5808. if (param.hasEffects(context))
  5809. return true;
  5810. }
  5811. const { ignore, brokenFlow } = context;
  5812. context.ignore = {
  5813. breaks: false,
  5814. continues: false,
  5815. labels: new Set(),
  5816. returnAwaitYield: true
  5817. };
  5818. if (this.body.hasEffects(context))
  5819. return true;
  5820. context.ignore = ignore;
  5821. context.brokenFlow = brokenFlow;
  5822. return false;
  5823. }
  5824. include(context, includeChildrenRecursively) {
  5825. this.included = true;
  5826. for (const param of this.params) {
  5827. if (!(param instanceof Identifier)) {
  5828. param.include(context, includeChildrenRecursively);
  5829. }
  5830. }
  5831. const { brokenFlow } = context;
  5832. context.brokenFlow = BROKEN_FLOW_NONE;
  5833. this.body.include(context, includeChildrenRecursively);
  5834. context.brokenFlow = brokenFlow;
  5835. }
  5836. includeCallArguments(context, args) {
  5837. this.scope.includeCallArguments(context, args);
  5838. }
  5839. initialise() {
  5840. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  5841. if (this.body instanceof BlockStatement) {
  5842. this.body.addImplicitReturnExpressionToScope();
  5843. }
  5844. else {
  5845. this.scope.addReturnExpression(this.body);
  5846. }
  5847. }
  5848. parseNode(esTreeNode) {
  5849. if (esTreeNode.body.type === BlockStatement$1) {
  5850. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5851. }
  5852. super.parseNode(esTreeNode);
  5853. }
  5854. }
  5855. ArrowFunctionExpression.prototype.preventChildBlockScope = true;
  5856. class AssignmentExpression extends NodeBase {
  5857. constructor() {
  5858. super(...arguments);
  5859. this.deoptimized = false;
  5860. }
  5861. hasEffects(context) {
  5862. if (!this.deoptimized)
  5863. this.applyDeoptimizations();
  5864. return (this.right.hasEffects(context) ||
  5865. this.left.hasEffects(context) ||
  5866. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  5867. }
  5868. hasEffectsWhenAccessedAtPath(path, context) {
  5869. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  5870. }
  5871. include(context, includeChildrenRecursively) {
  5872. if (!this.deoptimized)
  5873. this.applyDeoptimizations();
  5874. this.included = true;
  5875. let hasEffectsContext;
  5876. if (includeChildrenRecursively ||
  5877. this.operator !== '=' ||
  5878. this.left.included ||
  5879. ((hasEffectsContext = createHasEffectsContext()),
  5880. this.left.hasEffects(hasEffectsContext) ||
  5881. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, hasEffectsContext))) {
  5882. this.left.include(context, includeChildrenRecursively);
  5883. }
  5884. this.right.include(context, includeChildrenRecursively);
  5885. }
  5886. render(code, options, { preventASI, renderedParentType } = BLANK) {
  5887. if (this.left.included) {
  5888. this.left.render(code, options);
  5889. this.right.render(code, options);
  5890. }
  5891. else {
  5892. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', this.left.end) + 1);
  5893. code.remove(this.start, inclusionStart);
  5894. if (preventASI) {
  5895. removeLineBreaks(code, inclusionStart, this.right.start);
  5896. }
  5897. this.right.render(code, options, {
  5898. renderedParentType: renderedParentType || this.parent.type
  5899. });
  5900. }
  5901. if (options.format === 'system') {
  5902. const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
  5903. if (this.left.type === 'Identifier' && exportNames) {
  5904. const _ = options.compact ? '' : ' ';
  5905. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  5906. const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
  5907. code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
  5908. ? `exports('${exportNames[0]}',${_}`
  5909. : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
  5910. code.appendLeft(this.right.end, ')');
  5911. }
  5912. else {
  5913. const systemPatternExports = [];
  5914. this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  5915. if (systemPatternExports.length > 0) {
  5916. code.prependRight(this.start, `(${getSystemExportFunctionLeft(systemPatternExports, true, options)}`);
  5917. code.appendLeft(this.end, '))');
  5918. }
  5919. }
  5920. }
  5921. }
  5922. applyDeoptimizations() {
  5923. this.deoptimized = true;
  5924. this.left.deoptimizePath(EMPTY_PATH);
  5925. this.right.deoptimizePath(UNKNOWN_PATH);
  5926. }
  5927. }
  5928. class AssignmentPattern extends NodeBase {
  5929. addExportedVariables(variables, exportNamesByVariable) {
  5930. this.left.addExportedVariables(variables, exportNamesByVariable);
  5931. }
  5932. bind() {
  5933. super.bind();
  5934. this.left.deoptimizePath(EMPTY_PATH);
  5935. this.right.deoptimizePath(UNKNOWN_PATH);
  5936. }
  5937. declare(kind, init) {
  5938. return this.left.declare(kind, init);
  5939. }
  5940. deoptimizePath(path) {
  5941. path.length === 0 && this.left.deoptimizePath(path);
  5942. }
  5943. hasEffectsWhenAssignedAtPath(path, context) {
  5944. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  5945. }
  5946. render(code, options, { isShorthandProperty } = BLANK) {
  5947. this.left.render(code, options, { isShorthandProperty });
  5948. this.right.render(code, options);
  5949. }
  5950. }
  5951. class AwaitExpression extends NodeBase {
  5952. hasEffects(context) {
  5953. return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
  5954. }
  5955. include(context, includeChildrenRecursively) {
  5956. if (!this.included) {
  5957. this.included = true;
  5958. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  5959. let parent = this.parent;
  5960. do {
  5961. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  5962. break checkTopLevelAwait;
  5963. } while ((parent = parent.parent));
  5964. this.context.usesTopLevelAwait = true;
  5965. }
  5966. }
  5967. this.argument.include(context, includeChildrenRecursively);
  5968. }
  5969. }
  5970. const binaryOperators = {
  5971. '!=': (left, right) => left != right,
  5972. '!==': (left, right) => left !== right,
  5973. '%': (left, right) => left % right,
  5974. '&': (left, right) => left & right,
  5975. '*': (left, right) => left * right,
  5976. // At the moment, "**" will be transpiled to Math.pow
  5977. '**': (left, right) => left ** right,
  5978. '+': (left, right) => left + right,
  5979. '-': (left, right) => left - right,
  5980. '/': (left, right) => left / right,
  5981. '<': (left, right) => left < right,
  5982. '<<': (left, right) => left << right,
  5983. '<=': (left, right) => left <= right,
  5984. '==': (left, right) => left == right,
  5985. '===': (left, right) => left === right,
  5986. '>': (left, right) => left > right,
  5987. '>=': (left, right) => left >= right,
  5988. '>>': (left, right) => left >> right,
  5989. '>>>': (left, right) => left >>> right,
  5990. '^': (left, right) => left ^ right,
  5991. in: () => UnknownValue,
  5992. instanceof: () => UnknownValue,
  5993. '|': (left, right) => left | right
  5994. };
  5995. class BinaryExpression extends NodeBase {
  5996. deoptimizeCache() { }
  5997. getLiteralValueAtPath(path, recursionTracker, origin) {
  5998. if (path.length > 0)
  5999. return UnknownValue;
  6000. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6001. if (leftValue === UnknownValue)
  6002. return UnknownValue;
  6003. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6004. if (rightValue === UnknownValue)
  6005. return UnknownValue;
  6006. const operatorFn = binaryOperators[this.operator];
  6007. if (!operatorFn)
  6008. return UnknownValue;
  6009. return operatorFn(leftValue, rightValue);
  6010. }
  6011. hasEffects(context) {
  6012. // support some implicit type coercion runtime errors
  6013. if (this.operator === '+' &&
  6014. this.parent instanceof ExpressionStatement &&
  6015. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  6016. return true;
  6017. return super.hasEffects(context);
  6018. }
  6019. hasEffectsWhenAccessedAtPath(path) {
  6020. return path.length > 1;
  6021. }
  6022. }
  6023. class BreakStatement extends NodeBase {
  6024. hasEffects(context) {
  6025. if (this.label) {
  6026. if (!context.ignore.labels.has(this.label.name))
  6027. return true;
  6028. context.includedLabels.add(this.label.name);
  6029. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6030. }
  6031. else {
  6032. if (!context.ignore.breaks)
  6033. return true;
  6034. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6035. }
  6036. return false;
  6037. }
  6038. include(context) {
  6039. this.included = true;
  6040. if (this.label) {
  6041. this.label.include();
  6042. context.includedLabels.add(this.label.name);
  6043. }
  6044. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6045. }
  6046. }
  6047. class Literal extends NodeBase {
  6048. getLiteralValueAtPath(path) {
  6049. if (path.length > 0 ||
  6050. // unknown literals can also be null but do not start with an "n"
  6051. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  6052. typeof this.value === 'bigint' ||
  6053. // to support shims for regular expressions
  6054. this.context.code.charCodeAt(this.start) === 47) {
  6055. return UnknownValue;
  6056. }
  6057. return this.value;
  6058. }
  6059. getReturnExpressionWhenCalledAtPath(path) {
  6060. if (path.length !== 1)
  6061. return UNKNOWN_EXPRESSION;
  6062. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6063. }
  6064. hasEffectsWhenAccessedAtPath(path) {
  6065. if (this.value === null) {
  6066. return path.length > 0;
  6067. }
  6068. return path.length > 1;
  6069. }
  6070. hasEffectsWhenAssignedAtPath(path) {
  6071. return path.length > 0;
  6072. }
  6073. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6074. if (path.length === 1) {
  6075. return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
  6076. }
  6077. return true;
  6078. }
  6079. initialise() {
  6080. this.members = getLiteralMembersForValue(this.value);
  6081. }
  6082. parseNode(esTreeNode) {
  6083. this.value = esTreeNode.value;
  6084. this.regex = esTreeNode.regex;
  6085. super.parseNode(esTreeNode);
  6086. }
  6087. render(code) {
  6088. if (typeof this.value === 'string') {
  6089. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6090. }
  6091. }
  6092. }
  6093. function getResolvablePropertyKey(memberExpression) {
  6094. return memberExpression.computed
  6095. ? getResolvableComputedPropertyKey(memberExpression.property)
  6096. : memberExpression.property.name;
  6097. }
  6098. function getResolvableComputedPropertyKey(propertyKey) {
  6099. if (propertyKey instanceof Literal) {
  6100. return String(propertyKey.value);
  6101. }
  6102. return null;
  6103. }
  6104. function getPathIfNotComputed(memberExpression) {
  6105. const nextPathKey = memberExpression.propertyKey;
  6106. const object = memberExpression.object;
  6107. if (typeof nextPathKey === 'string') {
  6108. if (object instanceof Identifier) {
  6109. return [
  6110. { key: object.name, pos: object.start },
  6111. { key: nextPathKey, pos: memberExpression.property.start }
  6112. ];
  6113. }
  6114. if (object instanceof MemberExpression) {
  6115. const parentPath = getPathIfNotComputed(object);
  6116. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6117. }
  6118. }
  6119. return null;
  6120. }
  6121. function getStringFromPath(path) {
  6122. let pathString = path[0].key;
  6123. for (let index = 1; index < path.length; index++) {
  6124. pathString += '.' + path[index].key;
  6125. }
  6126. return pathString;
  6127. }
  6128. class MemberExpression extends NodeBase {
  6129. constructor() {
  6130. super(...arguments);
  6131. this.variable = null;
  6132. this.bound = false;
  6133. this.expressionsToBeDeoptimized = [];
  6134. this.replacement = null;
  6135. this.wasPathDeoptimizedWhileOptimized = false;
  6136. }
  6137. bind() {
  6138. if (this.bound)
  6139. return;
  6140. this.bound = true;
  6141. const path = getPathIfNotComputed(this);
  6142. const baseVariable = path && this.scope.findVariable(path[0].key);
  6143. if (baseVariable && baseVariable.isNamespace) {
  6144. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6145. if (!resolvedVariable) {
  6146. super.bind();
  6147. }
  6148. else if (typeof resolvedVariable === 'string') {
  6149. this.replacement = resolvedVariable;
  6150. }
  6151. else {
  6152. if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
  6153. resolvedVariable.module.suggestName(path[0].key);
  6154. }
  6155. this.variable = resolvedVariable;
  6156. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6157. }
  6158. }
  6159. else {
  6160. super.bind();
  6161. // ensure the propertyKey is set for the tree-shaking passes
  6162. this.getPropertyKey();
  6163. }
  6164. }
  6165. deoptimizeCache() {
  6166. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6167. this.expressionsToBeDeoptimized = [];
  6168. this.propertyKey = UnknownKey;
  6169. if (this.wasPathDeoptimizedWhileOptimized) {
  6170. this.object.deoptimizePath(UNKNOWN_PATH);
  6171. }
  6172. for (const expression of expressionsToBeDeoptimized) {
  6173. expression.deoptimizeCache();
  6174. }
  6175. }
  6176. deoptimizePath(path) {
  6177. if (!this.bound)
  6178. this.bind();
  6179. if (path.length === 0)
  6180. this.disallowNamespaceReassignment();
  6181. if (this.variable) {
  6182. this.variable.deoptimizePath(path);
  6183. }
  6184. else {
  6185. const propertyKey = this.getPropertyKey();
  6186. if (propertyKey === UnknownKey) {
  6187. this.object.deoptimizePath(UNKNOWN_PATH);
  6188. }
  6189. else {
  6190. this.wasPathDeoptimizedWhileOptimized = true;
  6191. this.object.deoptimizePath([propertyKey, ...path]);
  6192. }
  6193. }
  6194. }
  6195. getLiteralValueAtPath(path, recursionTracker, origin) {
  6196. if (!this.bound)
  6197. this.bind();
  6198. if (this.variable !== null) {
  6199. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6200. }
  6201. this.expressionsToBeDeoptimized.push(origin);
  6202. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6203. }
  6204. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6205. if (!this.bound)
  6206. this.bind();
  6207. if (this.variable !== null) {
  6208. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6209. }
  6210. this.expressionsToBeDeoptimized.push(origin);
  6211. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6212. }
  6213. hasEffects(context) {
  6214. return (this.property.hasEffects(context) ||
  6215. this.object.hasEffects(context) ||
  6216. (this.context.options.treeshake.propertyReadSideEffects &&
  6217. this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
  6218. }
  6219. hasEffectsWhenAccessedAtPath(path, context) {
  6220. if (path.length === 0)
  6221. return false;
  6222. if (this.variable !== null) {
  6223. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6224. }
  6225. return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
  6226. }
  6227. hasEffectsWhenAssignedAtPath(path, context) {
  6228. if (this.variable !== null) {
  6229. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6230. }
  6231. return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
  6232. }
  6233. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6234. if (this.variable !== null) {
  6235. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6236. }
  6237. return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
  6238. }
  6239. include(context, includeChildrenRecursively) {
  6240. if (!this.included) {
  6241. this.included = true;
  6242. if (this.variable !== null) {
  6243. this.context.includeVariableInModule(this.variable);
  6244. }
  6245. }
  6246. this.object.include(context, includeChildrenRecursively);
  6247. this.property.include(context, includeChildrenRecursively);
  6248. }
  6249. includeCallArguments(context, args) {
  6250. if (this.variable) {
  6251. this.variable.includeCallArguments(context, args);
  6252. }
  6253. else {
  6254. super.includeCallArguments(context, args);
  6255. }
  6256. }
  6257. initialise() {
  6258. this.propertyKey = getResolvablePropertyKey(this);
  6259. }
  6260. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  6261. const isCalleeOfDifferentParent = renderedParentType === CallExpression$1 && isCalleeOfRenderedParent;
  6262. if (this.variable || this.replacement) {
  6263. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6264. if (isCalleeOfDifferentParent)
  6265. replacement = '0, ' + replacement;
  6266. code.overwrite(this.start, this.end, replacement, {
  6267. contentOnly: true,
  6268. storeName: true
  6269. });
  6270. }
  6271. else {
  6272. if (isCalleeOfDifferentParent) {
  6273. code.appendRight(this.start, '0, ');
  6274. }
  6275. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6276. this.object.render(code, options, surroundingElement ? { renderedSurroundingElement: surroundingElement } : BLANK);
  6277. this.property.render(code, options);
  6278. }
  6279. }
  6280. disallowNamespaceReassignment() {
  6281. if (this.object instanceof Identifier) {
  6282. const variable = this.scope.findVariable(this.object.name);
  6283. if (variable.isNamespace) {
  6284. if (this.variable) {
  6285. this.context.includeVariableInModule(this.variable);
  6286. }
  6287. this.context.warn({
  6288. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6289. message: `Illegal reassignment to import '${this.object.name}'`
  6290. }, this.start);
  6291. }
  6292. }
  6293. }
  6294. getPropertyKey() {
  6295. if (this.propertyKey === null) {
  6296. this.propertyKey = UnknownKey;
  6297. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6298. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6299. }
  6300. return this.propertyKey;
  6301. }
  6302. resolveNamespaceVariables(baseVariable, path) {
  6303. if (path.length === 0)
  6304. return baseVariable;
  6305. if (!baseVariable.isNamespace)
  6306. return null;
  6307. const exportName = path[0].key;
  6308. const variable = baseVariable instanceof ExternalVariable
  6309. ? baseVariable.module.getVariableForExportName(exportName)
  6310. : baseVariable.context.traceExport(exportName);
  6311. if (!variable) {
  6312. const fileName = baseVariable instanceof ExternalVariable
  6313. ? baseVariable.module.id
  6314. : baseVariable.context.fileName;
  6315. this.context.warn({
  6316. code: 'MISSING_EXPORT',
  6317. exporter: relativeId(fileName),
  6318. importer: relativeId(this.context.fileName),
  6319. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6320. missing: exportName,
  6321. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6322. }, path[0].pos);
  6323. return 'undefined';
  6324. }
  6325. return this.resolveNamespaceVariables(variable, path.slice(1));
  6326. }
  6327. }
  6328. class CallExpression extends NodeBase {
  6329. constructor() {
  6330. super(...arguments);
  6331. this.expressionsToBeDeoptimized = [];
  6332. this.returnExpression = null;
  6333. this.wasPathDeoptmizedWhileOptimized = false;
  6334. }
  6335. bind() {
  6336. super.bind();
  6337. if (this.callee instanceof Identifier) {
  6338. const variable = this.scope.findVariable(this.callee.name);
  6339. if (variable.isNamespace) {
  6340. this.context.warn({
  6341. code: 'CANNOT_CALL_NAMESPACE',
  6342. message: `Cannot call a namespace ('${this.callee.name}')`
  6343. }, this.start);
  6344. }
  6345. if (this.callee.name === 'eval') {
  6346. this.context.warn({
  6347. code: 'EVAL',
  6348. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6349. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6350. }, this.start);
  6351. }
  6352. }
  6353. // ensure the returnExpression is set for the tree-shaking passes
  6354. this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6355. // This deoptimizes "this" for non-namespace calls until we have a better solution
  6356. if (this.callee instanceof MemberExpression && !this.callee.variable) {
  6357. this.callee.object.deoptimizePath(UNKNOWN_PATH);
  6358. }
  6359. for (const argument of this.arguments) {
  6360. // This will make sure all properties of parameters behave as "unknown"
  6361. argument.deoptimizePath(UNKNOWN_PATH);
  6362. }
  6363. }
  6364. deoptimizeCache() {
  6365. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6366. this.returnExpression = null;
  6367. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6368. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6369. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6370. // We need to replace here because is possible new expressions are added
  6371. // while we are deoptimizing the old ones
  6372. this.expressionsToBeDeoptimized = [];
  6373. if (this.wasPathDeoptmizedWhileOptimized) {
  6374. returnExpression.deoptimizePath(UNKNOWN_PATH);
  6375. this.wasPathDeoptmizedWhileOptimized = false;
  6376. }
  6377. }
  6378. for (const expression of expressionsToBeDeoptimized) {
  6379. expression.deoptimizeCache();
  6380. }
  6381. }
  6382. }
  6383. deoptimizePath(path) {
  6384. if (path.length === 0)
  6385. return;
  6386. const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
  6387. if (trackedEntities.has(this))
  6388. return;
  6389. trackedEntities.add(this);
  6390. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6391. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6392. this.wasPathDeoptmizedWhileOptimized = true;
  6393. returnExpression.deoptimizePath(path);
  6394. }
  6395. }
  6396. getLiteralValueAtPath(path, recursionTracker, origin) {
  6397. const returnExpression = this.getReturnExpression(recursionTracker);
  6398. if (returnExpression === UNKNOWN_EXPRESSION) {
  6399. return UnknownValue;
  6400. }
  6401. const trackedEntities = recursionTracker.getEntities(path);
  6402. if (trackedEntities.has(returnExpression)) {
  6403. return UnknownValue;
  6404. }
  6405. this.expressionsToBeDeoptimized.push(origin);
  6406. trackedEntities.add(returnExpression);
  6407. const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6408. trackedEntities.delete(returnExpression);
  6409. return value;
  6410. }
  6411. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6412. const returnExpression = this.getReturnExpression(recursionTracker);
  6413. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6414. return UNKNOWN_EXPRESSION;
  6415. }
  6416. const trackedEntities = recursionTracker.getEntities(path);
  6417. if (trackedEntities.has(returnExpression)) {
  6418. return UNKNOWN_EXPRESSION;
  6419. }
  6420. this.expressionsToBeDeoptimized.push(origin);
  6421. trackedEntities.add(returnExpression);
  6422. const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6423. trackedEntities.delete(returnExpression);
  6424. return value;
  6425. }
  6426. hasEffects(context) {
  6427. for (const argument of this.arguments) {
  6428. if (argument.hasEffects(context))
  6429. return true;
  6430. }
  6431. if (this.context.options.treeshake.annotations &&
  6432. this.annotatedPure)
  6433. return false;
  6434. return (this.callee.hasEffects(context) ||
  6435. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6436. }
  6437. hasEffectsWhenAccessedAtPath(path, context) {
  6438. if (path.length === 0)
  6439. return false;
  6440. const trackedExpressions = context.accessed.getEntities(path);
  6441. if (trackedExpressions.has(this))
  6442. return false;
  6443. trackedExpressions.add(this);
  6444. return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
  6445. }
  6446. hasEffectsWhenAssignedAtPath(path, context) {
  6447. if (path.length === 0)
  6448. return true;
  6449. const trackedExpressions = context.assigned.getEntities(path);
  6450. if (trackedExpressions.has(this))
  6451. return false;
  6452. trackedExpressions.add(this);
  6453. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  6454. }
  6455. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6456. const trackedExpressions = (callOptions.withNew
  6457. ? context.instantiated
  6458. : context.called).getEntities(path, callOptions);
  6459. if (trackedExpressions.has(this))
  6460. return false;
  6461. trackedExpressions.add(this);
  6462. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6463. }
  6464. include(context, includeChildrenRecursively) {
  6465. if (includeChildrenRecursively) {
  6466. super.include(context, includeChildrenRecursively);
  6467. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6468. this.callee instanceof Identifier &&
  6469. this.callee.variable) {
  6470. this.callee.variable.markCalledFromTryStatement();
  6471. }
  6472. }
  6473. else {
  6474. this.included = true;
  6475. this.callee.include(context, false);
  6476. }
  6477. this.callee.includeCallArguments(context, this.arguments);
  6478. if (!this.returnExpression.included) {
  6479. this.returnExpression.include(context, false);
  6480. }
  6481. }
  6482. initialise() {
  6483. this.callOptions = {
  6484. args: this.arguments,
  6485. withNew: false
  6486. };
  6487. }
  6488. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6489. const surroundingELement = renderedParentType || renderedSurroundingElement;
  6490. this.callee.render(code, options, surroundingELement ? { renderedSurroundingElement: surroundingELement } : BLANK);
  6491. if (this.arguments.length > 0) {
  6492. if (this.arguments[this.arguments.length - 1].included) {
  6493. for (const arg of this.arguments) {
  6494. arg.render(code, options);
  6495. }
  6496. }
  6497. else {
  6498. let lastIncludedIndex = this.arguments.length - 2;
  6499. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6500. lastIncludedIndex--;
  6501. }
  6502. if (lastIncludedIndex >= 0) {
  6503. for (let index = 0; index <= lastIncludedIndex; index++) {
  6504. this.arguments[index].render(code, options);
  6505. }
  6506. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6507. }
  6508. else {
  6509. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6510. }
  6511. }
  6512. }
  6513. }
  6514. getReturnExpression(recursionTracker) {
  6515. if (this.returnExpression === null) {
  6516. this.returnExpression = UNKNOWN_EXPRESSION;
  6517. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
  6518. }
  6519. return this.returnExpression;
  6520. }
  6521. }
  6522. class CatchScope extends ParameterScope {
  6523. addDeclaration(identifier, context, init, isHoisted) {
  6524. if (isHoisted) {
  6525. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6526. }
  6527. else {
  6528. return super.addDeclaration(identifier, context, init, false);
  6529. }
  6530. }
  6531. }
  6532. class CatchClause extends NodeBase {
  6533. createScope(parentScope) {
  6534. this.scope = new CatchScope(parentScope, this.context);
  6535. }
  6536. initialise() {
  6537. if (this.param) {
  6538. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  6539. }
  6540. }
  6541. parseNode(esTreeNode) {
  6542. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
  6543. super.parseNode(esTreeNode);
  6544. }
  6545. }
  6546. CatchClause.prototype.preventChildBlockScope = true;
  6547. class ChainExpression extends NodeBase {
  6548. }
  6549. class ClassBodyScope extends ChildScope {
  6550. findLexicalBoundary() {
  6551. return this;
  6552. }
  6553. }
  6554. class MethodDefinition extends NodeBase {
  6555. hasEffects(context) {
  6556. return this.key.hasEffects(context);
  6557. }
  6558. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6559. return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6560. }
  6561. }
  6562. class ClassBody extends NodeBase {
  6563. createScope(parentScope) {
  6564. this.scope = new ClassBodyScope(parentScope);
  6565. }
  6566. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6567. if (path.length > 0)
  6568. return true;
  6569. return (this.classConstructor !== null &&
  6570. this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6571. }
  6572. initialise() {
  6573. for (const method of this.body) {
  6574. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  6575. this.classConstructor = method;
  6576. return;
  6577. }
  6578. }
  6579. this.classConstructor = null;
  6580. }
  6581. }
  6582. class ClassExpression extends ClassNode {
  6583. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6584. super.render(code, options);
  6585. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6586. if (surroundingElement === ExpressionStatement$1) {
  6587. code.appendRight(this.start, '(');
  6588. code.prependLeft(this.end, ')');
  6589. }
  6590. }
  6591. }
  6592. class MultiExpression {
  6593. constructor(expressions) {
  6594. this.included = false;
  6595. this.expressions = expressions;
  6596. }
  6597. deoptimizePath(path) {
  6598. for (const expression of this.expressions) {
  6599. expression.deoptimizePath(path);
  6600. }
  6601. }
  6602. getLiteralValueAtPath() {
  6603. return UnknownValue;
  6604. }
  6605. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6606. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
  6607. }
  6608. hasEffectsWhenAccessedAtPath(path, context) {
  6609. for (const expression of this.expressions) {
  6610. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  6611. return true;
  6612. }
  6613. return false;
  6614. }
  6615. hasEffectsWhenAssignedAtPath(path, context) {
  6616. for (const expression of this.expressions) {
  6617. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  6618. return true;
  6619. }
  6620. return false;
  6621. }
  6622. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6623. for (const expression of this.expressions) {
  6624. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  6625. return true;
  6626. }
  6627. return false;
  6628. }
  6629. include(context, includeChildrenRecursively) {
  6630. // This is only relevant to include values that do not have an AST representation,
  6631. // such as UnknownArrayExpression. Thus we only need to include them once.
  6632. for (const expression of this.expressions) {
  6633. if (!expression.included) {
  6634. expression.include(context, includeChildrenRecursively);
  6635. }
  6636. }
  6637. }
  6638. includeCallArguments() { }
  6639. }
  6640. class ConditionalExpression extends NodeBase {
  6641. constructor() {
  6642. super(...arguments);
  6643. this.expressionsToBeDeoptimized = [];
  6644. this.isBranchResolutionAnalysed = false;
  6645. this.usedBranch = null;
  6646. this.wasPathDeoptimizedWhileOptimized = false;
  6647. }
  6648. bind() {
  6649. super.bind();
  6650. // ensure the usedBranch is set for the tree-shaking passes
  6651. this.getUsedBranch();
  6652. }
  6653. deoptimizeCache() {
  6654. if (this.usedBranch !== null) {
  6655. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  6656. this.usedBranch = null;
  6657. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6658. this.expressionsToBeDeoptimized = [];
  6659. if (this.wasPathDeoptimizedWhileOptimized) {
  6660. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  6661. }
  6662. for (const expression of expressionsToBeDeoptimized) {
  6663. expression.deoptimizeCache();
  6664. }
  6665. }
  6666. }
  6667. deoptimizePath(path) {
  6668. if (path.length > 0) {
  6669. const usedBranch = this.getUsedBranch();
  6670. if (usedBranch === null) {
  6671. this.consequent.deoptimizePath(path);
  6672. this.alternate.deoptimizePath(path);
  6673. }
  6674. else {
  6675. this.wasPathDeoptimizedWhileOptimized = true;
  6676. usedBranch.deoptimizePath(path);
  6677. }
  6678. }
  6679. }
  6680. getLiteralValueAtPath(path, recursionTracker, origin) {
  6681. const usedBranch = this.getUsedBranch();
  6682. if (usedBranch === null)
  6683. return UnknownValue;
  6684. this.expressionsToBeDeoptimized.push(origin);
  6685. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  6686. }
  6687. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6688. const usedBranch = this.getUsedBranch();
  6689. if (usedBranch === null)
  6690. return new MultiExpression([
  6691. this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  6692. this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  6693. ]);
  6694. this.expressionsToBeDeoptimized.push(origin);
  6695. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6696. }
  6697. hasEffects(context) {
  6698. if (this.test.hasEffects(context))
  6699. return true;
  6700. if (this.usedBranch === null) {
  6701. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  6702. }
  6703. return this.usedBranch.hasEffects(context);
  6704. }
  6705. hasEffectsWhenAccessedAtPath(path, context) {
  6706. if (path.length === 0)
  6707. return false;
  6708. if (this.usedBranch === null) {
  6709. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  6710. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  6711. }
  6712. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  6713. }
  6714. hasEffectsWhenAssignedAtPath(path, context) {
  6715. if (path.length === 0)
  6716. return true;
  6717. if (this.usedBranch === null) {
  6718. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  6719. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  6720. }
  6721. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  6722. }
  6723. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6724. if (this.usedBranch === null) {
  6725. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  6726. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  6727. }
  6728. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6729. }
  6730. include(context, includeChildrenRecursively) {
  6731. this.included = true;
  6732. if (includeChildrenRecursively ||
  6733. this.test.shouldBeIncluded(context) ||
  6734. this.usedBranch === null) {
  6735. this.test.include(context, includeChildrenRecursively);
  6736. this.consequent.include(context, includeChildrenRecursively);
  6737. this.alternate.include(context, includeChildrenRecursively);
  6738. }
  6739. else {
  6740. this.usedBranch.include(context, includeChildrenRecursively);
  6741. }
  6742. }
  6743. includeCallArguments(context, args) {
  6744. if (this.usedBranch === null) {
  6745. this.consequent.includeCallArguments(context, args);
  6746. this.alternate.includeCallArguments(context, args);
  6747. }
  6748. else {
  6749. this.usedBranch.includeCallArguments(context, args);
  6750. }
  6751. }
  6752. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  6753. if (!this.test.included) {
  6754. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  6755. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  6756. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  6757. : colonPos) + 1);
  6758. if (preventASI) {
  6759. removeLineBreaks(code, inclusionStart, this.usedBranch.start);
  6760. }
  6761. code.remove(this.start, inclusionStart);
  6762. if (this.consequent.included) {
  6763. code.remove(colonPos, this.end);
  6764. }
  6765. removeAnnotations(this, code);
  6766. this.usedBranch.render(code, options, {
  6767. isCalleeOfRenderedParent: renderedParentType
  6768. ? isCalleeOfRenderedParent
  6769. : this.parent.callee === this,
  6770. preventASI: true,
  6771. renderedParentType: renderedParentType || this.parent.type
  6772. });
  6773. }
  6774. else {
  6775. super.render(code, options);
  6776. }
  6777. }
  6778. getUsedBranch() {
  6779. if (this.isBranchResolutionAnalysed) {
  6780. return this.usedBranch;
  6781. }
  6782. this.isBranchResolutionAnalysed = true;
  6783. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6784. return testValue === UnknownValue
  6785. ? null
  6786. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  6787. }
  6788. }
  6789. class ContinueStatement extends NodeBase {
  6790. hasEffects(context) {
  6791. if (this.label) {
  6792. if (!context.ignore.labels.has(this.label.name))
  6793. return true;
  6794. context.includedLabels.add(this.label.name);
  6795. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6796. }
  6797. else {
  6798. if (!context.ignore.continues)
  6799. return true;
  6800. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6801. }
  6802. return false;
  6803. }
  6804. include(context) {
  6805. this.included = true;
  6806. if (this.label) {
  6807. this.label.include();
  6808. context.includedLabels.add(this.label.name);
  6809. }
  6810. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6811. }
  6812. }
  6813. class DoWhileStatement extends NodeBase {
  6814. hasEffects(context) {
  6815. if (this.test.hasEffects(context))
  6816. return true;
  6817. const { brokenFlow, ignore: { breaks, continues } } = context;
  6818. context.ignore.breaks = true;
  6819. context.ignore.continues = true;
  6820. if (this.body.hasEffects(context))
  6821. return true;
  6822. context.ignore.breaks = breaks;
  6823. context.ignore.continues = continues;
  6824. context.brokenFlow = brokenFlow;
  6825. return false;
  6826. }
  6827. include(context, includeChildrenRecursively) {
  6828. this.included = true;
  6829. this.test.include(context, includeChildrenRecursively);
  6830. const { brokenFlow } = context;
  6831. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6832. context.brokenFlow = brokenFlow;
  6833. }
  6834. }
  6835. class EmptyStatement extends NodeBase {
  6836. hasEffects() {
  6837. return false;
  6838. }
  6839. }
  6840. class ExportNamedDeclaration extends NodeBase {
  6841. bind() {
  6842. // Do not bind specifiers
  6843. if (this.declaration !== null)
  6844. this.declaration.bind();
  6845. }
  6846. hasEffects(context) {
  6847. return this.declaration !== null && this.declaration.hasEffects(context);
  6848. }
  6849. initialise() {
  6850. this.context.addExport(this);
  6851. }
  6852. render(code, options, nodeRenderOptions) {
  6853. const { start, end } = nodeRenderOptions;
  6854. if (this.declaration === null) {
  6855. code.remove(start, end);
  6856. }
  6857. else {
  6858. code.remove(this.start, this.declaration.start);
  6859. this.declaration.render(code, options, { start, end });
  6860. }
  6861. }
  6862. }
  6863. ExportNamedDeclaration.prototype.needsBoundaries = true;
  6864. class ExportSpecifier extends NodeBase {
  6865. }
  6866. class ForInStatement extends NodeBase {
  6867. bind() {
  6868. this.left.bind();
  6869. this.left.deoptimizePath(EMPTY_PATH);
  6870. this.right.bind();
  6871. this.body.bind();
  6872. }
  6873. createScope(parentScope) {
  6874. this.scope = new BlockScope(parentScope);
  6875. }
  6876. hasEffects(context) {
  6877. if ((this.left &&
  6878. (this.left.hasEffects(context) ||
  6879. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  6880. (this.right && this.right.hasEffects(context)))
  6881. return true;
  6882. const { brokenFlow, ignore: { breaks, continues } } = context;
  6883. context.ignore.breaks = true;
  6884. context.ignore.continues = true;
  6885. if (this.body.hasEffects(context))
  6886. return true;
  6887. context.ignore.breaks = breaks;
  6888. context.ignore.continues = continues;
  6889. context.brokenFlow = brokenFlow;
  6890. return false;
  6891. }
  6892. include(context, includeChildrenRecursively) {
  6893. this.included = true;
  6894. this.left.include(context, includeChildrenRecursively || true);
  6895. this.left.deoptimizePath(EMPTY_PATH);
  6896. this.right.include(context, includeChildrenRecursively);
  6897. const { brokenFlow } = context;
  6898. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6899. context.brokenFlow = brokenFlow;
  6900. }
  6901. render(code, options) {
  6902. this.left.render(code, options, NO_SEMICOLON);
  6903. this.right.render(code, options, NO_SEMICOLON);
  6904. // handle no space between "in" and the right side
  6905. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  6906. code.prependLeft(this.right.start, ' ');
  6907. }
  6908. this.body.render(code, options);
  6909. }
  6910. }
  6911. class ForOfStatement extends NodeBase {
  6912. bind() {
  6913. this.left.bind();
  6914. this.left.deoptimizePath(EMPTY_PATH);
  6915. this.right.bind();
  6916. this.body.bind();
  6917. }
  6918. createScope(parentScope) {
  6919. this.scope = new BlockScope(parentScope);
  6920. }
  6921. hasEffects() {
  6922. // Placeholder until proper Symbol.Iterator support
  6923. return true;
  6924. }
  6925. include(context, includeChildrenRecursively) {
  6926. this.included = true;
  6927. this.left.include(context, includeChildrenRecursively || true);
  6928. this.left.deoptimizePath(EMPTY_PATH);
  6929. this.right.include(context, includeChildrenRecursively);
  6930. const { brokenFlow } = context;
  6931. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6932. context.brokenFlow = brokenFlow;
  6933. }
  6934. render(code, options) {
  6935. this.left.render(code, options, NO_SEMICOLON);
  6936. this.right.render(code, options, NO_SEMICOLON);
  6937. // handle no space between "of" and the right side
  6938. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  6939. code.prependLeft(this.right.start, ' ');
  6940. }
  6941. this.body.render(code, options);
  6942. }
  6943. }
  6944. class ForStatement extends NodeBase {
  6945. createScope(parentScope) {
  6946. this.scope = new BlockScope(parentScope);
  6947. }
  6948. hasEffects(context) {
  6949. if ((this.init && this.init.hasEffects(context)) ||
  6950. (this.test && this.test.hasEffects(context)) ||
  6951. (this.update && this.update.hasEffects(context)))
  6952. return true;
  6953. const { brokenFlow, ignore: { breaks, continues } } = context;
  6954. context.ignore.breaks = true;
  6955. context.ignore.continues = true;
  6956. if (this.body.hasEffects(context))
  6957. return true;
  6958. context.ignore.breaks = breaks;
  6959. context.ignore.continues = continues;
  6960. context.brokenFlow = brokenFlow;
  6961. return false;
  6962. }
  6963. include(context, includeChildrenRecursively) {
  6964. this.included = true;
  6965. if (this.init)
  6966. this.init.includeAsSingleStatement(context, includeChildrenRecursively);
  6967. if (this.test)
  6968. this.test.include(context, includeChildrenRecursively);
  6969. const { brokenFlow } = context;
  6970. if (this.update)
  6971. this.update.include(context, includeChildrenRecursively);
  6972. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6973. context.brokenFlow = brokenFlow;
  6974. }
  6975. render(code, options) {
  6976. if (this.init)
  6977. this.init.render(code, options, NO_SEMICOLON);
  6978. if (this.test)
  6979. this.test.render(code, options, NO_SEMICOLON);
  6980. if (this.update)
  6981. this.update.render(code, options, NO_SEMICOLON);
  6982. this.body.render(code, options);
  6983. }
  6984. }
  6985. class FunctionExpression extends FunctionNode {
  6986. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  6987. super.render(code, options);
  6988. const surroundingElement = renderedParentType || renderedSurroundingElement;
  6989. if (surroundingElement === ExpressionStatement$1) {
  6990. code.appendRight(this.start, '(');
  6991. code.prependLeft(this.end, ')');
  6992. }
  6993. }
  6994. }
  6995. class TrackingScope extends BlockScope {
  6996. constructor() {
  6997. super(...arguments);
  6998. this.hoistedDeclarations = [];
  6999. }
  7000. addDeclaration(identifier, context, init, isHoisted) {
  7001. this.hoistedDeclarations.push(identifier);
  7002. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  7003. }
  7004. }
  7005. const unset = Symbol('unset');
  7006. class IfStatement extends NodeBase {
  7007. constructor() {
  7008. super(...arguments);
  7009. this.testValue = unset;
  7010. }
  7011. deoptimizeCache() {
  7012. this.testValue = UnknownValue;
  7013. }
  7014. hasEffects(context) {
  7015. if (this.test.hasEffects(context)) {
  7016. return true;
  7017. }
  7018. const testValue = this.getTestValue();
  7019. if (testValue === UnknownValue) {
  7020. const { brokenFlow } = context;
  7021. if (this.consequent.hasEffects(context))
  7022. return true;
  7023. const consequentBrokenFlow = context.brokenFlow;
  7024. context.brokenFlow = brokenFlow;
  7025. if (this.alternate === null)
  7026. return false;
  7027. if (this.alternate.hasEffects(context))
  7028. return true;
  7029. context.brokenFlow =
  7030. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7031. return false;
  7032. }
  7033. return testValue
  7034. ? this.consequent.hasEffects(context)
  7035. : this.alternate !== null && this.alternate.hasEffects(context);
  7036. }
  7037. include(context, includeChildrenRecursively) {
  7038. this.included = true;
  7039. if (includeChildrenRecursively) {
  7040. this.includeRecursively(includeChildrenRecursively, context);
  7041. }
  7042. else {
  7043. const testValue = this.getTestValue();
  7044. if (testValue === UnknownValue) {
  7045. this.includeUnknownTest(context);
  7046. }
  7047. else {
  7048. this.includeKnownTest(context, testValue);
  7049. }
  7050. }
  7051. }
  7052. parseNode(esTreeNode) {
  7053. this.consequentScope = new TrackingScope(this.scope);
  7054. this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
  7055. this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
  7056. if (esTreeNode.alternate) {
  7057. this.alternateScope = new TrackingScope(this.scope);
  7058. this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
  7059. this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
  7060. }
  7061. super.parseNode(esTreeNode);
  7062. }
  7063. render(code, options) {
  7064. // Note that unknown test values are always included
  7065. const testValue = this.getTestValue();
  7066. const hoistedDeclarations = [];
  7067. const includesIfElse = this.test.included;
  7068. const noTreeshake = !this.context.options.treeshake;
  7069. if (includesIfElse) {
  7070. this.test.render(code, options);
  7071. }
  7072. else {
  7073. removeAnnotations(this, code);
  7074. code.remove(this.start, this.consequent.start);
  7075. }
  7076. if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
  7077. this.consequent.render(code, options);
  7078. }
  7079. else {
  7080. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  7081. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  7082. }
  7083. if (this.alternate) {
  7084. if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
  7085. if (includesIfElse) {
  7086. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  7087. code.prependLeft(this.alternate.start, ' ');
  7088. }
  7089. }
  7090. else {
  7091. code.remove(this.consequent.end, this.alternate.start);
  7092. }
  7093. this.alternate.render(code, options);
  7094. }
  7095. else {
  7096. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  7097. code.overwrite(this.alternate.start, this.end, ';');
  7098. }
  7099. else {
  7100. code.remove(this.consequent.end, this.end);
  7101. }
  7102. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  7103. }
  7104. }
  7105. this.renderHoistedDeclarations(hoistedDeclarations, code);
  7106. }
  7107. getTestValue() {
  7108. if (this.testValue === unset) {
  7109. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7110. }
  7111. return this.testValue;
  7112. }
  7113. includeKnownTest(context, testValue) {
  7114. if (this.test.shouldBeIncluded(context)) {
  7115. this.test.include(context, false);
  7116. }
  7117. if (testValue && this.consequent.shouldBeIncluded(context)) {
  7118. this.consequent.includeAsSingleStatement(context, false);
  7119. }
  7120. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  7121. this.alternate.includeAsSingleStatement(context, false);
  7122. }
  7123. }
  7124. includeRecursively(includeChildrenRecursively, context) {
  7125. this.test.include(context, includeChildrenRecursively);
  7126. this.consequent.include(context, includeChildrenRecursively);
  7127. if (this.alternate !== null) {
  7128. this.alternate.include(context, includeChildrenRecursively);
  7129. }
  7130. }
  7131. includeUnknownTest(context) {
  7132. this.test.include(context, false);
  7133. const { brokenFlow } = context;
  7134. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  7135. if (this.consequent.shouldBeIncluded(context)) {
  7136. this.consequent.includeAsSingleStatement(context, false);
  7137. consequentBrokenFlow = context.brokenFlow;
  7138. context.brokenFlow = brokenFlow;
  7139. }
  7140. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  7141. this.alternate.includeAsSingleStatement(context, false);
  7142. context.brokenFlow =
  7143. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7144. }
  7145. }
  7146. renderHoistedDeclarations(hoistedDeclarations, code) {
  7147. const hoistedVars = [
  7148. ...new Set(hoistedDeclarations.map(identifier => {
  7149. const variable = identifier.variable;
  7150. return variable.included ? variable.getName() : '';
  7151. }))
  7152. ]
  7153. .filter(Boolean)
  7154. .join(', ');
  7155. if (hoistedVars) {
  7156. const parentType = this.parent.type;
  7157. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  7158. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  7159. if (needsBraces) {
  7160. code.appendLeft(this.end, ` }`);
  7161. }
  7162. }
  7163. }
  7164. shouldKeepAlternateBranch() {
  7165. let currentParent = this.parent;
  7166. do {
  7167. if (currentParent instanceof IfStatement && currentParent.alternate) {
  7168. return true;
  7169. }
  7170. if (currentParent instanceof BlockStatement) {
  7171. return false;
  7172. }
  7173. currentParent = currentParent.parent;
  7174. } while (currentParent);
  7175. return false;
  7176. }
  7177. }
  7178. class ImportDeclaration extends NodeBase {
  7179. bind() { }
  7180. hasEffects() {
  7181. return false;
  7182. }
  7183. initialise() {
  7184. this.context.addImport(this);
  7185. }
  7186. render(code, _options, nodeRenderOptions) {
  7187. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7188. }
  7189. }
  7190. ImportDeclaration.prototype.needsBoundaries = true;
  7191. class ImportDefaultSpecifier extends NodeBase {
  7192. }
  7193. class ImportExpression extends NodeBase {
  7194. constructor() {
  7195. super(...arguments);
  7196. this.inlineNamespace = null;
  7197. this.mechanism = null;
  7198. this.resolution = null;
  7199. }
  7200. hasEffects() {
  7201. return true;
  7202. }
  7203. include(context, includeChildrenRecursively) {
  7204. if (!this.included) {
  7205. this.included = true;
  7206. this.context.includeDynamicImport(this);
  7207. this.scope.addAccessedDynamicImport(this);
  7208. }
  7209. this.source.include(context, includeChildrenRecursively);
  7210. }
  7211. initialise() {
  7212. this.context.addDynamicImport(this);
  7213. }
  7214. render(code, options) {
  7215. if (this.inlineNamespace) {
  7216. const _ = options.compact ? '' : ' ';
  7217. const s = options.compact ? '' : ';';
  7218. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
  7219. return;
  7220. }
  7221. if (this.mechanism) {
  7222. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  7223. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  7224. }
  7225. this.source.render(code, options);
  7226. }
  7227. renderFinalResolution(code, resolution, namespaceExportName, options) {
  7228. code.overwrite(this.source.start, this.source.end, resolution);
  7229. if (namespaceExportName) {
  7230. const _ = options.compact ? '' : ' ';
  7231. const s = options.compact ? '' : ';';
  7232. code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
  7233. }
  7234. }
  7235. setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
  7236. this.resolution = resolution;
  7237. const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
  7238. let helper;
  7239. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
  7240. if (helper) {
  7241. accessedGlobals.push(helper);
  7242. }
  7243. if (accessedGlobals.length > 0) {
  7244. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7245. }
  7246. }
  7247. setInternalResolution(inlineNamespace) {
  7248. this.inlineNamespace = inlineNamespace;
  7249. }
  7250. getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
  7251. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  7252. {
  7253. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  7254. format: options.format,
  7255. moduleId: this.context.module.id,
  7256. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  7257. }
  7258. ]);
  7259. if (mechanism) {
  7260. return { helper: null, mechanism };
  7261. }
  7262. switch (options.format) {
  7263. case 'cjs': {
  7264. const _ = options.compact ? '' : ' ';
  7265. const s = options.compact ? '' : ';';
  7266. const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
  7267. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7268. return {
  7269. helper,
  7270. mechanism: helper
  7271. ? {
  7272. left: `${leftStart} /*#__PURE__*/${helper}(require(`,
  7273. right: `))${s}${_}})`
  7274. }
  7275. : {
  7276. left: `${leftStart} require(`,
  7277. right: `)${s}${_}})`
  7278. }
  7279. };
  7280. }
  7281. case 'amd': {
  7282. const _ = options.compact ? '' : ' ';
  7283. const resolve = options.compact ? 'c' : 'resolve';
  7284. const reject = options.compact ? 'e' : 'reject';
  7285. const helper = this.getInteropHelper(resolution, exportMode, options.interop);
  7286. const resolveNamespace = helper
  7287. ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
  7288. : resolve;
  7289. return {
  7290. helper,
  7291. mechanism: {
  7292. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7293. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7294. }
  7295. };
  7296. }
  7297. case 'system':
  7298. return {
  7299. helper: null,
  7300. mechanism: {
  7301. left: 'module.import(',
  7302. right: ')'
  7303. }
  7304. };
  7305. case 'es':
  7306. if (options.dynamicImportFunction) {
  7307. return {
  7308. helper: null,
  7309. mechanism: {
  7310. left: `${options.dynamicImportFunction}(`,
  7311. right: ')'
  7312. }
  7313. };
  7314. }
  7315. }
  7316. return { helper: null, mechanism: null };
  7317. }
  7318. getInteropHelper(resolution, exportMode, interop) {
  7319. return exportMode === 'external'
  7320. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  7321. : exportMode === 'default'
  7322. ? getDefaultOnlyHelper()
  7323. : null;
  7324. }
  7325. }
  7326. const accessedImportGlobals = {
  7327. amd: ['require'],
  7328. cjs: ['require'],
  7329. system: ['module']
  7330. };
  7331. class ImportNamespaceSpecifier extends NodeBase {
  7332. }
  7333. class ImportSpecifier extends NodeBase {
  7334. }
  7335. class LabeledStatement extends NodeBase {
  7336. hasEffects(context) {
  7337. const brokenFlow = context.brokenFlow;
  7338. context.ignore.labels.add(this.label.name);
  7339. if (this.body.hasEffects(context))
  7340. return true;
  7341. context.ignore.labels.delete(this.label.name);
  7342. if (context.includedLabels.has(this.label.name)) {
  7343. context.includedLabels.delete(this.label.name);
  7344. context.brokenFlow = brokenFlow;
  7345. }
  7346. return false;
  7347. }
  7348. include(context, includeChildrenRecursively) {
  7349. this.included = true;
  7350. const brokenFlow = context.brokenFlow;
  7351. this.body.include(context, includeChildrenRecursively);
  7352. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  7353. this.label.include();
  7354. context.includedLabels.delete(this.label.name);
  7355. context.brokenFlow = brokenFlow;
  7356. }
  7357. }
  7358. render(code, options) {
  7359. if (this.label.included) {
  7360. this.label.render(code, options);
  7361. }
  7362. else {
  7363. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  7364. }
  7365. this.body.render(code, options);
  7366. }
  7367. }
  7368. class LogicalExpression extends NodeBase {
  7369. constructor() {
  7370. super(...arguments);
  7371. // We collect deoptimization information if usedBranch !== null
  7372. this.expressionsToBeDeoptimized = [];
  7373. this.isBranchResolutionAnalysed = false;
  7374. this.unusedBranch = null;
  7375. this.usedBranch = null;
  7376. this.wasPathDeoptimizedWhileOptimized = false;
  7377. }
  7378. bind() {
  7379. super.bind();
  7380. // ensure the usedBranch is set for the tree-shaking passes
  7381. this.getUsedBranch();
  7382. }
  7383. deoptimizeCache() {
  7384. if (this.usedBranch !== null) {
  7385. this.usedBranch = null;
  7386. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7387. this.expressionsToBeDeoptimized = [];
  7388. if (this.wasPathDeoptimizedWhileOptimized) {
  7389. this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7390. }
  7391. for (const expression of expressionsToBeDeoptimized) {
  7392. expression.deoptimizeCache();
  7393. }
  7394. }
  7395. }
  7396. deoptimizePath(path) {
  7397. const usedBranch = this.getUsedBranch();
  7398. if (usedBranch === null) {
  7399. this.left.deoptimizePath(path);
  7400. this.right.deoptimizePath(path);
  7401. }
  7402. else {
  7403. this.wasPathDeoptimizedWhileOptimized = true;
  7404. usedBranch.deoptimizePath(path);
  7405. }
  7406. }
  7407. getLiteralValueAtPath(path, recursionTracker, origin) {
  7408. const usedBranch = this.getUsedBranch();
  7409. if (usedBranch === null)
  7410. return UnknownValue;
  7411. this.expressionsToBeDeoptimized.push(origin);
  7412. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7413. }
  7414. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7415. const usedBranch = this.getUsedBranch();
  7416. if (usedBranch === null)
  7417. return new MultiExpression([
  7418. this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  7419. this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  7420. ]);
  7421. this.expressionsToBeDeoptimized.push(origin);
  7422. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7423. }
  7424. hasEffects(context) {
  7425. if (this.left.hasEffects(context)) {
  7426. return true;
  7427. }
  7428. if (this.usedBranch !== this.left) {
  7429. return this.right.hasEffects(context);
  7430. }
  7431. return false;
  7432. }
  7433. hasEffectsWhenAccessedAtPath(path, context) {
  7434. if (path.length === 0)
  7435. return false;
  7436. if (this.usedBranch === null) {
  7437. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7438. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7439. }
  7440. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7441. }
  7442. hasEffectsWhenAssignedAtPath(path, context) {
  7443. if (path.length === 0)
  7444. return true;
  7445. if (this.usedBranch === null) {
  7446. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7447. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7448. }
  7449. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7450. }
  7451. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7452. if (this.usedBranch === null) {
  7453. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7454. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7455. }
  7456. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7457. }
  7458. include(context, includeChildrenRecursively) {
  7459. this.included = true;
  7460. if (includeChildrenRecursively ||
  7461. (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  7462. this.usedBranch === null) {
  7463. this.left.include(context, includeChildrenRecursively);
  7464. this.right.include(context, includeChildrenRecursively);
  7465. }
  7466. else {
  7467. this.usedBranch.include(context, includeChildrenRecursively);
  7468. }
  7469. }
  7470. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  7471. if (!this.left.included || !this.right.included) {
  7472. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  7473. if (this.right.included) {
  7474. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  7475. code.remove(this.start, removePos);
  7476. if (preventASI) {
  7477. removeLineBreaks(code, removePos, this.right.start);
  7478. }
  7479. }
  7480. else {
  7481. code.remove(operatorPos, this.end);
  7482. }
  7483. removeAnnotations(this, code);
  7484. this.usedBranch.render(code, options, {
  7485. isCalleeOfRenderedParent: renderedParentType
  7486. ? isCalleeOfRenderedParent
  7487. : this.parent.callee === this,
  7488. preventASI,
  7489. renderedParentType: renderedParentType || this.parent.type
  7490. });
  7491. }
  7492. else {
  7493. this.left.render(code, options, { preventASI });
  7494. this.right.render(code, options);
  7495. }
  7496. }
  7497. getUsedBranch() {
  7498. if (!this.isBranchResolutionAnalysed) {
  7499. this.isBranchResolutionAnalysed = true;
  7500. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7501. if (leftValue === UnknownValue) {
  7502. return null;
  7503. }
  7504. else {
  7505. if ((this.operator === '||' && leftValue) ||
  7506. (this.operator === '&&' && !leftValue) ||
  7507. (this.operator === '??' && leftValue != null)) {
  7508. this.usedBranch = this.left;
  7509. this.unusedBranch = this.right;
  7510. }
  7511. else {
  7512. this.usedBranch = this.right;
  7513. this.unusedBranch = this.left;
  7514. }
  7515. }
  7516. }
  7517. return this.usedBranch;
  7518. }
  7519. }
  7520. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  7521. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  7522. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7523. class MetaProperty extends NodeBase {
  7524. addAccessedGlobals(format, accessedGlobalsByScope) {
  7525. const metaProperty = this.metaProperty;
  7526. const accessedGlobals = (metaProperty &&
  7527. (metaProperty.startsWith(FILE_PREFIX) ||
  7528. metaProperty.startsWith(ASSET_PREFIX) ||
  7529. metaProperty.startsWith(CHUNK_PREFIX))
  7530. ? accessedFileUrlGlobals
  7531. : accessedMetaUrlGlobals)[format];
  7532. if (accessedGlobals.length > 0) {
  7533. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7534. }
  7535. }
  7536. getReferencedFileName(outputPluginDriver) {
  7537. const metaProperty = this.metaProperty;
  7538. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  7539. return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
  7540. }
  7541. return null;
  7542. }
  7543. hasEffects() {
  7544. return false;
  7545. }
  7546. hasEffectsWhenAccessedAtPath(path) {
  7547. return path.length > 1;
  7548. }
  7549. include() {
  7550. if (!this.included) {
  7551. this.included = true;
  7552. if (this.meta.name === 'import') {
  7553. this.context.addImportMeta(this);
  7554. const parent = this.parent;
  7555. this.metaProperty =
  7556. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7557. ? parent.propertyKey
  7558. : null;
  7559. }
  7560. }
  7561. }
  7562. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  7563. var _a;
  7564. const parent = this.parent;
  7565. const metaProperty = this.metaProperty;
  7566. if (metaProperty &&
  7567. (metaProperty.startsWith(FILE_PREFIX) ||
  7568. metaProperty.startsWith(ASSET_PREFIX) ||
  7569. metaProperty.startsWith(CHUNK_PREFIX))) {
  7570. let referenceId = null;
  7571. let assetReferenceId = null;
  7572. let chunkReferenceId = null;
  7573. let fileName;
  7574. if (metaProperty.startsWith(FILE_PREFIX)) {
  7575. referenceId = metaProperty.substr(FILE_PREFIX.length);
  7576. fileName = outputPluginDriver.getFileName(referenceId);
  7577. }
  7578. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  7579. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7580. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  7581. fileName = outputPluginDriver.getFileName(assetReferenceId);
  7582. }
  7583. else {
  7584. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  7585. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  7586. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  7587. }
  7588. const relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
  7589. let replacement;
  7590. if (assetReferenceId !== null) {
  7591. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  7592. {
  7593. assetFileName: fileName,
  7594. chunkId,
  7595. format,
  7596. moduleId: this.context.module.id,
  7597. relativeAssetPath: relativePath
  7598. }
  7599. ]);
  7600. }
  7601. if (!replacement) {
  7602. replacement =
  7603. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  7604. {
  7605. assetReferenceId,
  7606. chunkId,
  7607. chunkReferenceId,
  7608. fileName,
  7609. format,
  7610. moduleId: this.context.module.id,
  7611. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  7612. relativePath
  7613. }
  7614. ]) || relativeUrlMechanisms[format](relativePath);
  7615. }
  7616. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7617. return;
  7618. }
  7619. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  7620. metaProperty,
  7621. {
  7622. chunkId,
  7623. format,
  7624. moduleId: this.context.module.id
  7625. }
  7626. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
  7627. if (typeof replacement === 'string') {
  7628. if (parent instanceof MemberExpression) {
  7629. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7630. }
  7631. else {
  7632. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  7633. }
  7634. }
  7635. }
  7636. }
  7637. const accessedMetaUrlGlobals = {
  7638. amd: ['document', 'module', 'URL'],
  7639. cjs: ['document', 'require', 'URL'],
  7640. es: [],
  7641. iife: ['document', 'URL'],
  7642. system: ['module'],
  7643. umd: ['document', 'require', 'URL']
  7644. };
  7645. const accessedFileUrlGlobals = {
  7646. amd: ['document', 'require', 'URL'],
  7647. cjs: ['document', 'require', 'URL'],
  7648. es: [],
  7649. iife: ['document', 'URL'],
  7650. system: ['module', 'URL'],
  7651. umd: ['document', 'require', 'URL']
  7652. };
  7653. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7654. const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
  7655. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  7656. const urlMechanism = getUrl(chunkId);
  7657. return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
  7658. };
  7659. const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  7660. const relativeUrlMechanisms = {
  7661. amd: relativePath => {
  7662. if (relativePath[0] !== '.')
  7663. relativePath = './' + relativePath;
  7664. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  7665. },
  7666. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7667. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  7668. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7669. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  7670. umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
  7671. };
  7672. const importMetaMechanisms = {
  7673. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7674. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  7675. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7676. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  7677. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
  7678. };
  7679. class NewExpression extends NodeBase {
  7680. bind() {
  7681. super.bind();
  7682. for (const argument of this.arguments) {
  7683. // This will make sure all properties of parameters behave as "unknown"
  7684. argument.deoptimizePath(UNKNOWN_PATH);
  7685. }
  7686. }
  7687. hasEffects(context) {
  7688. for (const argument of this.arguments) {
  7689. if (argument.hasEffects(context))
  7690. return true;
  7691. }
  7692. if (this.context.options.treeshake.annotations &&
  7693. this.annotatedPure)
  7694. return false;
  7695. return (this.callee.hasEffects(context) ||
  7696. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  7697. }
  7698. hasEffectsWhenAccessedAtPath(path) {
  7699. return path.length > 1;
  7700. }
  7701. initialise() {
  7702. this.callOptions = {
  7703. args: this.arguments,
  7704. withNew: true
  7705. };
  7706. }
  7707. }
  7708. class ObjectExpression extends NodeBase {
  7709. constructor() {
  7710. super(...arguments);
  7711. this.deoptimizedPaths = new Set();
  7712. // We collect deoptimization information if we can resolve a computed property access
  7713. this.expressionsToBeDeoptimized = new Map();
  7714. this.hasUnknownDeoptimizedProperty = false;
  7715. this.propertyMap = null;
  7716. this.unmatchablePropertiesRead = [];
  7717. this.unmatchablePropertiesWrite = [];
  7718. }
  7719. bind() {
  7720. super.bind();
  7721. // ensure the propertyMap is set for the tree-shaking passes
  7722. this.getPropertyMap();
  7723. }
  7724. // We could also track this per-property but this would quickly become much more complex
  7725. deoptimizeCache() {
  7726. if (!this.hasUnknownDeoptimizedProperty)
  7727. this.deoptimizeAllProperties();
  7728. }
  7729. deoptimizePath(path) {
  7730. if (this.hasUnknownDeoptimizedProperty)
  7731. return;
  7732. const propertyMap = this.getPropertyMap();
  7733. const key = path[0];
  7734. if (path.length === 1) {
  7735. if (typeof key !== 'string') {
  7736. this.deoptimizeAllProperties();
  7737. return;
  7738. }
  7739. if (!this.deoptimizedPaths.has(key)) {
  7740. this.deoptimizedPaths.add(key);
  7741. // we only deoptimizeCache exact matches as in all other cases,
  7742. // we do not return a literal value or return expression
  7743. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  7744. if (expressionsToBeDeoptimized) {
  7745. for (const expression of expressionsToBeDeoptimized) {
  7746. expression.deoptimizeCache();
  7747. }
  7748. }
  7749. }
  7750. }
  7751. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7752. for (const property of typeof key === 'string'
  7753. ? propertyMap[key]
  7754. ? propertyMap[key].propertiesRead
  7755. : []
  7756. : this.properties) {
  7757. property.deoptimizePath(subPath);
  7758. }
  7759. }
  7760. getLiteralValueAtPath(path, recursionTracker, origin) {
  7761. const propertyMap = this.getPropertyMap();
  7762. const key = path[0];
  7763. if (path.length === 0 ||
  7764. this.hasUnknownDeoptimizedProperty ||
  7765. typeof key !== 'string' ||
  7766. this.deoptimizedPaths.has(key)) {
  7767. return UnknownValue;
  7768. }
  7769. if (path.length === 1 &&
  7770. !propertyMap[key] &&
  7771. !objectMembers[key] &&
  7772. this.unmatchablePropertiesRead.length === 0) {
  7773. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7774. return undefined;
  7775. }
  7776. if (!propertyMap[key] ||
  7777. propertyMap[key].exactMatchRead === null ||
  7778. propertyMap[key].propertiesRead.length > 1) {
  7779. return UnknownValue;
  7780. }
  7781. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7782. return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  7783. }
  7784. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7785. const propertyMap = this.getPropertyMap();
  7786. const key = path[0];
  7787. if (path.length === 0 ||
  7788. this.hasUnknownDeoptimizedProperty ||
  7789. typeof key !== 'string' ||
  7790. this.deoptimizedPaths.has(key)) {
  7791. return UNKNOWN_EXPRESSION;
  7792. }
  7793. if (path.length === 1 &&
  7794. objectMembers[key] &&
  7795. this.unmatchablePropertiesRead.length === 0 &&
  7796. (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
  7797. return getMemberReturnExpressionWhenCalled(objectMembers, key);
  7798. }
  7799. if (!propertyMap[key] ||
  7800. propertyMap[key].exactMatchRead === null ||
  7801. propertyMap[key].propertiesRead.length > 1) {
  7802. return UNKNOWN_EXPRESSION;
  7803. }
  7804. getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
  7805. return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
  7806. }
  7807. hasEffectsWhenAccessedAtPath(path, context) {
  7808. if (path.length === 0)
  7809. return false;
  7810. const key = path[0];
  7811. const propertyMap = this.propertyMap;
  7812. if (path.length > 1 &&
  7813. (this.hasUnknownDeoptimizedProperty ||
  7814. typeof key !== 'string' ||
  7815. this.deoptimizedPaths.has(key) ||
  7816. !propertyMap[key] ||
  7817. propertyMap[key].exactMatchRead === null))
  7818. return true;
  7819. const subPath = path.slice(1);
  7820. for (const property of typeof key !== 'string'
  7821. ? this.properties
  7822. : propertyMap[key]
  7823. ? propertyMap[key].propertiesRead
  7824. : []) {
  7825. if (property.hasEffectsWhenAccessedAtPath(subPath, context))
  7826. return true;
  7827. }
  7828. return false;
  7829. }
  7830. hasEffectsWhenAssignedAtPath(path, context) {
  7831. const key = path[0];
  7832. const propertyMap = this.propertyMap;
  7833. if (path.length > 1 &&
  7834. (this.hasUnknownDeoptimizedProperty ||
  7835. this.deoptimizedPaths.has(key) ||
  7836. !propertyMap[key] ||
  7837. propertyMap[key].exactMatchRead === null)) {
  7838. return true;
  7839. }
  7840. const subPath = path.slice(1);
  7841. for (const property of typeof key !== 'string'
  7842. ? this.properties
  7843. : path.length > 1
  7844. ? propertyMap[key].propertiesRead
  7845. : propertyMap[key]
  7846. ? propertyMap[key].propertiesWrite
  7847. : []) {
  7848. if (property.hasEffectsWhenAssignedAtPath(subPath, context))
  7849. return true;
  7850. }
  7851. return false;
  7852. }
  7853. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7854. const key = path[0];
  7855. if (typeof key !== 'string' ||
  7856. this.hasUnknownDeoptimizedProperty ||
  7857. this.deoptimizedPaths.has(key) ||
  7858. (this.propertyMap[key]
  7859. ? !this.propertyMap[key].exactMatchRead
  7860. : path.length > 1 || !objectMembers[key])) {
  7861. return true;
  7862. }
  7863. const subPath = path.slice(1);
  7864. if (this.propertyMap[key]) {
  7865. for (const property of this.propertyMap[key].propertiesRead) {
  7866. if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
  7867. return true;
  7868. }
  7869. }
  7870. if (path.length === 1 && objectMembers[key])
  7871. return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
  7872. return false;
  7873. }
  7874. render(code, options, { renderedParentType, renderedSurroundingElement } = BLANK) {
  7875. super.render(code, options);
  7876. const surroundingElement = renderedParentType || renderedSurroundingElement;
  7877. if (surroundingElement === ExpressionStatement$1 ||
  7878. surroundingElement === ArrowFunctionExpression$1) {
  7879. code.appendRight(this.start, '(');
  7880. code.prependLeft(this.end, ')');
  7881. }
  7882. }
  7883. deoptimizeAllProperties() {
  7884. this.hasUnknownDeoptimizedProperty = true;
  7885. for (const property of this.properties) {
  7886. property.deoptimizePath(UNKNOWN_PATH);
  7887. }
  7888. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
  7889. for (const expression of expressionsToBeDeoptimized) {
  7890. expression.deoptimizeCache();
  7891. }
  7892. }
  7893. }
  7894. getPropertyMap() {
  7895. if (this.propertyMap !== null) {
  7896. return this.propertyMap;
  7897. }
  7898. const propertyMap = (this.propertyMap = Object.create(null));
  7899. for (let index = this.properties.length - 1; index >= 0; index--) {
  7900. const property = this.properties[index];
  7901. if (property instanceof SpreadElement) {
  7902. this.unmatchablePropertiesRead.push(property);
  7903. continue;
  7904. }
  7905. const isWrite = property.kind !== 'get';
  7906. const isRead = property.kind !== 'set';
  7907. let key;
  7908. if (property.computed) {
  7909. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7910. if (keyValue === UnknownValue) {
  7911. if (isRead) {
  7912. this.unmatchablePropertiesRead.push(property);
  7913. }
  7914. else {
  7915. this.unmatchablePropertiesWrite.push(property);
  7916. }
  7917. continue;
  7918. }
  7919. key = String(keyValue);
  7920. }
  7921. else if (property.key instanceof Identifier) {
  7922. key = property.key.name;
  7923. }
  7924. else {
  7925. key = String(property.key.value);
  7926. }
  7927. const propertyMapProperty = propertyMap[key];
  7928. if (!propertyMapProperty) {
  7929. propertyMap[key] = {
  7930. exactMatchRead: isRead ? property : null,
  7931. exactMatchWrite: isWrite ? property : null,
  7932. propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
  7933. propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
  7934. };
  7935. continue;
  7936. }
  7937. if (isRead && propertyMapProperty.exactMatchRead === null) {
  7938. propertyMapProperty.exactMatchRead = property;
  7939. propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
  7940. }
  7941. if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
  7942. propertyMapProperty.exactMatchWrite = property;
  7943. propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
  7944. }
  7945. }
  7946. return propertyMap;
  7947. }
  7948. }
  7949. class ObjectPattern extends NodeBase {
  7950. addExportedVariables(variables, exportNamesByVariable) {
  7951. for (const property of this.properties) {
  7952. if (property.type === Property$1) {
  7953. property.value.addExportedVariables(variables, exportNamesByVariable);
  7954. }
  7955. else {
  7956. property.argument.addExportedVariables(variables, exportNamesByVariable);
  7957. }
  7958. }
  7959. }
  7960. declare(kind, init) {
  7961. const variables = [];
  7962. for (const property of this.properties) {
  7963. variables.push(...property.declare(kind, init));
  7964. }
  7965. return variables;
  7966. }
  7967. deoptimizePath(path) {
  7968. if (path.length === 0) {
  7969. for (const property of this.properties) {
  7970. property.deoptimizePath(path);
  7971. }
  7972. }
  7973. }
  7974. hasEffectsWhenAssignedAtPath(path, context) {
  7975. if (path.length > 0)
  7976. return true;
  7977. for (const property of this.properties) {
  7978. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  7979. return true;
  7980. }
  7981. return false;
  7982. }
  7983. }
  7984. class PrivateIdentifier extends NodeBase {
  7985. }
  7986. class Program extends NodeBase {
  7987. constructor() {
  7988. super(...arguments);
  7989. this.hasCachedEffect = false;
  7990. }
  7991. hasEffects(context) {
  7992. // We are caching here to later more efficiently identify side-effect-free modules
  7993. if (this.hasCachedEffect)
  7994. return true;
  7995. for (const node of this.body) {
  7996. if (node.hasEffects(context)) {
  7997. return (this.hasCachedEffect = true);
  7998. }
  7999. }
  8000. return false;
  8001. }
  8002. include(context, includeChildrenRecursively) {
  8003. this.included = true;
  8004. for (const node of this.body) {
  8005. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  8006. node.include(context, includeChildrenRecursively);
  8007. }
  8008. }
  8009. }
  8010. render(code, options) {
  8011. if (this.body.length) {
  8012. renderStatementList(this.body, code, this.start, this.end, options);
  8013. }
  8014. else {
  8015. super.render(code, options);
  8016. }
  8017. }
  8018. }
  8019. class Property extends NodeBase {
  8020. constructor() {
  8021. super(...arguments);
  8022. this.declarationInit = null;
  8023. this.returnExpression = null;
  8024. }
  8025. bind() {
  8026. super.bind();
  8027. if (this.kind === 'get') {
  8028. // ensure the returnExpression is set for the tree-shaking passes
  8029. this.getReturnExpression();
  8030. }
  8031. if (this.declarationInit !== null) {
  8032. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8033. }
  8034. }
  8035. declare(kind, init) {
  8036. this.declarationInit = init;
  8037. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  8038. }
  8039. // As getter properties directly receive their values from function expressions that always
  8040. // have a fixed return value, there is no known situation where a getter is deoptimized.
  8041. deoptimizeCache() { }
  8042. deoptimizePath(path) {
  8043. if (this.kind === 'get') {
  8044. this.getReturnExpression().deoptimizePath(path);
  8045. }
  8046. else {
  8047. this.value.deoptimizePath(path);
  8048. }
  8049. }
  8050. getLiteralValueAtPath(path, recursionTracker, origin) {
  8051. if (this.kind === 'get') {
  8052. return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
  8053. }
  8054. return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
  8055. }
  8056. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  8057. if (this.kind === 'get') {
  8058. return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  8059. }
  8060. return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  8061. }
  8062. hasEffects(context) {
  8063. return this.key.hasEffects(context) || this.value.hasEffects(context);
  8064. }
  8065. hasEffectsWhenAccessedAtPath(path, context) {
  8066. if (this.kind === 'get') {
  8067. const trackedExpressions = context.accessed.getEntities(path);
  8068. if (trackedExpressions.has(this))
  8069. return false;
  8070. trackedExpressions.add(this);
  8071. return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
  8072. (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
  8073. }
  8074. return this.value.hasEffectsWhenAccessedAtPath(path, context);
  8075. }
  8076. hasEffectsWhenAssignedAtPath(path, context) {
  8077. if (this.kind === 'get') {
  8078. const trackedExpressions = context.assigned.getEntities(path);
  8079. if (trackedExpressions.has(this))
  8080. return false;
  8081. trackedExpressions.add(this);
  8082. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  8083. }
  8084. if (this.kind === 'set') {
  8085. const trackedExpressions = context.assigned.getEntities(path);
  8086. if (trackedExpressions.has(this))
  8087. return false;
  8088. trackedExpressions.add(this);
  8089. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  8090. }
  8091. return this.value.hasEffectsWhenAssignedAtPath(path, context);
  8092. }
  8093. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8094. if (this.kind === 'get') {
  8095. const trackedExpressions = (callOptions.withNew
  8096. ? context.instantiated
  8097. : context.called).getEntities(path, callOptions);
  8098. if (trackedExpressions.has(this))
  8099. return false;
  8100. trackedExpressions.add(this);
  8101. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8102. }
  8103. return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8104. }
  8105. initialise() {
  8106. this.accessorCallOptions = {
  8107. args: NO_ARGS,
  8108. withNew: false
  8109. };
  8110. }
  8111. render(code, options) {
  8112. if (!this.shorthand) {
  8113. this.key.render(code, options);
  8114. }
  8115. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  8116. }
  8117. getReturnExpression() {
  8118. if (this.returnExpression === null) {
  8119. this.returnExpression = UNKNOWN_EXPRESSION;
  8120. return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  8121. }
  8122. return this.returnExpression;
  8123. }
  8124. }
  8125. class PropertyDefinition extends NodeBase {
  8126. hasEffects(context) {
  8127. return (this.key.hasEffects(context) ||
  8128. (this.static && this.value !== null && this.value.hasEffects(context)));
  8129. }
  8130. }
  8131. class ReturnStatement extends NodeBase {
  8132. hasEffects(context) {
  8133. if (!context.ignore.returnAwaitYield ||
  8134. (this.argument !== null && this.argument.hasEffects(context)))
  8135. return true;
  8136. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8137. return false;
  8138. }
  8139. include(context, includeChildrenRecursively) {
  8140. this.included = true;
  8141. if (this.argument) {
  8142. this.argument.include(context, includeChildrenRecursively);
  8143. }
  8144. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8145. }
  8146. initialise() {
  8147. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  8148. }
  8149. render(code, options) {
  8150. if (this.argument) {
  8151. this.argument.render(code, options, { preventASI: true });
  8152. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8153. code.prependLeft(this.start + 6, ' ');
  8154. }
  8155. }
  8156. }
  8157. }
  8158. class SequenceExpression extends NodeBase {
  8159. deoptimizePath(path) {
  8160. if (path.length > 0)
  8161. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8162. }
  8163. getLiteralValueAtPath(path, recursionTracker, origin) {
  8164. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8165. }
  8166. hasEffects(context) {
  8167. for (const expression of this.expressions) {
  8168. if (expression.hasEffects(context))
  8169. return true;
  8170. }
  8171. return false;
  8172. }
  8173. hasEffectsWhenAccessedAtPath(path, context) {
  8174. return (path.length > 0 &&
  8175. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8176. }
  8177. hasEffectsWhenAssignedAtPath(path, context) {
  8178. return (path.length === 0 ||
  8179. this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
  8180. }
  8181. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8182. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8183. }
  8184. include(context, includeChildrenRecursively) {
  8185. this.included = true;
  8186. for (let i = 0; i < this.expressions.length - 1; i++) {
  8187. const node = this.expressions[i];
  8188. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8189. node.include(context, includeChildrenRecursively);
  8190. }
  8191. this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
  8192. }
  8193. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8194. let includedNodes = 0;
  8195. for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8196. if (!node.included) {
  8197. treeshakeNode(node, code, start, end);
  8198. continue;
  8199. }
  8200. includedNodes++;
  8201. if (includedNodes === 1 && preventASI) {
  8202. removeLineBreaks(code, start, node.start);
  8203. }
  8204. if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
  8205. node.render(code, options, {
  8206. isCalleeOfRenderedParent: renderedParentType
  8207. ? isCalleeOfRenderedParent
  8208. : this.parent.callee === this,
  8209. renderedParentType: renderedParentType || this.parent.type
  8210. });
  8211. }
  8212. else {
  8213. node.render(code, options);
  8214. }
  8215. }
  8216. }
  8217. }
  8218. class Super extends NodeBase {
  8219. }
  8220. class SwitchCase extends NodeBase {
  8221. hasEffects(context) {
  8222. if (this.test && this.test.hasEffects(context))
  8223. return true;
  8224. for (const node of this.consequent) {
  8225. if (context.brokenFlow)
  8226. break;
  8227. if (node.hasEffects(context))
  8228. return true;
  8229. }
  8230. return false;
  8231. }
  8232. include(context, includeChildrenRecursively) {
  8233. this.included = true;
  8234. if (this.test)
  8235. this.test.include(context, includeChildrenRecursively);
  8236. for (const node of this.consequent) {
  8237. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8238. node.include(context, includeChildrenRecursively);
  8239. }
  8240. }
  8241. render(code, options, nodeRenderOptions) {
  8242. if (this.consequent.length) {
  8243. this.test && this.test.render(code, options);
  8244. const testEnd = this.test
  8245. ? this.test.end
  8246. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8247. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8248. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8249. }
  8250. else {
  8251. super.render(code, options);
  8252. }
  8253. }
  8254. }
  8255. SwitchCase.prototype.needsBoundaries = true;
  8256. class SwitchStatement extends NodeBase {
  8257. createScope(parentScope) {
  8258. this.scope = new BlockScope(parentScope);
  8259. }
  8260. hasEffects(context) {
  8261. if (this.discriminant.hasEffects(context))
  8262. return true;
  8263. const { brokenFlow, ignore: { breaks } } = context;
  8264. let minBrokenFlow = Infinity;
  8265. context.ignore.breaks = true;
  8266. for (const switchCase of this.cases) {
  8267. if (switchCase.hasEffects(context))
  8268. return true;
  8269. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8270. context.brokenFlow = brokenFlow;
  8271. }
  8272. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8273. context.brokenFlow = minBrokenFlow;
  8274. }
  8275. context.ignore.breaks = breaks;
  8276. return false;
  8277. }
  8278. include(context, includeChildrenRecursively) {
  8279. this.included = true;
  8280. this.discriminant.include(context, includeChildrenRecursively);
  8281. const { brokenFlow } = context;
  8282. let minBrokenFlow = Infinity;
  8283. let isCaseIncluded = includeChildrenRecursively ||
  8284. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8285. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8286. const switchCase = this.cases[caseIndex];
  8287. if (switchCase.included) {
  8288. isCaseIncluded = true;
  8289. }
  8290. if (!isCaseIncluded) {
  8291. const hasEffectsContext = createHasEffectsContext();
  8292. hasEffectsContext.ignore.breaks = true;
  8293. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8294. }
  8295. if (isCaseIncluded) {
  8296. switchCase.include(context, includeChildrenRecursively);
  8297. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8298. context.brokenFlow = brokenFlow;
  8299. }
  8300. else {
  8301. minBrokenFlow = brokenFlow;
  8302. }
  8303. }
  8304. if (isCaseIncluded &&
  8305. this.defaultCase !== null &&
  8306. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8307. context.brokenFlow = minBrokenFlow;
  8308. }
  8309. }
  8310. initialise() {
  8311. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8312. if (this.cases[caseIndex].test === null) {
  8313. this.defaultCase = caseIndex;
  8314. return;
  8315. }
  8316. }
  8317. this.defaultCase = null;
  8318. }
  8319. render(code, options) {
  8320. this.discriminant.render(code, options);
  8321. if (this.cases.length > 0) {
  8322. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8323. }
  8324. }
  8325. }
  8326. class TaggedTemplateExpression extends NodeBase {
  8327. bind() {
  8328. super.bind();
  8329. if (this.tag.type === Identifier$1) {
  8330. const name = this.tag.name;
  8331. const variable = this.scope.findVariable(name);
  8332. if (variable.isNamespace) {
  8333. this.context.warn({
  8334. code: 'CANNOT_CALL_NAMESPACE',
  8335. message: `Cannot call a namespace ('${name}')`,
  8336. }, this.start);
  8337. }
  8338. if (name === 'eval') {
  8339. this.context.warn({
  8340. code: 'EVAL',
  8341. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8342. url: 'https://rollupjs.org/guide/en/#avoiding-eval',
  8343. }, this.start);
  8344. }
  8345. }
  8346. }
  8347. hasEffects(context) {
  8348. return (super.hasEffects(context) ||
  8349. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8350. }
  8351. initialise() {
  8352. this.callOptions = {
  8353. args: NO_ARGS,
  8354. withNew: false,
  8355. };
  8356. }
  8357. }
  8358. class TemplateElement extends NodeBase {
  8359. bind() { }
  8360. hasEffects() {
  8361. return false;
  8362. }
  8363. include() {
  8364. this.included = true;
  8365. }
  8366. parseNode(esTreeNode) {
  8367. this.value = esTreeNode.value;
  8368. super.parseNode(esTreeNode);
  8369. }
  8370. render() { }
  8371. }
  8372. class TemplateLiteral extends NodeBase {
  8373. getLiteralValueAtPath(path) {
  8374. if (path.length > 0 || this.quasis.length !== 1) {
  8375. return UnknownValue;
  8376. }
  8377. return this.quasis[0].value.cooked;
  8378. }
  8379. render(code, options) {
  8380. code.indentExclusionRanges.push([this.start, this.end]);
  8381. super.render(code, options);
  8382. }
  8383. }
  8384. class ModuleScope extends ChildScope {
  8385. constructor(parent, context) {
  8386. super(parent);
  8387. this.context = context;
  8388. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8389. }
  8390. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8391. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8392. this.variables.set('default', variable);
  8393. return variable;
  8394. }
  8395. addNamespaceMemberAccess() { }
  8396. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8397. // all module level variables are already deconflicted when deconflicting the chunk
  8398. for (const scope of this.children)
  8399. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8400. }
  8401. findLexicalBoundary() {
  8402. return this;
  8403. }
  8404. findVariable(name) {
  8405. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8406. if (knownVariable) {
  8407. return knownVariable;
  8408. }
  8409. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8410. if (variable instanceof GlobalVariable) {
  8411. this.accessedOutsideVariables.set(name, variable);
  8412. }
  8413. return variable;
  8414. }
  8415. }
  8416. class ThisExpression extends NodeBase {
  8417. bind() {
  8418. super.bind();
  8419. this.variable = this.scope.findVariable('this');
  8420. }
  8421. hasEffectsWhenAccessedAtPath(path, context) {
  8422. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8423. }
  8424. hasEffectsWhenAssignedAtPath(path, context) {
  8425. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8426. }
  8427. initialise() {
  8428. this.alias =
  8429. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8430. if (this.alias === 'undefined') {
  8431. this.context.warn({
  8432. code: 'THIS_IS_UNDEFINED',
  8433. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8434. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8435. }, this.start);
  8436. }
  8437. }
  8438. render(code) {
  8439. if (this.alias !== null) {
  8440. code.overwrite(this.start, this.end, this.alias, {
  8441. contentOnly: false,
  8442. storeName: true
  8443. });
  8444. }
  8445. }
  8446. }
  8447. class ThrowStatement extends NodeBase {
  8448. hasEffects() {
  8449. return true;
  8450. }
  8451. include(context, includeChildrenRecursively) {
  8452. this.included = true;
  8453. this.argument.include(context, includeChildrenRecursively);
  8454. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8455. }
  8456. render(code, options) {
  8457. this.argument.render(code, options, { preventASI: true });
  8458. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8459. code.prependLeft(this.start + 5, ' ');
  8460. }
  8461. }
  8462. }
  8463. class TryStatement extends NodeBase {
  8464. constructor() {
  8465. super(...arguments);
  8466. this.directlyIncluded = false;
  8467. this.includedLabelsAfterBlock = null;
  8468. }
  8469. hasEffects(context) {
  8470. return ((this.context.options.treeshake.tryCatchDeoptimization
  8471. ? this.block.body.length > 0
  8472. : this.block.hasEffects(context)) ||
  8473. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8474. }
  8475. include(context, includeChildrenRecursively) {
  8476. var _a;
  8477. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  8478. const { brokenFlow } = context;
  8479. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  8480. this.included = true;
  8481. this.directlyIncluded = true;
  8482. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8483. if (context.includedLabels.size > 0) {
  8484. this.includedLabelsAfterBlock = [...context.includedLabels];
  8485. }
  8486. context.brokenFlow = brokenFlow;
  8487. }
  8488. else if (this.includedLabelsAfterBlock) {
  8489. for (const label of this.includedLabelsAfterBlock) {
  8490. context.includedLabels.add(label);
  8491. }
  8492. }
  8493. if (this.handler !== null) {
  8494. this.handler.include(context, includeChildrenRecursively);
  8495. context.brokenFlow = brokenFlow;
  8496. }
  8497. if (this.finalizer !== null) {
  8498. this.finalizer.include(context, includeChildrenRecursively);
  8499. }
  8500. }
  8501. }
  8502. const unaryOperators = {
  8503. '!': value => !value,
  8504. '+': value => +value,
  8505. '-': value => -value,
  8506. delete: () => UnknownValue,
  8507. typeof: value => typeof value,
  8508. void: () => undefined,
  8509. '~': value => ~value
  8510. };
  8511. class UnaryExpression extends NodeBase {
  8512. bind() {
  8513. super.bind();
  8514. if (this.operator === 'delete') {
  8515. this.argument.deoptimizePath(EMPTY_PATH);
  8516. }
  8517. }
  8518. getLiteralValueAtPath(path, recursionTracker, origin) {
  8519. if (path.length > 0)
  8520. return UnknownValue;
  8521. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8522. if (argumentValue === UnknownValue)
  8523. return UnknownValue;
  8524. return unaryOperators[this.operator](argumentValue);
  8525. }
  8526. hasEffects(context) {
  8527. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  8528. return false;
  8529. return (this.argument.hasEffects(context) ||
  8530. (this.operator === 'delete' &&
  8531. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8532. }
  8533. hasEffectsWhenAccessedAtPath(path) {
  8534. if (this.operator === 'void') {
  8535. return path.length > 0;
  8536. }
  8537. return path.length > 1;
  8538. }
  8539. }
  8540. class UnknownNode extends NodeBase {
  8541. hasEffects() {
  8542. return true;
  8543. }
  8544. include(context) {
  8545. super.include(context, true);
  8546. }
  8547. }
  8548. class UpdateExpression extends NodeBase {
  8549. bind() {
  8550. super.bind();
  8551. this.argument.deoptimizePath(EMPTY_PATH);
  8552. if (this.argument instanceof Identifier) {
  8553. const variable = this.scope.findVariable(this.argument.name);
  8554. variable.isReassigned = true;
  8555. }
  8556. }
  8557. hasEffects(context) {
  8558. return (this.argument.hasEffects(context) ||
  8559. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8560. }
  8561. hasEffectsWhenAccessedAtPath(path) {
  8562. return path.length > 1;
  8563. }
  8564. render(code, options) {
  8565. this.argument.render(code, options);
  8566. if (options.format === 'system') {
  8567. const variable = this.argument.variable;
  8568. const exportNames = options.exportNamesByVariable.get(variable);
  8569. if (exportNames && exportNames.length) {
  8570. const _ = options.compact ? '' : ' ';
  8571. const name = variable.getName();
  8572. if (this.prefix) {
  8573. if (exportNames.length === 1) {
  8574. code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
  8575. }
  8576. else {
  8577. code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
  8578. }
  8579. }
  8580. else if (exportNames.length > 1) {
  8581. code.overwrite(this.start, this.end, `(${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name}))`);
  8582. }
  8583. else {
  8584. let op;
  8585. switch (this.operator) {
  8586. case '++':
  8587. op = `${name}${_}+${_}1`;
  8588. break;
  8589. case '--':
  8590. op = `${name}${_}-${_}1`;
  8591. break;
  8592. }
  8593. code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
  8594. }
  8595. }
  8596. }
  8597. }
  8598. }
  8599. function isReassignedExportsMember(variable, exportNamesByVariable) {
  8600. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  8601. }
  8602. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  8603. for (const declarator of declarations) {
  8604. if (!declarator.id.included)
  8605. return false;
  8606. if (declarator.id.type === Identifier$1) {
  8607. if (exportNamesByVariable.has(declarator.id.variable))
  8608. return false;
  8609. }
  8610. else {
  8611. const exportedVariables = [];
  8612. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  8613. if (exportedVariables.length > 0)
  8614. return false;
  8615. }
  8616. }
  8617. return true;
  8618. }
  8619. class VariableDeclaration extends NodeBase {
  8620. deoptimizePath() {
  8621. for (const declarator of this.declarations) {
  8622. declarator.deoptimizePath(EMPTY_PATH);
  8623. }
  8624. }
  8625. hasEffectsWhenAssignedAtPath() {
  8626. return false;
  8627. }
  8628. include(context, includeChildrenRecursively) {
  8629. this.included = true;
  8630. for (const declarator of this.declarations) {
  8631. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  8632. declarator.include(context, includeChildrenRecursively);
  8633. }
  8634. }
  8635. includeAsSingleStatement(context, includeChildrenRecursively) {
  8636. this.included = true;
  8637. for (const declarator of this.declarations) {
  8638. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  8639. declarator.include(context, includeChildrenRecursively);
  8640. declarator.id.include(context, includeChildrenRecursively);
  8641. }
  8642. }
  8643. }
  8644. initialise() {
  8645. for (const declarator of this.declarations) {
  8646. declarator.declareDeclarator(this.kind);
  8647. }
  8648. }
  8649. render(code, options, nodeRenderOptions = BLANK) {
  8650. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  8651. for (const declarator of this.declarations) {
  8652. declarator.render(code, options);
  8653. }
  8654. if (!nodeRenderOptions.isNoStatement &&
  8655. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  8656. code.appendLeft(this.end, ';');
  8657. }
  8658. }
  8659. else {
  8660. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  8661. }
  8662. }
  8663. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement) {
  8664. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  8665. code.remove(this.end - 1, this.end);
  8666. }
  8667. if (!isNoStatement) {
  8668. separatorString += ';';
  8669. }
  8670. if (lastSeparatorPos !== null) {
  8671. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  8672. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  8673. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  8674. actualContentEnd--;
  8675. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  8676. actualContentEnd--;
  8677. }
  8678. }
  8679. if (actualContentEnd === lastSeparatorPos + 1) {
  8680. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  8681. }
  8682. else {
  8683. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8684. code.remove(actualContentEnd, renderedContentEnd);
  8685. }
  8686. }
  8687. else {
  8688. code.appendLeft(renderedContentEnd, separatorString);
  8689. }
  8690. if (systemPatternExports.length > 0) {
  8691. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  8692. }
  8693. }
  8694. renderReplacedDeclarations(code, options, { isNoStatement }) {
  8695. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  8696. let actualContentEnd, renderedContentEnd;
  8697. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  8698. let lastSeparatorPos = renderedContentEnd - 1;
  8699. code.remove(this.start, lastSeparatorPos);
  8700. let isInDeclaration = false;
  8701. let hasRenderedContent = false;
  8702. let separatorString = '', leadingString, nextSeparatorString;
  8703. const systemPatternExports = [];
  8704. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  8705. if (!node.included) {
  8706. code.remove(start, end);
  8707. continue;
  8708. }
  8709. leadingString = '';
  8710. nextSeparatorString = '';
  8711. if (!node.id.included ||
  8712. (node.id instanceof Identifier &&
  8713. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  8714. if (hasRenderedContent) {
  8715. separatorString += ';';
  8716. }
  8717. isInDeclaration = false;
  8718. }
  8719. else {
  8720. if (options.format === 'system' && node.init !== null) {
  8721. if (node.id.type !== Identifier$1) {
  8722. node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8723. }
  8724. else {
  8725. const exportNames = options.exportNamesByVariable.get(node.id.variable);
  8726. if (exportNames) {
  8727. const _ = options.compact ? '' : ' ';
  8728. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  8729. code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
  8730. ? `exports('${exportNames[0]}',${_}`
  8731. : getSystemExportFunctionLeft([node.id.variable], false, options));
  8732. nextSeparatorString += ')';
  8733. }
  8734. }
  8735. }
  8736. if (isInDeclaration) {
  8737. separatorString += ',';
  8738. }
  8739. else {
  8740. if (hasRenderedContent) {
  8741. separatorString += ';';
  8742. }
  8743. leadingString += `${this.kind} `;
  8744. isInDeclaration = true;
  8745. }
  8746. }
  8747. if (renderedContentEnd === lastSeparatorPos + 1) {
  8748. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  8749. }
  8750. else {
  8751. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8752. code.appendLeft(renderedContentEnd, leadingString);
  8753. }
  8754. node.render(code, options);
  8755. actualContentEnd = contentEnd;
  8756. renderedContentEnd = end;
  8757. hasRenderedContent = true;
  8758. lastSeparatorPos = separator;
  8759. separatorString = nextSeparatorString;
  8760. }
  8761. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement);
  8762. }
  8763. }
  8764. class VariableDeclarator extends NodeBase {
  8765. declareDeclarator(kind) {
  8766. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8767. }
  8768. deoptimizePath(path) {
  8769. this.id.deoptimizePath(path);
  8770. }
  8771. hasEffects(context) {
  8772. return this.id.hasEffects(context) || (this.init !== null && this.init.hasEffects(context));
  8773. }
  8774. include(context, includeChildrenRecursively) {
  8775. this.included = true;
  8776. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  8777. this.id.include(context, includeChildrenRecursively);
  8778. }
  8779. if (this.init) {
  8780. this.init.include(context, includeChildrenRecursively);
  8781. }
  8782. }
  8783. render(code, options) {
  8784. const renderId = this.id.included;
  8785. if (renderId) {
  8786. this.id.render(code, options);
  8787. }
  8788. else {
  8789. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  8790. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  8791. }
  8792. if (this.init) {
  8793. this.init.render(code, options, renderId ? BLANK : { renderedParentType: ExpressionStatement$1 });
  8794. }
  8795. else if (this.id instanceof Identifier &&
  8796. isReassignedExportsMember(this.id.variable, options.exportNamesByVariable)) {
  8797. const _ = options.compact ? '' : ' ';
  8798. code.appendLeft(this.end, `${_}=${_}void 0`);
  8799. }
  8800. }
  8801. }
  8802. class WhileStatement extends NodeBase {
  8803. hasEffects(context) {
  8804. if (this.test.hasEffects(context))
  8805. return true;
  8806. const { brokenFlow, ignore: { breaks, continues } } = context;
  8807. context.ignore.breaks = true;
  8808. context.ignore.continues = true;
  8809. if (this.body.hasEffects(context))
  8810. return true;
  8811. context.ignore.breaks = breaks;
  8812. context.ignore.continues = continues;
  8813. context.brokenFlow = brokenFlow;
  8814. return false;
  8815. }
  8816. include(context, includeChildrenRecursively) {
  8817. this.included = true;
  8818. this.test.include(context, includeChildrenRecursively);
  8819. const { brokenFlow } = context;
  8820. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  8821. context.brokenFlow = brokenFlow;
  8822. }
  8823. }
  8824. class YieldExpression extends NodeBase {
  8825. bind() {
  8826. super.bind();
  8827. if (this.argument !== null) {
  8828. this.argument.deoptimizePath(UNKNOWN_PATH);
  8829. }
  8830. }
  8831. hasEffects(context) {
  8832. return (!context.ignore.returnAwaitYield ||
  8833. (this.argument !== null && this.argument.hasEffects(context)));
  8834. }
  8835. render(code, options) {
  8836. if (this.argument) {
  8837. this.argument.render(code, options, { preventASI: true });
  8838. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  8839. code.prependLeft(this.start + 5, ' ');
  8840. }
  8841. }
  8842. }
  8843. }
  8844. const nodeConstructors = {
  8845. ArrayExpression,
  8846. ArrayPattern,
  8847. ArrowFunctionExpression,
  8848. AssignmentExpression,
  8849. AssignmentPattern,
  8850. AwaitExpression,
  8851. BinaryExpression,
  8852. BlockStatement,
  8853. BreakStatement,
  8854. CallExpression,
  8855. CatchClause,
  8856. ChainExpression,
  8857. ClassBody,
  8858. ClassDeclaration,
  8859. ClassExpression,
  8860. ConditionalExpression,
  8861. ContinueStatement,
  8862. DoWhileStatement,
  8863. EmptyStatement,
  8864. ExportAllDeclaration,
  8865. ExportDefaultDeclaration,
  8866. ExportNamedDeclaration,
  8867. ExportSpecifier,
  8868. ExpressionStatement,
  8869. ForInStatement,
  8870. ForOfStatement,
  8871. ForStatement,
  8872. FunctionDeclaration,
  8873. FunctionExpression,
  8874. Identifier,
  8875. IfStatement,
  8876. ImportDeclaration,
  8877. ImportDefaultSpecifier,
  8878. ImportExpression,
  8879. ImportNamespaceSpecifier,
  8880. ImportSpecifier,
  8881. LabeledStatement,
  8882. Literal,
  8883. LogicalExpression,
  8884. MemberExpression,
  8885. MetaProperty,
  8886. MethodDefinition,
  8887. NewExpression,
  8888. ObjectExpression,
  8889. ObjectPattern,
  8890. PrivateIdentifier,
  8891. Program,
  8892. Property,
  8893. PropertyDefinition,
  8894. RestElement,
  8895. ReturnStatement,
  8896. SequenceExpression,
  8897. SpreadElement,
  8898. Super,
  8899. SwitchCase,
  8900. SwitchStatement,
  8901. TaggedTemplateExpression,
  8902. TemplateElement,
  8903. TemplateLiteral,
  8904. ThisExpression,
  8905. ThrowStatement,
  8906. TryStatement,
  8907. UnaryExpression,
  8908. UnknownNode,
  8909. UpdateExpression,
  8910. VariableDeclaration,
  8911. VariableDeclarator,
  8912. WhileStatement,
  8913. YieldExpression
  8914. };
  8915. function getId(m) {
  8916. return m.id;
  8917. }
  8918. function getOriginalLocation(sourcemapChain, location) {
  8919. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  8920. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  8921. while (filteredSourcemapChain.length > 0) {
  8922. const sourcemap = filteredSourcemapChain.pop();
  8923. const line = sourcemap.mappings[location.line - 1];
  8924. let locationFound = false;
  8925. if (line !== undefined) {
  8926. for (const segment of line) {
  8927. if (segment[0] >= location.column) {
  8928. if (segment.length === 1)
  8929. break;
  8930. location = {
  8931. column: segment[3],
  8932. line: segment[2] + 1,
  8933. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  8934. source: sourcemap.sources[segment[1]]
  8935. };
  8936. locationFound = true;
  8937. break;
  8938. }
  8939. }
  8940. }
  8941. if (!locationFound) {
  8942. throw new Error("Can't resolve original location of error.");
  8943. }
  8944. }
  8945. return location;
  8946. }
  8947. // AST walker module for Mozilla Parser API compatible trees
  8948. function skipThrough(node, st, c) { c(node, st); }
  8949. function ignore(_node, _st, _c) {}
  8950. // Node walkers.
  8951. var base = {};
  8952. base.Program = base.BlockStatement = function (node, st, c) {
  8953. for (var i = 0, list = node.body; i < list.length; i += 1)
  8954. {
  8955. var stmt = list[i];
  8956. c(stmt, st, "Statement");
  8957. }
  8958. };
  8959. base.Statement = skipThrough;
  8960. base.EmptyStatement = ignore;
  8961. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  8962. function (node, st, c) { return c(node.expression, st, "Expression"); };
  8963. base.IfStatement = function (node, st, c) {
  8964. c(node.test, st, "Expression");
  8965. c(node.consequent, st, "Statement");
  8966. if (node.alternate) { c(node.alternate, st, "Statement"); }
  8967. };
  8968. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  8969. base.BreakStatement = base.ContinueStatement = ignore;
  8970. base.WithStatement = function (node, st, c) {
  8971. c(node.object, st, "Expression");
  8972. c(node.body, st, "Statement");
  8973. };
  8974. base.SwitchStatement = function (node, st, c) {
  8975. c(node.discriminant, st, "Expression");
  8976. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  8977. var cs = list$1[i$1];
  8978. if (cs.test) { c(cs.test, st, "Expression"); }
  8979. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  8980. {
  8981. var cons = list[i];
  8982. c(cons, st, "Statement");
  8983. }
  8984. }
  8985. };
  8986. base.SwitchCase = function (node, st, c) {
  8987. if (node.test) { c(node.test, st, "Expression"); }
  8988. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  8989. {
  8990. var cons = list[i];
  8991. c(cons, st, "Statement");
  8992. }
  8993. };
  8994. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  8995. if (node.argument) { c(node.argument, st, "Expression"); }
  8996. };
  8997. base.ThrowStatement = base.SpreadElement =
  8998. function (node, st, c) { return c(node.argument, st, "Expression"); };
  8999. base.TryStatement = function (node, st, c) {
  9000. c(node.block, st, "Statement");
  9001. if (node.handler) { c(node.handler, st); }
  9002. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  9003. };
  9004. base.CatchClause = function (node, st, c) {
  9005. if (node.param) { c(node.param, st, "Pattern"); }
  9006. c(node.body, st, "Statement");
  9007. };
  9008. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  9009. c(node.test, st, "Expression");
  9010. c(node.body, st, "Statement");
  9011. };
  9012. base.ForStatement = function (node, st, c) {
  9013. if (node.init) { c(node.init, st, "ForInit"); }
  9014. if (node.test) { c(node.test, st, "Expression"); }
  9015. if (node.update) { c(node.update, st, "Expression"); }
  9016. c(node.body, st, "Statement");
  9017. };
  9018. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  9019. c(node.left, st, "ForInit");
  9020. c(node.right, st, "Expression");
  9021. c(node.body, st, "Statement");
  9022. };
  9023. base.ForInit = function (node, st, c) {
  9024. if (node.type === "VariableDeclaration") { c(node, st); }
  9025. else { c(node, st, "Expression"); }
  9026. };
  9027. base.DebuggerStatement = ignore;
  9028. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  9029. base.VariableDeclaration = function (node, st, c) {
  9030. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  9031. {
  9032. var decl = list[i];
  9033. c(decl, st);
  9034. }
  9035. };
  9036. base.VariableDeclarator = function (node, st, c) {
  9037. c(node.id, st, "Pattern");
  9038. if (node.init) { c(node.init, st, "Expression"); }
  9039. };
  9040. base.Function = function (node, st, c) {
  9041. if (node.id) { c(node.id, st, "Pattern"); }
  9042. for (var i = 0, list = node.params; i < list.length; i += 1)
  9043. {
  9044. var param = list[i];
  9045. c(param, st, "Pattern");
  9046. }
  9047. c(node.body, st, node.expression ? "Expression" : "Statement");
  9048. };
  9049. base.Pattern = function (node, st, c) {
  9050. if (node.type === "Identifier")
  9051. { c(node, st, "VariablePattern"); }
  9052. else if (node.type === "MemberExpression")
  9053. { c(node, st, "MemberPattern"); }
  9054. else
  9055. { c(node, st); }
  9056. };
  9057. base.VariablePattern = ignore;
  9058. base.MemberPattern = skipThrough;
  9059. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  9060. base.ArrayPattern = function (node, st, c) {
  9061. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  9062. var elt = list[i];
  9063. if (elt) { c(elt, st, "Pattern"); }
  9064. }
  9065. };
  9066. base.ObjectPattern = function (node, st, c) {
  9067. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  9068. var prop = list[i];
  9069. if (prop.type === "Property") {
  9070. if (prop.computed) { c(prop.key, st, "Expression"); }
  9071. c(prop.value, st, "Pattern");
  9072. } else if (prop.type === "RestElement") {
  9073. c(prop.argument, st, "Pattern");
  9074. }
  9075. }
  9076. };
  9077. base.Expression = skipThrough;
  9078. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  9079. base.ArrayExpression = function (node, st, c) {
  9080. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  9081. var elt = list[i];
  9082. if (elt) { c(elt, st, "Expression"); }
  9083. }
  9084. };
  9085. base.ObjectExpression = function (node, st, c) {
  9086. for (var i = 0, list = node.properties; i < list.length; i += 1)
  9087. {
  9088. var prop = list[i];
  9089. c(prop, st);
  9090. }
  9091. };
  9092. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  9093. base.SequenceExpression = function (node, st, c) {
  9094. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  9095. {
  9096. var expr = list[i];
  9097. c(expr, st, "Expression");
  9098. }
  9099. };
  9100. base.TemplateLiteral = function (node, st, c) {
  9101. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  9102. {
  9103. var quasi = list[i];
  9104. c(quasi, st);
  9105. }
  9106. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  9107. {
  9108. var expr = list$1[i$1];
  9109. c(expr, st, "Expression");
  9110. }
  9111. };
  9112. base.TemplateElement = ignore;
  9113. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  9114. c(node.argument, st, "Expression");
  9115. };
  9116. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  9117. c(node.left, st, "Expression");
  9118. c(node.right, st, "Expression");
  9119. };
  9120. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  9121. c(node.left, st, "Pattern");
  9122. c(node.right, st, "Expression");
  9123. };
  9124. base.ConditionalExpression = function (node, st, c) {
  9125. c(node.test, st, "Expression");
  9126. c(node.consequent, st, "Expression");
  9127. c(node.alternate, st, "Expression");
  9128. };
  9129. base.NewExpression = base.CallExpression = function (node, st, c) {
  9130. c(node.callee, st, "Expression");
  9131. if (node.arguments)
  9132. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  9133. {
  9134. var arg = list[i];
  9135. c(arg, st, "Expression");
  9136. } }
  9137. };
  9138. base.MemberExpression = function (node, st, c) {
  9139. c(node.object, st, "Expression");
  9140. if (node.computed) { c(node.property, st, "Expression"); }
  9141. };
  9142. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  9143. if (node.declaration)
  9144. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  9145. if (node.source) { c(node.source, st, "Expression"); }
  9146. };
  9147. base.ExportAllDeclaration = function (node, st, c) {
  9148. if (node.exported)
  9149. { c(node.exported, st); }
  9150. c(node.source, st, "Expression");
  9151. };
  9152. base.ImportDeclaration = function (node, st, c) {
  9153. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  9154. {
  9155. var spec = list[i];
  9156. c(spec, st);
  9157. }
  9158. c(node.source, st, "Expression");
  9159. };
  9160. base.ImportExpression = function (node, st, c) {
  9161. c(node.source, st, "Expression");
  9162. };
  9163. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
  9164. base.TaggedTemplateExpression = function (node, st, c) {
  9165. c(node.tag, st, "Expression");
  9166. c(node.quasi, st, "Expression");
  9167. };
  9168. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  9169. base.Class = function (node, st, c) {
  9170. if (node.id) { c(node.id, st, "Pattern"); }
  9171. if (node.superClass) { c(node.superClass, st, "Expression"); }
  9172. c(node.body, st);
  9173. };
  9174. base.ClassBody = function (node, st, c) {
  9175. for (var i = 0, list = node.body; i < list.length; i += 1)
  9176. {
  9177. var elt = list[i];
  9178. c(elt, st);
  9179. }
  9180. };
  9181. base.MethodDefinition = base.Property = function (node, st, c) {
  9182. if (node.computed) { c(node.key, st, "Expression"); }
  9183. c(node.value, st, "Expression");
  9184. };
  9185. // patch up acorn-walk until class-fields are officially supported
  9186. base.PropertyDefinition = function (node, st, c) {
  9187. if (node.computed) {
  9188. c(node.key, st, 'Expression');
  9189. }
  9190. if (node.value) {
  9191. c(node.value, st, 'Expression');
  9192. }
  9193. };
  9194. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  9195. let commentNode = state.commentNodes[state.commentIndex];
  9196. while (commentNode && node.start >= commentNode.end) {
  9197. markPureNode(node, commentNode);
  9198. commentNode = state.commentNodes[++state.commentIndex];
  9199. }
  9200. if (commentNode && commentNode.end <= node.end) {
  9201. base[type](node, state, handlePureAnnotationsOfNode);
  9202. }
  9203. }
  9204. function markPureNode(node, comment) {
  9205. if (node.annotations) {
  9206. node.annotations.push(comment);
  9207. }
  9208. else {
  9209. node.annotations = [comment];
  9210. }
  9211. if (node.type === ExpressionStatement$1) {
  9212. node = node.expression;
  9213. }
  9214. if (node.type === CallExpression$1 || node.type === NewExpression$1) {
  9215. node.annotatedPure = true;
  9216. }
  9217. }
  9218. const pureCommentRegex = /[@#]__PURE__/;
  9219. const isPureComment = (comment) => pureCommentRegex.test(comment.text);
  9220. function markPureCallExpressions(comments, esTreeAst) {
  9221. handlePureAnnotationsOfNode(esTreeAst, {
  9222. commentIndex: 0,
  9223. commentNodes: comments.filter(isPureComment)
  9224. });
  9225. }
  9226. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  9227. // this for an actual sourceMappingURL
  9228. let SOURCEMAPPING_URL = 'sourceMa';
  9229. SOURCEMAPPING_URL += 'ppingURL';
  9230. const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
  9231. const NOOP = () => { };
  9232. let getStartTime = () => [0, 0];
  9233. let getElapsedTime = () => 0;
  9234. let getMemory = () => 0;
  9235. let timers = {};
  9236. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9237. function setTimeHelpers() {
  9238. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9239. getStartTime = process.hrtime.bind(process);
  9240. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9241. }
  9242. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9243. getStartTime = () => [performance.now(), 0];
  9244. getElapsedTime = previous => performance.now() - previous[0];
  9245. }
  9246. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9247. getMemory = () => process.memoryUsage().heapUsed;
  9248. }
  9249. }
  9250. function getPersistedLabel(label, level) {
  9251. switch (level) {
  9252. case 1:
  9253. return `# ${label}`;
  9254. case 2:
  9255. return `## ${label}`;
  9256. case 3:
  9257. return label;
  9258. default:
  9259. return `${' '.repeat(level - 4)}- ${label}`;
  9260. }
  9261. }
  9262. function timeStartImpl(label, level = 3) {
  9263. label = getPersistedLabel(label, level);
  9264. if (!timers.hasOwnProperty(label)) {
  9265. timers[label] = {
  9266. memory: 0,
  9267. startMemory: undefined,
  9268. startTime: undefined,
  9269. time: 0,
  9270. totalMemory: 0
  9271. };
  9272. }
  9273. const currentMemory = getMemory();
  9274. timers[label].startTime = getStartTime();
  9275. timers[label].startMemory = currentMemory;
  9276. }
  9277. function timeEndImpl(label, level = 3) {
  9278. label = getPersistedLabel(label, level);
  9279. if (timers.hasOwnProperty(label)) {
  9280. const currentMemory = getMemory();
  9281. timers[label].time += getElapsedTime(timers[label].startTime);
  9282. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9283. timers[label].memory += currentMemory - timers[label].startMemory;
  9284. }
  9285. }
  9286. function getTimings() {
  9287. const newTimings = {};
  9288. for (const label of Object.keys(timers)) {
  9289. newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
  9290. }
  9291. return newTimings;
  9292. }
  9293. let timeStart = NOOP, timeEnd = NOOP;
  9294. const TIMED_PLUGIN_HOOKS = {
  9295. load: true,
  9296. resolveDynamicImport: true,
  9297. resolveId: true,
  9298. transform: true
  9299. };
  9300. function getPluginWithTimers(plugin, index) {
  9301. const timedPlugin = {};
  9302. for (const hook of Object.keys(plugin)) {
  9303. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9304. let timerLabel = `plugin ${index}`;
  9305. if (plugin.name) {
  9306. timerLabel += ` (${plugin.name})`;
  9307. }
  9308. timerLabel += ` - ${hook}`;
  9309. timedPlugin[hook] = function () {
  9310. timeStart(timerLabel, 4);
  9311. const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
  9312. timeEnd(timerLabel, 4);
  9313. if (result && typeof result.then === 'function') {
  9314. timeStart(`${timerLabel} (async)`, 4);
  9315. result.then(() => timeEnd(`${timerLabel} (async)`, 4));
  9316. }
  9317. return result;
  9318. };
  9319. }
  9320. else {
  9321. timedPlugin[hook] = plugin[hook];
  9322. }
  9323. }
  9324. return timedPlugin;
  9325. }
  9326. function initialiseTimers(inputOptions) {
  9327. if (inputOptions.perf) {
  9328. timers = {};
  9329. setTimeHelpers();
  9330. timeStart = timeStartImpl;
  9331. timeEnd = timeEndImpl;
  9332. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9333. }
  9334. else {
  9335. timeStart = NOOP;
  9336. timeEnd = NOOP;
  9337. }
  9338. }
  9339. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  9340. baseModule.isExecuted = true;
  9341. const modules = [baseModule];
  9342. const visitedModules = new Set();
  9343. for (const module of modules) {
  9344. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  9345. if (!(dependency instanceof ExternalModule) &&
  9346. !dependency.isExecuted &&
  9347. (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  9348. !visitedModules.has(dependency.id)) {
  9349. dependency.isExecuted = true;
  9350. visitedModules.add(dependency.id);
  9351. modules.push(dependency);
  9352. }
  9353. }
  9354. }
  9355. }
  9356. function tryParse(module, Parser, acornOptions) {
  9357. try {
  9358. return Parser.parse(module.info.code, {
  9359. ...acornOptions,
  9360. onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
  9361. });
  9362. }
  9363. catch (err) {
  9364. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9365. if (module.id.endsWith('.json')) {
  9366. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9367. }
  9368. else if (!module.id.endsWith('.js')) {
  9369. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9370. }
  9371. return module.error({
  9372. code: 'PARSE_ERROR',
  9373. message,
  9374. parserError: err
  9375. }, err.pos);
  9376. }
  9377. }
  9378. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9379. identifier: null,
  9380. localName: MISSING_EXPORT_SHIM_VARIABLE
  9381. };
  9382. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  9383. const searchedModules = searchedNamesAndModules.get(name);
  9384. if (searchedModules) {
  9385. if (searchedModules.has(target)) {
  9386. return isExportAllSearch ? null : error(errCircularReexport(name, target.id));
  9387. }
  9388. searchedModules.add(target);
  9389. }
  9390. else {
  9391. searchedNamesAndModules.set(name, new Set([target]));
  9392. }
  9393. return target.getVariableForExportName(name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules);
  9394. }
  9395. function getAndExtendSideEffectModules(variable, module) {
  9396. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  9397. let currentVariable = variable;
  9398. const referencedVariables = new Set([currentVariable]);
  9399. while (true) {
  9400. const importingModule = currentVariable.module;
  9401. currentVariable =
  9402. currentVariable instanceof ExportDefaultVariable
  9403. ? currentVariable.getDirectOriginalVariable()
  9404. : currentVariable instanceof SyntheticNamedExportVariable
  9405. ? currentVariable.syntheticNamespace
  9406. : null;
  9407. if (!currentVariable || referencedVariables.has(currentVariable)) {
  9408. break;
  9409. }
  9410. referencedVariables.add(currentVariable);
  9411. sideEffectModules.add(importingModule);
  9412. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  9413. if (originalSideEffects) {
  9414. for (const module of originalSideEffects) {
  9415. sideEffectModules.add(module);
  9416. }
  9417. }
  9418. }
  9419. return sideEffectModules;
  9420. }
  9421. class Module {
  9422. constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
  9423. this.graph = graph;
  9424. this.id = id;
  9425. this.options = options;
  9426. this.alternativeReexportModules = new Map();
  9427. this.ast = null;
  9428. this.chunkFileNames = new Set();
  9429. this.chunkName = null;
  9430. this.comments = [];
  9431. this.cycles = new Set();
  9432. this.dependencies = new Set();
  9433. this.dynamicDependencies = new Set();
  9434. this.dynamicImporters = [];
  9435. this.dynamicImports = [];
  9436. this.execIndex = Infinity;
  9437. this.exportAllSources = new Set();
  9438. this.exports = Object.create(null);
  9439. this.exportsAll = Object.create(null);
  9440. this.implicitlyLoadedAfter = new Set();
  9441. this.implicitlyLoadedBefore = new Set();
  9442. this.importDescriptions = Object.create(null);
  9443. this.importers = [];
  9444. this.importMetas = [];
  9445. this.imports = new Set();
  9446. this.includedDynamicImporters = [];
  9447. this.isExecuted = false;
  9448. this.isUserDefinedEntryPoint = false;
  9449. this.preserveSignature = this.options.preserveEntrySignatures;
  9450. this.reexportDescriptions = Object.create(null);
  9451. this.sideEffectDependenciesByVariable = new Map();
  9452. this.sources = new Set();
  9453. this.userChunkNames = new Set();
  9454. this.usesTopLevelAwait = false;
  9455. this.allExportNames = null;
  9456. this.exportAllModules = [];
  9457. this.exportNamesByVariable = null;
  9458. this.exportShimVariable = new ExportShimVariable(this);
  9459. this.relevantDependencies = null;
  9460. this.syntheticExports = new Map();
  9461. this.syntheticNamespace = null;
  9462. this.transformDependencies = [];
  9463. this.transitiveReexports = null;
  9464. this.excludeFromSourcemap = /\0/.test(id);
  9465. this.context = options.moduleContext(id);
  9466. const module = this;
  9467. this.info = {
  9468. ast: null,
  9469. code: null,
  9470. get dynamicallyImportedIds() {
  9471. const dynamicallyImportedIds = [];
  9472. for (const { resolution } of module.dynamicImports) {
  9473. if (resolution instanceof Module || resolution instanceof ExternalModule) {
  9474. dynamicallyImportedIds.push(resolution.id);
  9475. }
  9476. }
  9477. return dynamicallyImportedIds;
  9478. },
  9479. get dynamicImporters() {
  9480. return module.dynamicImporters.sort();
  9481. },
  9482. hasModuleSideEffects,
  9483. id,
  9484. get implicitlyLoadedAfterOneOf() {
  9485. return Array.from(module.implicitlyLoadedAfter, getId);
  9486. },
  9487. get implicitlyLoadedBefore() {
  9488. return Array.from(module.implicitlyLoadedBefore, getId);
  9489. },
  9490. get importedIds() {
  9491. return Array.from(module.sources, source => module.resolvedIds[source].id);
  9492. },
  9493. get importers() {
  9494. return module.importers.sort();
  9495. },
  9496. isEntry,
  9497. isExternal: false,
  9498. meta,
  9499. syntheticNamedExports
  9500. };
  9501. }
  9502. basename() {
  9503. const base = path.basename(this.id);
  9504. const ext = path.extname(this.id);
  9505. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9506. }
  9507. bindReferences() {
  9508. this.ast.bind();
  9509. }
  9510. error(props, pos) {
  9511. this.addLocationToLogProps(props, pos);
  9512. return error(props);
  9513. }
  9514. getAllExportNames() {
  9515. if (this.allExportNames) {
  9516. return this.allExportNames;
  9517. }
  9518. const allExportNames = (this.allExportNames = new Set());
  9519. for (const name of Object.keys(this.exports)) {
  9520. allExportNames.add(name);
  9521. }
  9522. for (const name of Object.keys(this.reexportDescriptions)) {
  9523. allExportNames.add(name);
  9524. }
  9525. for (const module of this.exportAllModules) {
  9526. if (module instanceof ExternalModule) {
  9527. allExportNames.add(`*${module.id}`);
  9528. continue;
  9529. }
  9530. for (const name of module.getAllExportNames()) {
  9531. if (name !== 'default')
  9532. allExportNames.add(name);
  9533. }
  9534. }
  9535. return allExportNames;
  9536. }
  9537. getDependenciesToBeIncluded() {
  9538. if (this.relevantDependencies)
  9539. return this.relevantDependencies;
  9540. const relevantDependencies = new Set();
  9541. const necessaryDependencies = new Set();
  9542. const alwaysCheckedDependencies = new Set();
  9543. let dependencyVariables = this.imports.keys();
  9544. if (this.info.isEntry ||
  9545. this.includedDynamicImporters.length > 0 ||
  9546. this.namespace.included ||
  9547. this.implicitlyLoadedAfter.size > 0) {
  9548. dependencyVariables = new Set(dependencyVariables);
  9549. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  9550. dependencyVariables.add(this.getVariableForExportName(exportName));
  9551. }
  9552. }
  9553. for (let variable of dependencyVariables) {
  9554. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  9555. if (sideEffectDependencies) {
  9556. for (const module of sideEffectDependencies) {
  9557. alwaysCheckedDependencies.add(module);
  9558. }
  9559. }
  9560. if (variable instanceof SyntheticNamedExportVariable) {
  9561. variable = variable.getBaseVariable();
  9562. }
  9563. else if (variable instanceof ExportDefaultVariable) {
  9564. variable = variable.getOriginalVariable();
  9565. }
  9566. necessaryDependencies.add(variable.module);
  9567. }
  9568. if (this.options.treeshake && this.info.hasModuleSideEffects !== 'no-treeshake') {
  9569. this.addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  9570. }
  9571. else {
  9572. for (const dependency of this.dependencies) {
  9573. relevantDependencies.add(dependency);
  9574. }
  9575. }
  9576. for (const dependency of necessaryDependencies) {
  9577. relevantDependencies.add(dependency);
  9578. }
  9579. return (this.relevantDependencies = relevantDependencies);
  9580. }
  9581. getExportNamesByVariable() {
  9582. if (this.exportNamesByVariable) {
  9583. return this.exportNamesByVariable;
  9584. }
  9585. const exportNamesByVariable = new Map();
  9586. for (const exportName of this.getAllExportNames()) {
  9587. if (exportName === this.info.syntheticNamedExports)
  9588. continue;
  9589. let tracedVariable = this.getVariableForExportName(exportName);
  9590. if (tracedVariable instanceof ExportDefaultVariable) {
  9591. tracedVariable = tracedVariable.getOriginalVariable();
  9592. }
  9593. if (!tracedVariable ||
  9594. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9595. continue;
  9596. }
  9597. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9598. if (existingExportNames) {
  9599. existingExportNames.push(exportName);
  9600. }
  9601. else {
  9602. exportNamesByVariable.set(tracedVariable, [exportName]);
  9603. }
  9604. }
  9605. return (this.exportNamesByVariable = exportNamesByVariable);
  9606. }
  9607. getExports() {
  9608. return Object.keys(this.exports);
  9609. }
  9610. getReexports() {
  9611. if (this.transitiveReexports) {
  9612. return this.transitiveReexports;
  9613. }
  9614. // to avoid infinite recursion when using circular `export * from X`
  9615. this.transitiveReexports = [];
  9616. const reexports = new Set();
  9617. for (const name in this.reexportDescriptions) {
  9618. reexports.add(name);
  9619. }
  9620. for (const module of this.exportAllModules) {
  9621. if (module instanceof ExternalModule) {
  9622. reexports.add(`*${module.id}`);
  9623. }
  9624. else {
  9625. for (const name of [...module.getReexports(), ...module.getExports()]) {
  9626. if (name !== 'default')
  9627. reexports.add(name);
  9628. }
  9629. }
  9630. }
  9631. return (this.transitiveReexports = [...reexports]);
  9632. }
  9633. getRenderedExports() {
  9634. // only direct exports are counted here, not reexports at all
  9635. const renderedExports = [];
  9636. const removedExports = [];
  9637. for (const exportName in this.exports) {
  9638. const variable = this.getVariableForExportName(exportName);
  9639. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9640. }
  9641. return { renderedExports, removedExports };
  9642. }
  9643. getSyntheticNamespace() {
  9644. if (this.syntheticNamespace === null) {
  9645. this.syntheticNamespace = undefined;
  9646. this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  9647. ? this.info.syntheticNamedExports
  9648. : 'default');
  9649. }
  9650. if (!this.syntheticNamespace) {
  9651. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  9652. }
  9653. return this.syntheticNamespace;
  9654. }
  9655. getVariableForExportName(name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules) {
  9656. if (name[0] === '*') {
  9657. if (name.length === 1) {
  9658. // export * from './other'
  9659. return this.namespace;
  9660. }
  9661. else {
  9662. // export * from 'external'
  9663. const module = this.graph.modulesById.get(name.slice(1));
  9664. return module.getVariableForExportName('*');
  9665. }
  9666. }
  9667. // export { foo } from './other'
  9668. const reexportDeclaration = this.reexportDescriptions[name];
  9669. if (reexportDeclaration) {
  9670. const variable = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  9671. if (!variable) {
  9672. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  9673. }
  9674. if (importerForSideEffects) {
  9675. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9676. }
  9677. return variable;
  9678. }
  9679. const exportDeclaration = this.exports[name];
  9680. if (exportDeclaration) {
  9681. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9682. return this.exportShimVariable;
  9683. }
  9684. const name = exportDeclaration.localName;
  9685. const variable = this.traceVariable(name, importerForSideEffects);
  9686. if (importerForSideEffects) {
  9687. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  9688. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9689. }
  9690. return variable;
  9691. }
  9692. if (name !== 'default') {
  9693. let foundSyntheticDeclaration = null;
  9694. for (const module of this.exportAllModules) {
  9695. const declaration = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, searchedNamesAndModules);
  9696. if (declaration) {
  9697. if (!(declaration instanceof SyntheticNamedExportVariable)) {
  9698. return declaration;
  9699. }
  9700. if (!foundSyntheticDeclaration) {
  9701. foundSyntheticDeclaration = declaration;
  9702. }
  9703. }
  9704. }
  9705. if (foundSyntheticDeclaration) {
  9706. return foundSyntheticDeclaration;
  9707. }
  9708. }
  9709. if (this.info.syntheticNamedExports) {
  9710. let syntheticExport = this.syntheticExports.get(name);
  9711. if (!syntheticExport) {
  9712. const syntheticNamespace = this.getSyntheticNamespace();
  9713. syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
  9714. this.syntheticExports.set(name, syntheticExport);
  9715. return syntheticExport;
  9716. }
  9717. return syntheticExport;
  9718. }
  9719. // we don't want to create shims when we are just
  9720. // probing export * modules for exports
  9721. if (!isExportAllSearch) {
  9722. if (this.options.shimMissingExports) {
  9723. this.shimMissingExport(name);
  9724. return this.exportShimVariable;
  9725. }
  9726. }
  9727. return null;
  9728. }
  9729. hasEffects() {
  9730. return (this.info.hasModuleSideEffects === 'no-treeshake' ||
  9731. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  9732. }
  9733. include() {
  9734. const context = createInclusionContext();
  9735. if (this.ast.shouldBeIncluded(context))
  9736. this.ast.include(context, false);
  9737. }
  9738. includeAllExports(includeNamespaceMembers) {
  9739. if (!this.isExecuted) {
  9740. this.graph.needsTreeshakingPass = true;
  9741. markModuleAndImpureDependenciesAsExecuted(this);
  9742. }
  9743. for (const exportName of this.getExports()) {
  9744. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  9745. const variable = this.getVariableForExportName(exportName);
  9746. variable.deoptimizePath(UNKNOWN_PATH);
  9747. if (!variable.included) {
  9748. this.includeVariable(variable);
  9749. }
  9750. }
  9751. }
  9752. for (const name of this.getReexports()) {
  9753. const variable = this.getVariableForExportName(name);
  9754. variable.deoptimizePath(UNKNOWN_PATH);
  9755. if (!variable.included) {
  9756. this.includeVariable(variable);
  9757. }
  9758. if (variable instanceof ExternalVariable) {
  9759. variable.module.reexported = true;
  9760. }
  9761. }
  9762. if (includeNamespaceMembers) {
  9763. this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
  9764. }
  9765. }
  9766. includeAllInBundle() {
  9767. this.ast.include(createInclusionContext(), true);
  9768. }
  9769. isIncluded() {
  9770. return this.ast.included || this.namespace.included;
  9771. }
  9772. linkImports() {
  9773. this.addModulesToImportDescriptions(this.importDescriptions);
  9774. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9775. for (const name in this.exports) {
  9776. if (name !== 'default' && name !== this.info.syntheticNamedExports) {
  9777. this.exportsAll[name] = this.id;
  9778. }
  9779. }
  9780. const externalExportAllModules = [];
  9781. for (const source of this.exportAllSources) {
  9782. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  9783. if (module instanceof ExternalModule) {
  9784. externalExportAllModules.push(module);
  9785. continue;
  9786. }
  9787. this.exportAllModules.push(module);
  9788. for (const name in module.exportsAll) {
  9789. if (name in this.exportsAll) {
  9790. this.options.onwarn(errNamespaceConflict(name, this, module));
  9791. }
  9792. else {
  9793. this.exportsAll[name] = module.exportsAll[name];
  9794. }
  9795. }
  9796. }
  9797. this.exportAllModules.push(...externalExportAllModules);
  9798. }
  9799. render(options) {
  9800. const magicString = this.magicString.clone();
  9801. this.ast.render(magicString, options);
  9802. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9803. return magicString;
  9804. }
  9805. setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  9806. this.info.code = code;
  9807. this.originalCode = originalCode;
  9808. this.originalSourcemap = originalSourcemap;
  9809. this.sourcemapChain = sourcemapChain;
  9810. if (transformFiles) {
  9811. this.transformFiles = transformFiles;
  9812. }
  9813. this.transformDependencies = transformDependencies;
  9814. this.customTransformCache = customTransformCache;
  9815. this.updateOptions(moduleOptions);
  9816. timeStart('generate ast', 3);
  9817. this.alwaysRemovedCode = alwaysRemovedCode || [];
  9818. if (!ast) {
  9819. ast = tryParse(this, this.graph.acornParser, this.options.acorn);
  9820. for (const comment of this.comments) {
  9821. if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
  9822. this.alwaysRemovedCode.push([comment.start, comment.end]);
  9823. }
  9824. }
  9825. markPureCallExpressions(this.comments, ast);
  9826. }
  9827. timeEnd('generate ast', 3);
  9828. this.resolvedIds = resolvedIds || Object.create(null);
  9829. // By default, `id` is the file name. Custom resolvers and loaders
  9830. // can change that, but it makes sense to use it for the source file name
  9831. const fileName = this.id;
  9832. this.magicString = new MagicString(code, {
  9833. filename: (this.excludeFromSourcemap ? null : fileName),
  9834. indentExclusionRanges: []
  9835. });
  9836. for (const [start, end] of this.alwaysRemovedCode) {
  9837. this.magicString.remove(start, end);
  9838. }
  9839. timeStart('analyse ast', 3);
  9840. this.astContext = {
  9841. addDynamicImport: this.addDynamicImport.bind(this),
  9842. addExport: this.addExport.bind(this),
  9843. addImport: this.addImport.bind(this),
  9844. addImportMeta: this.addImportMeta.bind(this),
  9845. code,
  9846. deoptimizationTracker: this.graph.deoptimizationTracker,
  9847. error: this.error.bind(this),
  9848. fileName,
  9849. getExports: this.getExports.bind(this),
  9850. getModuleExecIndex: () => this.execIndex,
  9851. getModuleName: this.basename.bind(this),
  9852. getReexports: this.getReexports.bind(this),
  9853. importDescriptions: this.importDescriptions,
  9854. includeAllExports: () => this.includeAllExports(true),
  9855. includeDynamicImport: this.includeDynamicImport.bind(this),
  9856. includeVariableInModule: this.includeVariableInModule.bind(this),
  9857. magicString: this.magicString,
  9858. module: this,
  9859. moduleContext: this.context,
  9860. nodeConstructors,
  9861. options: this.options,
  9862. traceExport: this.getVariableForExportName.bind(this),
  9863. traceVariable: this.traceVariable.bind(this),
  9864. usesTopLevelAwait: false,
  9865. warn: this.warn.bind(this)
  9866. };
  9867. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9868. this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
  9869. this.ast = new Program(ast, { type: 'Module', context: this.astContext }, this.scope);
  9870. this.info.ast = ast;
  9871. timeEnd('analyse ast', 3);
  9872. }
  9873. toJSON() {
  9874. return {
  9875. alwaysRemovedCode: this.alwaysRemovedCode,
  9876. ast: this.ast.esTreeNode,
  9877. code: this.info.code,
  9878. customTransformCache: this.customTransformCache,
  9879. dependencies: Array.from(this.dependencies, getId),
  9880. id: this.id,
  9881. meta: this.info.meta,
  9882. moduleSideEffects: this.info.hasModuleSideEffects,
  9883. originalCode: this.originalCode,
  9884. originalSourcemap: this.originalSourcemap,
  9885. resolvedIds: this.resolvedIds,
  9886. sourcemapChain: this.sourcemapChain,
  9887. syntheticNamedExports: this.info.syntheticNamedExports,
  9888. transformDependencies: this.transformDependencies,
  9889. transformFiles: this.transformFiles
  9890. };
  9891. }
  9892. traceVariable(name, importerForSideEffects) {
  9893. const localVariable = this.scope.variables.get(name);
  9894. if (localVariable) {
  9895. return localVariable;
  9896. }
  9897. if (name in this.importDescriptions) {
  9898. const importDeclaration = this.importDescriptions[name];
  9899. const otherModule = importDeclaration.module;
  9900. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9901. return otherModule.namespace;
  9902. }
  9903. const declaration = otherModule.getVariableForExportName(importDeclaration.name, importerForSideEffects || this);
  9904. if (!declaration) {
  9905. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  9906. }
  9907. return declaration;
  9908. }
  9909. return null;
  9910. }
  9911. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  9912. if (moduleSideEffects != null) {
  9913. this.info.hasModuleSideEffects = moduleSideEffects;
  9914. }
  9915. if (syntheticNamedExports != null) {
  9916. this.info.syntheticNamedExports = syntheticNamedExports;
  9917. }
  9918. if (meta != null) {
  9919. this.info.meta = { ...this.info.meta, ...meta };
  9920. }
  9921. }
  9922. warn(props, pos) {
  9923. this.addLocationToLogProps(props, pos);
  9924. this.options.onwarn(props);
  9925. }
  9926. addDynamicImport(node) {
  9927. let argument = node.source;
  9928. if (argument instanceof TemplateLiteral) {
  9929. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  9930. argument = argument.quasis[0].value.cooked;
  9931. }
  9932. }
  9933. else if (argument instanceof Literal && typeof argument.value === 'string') {
  9934. argument = argument.value;
  9935. }
  9936. this.dynamicImports.push({ node, resolution: null, argument });
  9937. }
  9938. addExport(node) {
  9939. if (node instanceof ExportDefaultDeclaration) {
  9940. // export default foo;
  9941. this.exports.default = {
  9942. identifier: node.variable.getAssignedVariableName(),
  9943. localName: 'default'
  9944. };
  9945. }
  9946. else if (node instanceof ExportAllDeclaration) {
  9947. const source = node.source.value;
  9948. this.sources.add(source);
  9949. if (node.exported) {
  9950. // export * as name from './other'
  9951. const name = node.exported.name;
  9952. this.reexportDescriptions[name] = {
  9953. localName: '*',
  9954. module: null,
  9955. source,
  9956. start: node.start
  9957. };
  9958. }
  9959. else {
  9960. // export * from './other'
  9961. this.exportAllSources.add(source);
  9962. }
  9963. }
  9964. else if (node.source instanceof Literal) {
  9965. // export { name } from './other'
  9966. const source = node.source.value;
  9967. this.sources.add(source);
  9968. for (const specifier of node.specifiers) {
  9969. const name = specifier.exported.name;
  9970. this.reexportDescriptions[name] = {
  9971. localName: specifier.local.name,
  9972. module: null,
  9973. source,
  9974. start: specifier.start
  9975. };
  9976. }
  9977. }
  9978. else if (node.declaration) {
  9979. const declaration = node.declaration;
  9980. if (declaration instanceof VariableDeclaration) {
  9981. // export var { foo, bar } = ...
  9982. // export var foo = 1, bar = 2;
  9983. for (const declarator of declaration.declarations) {
  9984. for (const localName of extractAssignedNames(declarator.id)) {
  9985. this.exports[localName] = { identifier: null, localName };
  9986. }
  9987. }
  9988. }
  9989. else {
  9990. // export function foo () {}
  9991. const localName = declaration.id.name;
  9992. this.exports[localName] = { identifier: null, localName };
  9993. }
  9994. }
  9995. else {
  9996. // export { foo, bar, baz }
  9997. for (const specifier of node.specifiers) {
  9998. const localName = specifier.local.name;
  9999. const exportedName = specifier.exported.name;
  10000. this.exports[exportedName] = { identifier: null, localName };
  10001. }
  10002. }
  10003. }
  10004. addImport(node) {
  10005. const source = node.source.value;
  10006. this.sources.add(source);
  10007. for (const specifier of node.specifiers) {
  10008. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  10009. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  10010. const name = isDefault
  10011. ? 'default'
  10012. : isNamespace
  10013. ? '*'
  10014. : specifier.imported.name;
  10015. this.importDescriptions[specifier.local.name] = {
  10016. module: null,
  10017. name,
  10018. source,
  10019. start: specifier.start
  10020. };
  10021. }
  10022. }
  10023. addImportMeta(node) {
  10024. this.importMetas.push(node);
  10025. }
  10026. addLocationToLogProps(props, pos) {
  10027. props.id = this.id;
  10028. props.pos = pos;
  10029. let code = this.info.code;
  10030. let { column, line } = locate(code, pos, { offsetLine: 1 });
  10031. try {
  10032. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  10033. code = this.originalCode;
  10034. }
  10035. catch (e) {
  10036. this.options.onwarn({
  10037. code: 'SOURCEMAP_ERROR',
  10038. id: this.id,
  10039. loc: {
  10040. column,
  10041. file: this.id,
  10042. line
  10043. },
  10044. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  10045. pos
  10046. });
  10047. }
  10048. augmentCodeLocation(props, { column, line }, code, this.id);
  10049. }
  10050. addModulesToImportDescriptions(importDescription) {
  10051. for (const name of Object.keys(importDescription)) {
  10052. const specifier = importDescription[name];
  10053. const id = this.resolvedIds[specifier.source].id;
  10054. specifier.module = this.graph.modulesById.get(id);
  10055. }
  10056. }
  10057. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  10058. const handledDependencies = new Set();
  10059. const addSideEffectDependencies = (possibleDependencies) => {
  10060. for (const dependency of possibleDependencies) {
  10061. if (handledDependencies.has(dependency)) {
  10062. continue;
  10063. }
  10064. handledDependencies.add(dependency);
  10065. if (necessaryDependencies.has(dependency)) {
  10066. relevantDependencies.add(dependency);
  10067. continue;
  10068. }
  10069. if (!(dependency.info.hasModuleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  10070. continue;
  10071. }
  10072. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  10073. relevantDependencies.add(dependency);
  10074. continue;
  10075. }
  10076. addSideEffectDependencies(dependency.dependencies);
  10077. }
  10078. };
  10079. addSideEffectDependencies(this.dependencies);
  10080. addSideEffectDependencies(alwaysCheckedDependencies);
  10081. }
  10082. includeAndGetAdditionalMergedNamespaces() {
  10083. const mergedNamespaces = [];
  10084. for (const module of this.exportAllModules) {
  10085. if (module instanceof ExternalModule) {
  10086. const externalVariable = module.getVariableForExportName('*');
  10087. externalVariable.include();
  10088. this.imports.add(externalVariable);
  10089. mergedNamespaces.push(externalVariable);
  10090. }
  10091. else if (module.info.syntheticNamedExports) {
  10092. const syntheticNamespace = module.getSyntheticNamespace();
  10093. syntheticNamespace.include();
  10094. this.imports.add(syntheticNamespace);
  10095. mergedNamespaces.push(syntheticNamespace);
  10096. }
  10097. }
  10098. return mergedNamespaces;
  10099. }
  10100. includeDynamicImport(node) {
  10101. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  10102. if (resolution instanceof Module) {
  10103. resolution.includedDynamicImporters.push(this);
  10104. resolution.includeAllExports(true);
  10105. }
  10106. }
  10107. includeVariable(variable) {
  10108. if (!variable.included) {
  10109. variable.include();
  10110. this.graph.needsTreeshakingPass = true;
  10111. const variableModule = variable.module;
  10112. if (variableModule && variableModule instanceof Module) {
  10113. if (!variableModule.isExecuted) {
  10114. markModuleAndImpureDependenciesAsExecuted(variableModule);
  10115. }
  10116. if (variableModule !== this) {
  10117. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  10118. for (const module of sideEffectModules) {
  10119. if (!module.isExecuted) {
  10120. markModuleAndImpureDependenciesAsExecuted(module);
  10121. }
  10122. }
  10123. }
  10124. }
  10125. }
  10126. }
  10127. includeVariableInModule(variable) {
  10128. this.includeVariable(variable);
  10129. const variableModule = variable.module;
  10130. if (variableModule && variableModule !== this) {
  10131. this.imports.add(variable);
  10132. }
  10133. }
  10134. shimMissingExport(name) {
  10135. this.options.onwarn({
  10136. code: 'SHIMMED_EXPORT',
  10137. exporter: relativeId(this.id),
  10138. exportName: name,
  10139. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  10140. });
  10141. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  10142. }
  10143. }
  10144. // if there is a cyclic import in the reexport chain, we should not
  10145. // import from the original module but from the cyclic module to not
  10146. // mess up execution order.
  10147. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  10148. if (variable.module instanceof Module && variable.module !== reexporter) {
  10149. const exporterCycles = variable.module.cycles;
  10150. if (exporterCycles.size > 0) {
  10151. const importerCycles = reexporter.cycles;
  10152. for (const cycleSymbol of importerCycles) {
  10153. if (exporterCycles.has(cycleSymbol)) {
  10154. importer.alternativeReexportModules.set(variable, reexporter);
  10155. break;
  10156. }
  10157. }
  10158. }
  10159. }
  10160. }
  10161. class Source {
  10162. constructor(filename, content) {
  10163. this.isOriginal = true;
  10164. this.filename = filename;
  10165. this.content = content;
  10166. }
  10167. traceSegment(line, column, name) {
  10168. return { line, column, name, source: this };
  10169. }
  10170. }
  10171. class Link {
  10172. constructor(map, sources) {
  10173. this.sources = sources;
  10174. this.names = map.names;
  10175. this.mappings = map.mappings;
  10176. }
  10177. traceMappings() {
  10178. const sources = [];
  10179. const sourcesContent = [];
  10180. const names = [];
  10181. const mappings = [];
  10182. for (const line of this.mappings) {
  10183. const tracedLine = [];
  10184. for (const segment of line) {
  10185. if (segment.length == 1)
  10186. continue;
  10187. const source = this.sources[segment[1]];
  10188. if (!source)
  10189. continue;
  10190. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  10191. if (traced) {
  10192. // newer sources are more likely to be used, so search backwards.
  10193. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  10194. if (sourceIndex === -1) {
  10195. sourceIndex = sources.length;
  10196. sources.push(traced.source.filename);
  10197. sourcesContent[sourceIndex] = traced.source.content;
  10198. }
  10199. else if (sourcesContent[sourceIndex] == null) {
  10200. sourcesContent[sourceIndex] = traced.source.content;
  10201. }
  10202. else if (traced.source.content != null &&
  10203. sourcesContent[sourceIndex] !== traced.source.content) {
  10204. return error({
  10205. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  10206. });
  10207. }
  10208. const tracedSegment = [
  10209. segment[0],
  10210. sourceIndex,
  10211. traced.line,
  10212. traced.column
  10213. ];
  10214. if (traced.name) {
  10215. let nameIndex = names.indexOf(traced.name);
  10216. if (nameIndex === -1) {
  10217. nameIndex = names.length;
  10218. names.push(traced.name);
  10219. }
  10220. tracedSegment[4] = nameIndex;
  10221. }
  10222. tracedLine.push(tracedSegment);
  10223. }
  10224. }
  10225. mappings.push(tracedLine);
  10226. }
  10227. return { sources, sourcesContent, names, mappings };
  10228. }
  10229. traceSegment(line, column, name) {
  10230. const segments = this.mappings[line];
  10231. if (!segments)
  10232. return null;
  10233. // binary search through segments for the given column
  10234. let i = 0;
  10235. let j = segments.length - 1;
  10236. while (i <= j) {
  10237. const m = (i + j) >> 1;
  10238. const segment = segments[m];
  10239. if (segment[0] === column) {
  10240. if (segment.length == 1)
  10241. return null;
  10242. const source = this.sources[segment[1]];
  10243. if (!source)
  10244. return null;
  10245. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  10246. }
  10247. if (segment[0] > column) {
  10248. j = m - 1;
  10249. }
  10250. else {
  10251. i = m + 1;
  10252. }
  10253. }
  10254. return null;
  10255. }
  10256. }
  10257. function getLinkMap(warn) {
  10258. return function linkMap(source, map) {
  10259. if (map.mappings) {
  10260. return new Link(map, [source]);
  10261. }
  10262. warn({
  10263. code: 'SOURCEMAP_BROKEN',
  10264. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  10265. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  10266. 'documentation for help',
  10267. plugin: map.plugin,
  10268. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  10269. });
  10270. return new Link({
  10271. mappings: [],
  10272. names: []
  10273. }, [source]);
  10274. };
  10275. }
  10276. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  10277. let source;
  10278. if (!originalSourcemap) {
  10279. source = new Source(id, originalCode);
  10280. }
  10281. else {
  10282. const sources = originalSourcemap.sources;
  10283. const sourcesContent = originalSourcemap.sourcesContent || [];
  10284. const directory = path.dirname(id) || '.';
  10285. const sourceRoot = originalSourcemap.sourceRoot || '.';
  10286. const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
  10287. source = new Link(originalSourcemap, baseSources);
  10288. }
  10289. return sourcemapChain.reduce(linkMap, source);
  10290. }
  10291. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  10292. const linkMap = getLinkMap(warn);
  10293. const moduleSources = modules
  10294. .filter(module => !module.excludeFromSourcemap)
  10295. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  10296. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  10297. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  10298. let source = new Link(map, moduleSources);
  10299. source = bundleSourcemapChain.reduce(linkMap, source);
  10300. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  10301. if (file) {
  10302. const directory = path.dirname(file);
  10303. sources = sources.map((source) => path.relative(directory, source));
  10304. file = path.basename(file);
  10305. }
  10306. sourcesContent = (excludeContent ? null : sourcesContent);
  10307. return new SourceMap({ file, sources, sourcesContent, names, mappings });
  10308. }
  10309. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  10310. if (!sourcemapChain.length) {
  10311. return originalSourcemap;
  10312. }
  10313. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  10314. const map = source.traceMappings();
  10315. return { version: 3, ...map };
  10316. }
  10317. const createHash = () => crypto.createHash('sha256');
  10318. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  10319. amd: deconflictImportsOther,
  10320. cjs: deconflictImportsOther,
  10321. es: deconflictImportsEsmOrSystem,
  10322. iife: deconflictImportsOther,
  10323. system: deconflictImportsEsmOrSystem,
  10324. umd: deconflictImportsOther
  10325. };
  10326. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  10327. const reversedModules = modules.slice().reverse();
  10328. for (const module of reversedModules) {
  10329. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  10330. }
  10331. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  10332. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  10333. for (const module of reversedModules) {
  10334. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  10335. }
  10336. }
  10337. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  10338. // This is needed for namespace reexports
  10339. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  10340. if (preserveModules || dependency instanceof ExternalModule) {
  10341. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  10342. }
  10343. }
  10344. for (const variable of imports) {
  10345. const module = variable.module;
  10346. const name = variable.name;
  10347. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  10348. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  10349. }
  10350. else if (module instanceof ExternalModule && name === 'default') {
  10351. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  10352. ? module.suggestedVariableName + '__default'
  10353. : module.suggestedVariableName, usedNames));
  10354. }
  10355. else {
  10356. variable.setRenderNames(null, getSafeName(name, usedNames));
  10357. }
  10358. }
  10359. for (const variable of syntheticExports) {
  10360. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10361. }
  10362. }
  10363. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  10364. for (const chunkOrExternalModule of dependencies) {
  10365. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  10366. }
  10367. for (const externalModuleOrChunk of deconflictedNamespace) {
  10368. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  10369. }
  10370. for (const externalModule of deconflictedDefault) {
  10371. if (deconflictedNamespace.has(externalModule) &&
  10372. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  10373. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  10374. }
  10375. else {
  10376. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  10377. }
  10378. }
  10379. for (const variable of imports) {
  10380. const module = variable.module;
  10381. if (module instanceof ExternalModule) {
  10382. const name = variable.name;
  10383. if (name === 'default') {
  10384. const moduleInterop = String(interop(module.id));
  10385. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  10386. ? module.defaultVariableName
  10387. : module.variableName;
  10388. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  10389. variable.setRenderNames(variableName, 'default');
  10390. }
  10391. else {
  10392. variable.setRenderNames(null, variableName);
  10393. }
  10394. }
  10395. else if (name === '*') {
  10396. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  10397. ? module.namespaceVariableName
  10398. : module.variableName);
  10399. }
  10400. else {
  10401. // if the second parameter is `null`, it uses its "name" for the property name
  10402. variable.setRenderNames(module.variableName, null);
  10403. }
  10404. }
  10405. else {
  10406. const chunk = chunkByModule.get(module);
  10407. if (preserveModules && variable.isNamespace) {
  10408. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  10409. }
  10410. else if (chunk.exportMode === 'default') {
  10411. variable.setRenderNames(null, chunk.variableName);
  10412. }
  10413. else {
  10414. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  10415. }
  10416. }
  10417. }
  10418. }
  10419. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  10420. for (const module of modules) {
  10421. for (const variable of module.scope.variables.values()) {
  10422. if (variable.included &&
  10423. // this will only happen for exports in some formats
  10424. !(variable.renderBaseName ||
  10425. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  10426. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10427. }
  10428. }
  10429. if (includedNamespaces.has(module)) {
  10430. const namespace = module.namespace;
  10431. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  10432. }
  10433. }
  10434. }
  10435. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  10436. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  10437. const backSlashRegEx = /\\/g;
  10438. function escapeId(id) {
  10439. if (!id.match(needsEscapeRegEx))
  10440. return id;
  10441. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  10442. }
  10443. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  10444. let nameIndex = 0;
  10445. for (const variable of exports) {
  10446. let exportName = variable.name[0];
  10447. if (exportsByName[exportName]) {
  10448. do {
  10449. exportName = toBase64(++nameIndex);
  10450. // skip past leading number identifiers
  10451. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  10452. nameIndex += 9 * 64 ** (exportName.length - 1);
  10453. exportName = toBase64(nameIndex);
  10454. }
  10455. } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
  10456. }
  10457. exportsByName[exportName] = variable;
  10458. exportNamesByVariable.set(variable, [exportName]);
  10459. }
  10460. }
  10461. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  10462. for (const variable of exports) {
  10463. let nameIndex = 0;
  10464. let exportName = variable.name;
  10465. while (exportsByName[exportName]) {
  10466. exportName = variable.name + '$' + ++nameIndex;
  10467. }
  10468. exportsByName[exportName] = variable;
  10469. exportNamesByVariable.set(variable, [exportName]);
  10470. }
  10471. }
  10472. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  10473. const exportKeys = chunk.getExportNames();
  10474. if (exportMode === 'default') {
  10475. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  10476. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  10477. }
  10478. }
  10479. else if (exportMode === 'none' && exportKeys.length) {
  10480. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  10481. }
  10482. if (exportMode === 'auto') {
  10483. if (exportKeys.length === 0) {
  10484. exportMode = 'none';
  10485. }
  10486. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  10487. if (format === 'cjs' && unsetOptions.has('exports')) {
  10488. warn(errPreferNamedExports(facadeModuleId));
  10489. }
  10490. exportMode = 'default';
  10491. }
  10492. else {
  10493. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  10494. warn(errMixedExport(facadeModuleId, name));
  10495. }
  10496. exportMode = 'named';
  10497. }
  10498. }
  10499. return exportMode;
  10500. }
  10501. function guessIndentString(code) {
  10502. const lines = code.split('\n');
  10503. const tabbed = lines.filter(line => /^\t+/.test(line));
  10504. const spaced = lines.filter(line => /^ {2,}/.test(line));
  10505. if (tabbed.length === 0 && spaced.length === 0) {
  10506. return null;
  10507. }
  10508. // More lines tabbed than spaced? Assume tabs, and
  10509. // default to tabs in the case of a tie (or nothing
  10510. // to go on)
  10511. if (tabbed.length >= spaced.length) {
  10512. return '\t';
  10513. }
  10514. // Otherwise, we need to guess the multiple
  10515. const min = spaced.reduce((previous, current) => {
  10516. const numSpaces = /^ +/.exec(current)[0].length;
  10517. return Math.min(numSpaces, previous);
  10518. }, Infinity);
  10519. return new Array(min + 1).join(' ');
  10520. }
  10521. function getIndentString(modules, options) {
  10522. if (options.indent !== true)
  10523. return options.indent;
  10524. for (let i = 0; i < modules.length; i++) {
  10525. const indent = guessIndentString(modules[i].originalCode);
  10526. if (indent !== null)
  10527. return indent;
  10528. }
  10529. return '\t';
  10530. }
  10531. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  10532. const staticDependencyBlocks = [];
  10533. const handledDependencies = new Set();
  10534. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  10535. const module = orderedModules[modulePos];
  10536. if (!handledDependencies.has(module)) {
  10537. const staticDependencies = [];
  10538. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  10539. staticDependencyBlocks.unshift(staticDependencies);
  10540. }
  10541. }
  10542. const dependencies = new Set();
  10543. for (const block of staticDependencyBlocks) {
  10544. for (const dependency of block) {
  10545. dependencies.add(dependency);
  10546. }
  10547. }
  10548. return dependencies;
  10549. }
  10550. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  10551. const dependencies = module.getDependenciesToBeIncluded();
  10552. for (const dependency of dependencies) {
  10553. if (dependency instanceof ExternalModule) {
  10554. staticDependencies.push(dependency);
  10555. continue;
  10556. }
  10557. const dependencyChunk = chunkByModule.get(dependency);
  10558. if (dependencyChunk !== chunk) {
  10559. staticDependencies.push(dependencyChunk);
  10560. continue;
  10561. }
  10562. if (!handledModules.has(dependency)) {
  10563. handledModules.add(dependency);
  10564. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  10565. }
  10566. }
  10567. }
  10568. function decodedSourcemap(map) {
  10569. if (!map)
  10570. return null;
  10571. if (typeof map === 'string') {
  10572. map = JSON.parse(map);
  10573. }
  10574. if (map.mappings === '') {
  10575. return {
  10576. mappings: [],
  10577. names: [],
  10578. sources: [],
  10579. version: 3
  10580. };
  10581. }
  10582. let mappings;
  10583. if (typeof map.mappings === 'string') {
  10584. mappings = decode(map.mappings);
  10585. }
  10586. else {
  10587. mappings = map.mappings;
  10588. }
  10589. return { ...map, mappings };
  10590. }
  10591. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  10592. const renderChunkReducer = (code, result, plugin) => {
  10593. if (result == null)
  10594. return code;
  10595. if (typeof result === 'string')
  10596. result = {
  10597. code: result,
  10598. map: undefined
  10599. };
  10600. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  10601. if (result.map !== null) {
  10602. const map = decodedSourcemap(result.map);
  10603. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  10604. }
  10605. return result.code;
  10606. };
  10607. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  10608. }
  10609. function renderNamePattern(pattern, patternName, replacements) {
  10610. if (!isPlainPathFragment(pattern))
  10611. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
  10612. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  10613. if (!replacements.hasOwnProperty(type)) {
  10614. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  10615. }
  10616. const replacement = replacements[type]();
  10617. if (!isPlainPathFragment(replacement))
  10618. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  10619. return replacement;
  10620. });
  10621. }
  10622. function makeUnique(name, existingNames) {
  10623. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  10624. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  10625. return name;
  10626. const ext = path.extname(name);
  10627. name = name.substr(0, name.length - ext.length);
  10628. let uniqueName, uniqueIndex = 1;
  10629. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  10630. ;
  10631. return uniqueName;
  10632. }
  10633. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  10634. function getGlobalName(module, globals, hasExports, warn) {
  10635. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  10636. if (globalName) {
  10637. return globalName;
  10638. }
  10639. if (hasExports) {
  10640. warn({
  10641. code: 'MISSING_GLOBAL_NAME',
  10642. guess: module.variableName,
  10643. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  10644. source: module.id
  10645. });
  10646. return module.variableName;
  10647. }
  10648. }
  10649. class Chunk {
  10650. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  10651. this.orderedModules = orderedModules;
  10652. this.inputOptions = inputOptions;
  10653. this.outputOptions = outputOptions;
  10654. this.unsetOptions = unsetOptions;
  10655. this.pluginDriver = pluginDriver;
  10656. this.modulesById = modulesById;
  10657. this.chunkByModule = chunkByModule;
  10658. this.facadeChunkByModule = facadeChunkByModule;
  10659. this.includedNamespaces = includedNamespaces;
  10660. this.manualChunkAlias = manualChunkAlias;
  10661. this.entryModules = [];
  10662. this.exportMode = 'named';
  10663. this.facadeModule = null;
  10664. this.id = null;
  10665. this.namespaceVariableName = '';
  10666. this.variableName = '';
  10667. this.accessedGlobalsByScope = new Map();
  10668. this.dependencies = new Set();
  10669. this.dynamicDependencies = new Set();
  10670. this.dynamicEntryModules = [];
  10671. this.exportNamesByVariable = new Map();
  10672. this.exports = new Set();
  10673. this.exportsByName = Object.create(null);
  10674. this.fileName = null;
  10675. this.implicitEntryModules = [];
  10676. this.implicitlyLoadedBefore = new Set();
  10677. this.imports = new Set();
  10678. this.indentString = undefined;
  10679. this.isEmpty = true;
  10680. this.name = null;
  10681. this.needsExportsShim = false;
  10682. this.renderedDependencies = null;
  10683. this.renderedExports = null;
  10684. this.renderedHash = undefined;
  10685. this.renderedModules = Object.create(null);
  10686. this.renderedModuleSources = new Map();
  10687. this.renderedSource = null;
  10688. this.sortedExportNames = null;
  10689. this.strictFacade = false;
  10690. this.usedModules = undefined;
  10691. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  10692. const chunkModules = new Set(orderedModules);
  10693. for (const module of orderedModules) {
  10694. if (module.namespace.included) {
  10695. includedNamespaces.add(module);
  10696. }
  10697. if (this.isEmpty && module.isIncluded()) {
  10698. this.isEmpty = false;
  10699. }
  10700. if (module.info.isEntry || outputOptions.preserveModules) {
  10701. this.entryModules.push(module);
  10702. }
  10703. for (const importer of module.includedDynamicImporters) {
  10704. if (!chunkModules.has(importer)) {
  10705. this.dynamicEntryModules.push(module);
  10706. // Modules with synthetic exports need an artificial namespace for dynamic imports
  10707. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  10708. includedNamespaces.add(module);
  10709. this.exports.add(module.namespace);
  10710. }
  10711. }
  10712. }
  10713. if (module.implicitlyLoadedAfter.size > 0) {
  10714. this.implicitEntryModules.push(module);
  10715. }
  10716. }
  10717. this.suggestedVariableName = makeLegal(this.generateVariableName());
  10718. }
  10719. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  10720. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  10721. chunk.assignFacadeName(facadeName, facadedModule);
  10722. if (!facadeChunkByModule.has(facadedModule)) {
  10723. facadeChunkByModule.set(facadedModule, chunk);
  10724. }
  10725. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  10726. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  10727. }
  10728. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  10729. facadedModule.info.hasModuleSideEffects &&
  10730. facadedModule.hasEffects()) {
  10731. chunk.dependencies.add(chunkByModule.get(facadedModule));
  10732. }
  10733. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  10734. chunk.facadeModule = facadedModule;
  10735. chunk.strictFacade = true;
  10736. return chunk;
  10737. }
  10738. canModuleBeFacade(module, exposedVariables) {
  10739. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  10740. for (const exposedVariable of this.exports) {
  10741. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  10742. if (moduleExportNamesByVariable.size === 0 &&
  10743. module.isUserDefinedEntryPoint &&
  10744. module.preserveSignature === 'strict' &&
  10745. this.unsetOptions.has('preserveEntrySignatures')) {
  10746. this.inputOptions.onwarn({
  10747. code: 'EMPTY_FACADE',
  10748. id: module.id,
  10749. 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.`,
  10750. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  10751. });
  10752. }
  10753. return false;
  10754. }
  10755. }
  10756. for (const exposedVariable of exposedVariables) {
  10757. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  10758. return false;
  10759. }
  10760. }
  10761. return true;
  10762. }
  10763. generateExports() {
  10764. this.sortedExportNames = null;
  10765. const remainingExports = new Set(this.exports);
  10766. if (this.facadeModule !== null &&
  10767. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  10768. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  10769. for (const [variable, exportNames] of exportNamesByVariable) {
  10770. this.exportNamesByVariable.set(variable, [...exportNames]);
  10771. for (const exportName of exportNames) {
  10772. this.exportsByName[exportName] = variable;
  10773. }
  10774. remainingExports.delete(variable);
  10775. }
  10776. }
  10777. if (this.outputOptions.minifyInternalExports) {
  10778. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10779. }
  10780. else {
  10781. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  10782. }
  10783. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  10784. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  10785. }
  10786. generateFacades() {
  10787. var _a;
  10788. const facades = [];
  10789. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  10790. const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
  10791. for (const module of entryModules) {
  10792. if (module.preserveSignature) {
  10793. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  10794. exposedVariables.add(exportedVariable);
  10795. }
  10796. }
  10797. }
  10798. for (const module of entryModules) {
  10799. const requiredFacades = Array.from(module.userChunkNames, name => ({
  10800. name
  10801. }));
  10802. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  10803. requiredFacades.push({});
  10804. }
  10805. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  10806. if (requiredFacades.length === 0) {
  10807. requiredFacades.push({});
  10808. }
  10809. if (!this.facadeModule) {
  10810. const needsStrictFacade = module.preserveSignature === 'strict' ||
  10811. (module.preserveSignature === 'exports-only' &&
  10812. module.getExportNamesByVariable().size !== 0);
  10813. if (!needsStrictFacade ||
  10814. this.outputOptions.preserveModules ||
  10815. this.canModuleBeFacade(module, exposedVariables)) {
  10816. this.facadeModule = module;
  10817. this.facadeChunkByModule.set(module, this);
  10818. if (module.preserveSignature) {
  10819. this.strictFacade = needsStrictFacade;
  10820. }
  10821. this.assignFacadeName(requiredFacades.shift(), module);
  10822. }
  10823. }
  10824. for (const facadeName of requiredFacades) {
  10825. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  10826. }
  10827. }
  10828. for (const module of this.dynamicEntryModules) {
  10829. if (module.info.syntheticNamedExports)
  10830. continue;
  10831. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  10832. this.facadeModule = module;
  10833. this.facadeChunkByModule.set(module, this);
  10834. this.strictFacade = true;
  10835. this.assignFacadeName({}, module);
  10836. }
  10837. else if (this.facadeModule === module &&
  10838. !this.strictFacade &&
  10839. this.canModuleBeFacade(module, exposedVariables)) {
  10840. this.strictFacade = true;
  10841. }
  10842. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  10843. this.includedNamespaces.add(module);
  10844. this.exports.add(module.namespace);
  10845. }
  10846. }
  10847. return facades;
  10848. }
  10849. generateId(addons, options, existingNames, includeHash) {
  10850. if (this.fileName !== null) {
  10851. return this.fileName;
  10852. }
  10853. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  10854. ? [options.entryFileNames, 'output.entryFileNames']
  10855. : [options.chunkFileNames, 'output.chunkFileNames'];
  10856. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  10857. format: () => options.format,
  10858. hash: () => includeHash
  10859. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  10860. : '[hash]',
  10861. name: () => this.getChunkName()
  10862. }), existingNames);
  10863. }
  10864. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  10865. const id = this.orderedModules[0].id;
  10866. const sanitizedId = sanitizeFileName(id);
  10867. let path$1;
  10868. if (isAbsolute(id)) {
  10869. const extension = path.extname(id);
  10870. const pattern = unsetOptions.has('entryFileNames')
  10871. ? NON_ASSET_EXTENSIONS.includes(extension)
  10872. ? '[name].js'
  10873. : '[name][extname].js'
  10874. : options.entryFileNames;
  10875. const currentDir = path.dirname(sanitizedId);
  10876. const fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, 'output.entryFileNames', {
  10877. ext: () => extension.substr(1),
  10878. extname: () => extension,
  10879. format: () => options.format,
  10880. name: () => this.getChunkName()
  10881. });
  10882. const currentPath = `${currentDir}/${fileName}`;
  10883. const { preserveModulesRoot } = options;
  10884. if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
  10885. path$1 = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  10886. }
  10887. else {
  10888. path$1 = relative(preserveModulesRelativeDir, currentPath);
  10889. }
  10890. }
  10891. else {
  10892. path$1 = `_virtual/${path.basename(sanitizedId)}`;
  10893. }
  10894. return makeUnique(normalize(path$1), existingNames);
  10895. }
  10896. getChunkInfo() {
  10897. const facadeModule = this.facadeModule;
  10898. const getChunkName = this.getChunkName.bind(this);
  10899. return {
  10900. exports: this.getExportNames(),
  10901. facadeModuleId: facadeModule && facadeModule.id,
  10902. isDynamicEntry: this.dynamicEntryModules.length > 0,
  10903. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  10904. isImplicitEntry: this.implicitEntryModules.length > 0,
  10905. modules: this.renderedModules,
  10906. get name() {
  10907. return getChunkName();
  10908. },
  10909. type: 'chunk'
  10910. };
  10911. }
  10912. getChunkInfoWithFileNames() {
  10913. return Object.assign(this.getChunkInfo(), {
  10914. code: undefined,
  10915. dynamicImports: Array.from(this.dynamicDependencies, getId),
  10916. fileName: this.id,
  10917. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  10918. importedBindings: this.getImportedBindingsPerDependency(),
  10919. imports: Array.from(this.dependencies, getId),
  10920. map: undefined,
  10921. referencedFiles: this.getReferencedFiles()
  10922. });
  10923. }
  10924. getChunkName() {
  10925. return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
  10926. }
  10927. getExportNames() {
  10928. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
  10929. }
  10930. getRenderedHash() {
  10931. if (this.renderedHash)
  10932. return this.renderedHash;
  10933. const hash = createHash();
  10934. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  10935. if (pluginHash) {
  10936. augmentation += pluginHash;
  10937. }
  10938. return augmentation;
  10939. });
  10940. hash.update(hashAugmentation);
  10941. hash.update(this.renderedSource.toString());
  10942. hash.update(this.getExportNames()
  10943. .map(exportName => {
  10944. const variable = this.exportsByName[exportName];
  10945. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  10946. })
  10947. .join(','));
  10948. return (this.renderedHash = hash.digest('hex'));
  10949. }
  10950. getVariableExportName(variable) {
  10951. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  10952. return '*';
  10953. }
  10954. return this.exportNamesByVariable.get(variable)[0];
  10955. }
  10956. link() {
  10957. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  10958. for (const module of this.orderedModules) {
  10959. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  10960. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  10961. this.setUpChunkImportsAndExportsForModule(module);
  10962. }
  10963. }
  10964. // prerender allows chunk hashes and names to be generated before finalizing
  10965. preRender(options, inputBase) {
  10966. const magicString = new Bundle$1({ separator: options.compact ? '' : '\n\n' });
  10967. this.usedModules = [];
  10968. this.indentString = getIndentString(this.orderedModules, options);
  10969. const n = options.compact ? '' : '\n';
  10970. const _ = options.compact ? '' : ' ';
  10971. const renderOptions = {
  10972. compact: options.compact,
  10973. dynamicImportFunction: options.dynamicImportFunction,
  10974. exportNamesByVariable: this.exportNamesByVariable,
  10975. format: options.format,
  10976. freeze: options.freeze,
  10977. indent: this.indentString,
  10978. namespaceToStringTag: options.namespaceToStringTag,
  10979. outputPluginDriver: this.pluginDriver,
  10980. varOrConst: options.preferConst ? 'const' : 'var'
  10981. };
  10982. // for static and dynamic entry points, inline the execution list to avoid loading latency
  10983. if (options.hoistTransitiveImports &&
  10984. !this.outputOptions.preserveModules &&
  10985. this.facadeModule !== null) {
  10986. for (const dep of this.dependencies) {
  10987. if (dep instanceof Chunk)
  10988. this.inlineChunkDependencies(dep);
  10989. }
  10990. }
  10991. this.prepareDynamicImportsAndImportMetas();
  10992. this.setIdentifierRenderResolutions(options);
  10993. let hoistedSource = '';
  10994. const renderedModules = this.renderedModules;
  10995. for (const module of this.orderedModules) {
  10996. let renderedLength = 0;
  10997. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  10998. const source = module.render(renderOptions).trim();
  10999. renderedLength = source.length();
  11000. if (renderedLength) {
  11001. if (options.compact && source.lastLine().indexOf('//') !== -1)
  11002. source.append('\n');
  11003. this.renderedModuleSources.set(module, source);
  11004. magicString.addSource(source);
  11005. this.usedModules.push(module);
  11006. }
  11007. const namespace = module.namespace;
  11008. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  11009. const rendered = namespace.renderBlock(renderOptions);
  11010. if (namespace.renderFirst())
  11011. hoistedSource += n + rendered;
  11012. else
  11013. magicString.addSource(new MagicString(rendered));
  11014. }
  11015. }
  11016. const { renderedExports, removedExports } = module.getRenderedExports();
  11017. renderedModules[module.id] = {
  11018. originalLength: module.originalCode.length,
  11019. removedExports,
  11020. renderedExports,
  11021. renderedLength
  11022. };
  11023. }
  11024. if (hoistedSource)
  11025. magicString.prepend(hoistedSource + n + n);
  11026. if (this.needsExportsShim) {
  11027. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  11028. }
  11029. if (options.compact) {
  11030. this.renderedSource = magicString;
  11031. }
  11032. else {
  11033. this.renderedSource = magicString.trim();
  11034. }
  11035. this.renderedHash = undefined;
  11036. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  11037. const chunkName = this.getChunkName();
  11038. this.inputOptions.onwarn({
  11039. chunkName,
  11040. code: 'EMPTY_BUNDLE',
  11041. message: `Generated an empty chunk: "${chunkName}"`
  11042. });
  11043. }
  11044. this.setExternalRenderPaths(options, inputBase);
  11045. this.renderedDependencies = this.getChunkDependencyDeclarations(options);
  11046. this.renderedExports =
  11047. this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
  11048. }
  11049. async render(options, addons, outputChunk) {
  11050. timeStart('render format', 2);
  11051. const format = options.format;
  11052. const finalise = finalisers[format];
  11053. if (options.dynamicImportFunction && format !== 'es') {
  11054. this.inputOptions.onwarn({
  11055. code: 'INVALID_OPTION',
  11056. message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
  11057. });
  11058. }
  11059. // populate ids in the rendered declarations only here
  11060. // as chunk ids known only after prerender
  11061. for (const dependency of this.dependencies) {
  11062. const renderedDependency = this.renderedDependencies.get(dependency);
  11063. if (dependency instanceof ExternalModule) {
  11064. const originalId = dependency.renderPath;
  11065. renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
  11066. }
  11067. else {
  11068. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  11069. renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
  11070. }
  11071. }
  11072. this.finaliseDynamicImports(options);
  11073. this.finaliseImportMetas(format);
  11074. const hasExports = this.renderedExports.length !== 0 ||
  11075. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  11076. let usesTopLevelAwait = false;
  11077. const accessedGlobals = new Set();
  11078. for (const module of this.orderedModules) {
  11079. if (module.usesTopLevelAwait) {
  11080. usesTopLevelAwait = true;
  11081. }
  11082. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  11083. if (accessedGlobalVariables) {
  11084. for (const name of accessedGlobalVariables) {
  11085. accessedGlobals.add(name);
  11086. }
  11087. }
  11088. }
  11089. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  11090. return error({
  11091. code: 'INVALID_TLA_FORMAT',
  11092. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  11093. });
  11094. }
  11095. /* istanbul ignore next */
  11096. if (!this.id) {
  11097. throw new Error('Internal Error: expecting chunk id');
  11098. }
  11099. const magicString = finalise(this.renderedSource, {
  11100. accessedGlobals,
  11101. dependencies: [...this.renderedDependencies.values()],
  11102. exports: this.renderedExports,
  11103. hasExports,
  11104. id: this.id,
  11105. indentString: this.indentString,
  11106. intro: addons.intro,
  11107. isEntryFacade: this.outputOptions.preserveModules ||
  11108. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  11109. isModuleFacade: this.facadeModule !== null,
  11110. namedExportsMode: this.exportMode !== 'default',
  11111. outro: addons.outro,
  11112. usesTopLevelAwait,
  11113. varOrConst: options.preferConst ? 'const' : 'var',
  11114. warn: this.inputOptions.onwarn
  11115. }, options);
  11116. if (addons.banner)
  11117. magicString.prepend(addons.banner);
  11118. if (addons.footer)
  11119. magicString.append(addons.footer);
  11120. const prevCode = magicString.toString();
  11121. timeEnd('render format', 2);
  11122. let map = null;
  11123. const chunkSourcemapChain = [];
  11124. let code = await renderChunk({
  11125. code: prevCode,
  11126. options,
  11127. outputPluginDriver: this.pluginDriver,
  11128. renderChunk: outputChunk,
  11129. sourcemapChain: chunkSourcemapChain
  11130. });
  11131. if (options.sourcemap) {
  11132. timeStart('sourcemap', 2);
  11133. let file;
  11134. if (options.file)
  11135. file = path.resolve(options.sourcemapFile || options.file);
  11136. else if (options.dir)
  11137. file = path.resolve(options.dir, this.id);
  11138. else
  11139. file = path.resolve(this.id);
  11140. const decodedMap = magicString.generateDecodedMap({});
  11141. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  11142. map.sources = map.sources
  11143. .map(sourcePath => {
  11144. const { sourcemapPathTransform } = options;
  11145. if (sourcemapPathTransform) {
  11146. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  11147. if (typeof newSourcePath !== 'string') {
  11148. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  11149. }
  11150. return newSourcePath;
  11151. }
  11152. return sourcePath;
  11153. })
  11154. .map(normalize);
  11155. timeEnd('sourcemap', 2);
  11156. }
  11157. if (!options.compact && code[code.length - 1] !== '\n')
  11158. code += '\n';
  11159. return { code, map };
  11160. }
  11161. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  11162. for (const module of moduleDependencies) {
  11163. if (module instanceof Module) {
  11164. const chunk = this.chunkByModule.get(module);
  11165. if (chunk && chunk !== this) {
  11166. chunkDependencies.add(chunk);
  11167. }
  11168. }
  11169. else {
  11170. chunkDependencies.add(module);
  11171. }
  11172. }
  11173. }
  11174. assignFacadeName({ fileName, name }, facadedModule) {
  11175. if (fileName) {
  11176. this.fileName = fileName;
  11177. }
  11178. else {
  11179. this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
  11180. }
  11181. }
  11182. checkCircularDependencyImport(variable, importingModule) {
  11183. const variableModule = variable.module;
  11184. if (variableModule instanceof Module) {
  11185. const exportChunk = this.chunkByModule.get(variableModule);
  11186. let alternativeReexportModule;
  11187. do {
  11188. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  11189. if (alternativeReexportModule) {
  11190. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  11191. if (exportingChunk && exportingChunk !== exportChunk) {
  11192. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  11193. }
  11194. importingModule = alternativeReexportModule;
  11195. }
  11196. } while (alternativeReexportModule);
  11197. }
  11198. }
  11199. computeContentHashWithDependencies(addons, options, existingNames) {
  11200. const hash = createHash();
  11201. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  11202. hash.update(options.format);
  11203. const dependenciesForHashing = new Set([this]);
  11204. for (const current of dependenciesForHashing) {
  11205. if (current instanceof ExternalModule) {
  11206. hash.update(':' + current.renderPath);
  11207. }
  11208. else {
  11209. hash.update(current.getRenderedHash());
  11210. hash.update(current.generateId(addons, options, existingNames, false));
  11211. }
  11212. if (current instanceof ExternalModule)
  11213. continue;
  11214. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  11215. dependenciesForHashing.add(dependency);
  11216. }
  11217. }
  11218. return hash.digest('hex').substr(0, 8);
  11219. }
  11220. ensureReexportsAreAvailableForModule(module) {
  11221. const map = module.getExportNamesByVariable();
  11222. for (const exportedVariable of map.keys()) {
  11223. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  11224. const importedVariable = isSynthetic
  11225. ? exportedVariable.getBaseVariable()
  11226. : exportedVariable;
  11227. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  11228. this.checkCircularDependencyImport(importedVariable, module);
  11229. const exportingModule = importedVariable.module;
  11230. if (exportingModule instanceof Module) {
  11231. const chunk = this.chunkByModule.get(exportingModule);
  11232. if (chunk && chunk !== this) {
  11233. chunk.exports.add(importedVariable);
  11234. if (isSynthetic) {
  11235. this.imports.add(importedVariable);
  11236. }
  11237. }
  11238. }
  11239. }
  11240. }
  11241. }
  11242. finaliseDynamicImports(options) {
  11243. const stripKnownJsExtensions = options.format === 'amd';
  11244. for (const [module, code] of this.renderedModuleSources) {
  11245. for (const { node, resolution } of module.dynamicImports) {
  11246. const chunk = this.chunkByModule.get(resolution);
  11247. const facadeChunk = this.facadeChunkByModule.get(resolution);
  11248. if (!resolution || !node.included || chunk === this) {
  11249. continue;
  11250. }
  11251. const renderedResolution = resolution instanceof Module
  11252. ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
  11253. : resolution instanceof ExternalModule
  11254. ? `'${resolution.renormalizeRenderPath
  11255. ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
  11256. : resolution.renderPath}'`
  11257. : resolution;
  11258. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  11259. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  11260. chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
  11261. }
  11262. }
  11263. }
  11264. finaliseImportMetas(format) {
  11265. for (const [module, code] of this.renderedModuleSources) {
  11266. for (const importMeta of module.importMetas) {
  11267. importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
  11268. }
  11269. }
  11270. }
  11271. generateVariableName() {
  11272. if (this.manualChunkAlias) {
  11273. return this.manualChunkAlias;
  11274. }
  11275. const moduleForNaming = this.entryModules[0] ||
  11276. this.implicitEntryModules[0] ||
  11277. this.dynamicEntryModules[0] ||
  11278. this.orderedModules[this.orderedModules.length - 1];
  11279. if (moduleForNaming) {
  11280. return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
  11281. }
  11282. return 'chunk';
  11283. }
  11284. getChunkDependencyDeclarations(options) {
  11285. const importSpecifiers = this.getImportSpecifiers();
  11286. const reexportSpecifiers = this.getReexportSpecifiers();
  11287. const dependencyDeclaration = new Map();
  11288. for (const dep of this.dependencies) {
  11289. const imports = importSpecifiers.get(dep) || null;
  11290. const reexports = reexportSpecifiers.get(dep) || null;
  11291. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  11292. dependencyDeclaration.set(dep, {
  11293. defaultVariableName: dep.defaultVariableName,
  11294. globalName: (dep instanceof ExternalModule &&
  11295. (options.format === 'umd' || options.format === 'iife') &&
  11296. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  11297. id: undefined,
  11298. imports,
  11299. isChunk: dep instanceof Chunk,
  11300. name: dep.variableName,
  11301. namedExportsMode,
  11302. namespaceVariableName: dep.namespaceVariableName,
  11303. reexports
  11304. });
  11305. }
  11306. return dependencyDeclaration;
  11307. }
  11308. getChunkExportDeclarations(format) {
  11309. const exports = [];
  11310. for (const exportName of this.getExportNames()) {
  11311. if (exportName[0] === '*')
  11312. continue;
  11313. const variable = this.exportsByName[exportName];
  11314. if (!(variable instanceof SyntheticNamedExportVariable)) {
  11315. const module = variable.module;
  11316. if (module && this.chunkByModule.get(module) !== this)
  11317. continue;
  11318. }
  11319. let expression = null;
  11320. let hoisted = false;
  11321. let uninitialized = false;
  11322. let local = variable.getName();
  11323. if (variable instanceof LocalVariable) {
  11324. if (variable.init === UNDEFINED_EXPRESSION) {
  11325. uninitialized = true;
  11326. }
  11327. for (const declaration of variable.declarations) {
  11328. if (declaration.parent instanceof FunctionDeclaration ||
  11329. (declaration instanceof ExportDefaultDeclaration &&
  11330. declaration.declaration instanceof FunctionDeclaration)) {
  11331. hoisted = true;
  11332. break;
  11333. }
  11334. }
  11335. }
  11336. else if (variable instanceof SyntheticNamedExportVariable) {
  11337. expression = local;
  11338. if (format === 'es' && exportName !== 'default') {
  11339. local = variable.renderName;
  11340. }
  11341. }
  11342. exports.push({
  11343. exported: exportName,
  11344. expression,
  11345. hoisted,
  11346. local,
  11347. uninitialized
  11348. });
  11349. }
  11350. return exports;
  11351. }
  11352. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  11353. const dependencies = new Set();
  11354. const deconflictedDefault = new Set();
  11355. const deconflictedNamespace = new Set();
  11356. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  11357. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  11358. const module = variable.module;
  11359. if (module instanceof ExternalModule) {
  11360. dependencies.add(module);
  11361. if (addNonNamespacesAndInteropHelpers) {
  11362. if (variable.name === 'default') {
  11363. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  11364. deconflictedDefault.add(module);
  11365. }
  11366. }
  11367. else if (variable.name === '*') {
  11368. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  11369. deconflictedNamespace.add(module);
  11370. }
  11371. }
  11372. }
  11373. }
  11374. else {
  11375. const chunk = this.chunkByModule.get(module);
  11376. if (chunk !== this) {
  11377. dependencies.add(chunk);
  11378. if (addNonNamespacesAndInteropHelpers &&
  11379. chunk.exportMode === 'default' &&
  11380. variable.isNamespace) {
  11381. deconflictedNamespace.add(chunk);
  11382. }
  11383. }
  11384. }
  11385. }
  11386. }
  11387. if (addDependenciesWithoutBindings) {
  11388. for (const dependency of this.dependencies) {
  11389. dependencies.add(dependency);
  11390. }
  11391. }
  11392. return { deconflictedDefault, deconflictedNamespace, dependencies };
  11393. }
  11394. getFallbackChunkName() {
  11395. if (this.manualChunkAlias) {
  11396. return this.manualChunkAlias;
  11397. }
  11398. if (this.fileName) {
  11399. return getAliasName(this.fileName);
  11400. }
  11401. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  11402. }
  11403. getImportedBindingsPerDependency() {
  11404. const importSpecifiers = {};
  11405. for (const [dependency, declaration] of this.renderedDependencies) {
  11406. const specifiers = new Set();
  11407. if (declaration.imports) {
  11408. for (const { imported } of declaration.imports) {
  11409. specifiers.add(imported);
  11410. }
  11411. }
  11412. if (declaration.reexports) {
  11413. for (const { imported } of declaration.reexports) {
  11414. specifiers.add(imported);
  11415. }
  11416. }
  11417. importSpecifiers[dependency.id] = [...specifiers];
  11418. }
  11419. return importSpecifiers;
  11420. }
  11421. getImportSpecifiers() {
  11422. const { interop } = this.outputOptions;
  11423. const importsByDependency = new Map();
  11424. for (const variable of this.imports) {
  11425. const module = variable.module;
  11426. let dependency;
  11427. let imported;
  11428. if (module instanceof ExternalModule) {
  11429. dependency = module;
  11430. imported = variable.name;
  11431. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11432. return error(errUnexpectedNamedImport(module.id, imported, false));
  11433. }
  11434. }
  11435. else {
  11436. dependency = this.chunkByModule.get(module);
  11437. imported = dependency.getVariableExportName(variable);
  11438. }
  11439. getOrCreate(importsByDependency, dependency, () => []).push({
  11440. imported,
  11441. local: variable.getName()
  11442. });
  11443. }
  11444. return importsByDependency;
  11445. }
  11446. getReexportSpecifiers() {
  11447. const { externalLiveBindings, interop } = this.outputOptions;
  11448. const reexportSpecifiers = new Map();
  11449. for (let exportName of this.getExportNames()) {
  11450. let dependency;
  11451. let imported;
  11452. let needsLiveBinding = false;
  11453. if (exportName[0] === '*') {
  11454. const id = exportName.substr(1);
  11455. if (interop(id) === 'defaultOnly') {
  11456. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  11457. }
  11458. needsLiveBinding = externalLiveBindings;
  11459. dependency = this.modulesById.get(id);
  11460. imported = exportName = '*';
  11461. }
  11462. else {
  11463. const variable = this.exportsByName[exportName];
  11464. if (variable instanceof SyntheticNamedExportVariable)
  11465. continue;
  11466. const module = variable.module;
  11467. if (module instanceof Module) {
  11468. dependency = this.chunkByModule.get(module);
  11469. if (dependency === this)
  11470. continue;
  11471. imported = dependency.getVariableExportName(variable);
  11472. needsLiveBinding = variable.isReassigned;
  11473. }
  11474. else {
  11475. dependency = module;
  11476. imported = variable.name;
  11477. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  11478. return error(errUnexpectedNamedImport(module.id, imported, true));
  11479. }
  11480. needsLiveBinding =
  11481. externalLiveBindings &&
  11482. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  11483. }
  11484. }
  11485. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  11486. imported,
  11487. needsLiveBinding,
  11488. reexported: exportName
  11489. });
  11490. }
  11491. return reexportSpecifiers;
  11492. }
  11493. getReferencedFiles() {
  11494. const referencedFiles = [];
  11495. for (const module of this.orderedModules) {
  11496. for (const meta of module.importMetas) {
  11497. const fileName = meta.getReferencedFileName(this.pluginDriver);
  11498. if (fileName) {
  11499. referencedFiles.push(fileName);
  11500. }
  11501. }
  11502. }
  11503. return referencedFiles;
  11504. }
  11505. getRelativePath(targetPath, stripJsExtension) {
  11506. let relativePath = normalize(relative(path.dirname(this.id), targetPath));
  11507. if (stripJsExtension && relativePath.endsWith('.js')) {
  11508. relativePath = relativePath.slice(0, -3);
  11509. }
  11510. if (relativePath === '..')
  11511. return '../../' + path.basename(targetPath);
  11512. if (relativePath === '')
  11513. return '../' + path.basename(targetPath);
  11514. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  11515. }
  11516. inlineChunkDependencies(chunk) {
  11517. for (const dep of chunk.dependencies) {
  11518. if (this.dependencies.has(dep))
  11519. continue;
  11520. this.dependencies.add(dep);
  11521. if (dep instanceof Chunk) {
  11522. this.inlineChunkDependencies(dep);
  11523. }
  11524. }
  11525. }
  11526. prepareDynamicImportsAndImportMetas() {
  11527. var _a;
  11528. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  11529. for (const module of this.orderedModules) {
  11530. for (const { node, resolution } of module.dynamicImports) {
  11531. if (node.included) {
  11532. if (resolution instanceof Module) {
  11533. const chunk = this.chunkByModule.get(resolution);
  11534. if (chunk === this) {
  11535. node.setInternalResolution(resolution.namespace);
  11536. }
  11537. else {
  11538. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11539. }
  11540. }
  11541. else {
  11542. node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  11543. }
  11544. }
  11545. }
  11546. for (const importMeta of module.importMetas) {
  11547. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  11548. }
  11549. }
  11550. }
  11551. setExternalRenderPaths(options, inputBase) {
  11552. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  11553. if (dependency instanceof ExternalModule) {
  11554. dependency.setRenderPath(options, inputBase);
  11555. }
  11556. }
  11557. }
  11558. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  11559. const syntheticExports = new Set();
  11560. for (const exportName of this.getExportNames()) {
  11561. const exportVariable = this.exportsByName[exportName];
  11562. if (exportVariable instanceof ExportShimVariable) {
  11563. this.needsExportsShim = true;
  11564. }
  11565. if (format !== 'es' &&
  11566. format !== 'system' &&
  11567. exportVariable.isReassigned &&
  11568. !exportVariable.isId) {
  11569. exportVariable.setRenderNames('exports', exportName);
  11570. }
  11571. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  11572. syntheticExports.add(exportVariable);
  11573. }
  11574. else {
  11575. exportVariable.setRenderNames(null, null);
  11576. }
  11577. }
  11578. const usedNames = new Set(['Object', 'Promise']);
  11579. if (this.needsExportsShim) {
  11580. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  11581. }
  11582. if (namespaceToStringTag) {
  11583. usedNames.add('Symbol');
  11584. }
  11585. switch (format) {
  11586. case 'system':
  11587. usedNames.add('module').add('exports');
  11588. break;
  11589. case 'es':
  11590. break;
  11591. case 'cjs':
  11592. usedNames.add('module').add('require').add('__filename').add('__dirname');
  11593. // fallthrough
  11594. default:
  11595. usedNames.add('exports');
  11596. for (const helper of HELPER_NAMES) {
  11597. usedNames.add(helper);
  11598. }
  11599. }
  11600. 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);
  11601. }
  11602. setUpChunkImportsAndExportsForModule(module) {
  11603. const moduleImports = new Set(module.imports);
  11604. // when we are not preserving modules, we need to make all namespace variables available for
  11605. // rendering the namespace object
  11606. if (!this.outputOptions.preserveModules) {
  11607. if (this.includedNamespaces.has(module)) {
  11608. const memberVariables = module.namespace.getMemberVariables();
  11609. for (const name of Object.keys(memberVariables)) {
  11610. moduleImports.add(memberVariables[name]);
  11611. }
  11612. }
  11613. }
  11614. for (let variable of moduleImports) {
  11615. if (variable instanceof ExportDefaultVariable) {
  11616. variable = variable.getOriginalVariable();
  11617. }
  11618. if (variable instanceof SyntheticNamedExportVariable) {
  11619. variable = variable.getBaseVariable();
  11620. }
  11621. const chunk = this.chunkByModule.get(variable.module);
  11622. if (chunk !== this) {
  11623. this.imports.add(variable);
  11624. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  11625. variable.module instanceof Module) {
  11626. chunk.exports.add(variable);
  11627. this.checkCircularDependencyImport(variable, module);
  11628. }
  11629. }
  11630. }
  11631. if (this.includedNamespaces.has(module) ||
  11632. (module.info.isEntry && module.preserveSignature !== false) ||
  11633. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  11634. this.ensureReexportsAreAvailableForModule(module);
  11635. }
  11636. for (const { node, resolution } of module.dynamicImports) {
  11637. if (node.included &&
  11638. resolution instanceof Module &&
  11639. this.chunkByModule.get(resolution) === this &&
  11640. !this.includedNamespaces.has(resolution)) {
  11641. this.includedNamespaces.add(resolution);
  11642. this.ensureReexportsAreAvailableForModule(resolution);
  11643. }
  11644. }
  11645. }
  11646. }
  11647. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  11648. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  11649. async function createAddons(options, outputPluginDriver) {
  11650. try {
  11651. let [banner, footer, intro, outro] = await Promise.all([
  11652. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  11653. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  11654. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  11655. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  11656. ]);
  11657. if (intro)
  11658. intro += '\n\n';
  11659. if (outro)
  11660. outro = `\n\n${outro}`;
  11661. if (banner.length)
  11662. banner += '\n';
  11663. if (footer.length)
  11664. footer = '\n' + footer;
  11665. return { intro, outro, banner, footer };
  11666. }
  11667. catch (err) {
  11668. return error({
  11669. code: 'ADDON_ERROR',
  11670. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  11671. \tError Message: ${err.message}`
  11672. });
  11673. }
  11674. }
  11675. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  11676. const chunkDefinitions = [];
  11677. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  11678. const manualChunkModulesByAlias = Object.create(null);
  11679. for (const [entry, alias] of manualChunkAliasByEntry) {
  11680. const chunkModules = (manualChunkModulesByAlias[alias] =
  11681. manualChunkModulesByAlias[alias] || []);
  11682. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  11683. }
  11684. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  11685. chunkDefinitions.push({ alias, modules });
  11686. }
  11687. const assignedEntryPointsByModule = new Map();
  11688. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  11689. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  11690. const staticEntries = new Set(entryModules);
  11691. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  11692. const modulesToHandle = new Set([entry]);
  11693. for (const module of modulesToHandle) {
  11694. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  11695. if (dynamicDependentEntryPoints &&
  11696. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  11697. continue;
  11698. }
  11699. else {
  11700. assignedEntryPoints.add(entry);
  11701. }
  11702. for (const dependency of module.getDependenciesToBeIncluded()) {
  11703. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11704. modulesToHandle.add(dependency);
  11705. }
  11706. }
  11707. }
  11708. }
  11709. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  11710. const entriesToCheck = new Set(entryPoints);
  11711. for (const entry of entriesToCheck) {
  11712. if (!containedIn.has(entry)) {
  11713. if (staticEntries.has(entry))
  11714. return false;
  11715. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  11716. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  11717. entriesToCheck.add(dependentEntry);
  11718. }
  11719. }
  11720. }
  11721. return true;
  11722. }
  11723. for (const entry of entryModules) {
  11724. if (!modulesInManualChunks.has(entry)) {
  11725. assignEntryToStaticDependencies(entry, null);
  11726. }
  11727. }
  11728. for (const entry of dynamicEntryModules) {
  11729. if (!modulesInManualChunks.has(entry)) {
  11730. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  11731. }
  11732. }
  11733. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  11734. return chunkDefinitions;
  11735. }
  11736. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  11737. const modulesToHandle = new Set([entry]);
  11738. for (const module of modulesToHandle) {
  11739. modulesInManualChunks.add(module);
  11740. manualChunkModules.push(module);
  11741. for (const dependency of module.dependencies) {
  11742. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  11743. modulesToHandle.add(dependency);
  11744. }
  11745. }
  11746. }
  11747. }
  11748. function analyzeModuleGraph(entryModules) {
  11749. const dynamicEntryModules = new Set();
  11750. const dependentEntryPointsByModule = new Map();
  11751. const entriesToHandle = new Set(entryModules);
  11752. for (const currentEntry of entriesToHandle) {
  11753. const modulesToHandle = new Set([currentEntry]);
  11754. for (const module of modulesToHandle) {
  11755. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  11756. for (const dependency of module.getDependenciesToBeIncluded()) {
  11757. if (!(dependency instanceof ExternalModule)) {
  11758. modulesToHandle.add(dependency);
  11759. }
  11760. }
  11761. for (const { resolution } of module.dynamicImports) {
  11762. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  11763. dynamicEntryModules.add(resolution);
  11764. entriesToHandle.add(resolution);
  11765. }
  11766. }
  11767. for (const dependency of module.implicitlyLoadedBefore) {
  11768. dynamicEntryModules.add(dependency);
  11769. entriesToHandle.add(dependency);
  11770. }
  11771. }
  11772. }
  11773. return { dependentEntryPointsByModule, dynamicEntryModules };
  11774. }
  11775. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  11776. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  11777. for (const dynamicEntry of dynamicEntryModules) {
  11778. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  11779. for (const importer of [
  11780. ...dynamicEntry.includedDynamicImporters,
  11781. ...dynamicEntry.implicitlyLoadedAfter
  11782. ]) {
  11783. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  11784. dynamicDependentEntryPoints.add(entryPoint);
  11785. }
  11786. }
  11787. }
  11788. return dynamicallyDependentEntryPointsByDynamicEntry;
  11789. }
  11790. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  11791. const chunkModules = Object.create(null);
  11792. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  11793. let chunkSignature = '';
  11794. for (const entry of allEntryPoints) {
  11795. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  11796. }
  11797. const chunk = chunkModules[chunkSignature];
  11798. if (chunk) {
  11799. chunk.push(module);
  11800. }
  11801. else {
  11802. chunkModules[chunkSignature] = [module];
  11803. }
  11804. }
  11805. return Object.keys(chunkModules).map(chunkSignature => ({
  11806. alias: null,
  11807. modules: chunkModules[chunkSignature]
  11808. }));
  11809. }
  11810. // ported from https://github.com/substack/node-commondir
  11811. function commondir(files) {
  11812. if (files.length === 0)
  11813. return '/';
  11814. if (files.length === 1)
  11815. return path.dirname(files[0]);
  11816. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  11817. const pathSegements = file.split(/\/+|\\+/);
  11818. let i;
  11819. for (i = 0; commonSegments[i] === pathSegements[i] &&
  11820. i < Math.min(commonSegments.length, pathSegements.length); i++)
  11821. ;
  11822. return commonSegments.slice(0, i);
  11823. }, files[0].split(/\/+|\\+/));
  11824. // Windows correctly handles paths with forward-slashes
  11825. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  11826. }
  11827. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  11828. function sortByExecutionOrder(units) {
  11829. units.sort(compareExecIndex);
  11830. }
  11831. function analyseModuleExecution(entryModules) {
  11832. let nextExecIndex = 0;
  11833. const cyclePaths = [];
  11834. const analysedModules = new Set();
  11835. const dynamicImports = new Set();
  11836. const parents = new Map();
  11837. const orderedModules = [];
  11838. const analyseModule = (module) => {
  11839. if (module instanceof Module) {
  11840. for (const dependency of module.dependencies) {
  11841. if (parents.has(dependency)) {
  11842. if (!analysedModules.has(dependency)) {
  11843. cyclePaths.push(getCyclePath(dependency, module, parents));
  11844. }
  11845. continue;
  11846. }
  11847. parents.set(dependency, module);
  11848. analyseModule(dependency);
  11849. }
  11850. for (const dependency of module.implicitlyLoadedBefore) {
  11851. dynamicImports.add(dependency);
  11852. }
  11853. for (const { resolution } of module.dynamicImports) {
  11854. if (resolution instanceof Module) {
  11855. dynamicImports.add(resolution);
  11856. }
  11857. }
  11858. orderedModules.push(module);
  11859. }
  11860. module.execIndex = nextExecIndex++;
  11861. analysedModules.add(module);
  11862. };
  11863. for (const curEntry of entryModules) {
  11864. if (!parents.has(curEntry)) {
  11865. parents.set(curEntry, null);
  11866. analyseModule(curEntry);
  11867. }
  11868. }
  11869. for (const curEntry of dynamicImports) {
  11870. if (!parents.has(curEntry)) {
  11871. parents.set(curEntry, null);
  11872. analyseModule(curEntry);
  11873. }
  11874. }
  11875. return { orderedModules, cyclePaths };
  11876. }
  11877. function getCyclePath(module, parent, parents) {
  11878. const cycleSymbol = Symbol(module.id);
  11879. const path = [relativeId(module.id)];
  11880. let nextModule = parent;
  11881. module.cycles.add(cycleSymbol);
  11882. while (nextModule !== module) {
  11883. nextModule.cycles.add(cycleSymbol);
  11884. path.push(relativeId(nextModule.id));
  11885. nextModule = parents.get(nextModule);
  11886. }
  11887. path.push(path[0]);
  11888. path.reverse();
  11889. return path;
  11890. }
  11891. var BuildPhase;
  11892. (function (BuildPhase) {
  11893. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  11894. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  11895. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  11896. })(BuildPhase || (BuildPhase = {}));
  11897. function generateAssetFileName(name, source, output) {
  11898. const emittedName = name || 'asset';
  11899. return makeUnique(renderNamePattern(typeof output.assetFileNames === 'function'
  11900. ? output.assetFileNames({ name, source, type: 'asset' })
  11901. : output.assetFileNames, 'output.assetFileNames', {
  11902. hash() {
  11903. const hash = createHash();
  11904. hash.update(emittedName);
  11905. hash.update(':');
  11906. hash.update(source);
  11907. return hash.digest('hex').substr(0, 8);
  11908. },
  11909. ext: () => path.extname(emittedName).substr(1),
  11910. extname: () => path.extname(emittedName),
  11911. name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
  11912. }), output.bundle);
  11913. }
  11914. function reserveFileNameInBundle(fileName, bundle, warn) {
  11915. if (fileName in bundle) {
  11916. warn(errFileNameConflict(fileName));
  11917. }
  11918. bundle[fileName] = FILE_PLACEHOLDER;
  11919. }
  11920. const FILE_PLACEHOLDER = {
  11921. type: 'placeholder'
  11922. };
  11923. function hasValidType(emittedFile) {
  11924. return Boolean(emittedFile &&
  11925. (emittedFile.type === 'asset' ||
  11926. emittedFile.type === 'chunk'));
  11927. }
  11928. function hasValidName(emittedFile) {
  11929. const validatedName = emittedFile.fileName || emittedFile.name;
  11930. return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
  11931. }
  11932. function getValidSource(source, emittedFile, fileReferenceId) {
  11933. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  11934. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  11935. 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.`));
  11936. }
  11937. return source;
  11938. }
  11939. function getAssetFileName(file, referenceId) {
  11940. if (typeof file.fileName !== 'string') {
  11941. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  11942. }
  11943. return file.fileName;
  11944. }
  11945. function getChunkFileName(file, facadeChunkByModule) {
  11946. var _a;
  11947. 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));
  11948. if (!fileName)
  11949. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  11950. return fileName;
  11951. }
  11952. class FileEmitter {
  11953. constructor(graph, options, baseFileEmitter) {
  11954. this.graph = graph;
  11955. this.options = options;
  11956. this.facadeChunkByModule = null;
  11957. this.output = null;
  11958. this.assertAssetsFinalized = () => {
  11959. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  11960. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  11961. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  11962. }
  11963. };
  11964. this.emitFile = (emittedFile) => {
  11965. if (!hasValidType(emittedFile)) {
  11966. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  11967. }
  11968. if (!hasValidName(emittedFile)) {
  11969. return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || emittedFile.name}".`));
  11970. }
  11971. if (emittedFile.type === 'chunk') {
  11972. return this.emitChunk(emittedFile);
  11973. }
  11974. else {
  11975. return this.emitAsset(emittedFile);
  11976. }
  11977. };
  11978. this.getFileName = (fileReferenceId) => {
  11979. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  11980. if (!emittedFile)
  11981. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  11982. if (emittedFile.type === 'chunk') {
  11983. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  11984. }
  11985. else {
  11986. return getAssetFileName(emittedFile, fileReferenceId);
  11987. }
  11988. };
  11989. this.setAssetSource = (referenceId, requestedSource) => {
  11990. const consumedFile = this.filesByReferenceId.get(referenceId);
  11991. if (!consumedFile)
  11992. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  11993. if (consumedFile.type !== 'asset') {
  11994. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  11995. }
  11996. if (consumedFile.source !== undefined) {
  11997. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  11998. }
  11999. const source = getValidSource(requestedSource, consumedFile, referenceId);
  12000. if (this.output) {
  12001. this.finalizeAsset(consumedFile, source, referenceId, this.output);
  12002. }
  12003. else {
  12004. consumedFile.source = source;
  12005. }
  12006. };
  12007. this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
  12008. this.output = {
  12009. assetFileNames,
  12010. bundle: outputBundle
  12011. };
  12012. this.facadeChunkByModule = facadeChunkByModule;
  12013. for (const emittedFile of this.filesByReferenceId.values()) {
  12014. if (emittedFile.fileName) {
  12015. reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
  12016. }
  12017. }
  12018. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  12019. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  12020. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
  12021. }
  12022. }
  12023. };
  12024. this.filesByReferenceId = baseFileEmitter
  12025. ? new Map(baseFileEmitter.filesByReferenceId)
  12026. : new Map();
  12027. }
  12028. assignReferenceId(file, idBase) {
  12029. let referenceId;
  12030. do {
  12031. const hash = createHash();
  12032. if (referenceId) {
  12033. hash.update(referenceId);
  12034. }
  12035. else {
  12036. hash.update(idBase);
  12037. }
  12038. referenceId = hash.digest('hex').substr(0, 8);
  12039. } while (this.filesByReferenceId.has(referenceId));
  12040. this.filesByReferenceId.set(referenceId, file);
  12041. return referenceId;
  12042. }
  12043. emitAsset(emittedAsset) {
  12044. const source = typeof emittedAsset.source !== 'undefined'
  12045. ? getValidSource(emittedAsset.source, emittedAsset, null)
  12046. : undefined;
  12047. const consumedAsset = {
  12048. fileName: emittedAsset.fileName,
  12049. name: emittedAsset.name,
  12050. source,
  12051. type: 'asset'
  12052. };
  12053. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  12054. if (this.output) {
  12055. if (emittedAsset.fileName) {
  12056. reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
  12057. }
  12058. if (source !== undefined) {
  12059. this.finalizeAsset(consumedAsset, source, referenceId, this.output);
  12060. }
  12061. }
  12062. return referenceId;
  12063. }
  12064. emitChunk(emittedChunk) {
  12065. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  12066. return error(errInvalidRollupPhaseForChunkEmission());
  12067. }
  12068. if (typeof emittedChunk.id !== 'string') {
  12069. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  12070. }
  12071. const consumedChunk = {
  12072. fileName: emittedChunk.fileName,
  12073. module: null,
  12074. name: emittedChunk.name || emittedChunk.id,
  12075. type: 'chunk'
  12076. };
  12077. this.graph.moduleLoader
  12078. .emitChunk(emittedChunk)
  12079. .then(module => (consumedChunk.module = module))
  12080. .catch(() => {
  12081. // Avoid unhandled Promise rejection as the error will be thrown later
  12082. // once module loading has finished
  12083. });
  12084. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  12085. }
  12086. finalizeAsset(consumedFile, source, referenceId, output) {
  12087. const fileName = consumedFile.fileName ||
  12088. findExistingAssetFileNameWithSource(output.bundle, source) ||
  12089. generateAssetFileName(consumedFile.name, source, output);
  12090. // We must not modify the original assets to avoid interaction between outputs
  12091. const assetWithFileName = { ...consumedFile, source, fileName };
  12092. this.filesByReferenceId.set(referenceId, assetWithFileName);
  12093. const options = this.options;
  12094. output.bundle[fileName] = {
  12095. fileName,
  12096. name: consumedFile.name,
  12097. get isAsset() {
  12098. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  12099. return true;
  12100. },
  12101. source,
  12102. type: 'asset'
  12103. };
  12104. }
  12105. }
  12106. function findExistingAssetFileNameWithSource(bundle, source) {
  12107. for (const fileName of Object.keys(bundle)) {
  12108. const outputFile = bundle[fileName];
  12109. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  12110. return fileName;
  12111. }
  12112. return null;
  12113. }
  12114. function areSourcesEqual(sourceA, sourceB) {
  12115. if (typeof sourceA === 'string') {
  12116. return sourceA === sourceB;
  12117. }
  12118. if (typeof sourceB === 'string') {
  12119. return false;
  12120. }
  12121. if ('equals' in sourceA) {
  12122. return sourceA.equals(sourceB);
  12123. }
  12124. if (sourceA.length !== sourceB.length) {
  12125. return false;
  12126. }
  12127. for (let index = 0; index < sourceA.length; index++) {
  12128. if (sourceA[index] !== sourceB[index]) {
  12129. return false;
  12130. }
  12131. }
  12132. return true;
  12133. }
  12134. class Bundle {
  12135. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  12136. this.outputOptions = outputOptions;
  12137. this.unsetOptions = unsetOptions;
  12138. this.inputOptions = inputOptions;
  12139. this.pluginDriver = pluginDriver;
  12140. this.graph = graph;
  12141. this.facadeChunkByModule = new Map();
  12142. this.includedNamespaces = new Set();
  12143. }
  12144. async generate(isWrite) {
  12145. timeStart('GENERATE', 1);
  12146. const outputBundle = Object.create(null);
  12147. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
  12148. try {
  12149. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  12150. timeStart('generate chunks', 2);
  12151. const chunks = await this.generateChunks();
  12152. if (chunks.length > 1) {
  12153. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  12154. }
  12155. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  12156. timeEnd('generate chunks', 2);
  12157. timeStart('render modules', 2);
  12158. // We need to create addons before prerender because at the moment, there
  12159. // can be no async code between prerender and render due to internal state
  12160. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  12161. this.prerenderChunks(chunks, inputBase);
  12162. timeEnd('render modules', 2);
  12163. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
  12164. }
  12165. catch (error) {
  12166. await this.pluginDriver.hookParallel('renderError', [error]);
  12167. throw error;
  12168. }
  12169. await this.pluginDriver.hookSeq('generateBundle', [
  12170. this.outputOptions,
  12171. outputBundle,
  12172. isWrite
  12173. ]);
  12174. this.finaliseAssets(outputBundle);
  12175. timeEnd('GENERATE', 1);
  12176. return outputBundle;
  12177. }
  12178. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
  12179. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  12180. for (const chunk of chunks) {
  12181. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  12182. }
  12183. await Promise.all(chunks.map(async (chunk) => {
  12184. const outputChunk = outputBundle[chunk.id];
  12185. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
  12186. }));
  12187. }
  12188. async addManualChunks(manualChunks) {
  12189. const manualChunkAliasByEntry = new Map();
  12190. const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
  12191. alias,
  12192. entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
  12193. })));
  12194. for (const { alias, entries } of chunkEntries) {
  12195. for (const entry of entries) {
  12196. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  12197. }
  12198. }
  12199. return manualChunkAliasByEntry;
  12200. }
  12201. assignChunkIds(chunks, inputBase, addons, bundle) {
  12202. const entryChunks = [];
  12203. const otherChunks = [];
  12204. for (const chunk of chunks) {
  12205. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  12206. ? entryChunks
  12207. : otherChunks).push(chunk);
  12208. }
  12209. // make sure entry chunk names take precedence with regard to deconflicting
  12210. const chunksForNaming = entryChunks.concat(otherChunks);
  12211. for (const chunk of chunksForNaming) {
  12212. if (this.outputOptions.file) {
  12213. chunk.id = path.basename(this.outputOptions.file);
  12214. }
  12215. else if (this.outputOptions.preserveModules) {
  12216. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  12217. }
  12218. else {
  12219. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  12220. }
  12221. bundle[chunk.id] = FILE_PLACEHOLDER;
  12222. }
  12223. }
  12224. assignManualChunks(getManualChunk) {
  12225. const manualChunkAliasByEntry = new Map();
  12226. const manualChunksApi = {
  12227. getModuleIds: () => this.graph.modulesById.keys(),
  12228. getModuleInfo: this.graph.getModuleInfo
  12229. };
  12230. for (const module of this.graph.modulesById.values()) {
  12231. if (module instanceof Module) {
  12232. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  12233. if (typeof manualChunkAlias === 'string') {
  12234. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  12235. }
  12236. }
  12237. }
  12238. return manualChunkAliasByEntry;
  12239. }
  12240. finaliseAssets(outputBundle) {
  12241. for (const key of Object.keys(outputBundle)) {
  12242. const file = outputBundle[key];
  12243. if (!file.type) {
  12244. 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);
  12245. file.type = 'asset';
  12246. }
  12247. if (this.outputOptions.validate && typeof file.code == 'string') {
  12248. try {
  12249. this.graph.contextParse(file.code, {
  12250. allowHashBang: true,
  12251. ecmaVersion: 'latest'
  12252. });
  12253. }
  12254. catch (exception) {
  12255. this.inputOptions.onwarn(errChunkInvalid(file, exception));
  12256. }
  12257. }
  12258. }
  12259. this.pluginDriver.finaliseAssets();
  12260. }
  12261. async generateChunks() {
  12262. const { manualChunks } = this.outputOptions;
  12263. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  12264. ? await this.addManualChunks(manualChunks)
  12265. : this.assignManualChunks(manualChunks);
  12266. const chunks = [];
  12267. const chunkByModule = new Map();
  12268. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  12269. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  12270. : this.outputOptions.preserveModules
  12271. ? getIncludedModules(this.graph.modulesById).map(module => ({
  12272. alias: null,
  12273. modules: [module]
  12274. }))
  12275. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  12276. sortByExecutionOrder(modules);
  12277. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  12278. chunks.push(chunk);
  12279. for (const module of modules) {
  12280. chunkByModule.set(module, chunk);
  12281. }
  12282. }
  12283. for (const chunk of chunks) {
  12284. chunk.link();
  12285. }
  12286. const facades = [];
  12287. for (const chunk of chunks) {
  12288. facades.push(...chunk.generateFacades());
  12289. }
  12290. return [...chunks, ...facades];
  12291. }
  12292. prerenderChunks(chunks, inputBase) {
  12293. for (const chunk of chunks) {
  12294. chunk.generateExports();
  12295. }
  12296. for (const chunk of chunks) {
  12297. chunk.preRender(this.outputOptions, inputBase);
  12298. }
  12299. }
  12300. }
  12301. function getAbsoluteEntryModulePaths(chunks) {
  12302. const absoluteEntryModulePaths = [];
  12303. for (const chunk of chunks) {
  12304. for (const entryModule of chunk.entryModules) {
  12305. if (isAbsolute(entryModule.id)) {
  12306. absoluteEntryModulePaths.push(entryModule.id);
  12307. }
  12308. }
  12309. }
  12310. return absoluteEntryModulePaths;
  12311. }
  12312. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  12313. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  12314. return error({
  12315. code: 'INVALID_OPTION',
  12316. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  12317. });
  12318. if (typeof outputOptions.file === 'string')
  12319. return error({
  12320. code: 'INVALID_OPTION',
  12321. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
  12322. 'To inline dynamic imports, set the "inlineDynamicImports" option.'
  12323. });
  12324. if (outputOptions.sourcemapFile)
  12325. return error({
  12326. code: 'INVALID_OPTION',
  12327. message: '"output.sourcemapFile" is only supported for single-file builds.'
  12328. });
  12329. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  12330. onWarn({
  12331. code: 'INVALID_OPTION',
  12332. message: '"output.amd.id" is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath".'
  12333. });
  12334. }
  12335. function getIncludedModules(modulesById) {
  12336. return [...modulesById.values()].filter(module => module instanceof Module &&
  12337. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  12338. }
  12339. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  12340. const existingAlias = manualChunkAliasByEntry.get(module);
  12341. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  12342. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  12343. }
  12344. manualChunkAliasByEntry.set(module, alias);
  12345. }
  12346. // Reserved word lists for various dialects of the language
  12347. var reservedWords = {
  12348. 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",
  12349. 5: "class enum extends super const export import",
  12350. 6: "enum",
  12351. strict: "implements interface let package private protected public static yield",
  12352. strictBind: "eval arguments"
  12353. };
  12354. // And the keywords
  12355. 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";
  12356. var keywords = {
  12357. 5: ecma5AndLessKeywords,
  12358. "5module": ecma5AndLessKeywords + " export import",
  12359. 6: ecma5AndLessKeywords + " const class extends export import super"
  12360. };
  12361. var keywordRelationalOperator = /^in(stanceof)?$/;
  12362. // ## Character categories
  12363. // Big ugly regular expressions that match characters in the
  12364. // whitespace, identifier, and identifier-start categories. These
  12365. // are only applied when a character is found to actually have a
  12366. // code point above 128.
  12367. // Generated by `bin/generate-identifier-regex.js`.
  12368. 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\u08a0-\u08b4\u08b6-\u08c7\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\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\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-\u170c\u170e-\u1711\u1720-\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-\u1b4b\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-\u2c2e\u2c30-\u2c5e\u2c60-\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-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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";
  12369. 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\u08d3-\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\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-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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-\u1df9\u1dfb-\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";
  12370. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  12371. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  12372. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  12373. // These are a run-length and offset encoded representation of the
  12374. // >0xffff code points that are a valid part of identifiers. The
  12375. // offset starts at 0x10000, and each pair of numbers represents an
  12376. // offset to the next range, and then a size of the range. They were
  12377. // generated by bin/generate-identifier-regex.js
  12378. // eslint-disable-next-line comma-spacing
  12379. 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,157,310,10,21,11,7,153,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,107,20,28,22,13,52,76,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,230,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,35,56,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,2749,1070,4050,582,8634,568,8,30,114,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,8952,286,50,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,2357,44,11,6,17,0,370,43,1301,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,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
  12380. // eslint-disable-next-line comma-spacing
  12381. 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,176,2,54,14,32,9,16,3,46,10,54,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,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,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,419,13,1495,6,110,6,6,9,4759,9,787719,239];
  12382. // This has a complexity linear to the value of the code. The
  12383. // assumption is that looking up astral identifier characters is
  12384. // rare.
  12385. function isInAstralSet(code, set) {
  12386. var pos = 0x10000;
  12387. for (var i = 0; i < set.length; i += 2) {
  12388. pos += set[i];
  12389. if (pos > code) { return false }
  12390. pos += set[i + 1];
  12391. if (pos >= code) { return true }
  12392. }
  12393. }
  12394. // Test whether a given character code starts an identifier.
  12395. function isIdentifierStart(code, astral) {
  12396. if (code < 65) { return code === 36 }
  12397. if (code < 91) { return true }
  12398. if (code < 97) { return code === 95 }
  12399. if (code < 123) { return true }
  12400. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  12401. if (astral === false) { return false }
  12402. return isInAstralSet(code, astralIdentifierStartCodes)
  12403. }
  12404. // Test whether a given character is part of an identifier.
  12405. function isIdentifierChar(code, astral) {
  12406. if (code < 48) { return code === 36 }
  12407. if (code < 58) { return true }
  12408. if (code < 65) { return false }
  12409. if (code < 91) { return true }
  12410. if (code < 97) { return code === 95 }
  12411. if (code < 123) { return true }
  12412. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  12413. if (astral === false) { return false }
  12414. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  12415. }
  12416. // ## Token types
  12417. // The assignment of fine-grained, information-carrying type objects
  12418. // allows the tokenizer to store the information it has about a
  12419. // token in a way that is very cheap for the parser to look up.
  12420. // All token type variables start with an underscore, to make them
  12421. // easy to recognize.
  12422. // The `beforeExpr` property is used to disambiguate between regular
  12423. // expressions and divisions. It is set on all token types that can
  12424. // be followed by an expression (thus, a slash after them would be a
  12425. // regular expression).
  12426. //
  12427. // The `startsExpr` property is used to check if the token ends a
  12428. // `yield` expression. It is set on all token types that either can
  12429. // directly start an expression (like a quotation mark) or can
  12430. // continue an expression (like the body of a string).
  12431. //
  12432. // `isLoop` marks a keyword as starting a loop, which is important
  12433. // to know when parsing a label, in order to allow or disallow
  12434. // continue jumps to that label.
  12435. var TokenType = function TokenType(label, conf) {
  12436. if ( conf === void 0 ) conf = {};
  12437. this.label = label;
  12438. this.keyword = conf.keyword;
  12439. this.beforeExpr = !!conf.beforeExpr;
  12440. this.startsExpr = !!conf.startsExpr;
  12441. this.isLoop = !!conf.isLoop;
  12442. this.isAssign = !!conf.isAssign;
  12443. this.prefix = !!conf.prefix;
  12444. this.postfix = !!conf.postfix;
  12445. this.binop = conf.binop || null;
  12446. this.updateContext = null;
  12447. };
  12448. function binop(name, prec) {
  12449. return new TokenType(name, {beforeExpr: true, binop: prec})
  12450. }
  12451. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  12452. // Map keyword names to token types.
  12453. var keywords$1 = {};
  12454. // Succinct definitions of keyword token types
  12455. function kw(name, options) {
  12456. if ( options === void 0 ) options = {};
  12457. options.keyword = name;
  12458. return keywords$1[name] = new TokenType(name, options)
  12459. }
  12460. var types = {
  12461. num: new TokenType("num", startsExpr),
  12462. regexp: new TokenType("regexp", startsExpr),
  12463. string: new TokenType("string", startsExpr),
  12464. name: new TokenType("name", startsExpr),
  12465. eof: new TokenType("eof"),
  12466. // Punctuation token types.
  12467. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  12468. bracketR: new TokenType("]"),
  12469. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  12470. braceR: new TokenType("}"),
  12471. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  12472. parenR: new TokenType(")"),
  12473. comma: new TokenType(",", beforeExpr),
  12474. semi: new TokenType(";", beforeExpr),
  12475. colon: new TokenType(":", beforeExpr),
  12476. dot: new TokenType("."),
  12477. question: new TokenType("?", beforeExpr),
  12478. questionDot: new TokenType("?."),
  12479. arrow: new TokenType("=>", beforeExpr),
  12480. template: new TokenType("template"),
  12481. invalidTemplate: new TokenType("invalidTemplate"),
  12482. ellipsis: new TokenType("...", beforeExpr),
  12483. backQuote: new TokenType("`", startsExpr),
  12484. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  12485. // Operators. These carry several kinds of properties to help the
  12486. // parser use them properly (the presence of these properties is
  12487. // what categorizes them as operators).
  12488. //
  12489. // `binop`, when present, specifies that this operator is a binary
  12490. // operator, and will refer to its precedence.
  12491. //
  12492. // `prefix` and `postfix` mark the operator as a prefix or postfix
  12493. // unary operator.
  12494. //
  12495. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  12496. // binary operators with a very low precedence, that should result
  12497. // in AssignmentExpression nodes.
  12498. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  12499. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  12500. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  12501. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  12502. logicalOR: binop("||", 1),
  12503. logicalAND: binop("&&", 2),
  12504. bitwiseOR: binop("|", 3),
  12505. bitwiseXOR: binop("^", 4),
  12506. bitwiseAND: binop("&", 5),
  12507. equality: binop("==/!=/===/!==", 6),
  12508. relational: binop("</>/<=/>=", 7),
  12509. bitShift: binop("<</>>/>>>", 8),
  12510. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  12511. modulo: binop("%", 10),
  12512. star: binop("*", 10),
  12513. slash: binop("/", 10),
  12514. starstar: new TokenType("**", {beforeExpr: true}),
  12515. coalesce: binop("??", 1),
  12516. // Keyword token types.
  12517. _break: kw("break"),
  12518. _case: kw("case", beforeExpr),
  12519. _catch: kw("catch"),
  12520. _continue: kw("continue"),
  12521. _debugger: kw("debugger"),
  12522. _default: kw("default", beforeExpr),
  12523. _do: kw("do", {isLoop: true, beforeExpr: true}),
  12524. _else: kw("else", beforeExpr),
  12525. _finally: kw("finally"),
  12526. _for: kw("for", {isLoop: true}),
  12527. _function: kw("function", startsExpr),
  12528. _if: kw("if"),
  12529. _return: kw("return", beforeExpr),
  12530. _switch: kw("switch"),
  12531. _throw: kw("throw", beforeExpr),
  12532. _try: kw("try"),
  12533. _var: kw("var"),
  12534. _const: kw("const"),
  12535. _while: kw("while", {isLoop: true}),
  12536. _with: kw("with"),
  12537. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  12538. _this: kw("this", startsExpr),
  12539. _super: kw("super", startsExpr),
  12540. _class: kw("class", startsExpr),
  12541. _extends: kw("extends", beforeExpr),
  12542. _export: kw("export"),
  12543. _import: kw("import", startsExpr),
  12544. _null: kw("null", startsExpr),
  12545. _true: kw("true", startsExpr),
  12546. _false: kw("false", startsExpr),
  12547. _in: kw("in", {beforeExpr: true, binop: 7}),
  12548. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  12549. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  12550. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  12551. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  12552. };
  12553. // Matches a whole line break (where CRLF is considered a single
  12554. // line break). Used to count lines.
  12555. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  12556. var lineBreakG = new RegExp(lineBreak.source, "g");
  12557. function isNewLine(code, ecma2019String) {
  12558. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  12559. }
  12560. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  12561. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  12562. var ref = Object.prototype;
  12563. var hasOwnProperty = ref.hasOwnProperty;
  12564. var toString = ref.toString;
  12565. // Checks if an object has a property.
  12566. function has(obj, propName) {
  12567. return hasOwnProperty.call(obj, propName)
  12568. }
  12569. var isArray = Array.isArray || (function (obj) { return (
  12570. toString.call(obj) === "[object Array]"
  12571. ); });
  12572. function wordsRegexp(words) {
  12573. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  12574. }
  12575. // These are used when `options.locations` is on, for the
  12576. // `startLoc` and `endLoc` properties.
  12577. var Position = function Position(line, col) {
  12578. this.line = line;
  12579. this.column = col;
  12580. };
  12581. Position.prototype.offset = function offset (n) {
  12582. return new Position(this.line, this.column + n)
  12583. };
  12584. var SourceLocation = function SourceLocation(p, start, end) {
  12585. this.start = start;
  12586. this.end = end;
  12587. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  12588. };
  12589. // The `getLineInfo` function is mostly useful when the
  12590. // `locations` option is off (for performance reasons) and you
  12591. // want to find the line/column position for a given character
  12592. // offset. `input` should be the code string that the offset refers
  12593. // into.
  12594. function getLineInfo(input, offset) {
  12595. for (var line = 1, cur = 0;;) {
  12596. lineBreakG.lastIndex = cur;
  12597. var match = lineBreakG.exec(input);
  12598. if (match && match.index < offset) {
  12599. ++line;
  12600. cur = match.index + match[0].length;
  12601. } else {
  12602. return new Position(line, offset - cur)
  12603. }
  12604. }
  12605. }
  12606. // A second argument must be given to configure the parser process.
  12607. // These options are recognized (only `ecmaVersion` is required):
  12608. var defaultOptions = {
  12609. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  12610. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  12611. // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version
  12612. // the library supports). This influences support for strict mode,
  12613. // the set of reserved words, and support for new syntax features.
  12614. ecmaVersion: null,
  12615. // `sourceType` indicates the mode the code should be parsed in.
  12616. // Can be either `"script"` or `"module"`. This influences global
  12617. // strict mode and parsing of `import` and `export` declarations.
  12618. sourceType: "script",
  12619. // `onInsertedSemicolon` can be a callback that will be called
  12620. // when a semicolon is automatically inserted. It will be passed
  12621. // the position of the comma as an offset, and if `locations` is
  12622. // enabled, it is given the location as a `{line, column}` object
  12623. // as second argument.
  12624. onInsertedSemicolon: null,
  12625. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  12626. // trailing commas.
  12627. onTrailingComma: null,
  12628. // By default, reserved words are only enforced if ecmaVersion >= 5.
  12629. // Set `allowReserved` to a boolean value to explicitly turn this on
  12630. // an off. When this option has the value "never", reserved words
  12631. // and keywords can also not be used as property names.
  12632. allowReserved: null,
  12633. // When enabled, a return at the top level is not considered an
  12634. // error.
  12635. allowReturnOutsideFunction: false,
  12636. // When enabled, import/export statements are not constrained to
  12637. // appearing at the top of the program.
  12638. allowImportExportEverywhere: false,
  12639. // When enabled, await identifiers are allowed to appear at the top-level scope,
  12640. // but they are still not allowed in non-async functions.
  12641. allowAwaitOutsideFunction: false,
  12642. // When enabled, hashbang directive in the beginning of file
  12643. // is allowed and treated as a line comment.
  12644. allowHashBang: false,
  12645. // When `locations` is on, `loc` properties holding objects with
  12646. // `start` and `end` properties in `{line, column}` form (with
  12647. // line being 1-based and column 0-based) will be attached to the
  12648. // nodes.
  12649. locations: false,
  12650. // A function can be passed as `onToken` option, which will
  12651. // cause Acorn to call that function with object in the same
  12652. // format as tokens returned from `tokenizer().getToken()`. Note
  12653. // that you are not allowed to call the parser from the
  12654. // callback—that will corrupt its internal state.
  12655. onToken: null,
  12656. // A function can be passed as `onComment` option, which will
  12657. // cause Acorn to call that function with `(block, text, start,
  12658. // end)` parameters whenever a comment is skipped. `block` is a
  12659. // boolean indicating whether this is a block (`/* */`) comment,
  12660. // `text` is the content of the comment, and `start` and `end` are
  12661. // character offsets that denote the start and end of the comment.
  12662. // When the `locations` option is on, two more parameters are
  12663. // passed, the full `{line, column}` locations of the start and
  12664. // end of the comments. Note that you are not allowed to call the
  12665. // parser from the callback—that will corrupt its internal state.
  12666. onComment: null,
  12667. // Nodes have their start and end characters offsets recorded in
  12668. // `start` and `end` properties (directly on the node, rather than
  12669. // the `loc` object, which holds line/column data. To also add a
  12670. // [semi-standardized][range] `range` property holding a `[start,
  12671. // end]` array with the same numbers, set the `ranges` option to
  12672. // `true`.
  12673. //
  12674. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  12675. ranges: false,
  12676. // It is possible to parse multiple files into a single AST by
  12677. // passing the tree produced by parsing the first file as
  12678. // `program` option in subsequent parses. This will add the
  12679. // toplevel forms of the parsed file to the `Program` (top) node
  12680. // of an existing parse tree.
  12681. program: null,
  12682. // When `locations` is on, you can pass this to record the source
  12683. // file in every node's `loc` object.
  12684. sourceFile: null,
  12685. // This value, if given, is stored in every node, whether
  12686. // `locations` is on or off.
  12687. directSourceFile: null,
  12688. // When enabled, parenthesized expressions are represented by
  12689. // (non-standard) ParenthesizedExpression nodes
  12690. preserveParens: false
  12691. };
  12692. // Interpret and default an options object
  12693. var warnedAboutEcmaVersion = false;
  12694. function getOptions(opts) {
  12695. var options = {};
  12696. for (var opt in defaultOptions)
  12697. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  12698. if (options.ecmaVersion === "latest") {
  12699. options.ecmaVersion = 1e8;
  12700. } else if (options.ecmaVersion == null) {
  12701. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  12702. warnedAboutEcmaVersion = true;
  12703. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  12704. }
  12705. options.ecmaVersion = 11;
  12706. } else if (options.ecmaVersion >= 2015) {
  12707. options.ecmaVersion -= 2009;
  12708. }
  12709. if (options.allowReserved == null)
  12710. { options.allowReserved = options.ecmaVersion < 5; }
  12711. if (isArray(options.onToken)) {
  12712. var tokens = options.onToken;
  12713. options.onToken = function (token) { return tokens.push(token); };
  12714. }
  12715. if (isArray(options.onComment))
  12716. { options.onComment = pushComment(options, options.onComment); }
  12717. return options
  12718. }
  12719. function pushComment(options, array) {
  12720. return function(block, text, start, end, startLoc, endLoc) {
  12721. var comment = {
  12722. type: block ? "Block" : "Line",
  12723. value: text,
  12724. start: start,
  12725. end: end
  12726. };
  12727. if (options.locations)
  12728. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  12729. if (options.ranges)
  12730. { comment.range = [start, end]; }
  12731. array.push(comment);
  12732. }
  12733. }
  12734. // Each scope gets a bitset that may contain these flags
  12735. var
  12736. SCOPE_TOP = 1,
  12737. SCOPE_FUNCTION = 2,
  12738. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  12739. SCOPE_ASYNC = 4,
  12740. SCOPE_GENERATOR = 8,
  12741. SCOPE_ARROW = 16,
  12742. SCOPE_SIMPLE_CATCH = 32,
  12743. SCOPE_SUPER = 64,
  12744. SCOPE_DIRECT_SUPER = 128;
  12745. function functionFlags(async, generator) {
  12746. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  12747. }
  12748. // Used in checkLVal* and declareName to determine the type of a binding
  12749. var
  12750. BIND_NONE = 0, // Not a binding
  12751. BIND_VAR = 1, // Var-style binding
  12752. BIND_LEXICAL = 2, // Let- or const-style binding
  12753. BIND_FUNCTION = 3, // Function declaration
  12754. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  12755. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  12756. var Parser = function Parser(options, input, startPos) {
  12757. this.options = options = getOptions(options);
  12758. this.sourceFile = options.sourceFile;
  12759. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  12760. var reserved = "";
  12761. if (options.allowReserved !== true) {
  12762. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  12763. if (options.sourceType === "module") { reserved += " await"; }
  12764. }
  12765. this.reservedWords = wordsRegexp(reserved);
  12766. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  12767. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  12768. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  12769. this.input = String(input);
  12770. // Used to signal to callers of `readWord1` whether the word
  12771. // contained any escape sequences. This is needed because words with
  12772. // escape sequences must not be interpreted as keywords.
  12773. this.containsEsc = false;
  12774. // Set up token state
  12775. // The current position of the tokenizer in the input.
  12776. if (startPos) {
  12777. this.pos = startPos;
  12778. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  12779. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  12780. } else {
  12781. this.pos = this.lineStart = 0;
  12782. this.curLine = 1;
  12783. }
  12784. // Properties of the current token:
  12785. // Its type
  12786. this.type = types.eof;
  12787. // For tokens that include more information than their type, the value
  12788. this.value = null;
  12789. // Its start and end offset
  12790. this.start = this.end = this.pos;
  12791. // And, if locations are used, the {line, column} object
  12792. // corresponding to those offsets
  12793. this.startLoc = this.endLoc = this.curPosition();
  12794. // Position information for the previous token
  12795. this.lastTokEndLoc = this.lastTokStartLoc = null;
  12796. this.lastTokStart = this.lastTokEnd = this.pos;
  12797. // The context stack is used to superficially track syntactic
  12798. // context to predict whether a regular expression is allowed in a
  12799. // given position.
  12800. this.context = this.initialContext();
  12801. this.exprAllowed = true;
  12802. // Figure out if it's a module code.
  12803. this.inModule = options.sourceType === "module";
  12804. this.strict = this.inModule || this.strictDirective(this.pos);
  12805. // Used to signify the start of a potential arrow function
  12806. this.potentialArrowAt = -1;
  12807. // Positions to delayed-check that yield/await does not exist in default parameters.
  12808. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  12809. // Labels in scope.
  12810. this.labels = [];
  12811. // Thus-far undefined exports.
  12812. this.undefinedExports = Object.create(null);
  12813. // If enabled, skip leading hashbang line.
  12814. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  12815. { this.skipLineComment(2); }
  12816. // Scope tracking for duplicate variable names (see scope.js)
  12817. this.scopeStack = [];
  12818. this.enterScope(SCOPE_TOP);
  12819. // For RegExp validation
  12820. this.regexpState = null;
  12821. };
  12822. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  12823. Parser.prototype.parse = function parse () {
  12824. var node = this.options.program || this.startNode();
  12825. this.nextToken();
  12826. return this.parseTopLevel(node)
  12827. };
  12828. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  12829. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
  12830. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
  12831. prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
  12832. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  12833. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  12834. prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
  12835. Parser.extend = function extend () {
  12836. var plugins = [], len = arguments.length;
  12837. while ( len-- ) plugins[ len ] = arguments[ len ];
  12838. var cls = this;
  12839. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  12840. return cls
  12841. };
  12842. Parser.parse = function parse (input, options) {
  12843. return new this(options, input).parse()
  12844. };
  12845. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  12846. var parser = new this(options, input, pos);
  12847. parser.nextToken();
  12848. return parser.parseExpression()
  12849. };
  12850. Parser.tokenizer = function tokenizer (input, options) {
  12851. return new this(options, input)
  12852. };
  12853. Object.defineProperties( Parser.prototype, prototypeAccessors );
  12854. var pp = Parser.prototype;
  12855. // ## Parser utilities
  12856. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  12857. pp.strictDirective = function(start) {
  12858. for (;;) {
  12859. // Try to find string literal.
  12860. skipWhiteSpace.lastIndex = start;
  12861. start += skipWhiteSpace.exec(this.input)[0].length;
  12862. var match = literal.exec(this.input.slice(start));
  12863. if (!match) { return false }
  12864. if ((match[1] || match[2]) === "use strict") {
  12865. skipWhiteSpace.lastIndex = start + match[0].length;
  12866. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  12867. var next = this.input.charAt(end);
  12868. return next === ";" || next === "}" ||
  12869. (lineBreak.test(spaceAfter[0]) &&
  12870. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  12871. }
  12872. start += match[0].length;
  12873. // Skip semicolon, if any.
  12874. skipWhiteSpace.lastIndex = start;
  12875. start += skipWhiteSpace.exec(this.input)[0].length;
  12876. if (this.input[start] === ";")
  12877. { start++; }
  12878. }
  12879. };
  12880. // Predicate that tests whether the next token is of the given
  12881. // type, and if yes, consumes it as a side effect.
  12882. pp.eat = function(type) {
  12883. if (this.type === type) {
  12884. this.next();
  12885. return true
  12886. } else {
  12887. return false
  12888. }
  12889. };
  12890. // Tests whether parsed token is a contextual keyword.
  12891. pp.isContextual = function(name) {
  12892. return this.type === types.name && this.value === name && !this.containsEsc
  12893. };
  12894. // Consumes contextual keyword if possible.
  12895. pp.eatContextual = function(name) {
  12896. if (!this.isContextual(name)) { return false }
  12897. this.next();
  12898. return true
  12899. };
  12900. // Asserts that following token is given contextual keyword.
  12901. pp.expectContextual = function(name) {
  12902. if (!this.eatContextual(name)) { this.unexpected(); }
  12903. };
  12904. // Test whether a semicolon can be inserted at the current position.
  12905. pp.canInsertSemicolon = function() {
  12906. return this.type === types.eof ||
  12907. this.type === types.braceR ||
  12908. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  12909. };
  12910. pp.insertSemicolon = function() {
  12911. if (this.canInsertSemicolon()) {
  12912. if (this.options.onInsertedSemicolon)
  12913. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  12914. return true
  12915. }
  12916. };
  12917. // Consume a semicolon, or, failing that, see if we are allowed to
  12918. // pretend that there is a semicolon at this position.
  12919. pp.semicolon = function() {
  12920. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  12921. };
  12922. pp.afterTrailingComma = function(tokType, notNext) {
  12923. if (this.type === tokType) {
  12924. if (this.options.onTrailingComma)
  12925. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  12926. if (!notNext)
  12927. { this.next(); }
  12928. return true
  12929. }
  12930. };
  12931. // Expect a token of a given type. If found, consume it, otherwise,
  12932. // raise an unexpected token error.
  12933. pp.expect = function(type) {
  12934. this.eat(type) || this.unexpected();
  12935. };
  12936. // Raise an unexpected token error.
  12937. pp.unexpected = function(pos) {
  12938. this.raise(pos != null ? pos : this.start, "Unexpected token");
  12939. };
  12940. function DestructuringErrors() {
  12941. this.shorthandAssign =
  12942. this.trailingComma =
  12943. this.parenthesizedAssign =
  12944. this.parenthesizedBind =
  12945. this.doubleProto =
  12946. -1;
  12947. }
  12948. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  12949. if (!refDestructuringErrors) { return }
  12950. if (refDestructuringErrors.trailingComma > -1)
  12951. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  12952. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  12953. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  12954. };
  12955. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  12956. if (!refDestructuringErrors) { return false }
  12957. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  12958. var doubleProto = refDestructuringErrors.doubleProto;
  12959. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  12960. if (shorthandAssign >= 0)
  12961. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  12962. if (doubleProto >= 0)
  12963. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  12964. };
  12965. pp.checkYieldAwaitInDefaultParams = function() {
  12966. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  12967. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  12968. if (this.awaitPos)
  12969. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  12970. };
  12971. pp.isSimpleAssignTarget = function(expr) {
  12972. if (expr.type === "ParenthesizedExpression")
  12973. { return this.isSimpleAssignTarget(expr.expression) }
  12974. return expr.type === "Identifier" || expr.type === "MemberExpression"
  12975. };
  12976. var pp$1 = Parser.prototype;
  12977. // ### Statement parsing
  12978. // Parse a program. Initializes the parser, reads any number of
  12979. // statements, and wraps them in a Program node. Optionally takes a
  12980. // `program` argument. If present, the statements will be appended
  12981. // to its body instead of creating a new node.
  12982. pp$1.parseTopLevel = function(node) {
  12983. var exports = Object.create(null);
  12984. if (!node.body) { node.body = []; }
  12985. while (this.type !== types.eof) {
  12986. var stmt = this.parseStatement(null, true, exports);
  12987. node.body.push(stmt);
  12988. }
  12989. if (this.inModule)
  12990. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  12991. {
  12992. var name = list[i];
  12993. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  12994. } }
  12995. this.adaptDirectivePrologue(node.body);
  12996. this.next();
  12997. node.sourceType = this.options.sourceType;
  12998. return this.finishNode(node, "Program")
  12999. };
  13000. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  13001. pp$1.isLet = function(context) {
  13002. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  13003. skipWhiteSpace.lastIndex = this.pos;
  13004. var skip = skipWhiteSpace.exec(this.input);
  13005. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13006. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  13007. // Statement) is allowed here. If context is not empty then only a Statement
  13008. // is allowed. However, `let [` is an explicit negative lookahead for
  13009. // ExpressionStatement, so special-case it first.
  13010. if (nextCh === 91) { return true } // '['
  13011. if (context) { return false }
  13012. if (nextCh === 123) { return true } // '{'
  13013. if (isIdentifierStart(nextCh, true)) {
  13014. var pos = next + 1;
  13015. while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
  13016. var ident = this.input.slice(next, pos);
  13017. if (!keywordRelationalOperator.test(ident)) { return true }
  13018. }
  13019. return false
  13020. };
  13021. // check 'async [no LineTerminator here] function'
  13022. // - 'async /*foo*/ function' is OK.
  13023. // - 'async /*\n*/ function' is invalid.
  13024. pp$1.isAsyncFunction = function() {
  13025. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  13026. { return false }
  13027. skipWhiteSpace.lastIndex = this.pos;
  13028. var skip = skipWhiteSpace.exec(this.input);
  13029. var next = this.pos + skip[0].length;
  13030. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  13031. this.input.slice(next, next + 8) === "function" &&
  13032. (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
  13033. };
  13034. // Parse a single statement.
  13035. //
  13036. // If expecting a statement and finding a slash operator, parse a
  13037. // regular expression literal. This is to handle cases like
  13038. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  13039. // does not help.
  13040. pp$1.parseStatement = function(context, topLevel, exports) {
  13041. var starttype = this.type, node = this.startNode(), kind;
  13042. if (this.isLet(context)) {
  13043. starttype = types._var;
  13044. kind = "let";
  13045. }
  13046. // Most types of statements are recognized by the keyword they
  13047. // start with. Many are trivial to parse, some require a bit of
  13048. // complexity.
  13049. switch (starttype) {
  13050. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  13051. case types._debugger: return this.parseDebuggerStatement(node)
  13052. case types._do: return this.parseDoStatement(node)
  13053. case types._for: return this.parseForStatement(node)
  13054. case types._function:
  13055. // Function as sole body of either an if statement or a labeled statement
  13056. // works, but not when it is part of a labeled statement that is the sole
  13057. // body of an if statement.
  13058. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  13059. return this.parseFunctionStatement(node, false, !context)
  13060. case types._class:
  13061. if (context) { this.unexpected(); }
  13062. return this.parseClass(node, true)
  13063. case types._if: return this.parseIfStatement(node)
  13064. case types._return: return this.parseReturnStatement(node)
  13065. case types._switch: return this.parseSwitchStatement(node)
  13066. case types._throw: return this.parseThrowStatement(node)
  13067. case types._try: return this.parseTryStatement(node)
  13068. case types._const: case types._var:
  13069. kind = kind || this.value;
  13070. if (context && kind !== "var") { this.unexpected(); }
  13071. return this.parseVarStatement(node, kind)
  13072. case types._while: return this.parseWhileStatement(node)
  13073. case types._with: return this.parseWithStatement(node)
  13074. case types.braceL: return this.parseBlock(true, node)
  13075. case types.semi: return this.parseEmptyStatement(node)
  13076. case types._export:
  13077. case types._import:
  13078. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  13079. skipWhiteSpace.lastIndex = this.pos;
  13080. var skip = skipWhiteSpace.exec(this.input);
  13081. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13082. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  13083. { return this.parseExpressionStatement(node, this.parseExpression()) }
  13084. }
  13085. if (!this.options.allowImportExportEverywhere) {
  13086. if (!topLevel)
  13087. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  13088. if (!this.inModule)
  13089. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  13090. }
  13091. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  13092. // If the statement does not start with a statement keyword or a
  13093. // brace, it's an ExpressionStatement or LabeledStatement. We
  13094. // simply start parsing an expression, and afterwards, if the
  13095. // next token is a colon and the expression was a simple
  13096. // Identifier node, we switch to interpreting it as a label.
  13097. default:
  13098. if (this.isAsyncFunction()) {
  13099. if (context) { this.unexpected(); }
  13100. this.next();
  13101. return this.parseFunctionStatement(node, true, !context)
  13102. }
  13103. var maybeName = this.value, expr = this.parseExpression();
  13104. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  13105. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  13106. else { return this.parseExpressionStatement(node, expr) }
  13107. }
  13108. };
  13109. pp$1.parseBreakContinueStatement = function(node, keyword) {
  13110. var isBreak = keyword === "break";
  13111. this.next();
  13112. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  13113. else if (this.type !== types.name) { this.unexpected(); }
  13114. else {
  13115. node.label = this.parseIdent();
  13116. this.semicolon();
  13117. }
  13118. // Verify that there is an actual destination to break or
  13119. // continue to.
  13120. var i = 0;
  13121. for (; i < this.labels.length; ++i) {
  13122. var lab = this.labels[i];
  13123. if (node.label == null || lab.name === node.label.name) {
  13124. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  13125. if (node.label && isBreak) { break }
  13126. }
  13127. }
  13128. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  13129. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  13130. };
  13131. pp$1.parseDebuggerStatement = function(node) {
  13132. this.next();
  13133. this.semicolon();
  13134. return this.finishNode(node, "DebuggerStatement")
  13135. };
  13136. pp$1.parseDoStatement = function(node) {
  13137. this.next();
  13138. this.labels.push(loopLabel);
  13139. node.body = this.parseStatement("do");
  13140. this.labels.pop();
  13141. this.expect(types._while);
  13142. node.test = this.parseParenExpression();
  13143. if (this.options.ecmaVersion >= 6)
  13144. { this.eat(types.semi); }
  13145. else
  13146. { this.semicolon(); }
  13147. return this.finishNode(node, "DoWhileStatement")
  13148. };
  13149. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  13150. // loop is non-trivial. Basically, we have to parse the init `var`
  13151. // statement or expression, disallowing the `in` operator (see
  13152. // the second parameter to `parseExpression`), and then check
  13153. // whether the next token is `in` or `of`. When there is no init
  13154. // part (semicolon immediately after the opening parenthesis), it
  13155. // is a regular `for` loop.
  13156. pp$1.parseForStatement = function(node) {
  13157. this.next();
  13158. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  13159. this.labels.push(loopLabel);
  13160. this.enterScope(0);
  13161. this.expect(types.parenL);
  13162. if (this.type === types.semi) {
  13163. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13164. return this.parseFor(node, null)
  13165. }
  13166. var isLet = this.isLet();
  13167. if (this.type === types._var || this.type === types._const || isLet) {
  13168. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  13169. this.next();
  13170. this.parseVar(init$1, true, kind);
  13171. this.finishNode(init$1, "VariableDeclaration");
  13172. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  13173. if (this.options.ecmaVersion >= 9) {
  13174. if (this.type === types._in) {
  13175. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13176. } else { node.await = awaitAt > -1; }
  13177. }
  13178. return this.parseForIn(node, init$1)
  13179. }
  13180. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13181. return this.parseFor(node, init$1)
  13182. }
  13183. var refDestructuringErrors = new DestructuringErrors;
  13184. var init = this.parseExpression(true, refDestructuringErrors);
  13185. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  13186. if (this.options.ecmaVersion >= 9) {
  13187. if (this.type === types._in) {
  13188. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13189. } else { node.await = awaitAt > -1; }
  13190. }
  13191. this.toAssignable(init, false, refDestructuringErrors);
  13192. this.checkLValPattern(init);
  13193. return this.parseForIn(node, init)
  13194. } else {
  13195. this.checkExpressionErrors(refDestructuringErrors, true);
  13196. }
  13197. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13198. return this.parseFor(node, init)
  13199. };
  13200. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  13201. this.next();
  13202. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  13203. };
  13204. pp$1.parseIfStatement = function(node) {
  13205. this.next();
  13206. node.test = this.parseParenExpression();
  13207. // allow function declarations in branches, but only in non-strict mode
  13208. node.consequent = this.parseStatement("if");
  13209. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  13210. return this.finishNode(node, "IfStatement")
  13211. };
  13212. pp$1.parseReturnStatement = function(node) {
  13213. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  13214. { this.raise(this.start, "'return' outside of function"); }
  13215. this.next();
  13216. // In `return` (and `break`/`continue`), the keywords with
  13217. // optional arguments, we eagerly look for a semicolon or the
  13218. // possibility to insert one.
  13219. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  13220. else { node.argument = this.parseExpression(); this.semicolon(); }
  13221. return this.finishNode(node, "ReturnStatement")
  13222. };
  13223. pp$1.parseSwitchStatement = function(node) {
  13224. this.next();
  13225. node.discriminant = this.parseParenExpression();
  13226. node.cases = [];
  13227. this.expect(types.braceL);
  13228. this.labels.push(switchLabel);
  13229. this.enterScope(0);
  13230. // Statements under must be grouped (by label) in SwitchCase
  13231. // nodes. `cur` is used to keep the node that we are currently
  13232. // adding statements to.
  13233. var cur;
  13234. for (var sawDefault = false; this.type !== types.braceR;) {
  13235. if (this.type === types._case || this.type === types._default) {
  13236. var isCase = this.type === types._case;
  13237. if (cur) { this.finishNode(cur, "SwitchCase"); }
  13238. node.cases.push(cur = this.startNode());
  13239. cur.consequent = [];
  13240. this.next();
  13241. if (isCase) {
  13242. cur.test = this.parseExpression();
  13243. } else {
  13244. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  13245. sawDefault = true;
  13246. cur.test = null;
  13247. }
  13248. this.expect(types.colon);
  13249. } else {
  13250. if (!cur) { this.unexpected(); }
  13251. cur.consequent.push(this.parseStatement(null));
  13252. }
  13253. }
  13254. this.exitScope();
  13255. if (cur) { this.finishNode(cur, "SwitchCase"); }
  13256. this.next(); // Closing brace
  13257. this.labels.pop();
  13258. return this.finishNode(node, "SwitchStatement")
  13259. };
  13260. pp$1.parseThrowStatement = function(node) {
  13261. this.next();
  13262. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  13263. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  13264. node.argument = this.parseExpression();
  13265. this.semicolon();
  13266. return this.finishNode(node, "ThrowStatement")
  13267. };
  13268. // Reused empty array added for node fields that are always empty.
  13269. var empty = [];
  13270. pp$1.parseTryStatement = function(node) {
  13271. this.next();
  13272. node.block = this.parseBlock();
  13273. node.handler = null;
  13274. if (this.type === types._catch) {
  13275. var clause = this.startNode();
  13276. this.next();
  13277. if (this.eat(types.parenL)) {
  13278. clause.param = this.parseBindingAtom();
  13279. var simple = clause.param.type === "Identifier";
  13280. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  13281. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  13282. this.expect(types.parenR);
  13283. } else {
  13284. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  13285. clause.param = null;
  13286. this.enterScope(0);
  13287. }
  13288. clause.body = this.parseBlock(false);
  13289. this.exitScope();
  13290. node.handler = this.finishNode(clause, "CatchClause");
  13291. }
  13292. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  13293. if (!node.handler && !node.finalizer)
  13294. { this.raise(node.start, "Missing catch or finally clause"); }
  13295. return this.finishNode(node, "TryStatement")
  13296. };
  13297. pp$1.parseVarStatement = function(node, kind) {
  13298. this.next();
  13299. this.parseVar(node, false, kind);
  13300. this.semicolon();
  13301. return this.finishNode(node, "VariableDeclaration")
  13302. };
  13303. pp$1.parseWhileStatement = function(node) {
  13304. this.next();
  13305. node.test = this.parseParenExpression();
  13306. this.labels.push(loopLabel);
  13307. node.body = this.parseStatement("while");
  13308. this.labels.pop();
  13309. return this.finishNode(node, "WhileStatement")
  13310. };
  13311. pp$1.parseWithStatement = function(node) {
  13312. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  13313. this.next();
  13314. node.object = this.parseParenExpression();
  13315. node.body = this.parseStatement("with");
  13316. return this.finishNode(node, "WithStatement")
  13317. };
  13318. pp$1.parseEmptyStatement = function(node) {
  13319. this.next();
  13320. return this.finishNode(node, "EmptyStatement")
  13321. };
  13322. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  13323. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  13324. {
  13325. var label = list[i$1];
  13326. if (label.name === maybeName)
  13327. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  13328. } }
  13329. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  13330. for (var i = this.labels.length - 1; i >= 0; i--) {
  13331. var label$1 = this.labels[i];
  13332. if (label$1.statementStart === node.start) {
  13333. // Update information about previous labels on this node
  13334. label$1.statementStart = this.start;
  13335. label$1.kind = kind;
  13336. } else { break }
  13337. }
  13338. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  13339. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  13340. this.labels.pop();
  13341. node.label = expr;
  13342. return this.finishNode(node, "LabeledStatement")
  13343. };
  13344. pp$1.parseExpressionStatement = function(node, expr) {
  13345. node.expression = expr;
  13346. this.semicolon();
  13347. return this.finishNode(node, "ExpressionStatement")
  13348. };
  13349. // Parse a semicolon-enclosed block of statements, handling `"use
  13350. // strict"` declarations when `allowStrict` is true (used for
  13351. // function bodies).
  13352. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  13353. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  13354. if ( node === void 0 ) node = this.startNode();
  13355. node.body = [];
  13356. this.expect(types.braceL);
  13357. if (createNewLexicalScope) { this.enterScope(0); }
  13358. while (this.type !== types.braceR) {
  13359. var stmt = this.parseStatement(null);
  13360. node.body.push(stmt);
  13361. }
  13362. if (exitStrict) { this.strict = false; }
  13363. this.next();
  13364. if (createNewLexicalScope) { this.exitScope(); }
  13365. return this.finishNode(node, "BlockStatement")
  13366. };
  13367. // Parse a regular `for` loop. The disambiguation code in
  13368. // `parseStatement` will already have parsed the init statement or
  13369. // expression.
  13370. pp$1.parseFor = function(node, init) {
  13371. node.init = init;
  13372. this.expect(types.semi);
  13373. node.test = this.type === types.semi ? null : this.parseExpression();
  13374. this.expect(types.semi);
  13375. node.update = this.type === types.parenR ? null : this.parseExpression();
  13376. this.expect(types.parenR);
  13377. node.body = this.parseStatement("for");
  13378. this.exitScope();
  13379. this.labels.pop();
  13380. return this.finishNode(node, "ForStatement")
  13381. };
  13382. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  13383. // same from parser's perspective.
  13384. pp$1.parseForIn = function(node, init) {
  13385. var isForIn = this.type === types._in;
  13386. this.next();
  13387. if (
  13388. init.type === "VariableDeclaration" &&
  13389. init.declarations[0].init != null &&
  13390. (
  13391. !isForIn ||
  13392. this.options.ecmaVersion < 8 ||
  13393. this.strict ||
  13394. init.kind !== "var" ||
  13395. init.declarations[0].id.type !== "Identifier"
  13396. )
  13397. ) {
  13398. this.raise(
  13399. init.start,
  13400. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  13401. );
  13402. }
  13403. node.left = init;
  13404. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  13405. this.expect(types.parenR);
  13406. node.body = this.parseStatement("for");
  13407. this.exitScope();
  13408. this.labels.pop();
  13409. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  13410. };
  13411. // Parse a list of variable declarations.
  13412. pp$1.parseVar = function(node, isFor, kind) {
  13413. node.declarations = [];
  13414. node.kind = kind;
  13415. for (;;) {
  13416. var decl = this.startNode();
  13417. this.parseVarId(decl, kind);
  13418. if (this.eat(types.eq)) {
  13419. decl.init = this.parseMaybeAssign(isFor);
  13420. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  13421. this.unexpected();
  13422. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  13423. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  13424. } else {
  13425. decl.init = null;
  13426. }
  13427. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  13428. if (!this.eat(types.comma)) { break }
  13429. }
  13430. return node
  13431. };
  13432. pp$1.parseVarId = function(decl, kind) {
  13433. decl.id = this.parseBindingAtom();
  13434. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  13435. };
  13436. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  13437. // Parse a function declaration or literal (depending on the
  13438. // `statement & FUNC_STATEMENT`).
  13439. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  13440. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  13441. this.initFunction(node);
  13442. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  13443. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  13444. { this.unexpected(); }
  13445. node.generator = this.eat(types.star);
  13446. }
  13447. if (this.options.ecmaVersion >= 8)
  13448. { node.async = !!isAsync; }
  13449. if (statement & FUNC_STATEMENT) {
  13450. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  13451. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  13452. // If it is a regular function declaration in sloppy mode, then it is
  13453. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  13454. // mode depends on properties of the current scope (see
  13455. // treatFunctionsAsVar).
  13456. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  13457. }
  13458. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  13459. this.yieldPos = 0;
  13460. this.awaitPos = 0;
  13461. this.awaitIdentPos = 0;
  13462. this.enterScope(functionFlags(node.async, node.generator));
  13463. if (!(statement & FUNC_STATEMENT))
  13464. { node.id = this.type === types.name ? this.parseIdent() : null; }
  13465. this.parseFunctionParams(node);
  13466. this.parseFunctionBody(node, allowExpressionBody, false);
  13467. this.yieldPos = oldYieldPos;
  13468. this.awaitPos = oldAwaitPos;
  13469. this.awaitIdentPos = oldAwaitIdentPos;
  13470. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  13471. };
  13472. pp$1.parseFunctionParams = function(node) {
  13473. this.expect(types.parenL);
  13474. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  13475. this.checkYieldAwaitInDefaultParams();
  13476. };
  13477. // Parse a class declaration or literal (depending on the
  13478. // `isStatement` parameter).
  13479. pp$1.parseClass = function(node, isStatement) {
  13480. this.next();
  13481. // ecma-262 14.6 Class Definitions
  13482. // A class definition is always strict mode code.
  13483. var oldStrict = this.strict;
  13484. this.strict = true;
  13485. this.parseClassId(node, isStatement);
  13486. this.parseClassSuper(node);
  13487. var classBody = this.startNode();
  13488. var hadConstructor = false;
  13489. classBody.body = [];
  13490. this.expect(types.braceL);
  13491. while (this.type !== types.braceR) {
  13492. var element = this.parseClassElement(node.superClass !== null);
  13493. if (element) {
  13494. classBody.body.push(element);
  13495. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  13496. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  13497. hadConstructor = true;
  13498. }
  13499. }
  13500. }
  13501. this.strict = oldStrict;
  13502. this.next();
  13503. node.body = this.finishNode(classBody, "ClassBody");
  13504. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  13505. };
  13506. pp$1.parseClassElement = function(constructorAllowsSuper) {
  13507. var this$1 = this;
  13508. if (this.eat(types.semi)) { return null }
  13509. var method = this.startNode();
  13510. var tryContextual = function (k, noLineBreak) {
  13511. if ( noLineBreak === void 0 ) noLineBreak = false;
  13512. var start = this$1.start, startLoc = this$1.startLoc;
  13513. if (!this$1.eatContextual(k)) { return false }
  13514. if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
  13515. if (method.key) { this$1.unexpected(); }
  13516. method.computed = false;
  13517. method.key = this$1.startNodeAt(start, startLoc);
  13518. method.key.name = k;
  13519. this$1.finishNode(method.key, "Identifier");
  13520. return false
  13521. };
  13522. method.kind = "method";
  13523. method.static = tryContextual("static");
  13524. var isGenerator = this.eat(types.star);
  13525. var isAsync = false;
  13526. if (!isGenerator) {
  13527. if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
  13528. isAsync = true;
  13529. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  13530. } else if (tryContextual("get")) {
  13531. method.kind = "get";
  13532. } else if (tryContextual("set")) {
  13533. method.kind = "set";
  13534. }
  13535. }
  13536. if (!method.key) { this.parsePropertyName(method); }
  13537. var key = method.key;
  13538. var allowsDirectSuper = false;
  13539. if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
  13540. key.type === "Literal" && key.value === "constructor")) {
  13541. if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
  13542. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  13543. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  13544. method.kind = "constructor";
  13545. allowsDirectSuper = constructorAllowsSuper;
  13546. } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
  13547. this.raise(key.start, "Classes may not have a static property named prototype");
  13548. }
  13549. this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
  13550. if (method.kind === "get" && method.value.params.length !== 0)
  13551. { this.raiseRecoverable(method.value.start, "getter should have no params"); }
  13552. if (method.kind === "set" && method.value.params.length !== 1)
  13553. { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
  13554. if (method.kind === "set" && method.value.params[0].type === "RestElement")
  13555. { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
  13556. return method
  13557. };
  13558. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  13559. method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  13560. return this.finishNode(method, "MethodDefinition")
  13561. };
  13562. pp$1.parseClassId = function(node, isStatement) {
  13563. if (this.type === types.name) {
  13564. node.id = this.parseIdent();
  13565. if (isStatement)
  13566. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  13567. } else {
  13568. if (isStatement === true)
  13569. { this.unexpected(); }
  13570. node.id = null;
  13571. }
  13572. };
  13573. pp$1.parseClassSuper = function(node) {
  13574. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  13575. };
  13576. // Parses module export declaration.
  13577. pp$1.parseExport = function(node, exports) {
  13578. this.next();
  13579. // export * from '...'
  13580. if (this.eat(types.star)) {
  13581. if (this.options.ecmaVersion >= 11) {
  13582. if (this.eatContextual("as")) {
  13583. node.exported = this.parseIdent(true);
  13584. this.checkExport(exports, node.exported.name, this.lastTokStart);
  13585. } else {
  13586. node.exported = null;
  13587. }
  13588. }
  13589. this.expectContextual("from");
  13590. if (this.type !== types.string) { this.unexpected(); }
  13591. node.source = this.parseExprAtom();
  13592. this.semicolon();
  13593. return this.finishNode(node, "ExportAllDeclaration")
  13594. }
  13595. if (this.eat(types._default)) { // export default ...
  13596. this.checkExport(exports, "default", this.lastTokStart);
  13597. var isAsync;
  13598. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  13599. var fNode = this.startNode();
  13600. this.next();
  13601. if (isAsync) { this.next(); }
  13602. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  13603. } else if (this.type === types._class) {
  13604. var cNode = this.startNode();
  13605. node.declaration = this.parseClass(cNode, "nullableID");
  13606. } else {
  13607. node.declaration = this.parseMaybeAssign();
  13608. this.semicolon();
  13609. }
  13610. return this.finishNode(node, "ExportDefaultDeclaration")
  13611. }
  13612. // export var|const|let|function|class ...
  13613. if (this.shouldParseExportStatement()) {
  13614. node.declaration = this.parseStatement(null);
  13615. if (node.declaration.type === "VariableDeclaration")
  13616. { this.checkVariableExport(exports, node.declaration.declarations); }
  13617. else
  13618. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  13619. node.specifiers = [];
  13620. node.source = null;
  13621. } else { // export { x, y as z } [from '...']
  13622. node.declaration = null;
  13623. node.specifiers = this.parseExportSpecifiers(exports);
  13624. if (this.eatContextual("from")) {
  13625. if (this.type !== types.string) { this.unexpected(); }
  13626. node.source = this.parseExprAtom();
  13627. } else {
  13628. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  13629. // check for keywords used as local names
  13630. var spec = list[i];
  13631. this.checkUnreserved(spec.local);
  13632. // check if export is defined
  13633. this.checkLocalExport(spec.local);
  13634. }
  13635. node.source = null;
  13636. }
  13637. this.semicolon();
  13638. }
  13639. return this.finishNode(node, "ExportNamedDeclaration")
  13640. };
  13641. pp$1.checkExport = function(exports, name, pos) {
  13642. if (!exports) { return }
  13643. if (has(exports, name))
  13644. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  13645. exports[name] = true;
  13646. };
  13647. pp$1.checkPatternExport = function(exports, pat) {
  13648. var type = pat.type;
  13649. if (type === "Identifier")
  13650. { this.checkExport(exports, pat.name, pat.start); }
  13651. else if (type === "ObjectPattern")
  13652. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  13653. {
  13654. var prop = list[i];
  13655. this.checkPatternExport(exports, prop);
  13656. } }
  13657. else if (type === "ArrayPattern")
  13658. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  13659. var elt = list$1[i$1];
  13660. if (elt) { this.checkPatternExport(exports, elt); }
  13661. } }
  13662. else if (type === "Property")
  13663. { this.checkPatternExport(exports, pat.value); }
  13664. else if (type === "AssignmentPattern")
  13665. { this.checkPatternExport(exports, pat.left); }
  13666. else if (type === "RestElement")
  13667. { this.checkPatternExport(exports, pat.argument); }
  13668. else if (type === "ParenthesizedExpression")
  13669. { this.checkPatternExport(exports, pat.expression); }
  13670. };
  13671. pp$1.checkVariableExport = function(exports, decls) {
  13672. if (!exports) { return }
  13673. for (var i = 0, list = decls; i < list.length; i += 1)
  13674. {
  13675. var decl = list[i];
  13676. this.checkPatternExport(exports, decl.id);
  13677. }
  13678. };
  13679. pp$1.shouldParseExportStatement = function() {
  13680. return this.type.keyword === "var" ||
  13681. this.type.keyword === "const" ||
  13682. this.type.keyword === "class" ||
  13683. this.type.keyword === "function" ||
  13684. this.isLet() ||
  13685. this.isAsyncFunction()
  13686. };
  13687. // Parses a comma-separated list of module exports.
  13688. pp$1.parseExportSpecifiers = function(exports) {
  13689. var nodes = [], first = true;
  13690. // export { x, y as z } [from '...']
  13691. this.expect(types.braceL);
  13692. while (!this.eat(types.braceR)) {
  13693. if (!first) {
  13694. this.expect(types.comma);
  13695. if (this.afterTrailingComma(types.braceR)) { break }
  13696. } else { first = false; }
  13697. var node = this.startNode();
  13698. node.local = this.parseIdent(true);
  13699. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  13700. this.checkExport(exports, node.exported.name, node.exported.start);
  13701. nodes.push(this.finishNode(node, "ExportSpecifier"));
  13702. }
  13703. return nodes
  13704. };
  13705. // Parses import declaration.
  13706. pp$1.parseImport = function(node) {
  13707. this.next();
  13708. // import '...'
  13709. if (this.type === types.string) {
  13710. node.specifiers = empty;
  13711. node.source = this.parseExprAtom();
  13712. } else {
  13713. node.specifiers = this.parseImportSpecifiers();
  13714. this.expectContextual("from");
  13715. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  13716. }
  13717. this.semicolon();
  13718. return this.finishNode(node, "ImportDeclaration")
  13719. };
  13720. // Parses a comma-separated list of module imports.
  13721. pp$1.parseImportSpecifiers = function() {
  13722. var nodes = [], first = true;
  13723. if (this.type === types.name) {
  13724. // import defaultObj, { x, y as z } from '...'
  13725. var node = this.startNode();
  13726. node.local = this.parseIdent();
  13727. this.checkLValSimple(node.local, BIND_LEXICAL);
  13728. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  13729. if (!this.eat(types.comma)) { return nodes }
  13730. }
  13731. if (this.type === types.star) {
  13732. var node$1 = this.startNode();
  13733. this.next();
  13734. this.expectContextual("as");
  13735. node$1.local = this.parseIdent();
  13736. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  13737. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  13738. return nodes
  13739. }
  13740. this.expect(types.braceL);
  13741. while (!this.eat(types.braceR)) {
  13742. if (!first) {
  13743. this.expect(types.comma);
  13744. if (this.afterTrailingComma(types.braceR)) { break }
  13745. } else { first = false; }
  13746. var node$2 = this.startNode();
  13747. node$2.imported = this.parseIdent(true);
  13748. if (this.eatContextual("as")) {
  13749. node$2.local = this.parseIdent();
  13750. } else {
  13751. this.checkUnreserved(node$2.imported);
  13752. node$2.local = node$2.imported;
  13753. }
  13754. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  13755. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  13756. }
  13757. return nodes
  13758. };
  13759. // Set `ExpressionStatement#directive` property for directive prologues.
  13760. pp$1.adaptDirectivePrologue = function(statements) {
  13761. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  13762. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  13763. }
  13764. };
  13765. pp$1.isDirectiveCandidate = function(statement) {
  13766. return (
  13767. statement.type === "ExpressionStatement" &&
  13768. statement.expression.type === "Literal" &&
  13769. typeof statement.expression.value === "string" &&
  13770. // Reject parenthesized strings.
  13771. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  13772. )
  13773. };
  13774. var pp$2 = Parser.prototype;
  13775. // Convert existing expression atom to assignable pattern
  13776. // if possible.
  13777. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  13778. if (this.options.ecmaVersion >= 6 && node) {
  13779. switch (node.type) {
  13780. case "Identifier":
  13781. if (this.inAsync && node.name === "await")
  13782. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  13783. break
  13784. case "ObjectPattern":
  13785. case "ArrayPattern":
  13786. case "AssignmentPattern":
  13787. case "RestElement":
  13788. break
  13789. case "ObjectExpression":
  13790. node.type = "ObjectPattern";
  13791. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13792. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  13793. var prop = list[i];
  13794. this.toAssignable(prop, isBinding);
  13795. // Early error:
  13796. // AssignmentRestProperty[Yield, Await] :
  13797. // `...` DestructuringAssignmentTarget[Yield, Await]
  13798. //
  13799. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  13800. if (
  13801. prop.type === "RestElement" &&
  13802. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  13803. ) {
  13804. this.raise(prop.argument.start, "Unexpected token");
  13805. }
  13806. }
  13807. break
  13808. case "Property":
  13809. // AssignmentProperty has type === "Property"
  13810. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  13811. this.toAssignable(node.value, isBinding);
  13812. break
  13813. case "ArrayExpression":
  13814. node.type = "ArrayPattern";
  13815. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13816. this.toAssignableList(node.elements, isBinding);
  13817. break
  13818. case "SpreadElement":
  13819. node.type = "RestElement";
  13820. this.toAssignable(node.argument, isBinding);
  13821. if (node.argument.type === "AssignmentPattern")
  13822. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  13823. break
  13824. case "AssignmentExpression":
  13825. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  13826. node.type = "AssignmentPattern";
  13827. delete node.operator;
  13828. this.toAssignable(node.left, isBinding);
  13829. break
  13830. case "ParenthesizedExpression":
  13831. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  13832. break
  13833. case "ChainExpression":
  13834. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  13835. break
  13836. case "MemberExpression":
  13837. if (!isBinding) { break }
  13838. default:
  13839. this.raise(node.start, "Assigning to rvalue");
  13840. }
  13841. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  13842. return node
  13843. };
  13844. // Convert list of expression atoms to binding list.
  13845. pp$2.toAssignableList = function(exprList, isBinding) {
  13846. var end = exprList.length;
  13847. for (var i = 0; i < end; i++) {
  13848. var elt = exprList[i];
  13849. if (elt) { this.toAssignable(elt, isBinding); }
  13850. }
  13851. if (end) {
  13852. var last = exprList[end - 1];
  13853. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  13854. { this.unexpected(last.argument.start); }
  13855. }
  13856. return exprList
  13857. };
  13858. // Parses spread element.
  13859. pp$2.parseSpread = function(refDestructuringErrors) {
  13860. var node = this.startNode();
  13861. this.next();
  13862. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  13863. return this.finishNode(node, "SpreadElement")
  13864. };
  13865. pp$2.parseRestBinding = function() {
  13866. var node = this.startNode();
  13867. this.next();
  13868. // RestElement inside of a function parameter must be an identifier
  13869. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  13870. { this.unexpected(); }
  13871. node.argument = this.parseBindingAtom();
  13872. return this.finishNode(node, "RestElement")
  13873. };
  13874. // Parses lvalue (assignable) atom.
  13875. pp$2.parseBindingAtom = function() {
  13876. if (this.options.ecmaVersion >= 6) {
  13877. switch (this.type) {
  13878. case types.bracketL:
  13879. var node = this.startNode();
  13880. this.next();
  13881. node.elements = this.parseBindingList(types.bracketR, true, true);
  13882. return this.finishNode(node, "ArrayPattern")
  13883. case types.braceL:
  13884. return this.parseObj(true)
  13885. }
  13886. }
  13887. return this.parseIdent()
  13888. };
  13889. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  13890. var elts = [], first = true;
  13891. while (!this.eat(close)) {
  13892. if (first) { first = false; }
  13893. else { this.expect(types.comma); }
  13894. if (allowEmpty && this.type === types.comma) {
  13895. elts.push(null);
  13896. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  13897. break
  13898. } else if (this.type === types.ellipsis) {
  13899. var rest = this.parseRestBinding();
  13900. this.parseBindingListItem(rest);
  13901. elts.push(rest);
  13902. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  13903. this.expect(close);
  13904. break
  13905. } else {
  13906. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  13907. this.parseBindingListItem(elem);
  13908. elts.push(elem);
  13909. }
  13910. }
  13911. return elts
  13912. };
  13913. pp$2.parseBindingListItem = function(param) {
  13914. return param
  13915. };
  13916. // Parses assignment pattern around given atom if possible.
  13917. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  13918. left = left || this.parseBindingAtom();
  13919. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  13920. var node = this.startNodeAt(startPos, startLoc);
  13921. node.left = left;
  13922. node.right = this.parseMaybeAssign();
  13923. return this.finishNode(node, "AssignmentPattern")
  13924. };
  13925. // The following three functions all verify that a node is an lvalue —
  13926. // something that can be bound, or assigned to. In order to do so, they perform
  13927. // a variety of checks:
  13928. //
  13929. // - Check that none of the bound/assigned-to identifiers are reserved words.
  13930. // - Record name declarations for bindings in the appropriate scope.
  13931. // - Check duplicate argument names, if checkClashes is set.
  13932. //
  13933. // If a complex binding pattern is encountered (e.g., object and array
  13934. // destructuring), the entire pattern is recursively checked.
  13935. //
  13936. // There are three versions of checkLVal*() appropriate for different
  13937. // circumstances:
  13938. //
  13939. // - checkLValSimple() shall be used if the syntactic construct supports
  13940. // nothing other than identifiers and member expressions. Parenthesized
  13941. // expressions are also correctly handled. This is generally appropriate for
  13942. // constructs for which the spec says
  13943. //
  13944. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  13945. // > simple.
  13946. //
  13947. // It is also appropriate for checking if an identifier is valid and not
  13948. // defined elsewhere, like import declarations or function/class identifiers.
  13949. //
  13950. // Examples where this is used include:
  13951. // a += …;
  13952. // import a from '…';
  13953. // where a is the node to be checked.
  13954. //
  13955. // - checkLValPattern() shall be used if the syntactic construct supports
  13956. // anything checkLValSimple() supports, as well as object and array
  13957. // destructuring patterns. This is generally appropriate for constructs for
  13958. // which the spec says
  13959. //
  13960. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  13961. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  13962. // > simple.
  13963. //
  13964. // Examples where this is used include:
  13965. // (a = …);
  13966. // const a = …;
  13967. // try { … } catch (a) { … }
  13968. // where a is the node to be checked.
  13969. //
  13970. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  13971. // anything checkLValPattern() supports, as well as default assignment
  13972. // patterns, rest elements, and other constructs that may appear within an
  13973. // object or array destructuring pattern.
  13974. //
  13975. // As a special case, function parameters also use checkLValInnerPattern(),
  13976. // as they also support defaults and rest constructs.
  13977. //
  13978. // These functions deliberately support both assignment and binding constructs,
  13979. // as the logic for both is exceedingly similar. If the node is the target of
  13980. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  13981. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  13982. // BIND_LEXICAL.
  13983. //
  13984. // If the function is called with a non-BIND_NONE bindingType, then
  13985. // additionally a checkClashes object may be specified to allow checking for
  13986. // duplicate argument names. checkClashes is ignored if the provided construct
  13987. // is an assignment (i.e., bindingType is BIND_NONE).
  13988. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  13989. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  13990. var isBind = bindingType !== BIND_NONE;
  13991. switch (expr.type) {
  13992. case "Identifier":
  13993. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  13994. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  13995. if (isBind) {
  13996. if (bindingType === BIND_LEXICAL && expr.name === "let")
  13997. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  13998. if (checkClashes) {
  13999. if (has(checkClashes, expr.name))
  14000. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  14001. checkClashes[expr.name] = true;
  14002. }
  14003. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  14004. }
  14005. break
  14006. case "ChainExpression":
  14007. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  14008. break
  14009. case "MemberExpression":
  14010. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  14011. break
  14012. case "ParenthesizedExpression":
  14013. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  14014. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  14015. default:
  14016. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  14017. }
  14018. };
  14019. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  14020. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  14021. switch (expr.type) {
  14022. case "ObjectPattern":
  14023. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  14024. var prop = list[i];
  14025. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  14026. }
  14027. break
  14028. case "ArrayPattern":
  14029. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  14030. var elem = list$1[i$1];
  14031. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  14032. }
  14033. break
  14034. default:
  14035. this.checkLValSimple(expr, bindingType, checkClashes);
  14036. }
  14037. };
  14038. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  14039. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  14040. switch (expr.type) {
  14041. case "Property":
  14042. // AssignmentProperty has type === "Property"
  14043. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  14044. break
  14045. case "AssignmentPattern":
  14046. this.checkLValPattern(expr.left, bindingType, checkClashes);
  14047. break
  14048. case "RestElement":
  14049. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  14050. break
  14051. default:
  14052. this.checkLValPattern(expr, bindingType, checkClashes);
  14053. }
  14054. };
  14055. // A recursive descent parser operates by defining functions for all
  14056. var pp$3 = Parser.prototype;
  14057. // Check if property name clashes with already added.
  14058. // Object/class getters and setters are not allowed to clash —
  14059. // either with each other or with an init property — and in
  14060. // strict mode, init properties are also not allowed to be repeated.
  14061. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  14062. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  14063. { return }
  14064. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  14065. { return }
  14066. var key = prop.key;
  14067. var name;
  14068. switch (key.type) {
  14069. case "Identifier": name = key.name; break
  14070. case "Literal": name = String(key.value); break
  14071. default: return
  14072. }
  14073. var kind = prop.kind;
  14074. if (this.options.ecmaVersion >= 6) {
  14075. if (name === "__proto__" && kind === "init") {
  14076. if (propHash.proto) {
  14077. if (refDestructuringErrors) {
  14078. if (refDestructuringErrors.doubleProto < 0)
  14079. { refDestructuringErrors.doubleProto = key.start; }
  14080. // Backwards-compat kludge. Can be removed in version 6.0
  14081. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  14082. }
  14083. propHash.proto = true;
  14084. }
  14085. return
  14086. }
  14087. name = "$" + name;
  14088. var other = propHash[name];
  14089. if (other) {
  14090. var redefinition;
  14091. if (kind === "init") {
  14092. redefinition = this.strict && other.init || other.get || other.set;
  14093. } else {
  14094. redefinition = other.init || other[kind];
  14095. }
  14096. if (redefinition)
  14097. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  14098. } else {
  14099. other = propHash[name] = {
  14100. init: false,
  14101. get: false,
  14102. set: false
  14103. };
  14104. }
  14105. other[kind] = true;
  14106. };
  14107. // ### Expression parsing
  14108. // These nest, from the most general expression type at the top to
  14109. // 'atomic', nondivisible expression types at the bottom. Most of
  14110. // the functions will simply let the function(s) below them parse,
  14111. // and, *if* the syntactic construct they handle is present, wrap
  14112. // the AST node that the inner parser gave them in another node.
  14113. // Parse a full expression. The optional arguments are used to
  14114. // forbid the `in` operator (in for loops initalization expressions)
  14115. // and provide reference for storing '=' operator inside shorthand
  14116. // property assignment in contexts where both object expression
  14117. // and object pattern might appear (so it's possible to raise
  14118. // delayed syntax error at correct position).
  14119. pp$3.parseExpression = function(noIn, refDestructuringErrors) {
  14120. var startPos = this.start, startLoc = this.startLoc;
  14121. var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
  14122. if (this.type === types.comma) {
  14123. var node = this.startNodeAt(startPos, startLoc);
  14124. node.expressions = [expr];
  14125. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
  14126. return this.finishNode(node, "SequenceExpression")
  14127. }
  14128. return expr
  14129. };
  14130. // Parse an assignment expression. This includes applications of
  14131. // operators like `+=`.
  14132. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
  14133. if (this.isContextual("yield")) {
  14134. if (this.inGenerator) { return this.parseYield(noIn) }
  14135. // The tokenizer will assume an expression is allowed after
  14136. // `yield`, but this isn't that kind of yield
  14137. else { this.exprAllowed = false; }
  14138. }
  14139. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  14140. if (refDestructuringErrors) {
  14141. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  14142. oldTrailingComma = refDestructuringErrors.trailingComma;
  14143. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  14144. } else {
  14145. refDestructuringErrors = new DestructuringErrors;
  14146. ownDestructuringErrors = true;
  14147. }
  14148. var startPos = this.start, startLoc = this.startLoc;
  14149. if (this.type === types.parenL || this.type === types.name)
  14150. { this.potentialArrowAt = this.start; }
  14151. var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
  14152. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  14153. if (this.type.isAssign) {
  14154. var node = this.startNodeAt(startPos, startLoc);
  14155. node.operator = this.value;
  14156. if (this.type === types.eq)
  14157. { left = this.toAssignable(left, false, refDestructuringErrors); }
  14158. if (!ownDestructuringErrors) {
  14159. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  14160. }
  14161. if (refDestructuringErrors.shorthandAssign >= left.start)
  14162. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  14163. if (this.type === types.eq)
  14164. { this.checkLValPattern(left); }
  14165. else
  14166. { this.checkLValSimple(left); }
  14167. node.left = left;
  14168. this.next();
  14169. node.right = this.parseMaybeAssign(noIn);
  14170. return this.finishNode(node, "AssignmentExpression")
  14171. } else {
  14172. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  14173. }
  14174. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  14175. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  14176. return left
  14177. };
  14178. // Parse a ternary conditional (`?:`) operator.
  14179. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
  14180. var startPos = this.start, startLoc = this.startLoc;
  14181. var expr = this.parseExprOps(noIn, refDestructuringErrors);
  14182. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14183. if (this.eat(types.question)) {
  14184. var node = this.startNodeAt(startPos, startLoc);
  14185. node.test = expr;
  14186. node.consequent = this.parseMaybeAssign();
  14187. this.expect(types.colon);
  14188. node.alternate = this.parseMaybeAssign(noIn);
  14189. return this.finishNode(node, "ConditionalExpression")
  14190. }
  14191. return expr
  14192. };
  14193. // Start the precedence parser.
  14194. pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
  14195. var startPos = this.start, startLoc = this.startLoc;
  14196. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  14197. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14198. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
  14199. };
  14200. // Parse binary operators with the operator precedence parsing
  14201. // algorithm. `left` is the left-hand side of the operator.
  14202. // `minPrec` provides context that allows the function to stop and
  14203. // defer further parser to one of its callers when it encounters an
  14204. // operator that has a lower precedence than the set it is parsing.
  14205. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  14206. var prec = this.type.binop;
  14207. if (prec != null && (!noIn || this.type !== types._in)) {
  14208. if (prec > minPrec) {
  14209. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  14210. var coalesce = this.type === types.coalesce;
  14211. if (coalesce) {
  14212. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  14213. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  14214. prec = types.logicalAND.binop;
  14215. }
  14216. var op = this.value;
  14217. this.next();
  14218. var startPos = this.start, startLoc = this.startLoc;
  14219. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
  14220. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  14221. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  14222. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  14223. }
  14224. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
  14225. }
  14226. }
  14227. return left
  14228. };
  14229. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  14230. var node = this.startNodeAt(startPos, startLoc);
  14231. node.left = left;
  14232. node.operator = op;
  14233. node.right = right;
  14234. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  14235. };
  14236. // Parse unary operators, both prefix and postfix.
  14237. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
  14238. var startPos = this.start, startLoc = this.startLoc, expr;
  14239. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  14240. expr = this.parseAwait();
  14241. sawUnary = true;
  14242. } else if (this.type.prefix) {
  14243. var node = this.startNode(), update = this.type === types.incDec;
  14244. node.operator = this.value;
  14245. node.prefix = true;
  14246. this.next();
  14247. node.argument = this.parseMaybeUnary(null, true);
  14248. this.checkExpressionErrors(refDestructuringErrors, true);
  14249. if (update) { this.checkLValSimple(node.argument); }
  14250. else if (this.strict && node.operator === "delete" &&
  14251. node.argument.type === "Identifier")
  14252. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  14253. else { sawUnary = true; }
  14254. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  14255. } else {
  14256. expr = this.parseExprSubscripts(refDestructuringErrors);
  14257. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  14258. while (this.type.postfix && !this.canInsertSemicolon()) {
  14259. var node$1 = this.startNodeAt(startPos, startLoc);
  14260. node$1.operator = this.value;
  14261. node$1.prefix = false;
  14262. node$1.argument = expr;
  14263. this.checkLValSimple(expr);
  14264. this.next();
  14265. expr = this.finishNode(node$1, "UpdateExpression");
  14266. }
  14267. }
  14268. if (!sawUnary && this.eat(types.starstar))
  14269. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  14270. else
  14271. { return expr }
  14272. };
  14273. // Parse call, dot, and `[]`-subscript expressions.
  14274. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  14275. var startPos = this.start, startLoc = this.startLoc;
  14276. var expr = this.parseExprAtom(refDestructuringErrors);
  14277. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  14278. { return expr }
  14279. var result = this.parseSubscripts(expr, startPos, startLoc);
  14280. if (refDestructuringErrors && result.type === "MemberExpression") {
  14281. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  14282. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  14283. }
  14284. return result
  14285. };
  14286. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  14287. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  14288. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  14289. this.potentialArrowAt === base.start;
  14290. var optionalChained = false;
  14291. while (true) {
  14292. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  14293. if (element.optional) { optionalChained = true; }
  14294. if (element === base || element.type === "ArrowFunctionExpression") {
  14295. if (optionalChained) {
  14296. var chainNode = this.startNodeAt(startPos, startLoc);
  14297. chainNode.expression = element;
  14298. element = this.finishNode(chainNode, "ChainExpression");
  14299. }
  14300. return element
  14301. }
  14302. base = element;
  14303. }
  14304. };
  14305. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  14306. var optionalSupported = this.options.ecmaVersion >= 11;
  14307. var optional = optionalSupported && this.eat(types.questionDot);
  14308. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  14309. var computed = this.eat(types.bracketL);
  14310. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  14311. var node = this.startNodeAt(startPos, startLoc);
  14312. node.object = base;
  14313. node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
  14314. node.computed = !!computed;
  14315. if (computed) { this.expect(types.bracketR); }
  14316. if (optionalSupported) {
  14317. node.optional = optional;
  14318. }
  14319. base = this.finishNode(node, "MemberExpression");
  14320. } else if (!noCalls && this.eat(types.parenL)) {
  14321. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14322. this.yieldPos = 0;
  14323. this.awaitPos = 0;
  14324. this.awaitIdentPos = 0;
  14325. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  14326. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  14327. this.checkPatternErrors(refDestructuringErrors, false);
  14328. this.checkYieldAwaitInDefaultParams();
  14329. if (this.awaitIdentPos > 0)
  14330. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  14331. this.yieldPos = oldYieldPos;
  14332. this.awaitPos = oldAwaitPos;
  14333. this.awaitIdentPos = oldAwaitIdentPos;
  14334. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  14335. }
  14336. this.checkExpressionErrors(refDestructuringErrors, true);
  14337. this.yieldPos = oldYieldPos || this.yieldPos;
  14338. this.awaitPos = oldAwaitPos || this.awaitPos;
  14339. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  14340. var node$1 = this.startNodeAt(startPos, startLoc);
  14341. node$1.callee = base;
  14342. node$1.arguments = exprList;
  14343. if (optionalSupported) {
  14344. node$1.optional = optional;
  14345. }
  14346. base = this.finishNode(node$1, "CallExpression");
  14347. } else if (this.type === types.backQuote) {
  14348. if (optional || optionalChained) {
  14349. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  14350. }
  14351. var node$2 = this.startNodeAt(startPos, startLoc);
  14352. node$2.tag = base;
  14353. node$2.quasi = this.parseTemplate({isTagged: true});
  14354. base = this.finishNode(node$2, "TaggedTemplateExpression");
  14355. }
  14356. return base
  14357. };
  14358. // Parse an atomic expression — either a single token that is an
  14359. // expression, an expression started by a keyword like `function` or
  14360. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  14361. // or `{}`.
  14362. pp$3.parseExprAtom = function(refDestructuringErrors) {
  14363. // If a division operator appears in an expression position, the
  14364. // tokenizer got confused, and we force it to read a regexp instead.
  14365. if (this.type === types.slash) { this.readRegexp(); }
  14366. var node, canBeArrow = this.potentialArrowAt === this.start;
  14367. switch (this.type) {
  14368. case types._super:
  14369. if (!this.allowSuper)
  14370. { this.raise(this.start, "'super' keyword outside a method"); }
  14371. node = this.startNode();
  14372. this.next();
  14373. if (this.type === types.parenL && !this.allowDirectSuper)
  14374. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  14375. // The `super` keyword can appear at below:
  14376. // SuperProperty:
  14377. // super [ Expression ]
  14378. // super . IdentifierName
  14379. // SuperCall:
  14380. // super ( Arguments )
  14381. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  14382. { this.unexpected(); }
  14383. return this.finishNode(node, "Super")
  14384. case types._this:
  14385. node = this.startNode();
  14386. this.next();
  14387. return this.finishNode(node, "ThisExpression")
  14388. case types.name:
  14389. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  14390. var id = this.parseIdent(false);
  14391. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  14392. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  14393. if (canBeArrow && !this.canInsertSemicolon()) {
  14394. if (this.eat(types.arrow))
  14395. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  14396. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
  14397. id = this.parseIdent(false);
  14398. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  14399. { this.unexpected(); }
  14400. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  14401. }
  14402. }
  14403. return id
  14404. case types.regexp:
  14405. var value = this.value;
  14406. node = this.parseLiteral(value.value);
  14407. node.regex = {pattern: value.pattern, flags: value.flags};
  14408. return node
  14409. case types.num: case types.string:
  14410. return this.parseLiteral(this.value)
  14411. case types._null: case types._true: case types._false:
  14412. node = this.startNode();
  14413. node.value = this.type === types._null ? null : this.type === types._true;
  14414. node.raw = this.type.keyword;
  14415. this.next();
  14416. return this.finishNode(node, "Literal")
  14417. case types.parenL:
  14418. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  14419. if (refDestructuringErrors) {
  14420. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  14421. { refDestructuringErrors.parenthesizedAssign = start; }
  14422. if (refDestructuringErrors.parenthesizedBind < 0)
  14423. { refDestructuringErrors.parenthesizedBind = start; }
  14424. }
  14425. return expr
  14426. case types.bracketL:
  14427. node = this.startNode();
  14428. this.next();
  14429. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  14430. return this.finishNode(node, "ArrayExpression")
  14431. case types.braceL:
  14432. return this.parseObj(false, refDestructuringErrors)
  14433. case types._function:
  14434. node = this.startNode();
  14435. this.next();
  14436. return this.parseFunction(node, 0)
  14437. case types._class:
  14438. return this.parseClass(this.startNode(), false)
  14439. case types._new:
  14440. return this.parseNew()
  14441. case types.backQuote:
  14442. return this.parseTemplate()
  14443. case types._import:
  14444. if (this.options.ecmaVersion >= 11) {
  14445. return this.parseExprImport()
  14446. } else {
  14447. return this.unexpected()
  14448. }
  14449. default:
  14450. this.unexpected();
  14451. }
  14452. };
  14453. pp$3.parseExprImport = function() {
  14454. var node = this.startNode();
  14455. // Consume `import` as an identifier for `import.meta`.
  14456. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  14457. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  14458. var meta = this.parseIdent(true);
  14459. switch (this.type) {
  14460. case types.parenL:
  14461. return this.parseDynamicImport(node)
  14462. case types.dot:
  14463. node.meta = meta;
  14464. return this.parseImportMeta(node)
  14465. default:
  14466. this.unexpected();
  14467. }
  14468. };
  14469. pp$3.parseDynamicImport = function(node) {
  14470. this.next(); // skip `(`
  14471. // Parse node.source.
  14472. node.source = this.parseMaybeAssign();
  14473. // Verify ending.
  14474. if (!this.eat(types.parenR)) {
  14475. var errorPos = this.start;
  14476. if (this.eat(types.comma) && this.eat(types.parenR)) {
  14477. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  14478. } else {
  14479. this.unexpected(errorPos);
  14480. }
  14481. }
  14482. return this.finishNode(node, "ImportExpression")
  14483. };
  14484. pp$3.parseImportMeta = function(node) {
  14485. this.next(); // skip `.`
  14486. var containsEsc = this.containsEsc;
  14487. node.property = this.parseIdent(true);
  14488. if (node.property.name !== "meta")
  14489. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  14490. if (containsEsc)
  14491. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  14492. if (this.options.sourceType !== "module")
  14493. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  14494. return this.finishNode(node, "MetaProperty")
  14495. };
  14496. pp$3.parseLiteral = function(value) {
  14497. var node = this.startNode();
  14498. node.value = value;
  14499. node.raw = this.input.slice(this.start, this.end);
  14500. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  14501. this.next();
  14502. return this.finishNode(node, "Literal")
  14503. };
  14504. pp$3.parseParenExpression = function() {
  14505. this.expect(types.parenL);
  14506. var val = this.parseExpression();
  14507. this.expect(types.parenR);
  14508. return val
  14509. };
  14510. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  14511. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  14512. if (this.options.ecmaVersion >= 6) {
  14513. this.next();
  14514. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  14515. var exprList = [], first = true, lastIsComma = false;
  14516. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  14517. this.yieldPos = 0;
  14518. this.awaitPos = 0;
  14519. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  14520. while (this.type !== types.parenR) {
  14521. first ? first = false : this.expect(types.comma);
  14522. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  14523. lastIsComma = true;
  14524. break
  14525. } else if (this.type === types.ellipsis) {
  14526. spreadStart = this.start;
  14527. exprList.push(this.parseParenItem(this.parseRestBinding()));
  14528. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  14529. break
  14530. } else {
  14531. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  14532. }
  14533. }
  14534. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  14535. this.expect(types.parenR);
  14536. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  14537. this.checkPatternErrors(refDestructuringErrors, false);
  14538. this.checkYieldAwaitInDefaultParams();
  14539. this.yieldPos = oldYieldPos;
  14540. this.awaitPos = oldAwaitPos;
  14541. return this.parseParenArrowList(startPos, startLoc, exprList)
  14542. }
  14543. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  14544. if (spreadStart) { this.unexpected(spreadStart); }
  14545. this.checkExpressionErrors(refDestructuringErrors, true);
  14546. this.yieldPos = oldYieldPos || this.yieldPos;
  14547. this.awaitPos = oldAwaitPos || this.awaitPos;
  14548. if (exprList.length > 1) {
  14549. val = this.startNodeAt(innerStartPos, innerStartLoc);
  14550. val.expressions = exprList;
  14551. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  14552. } else {
  14553. val = exprList[0];
  14554. }
  14555. } else {
  14556. val = this.parseParenExpression();
  14557. }
  14558. if (this.options.preserveParens) {
  14559. var par = this.startNodeAt(startPos, startLoc);
  14560. par.expression = val;
  14561. return this.finishNode(par, "ParenthesizedExpression")
  14562. } else {
  14563. return val
  14564. }
  14565. };
  14566. pp$3.parseParenItem = function(item) {
  14567. return item
  14568. };
  14569. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  14570. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  14571. };
  14572. // New's precedence is slightly tricky. It must allow its argument to
  14573. // be a `[]` or dot subscript expression, but not a call — at least,
  14574. // not without wrapping it in parentheses. Thus, it uses the noCalls
  14575. // argument to parseSubscripts to prevent it from consuming the
  14576. // argument list.
  14577. var empty$1 = [];
  14578. pp$3.parseNew = function() {
  14579. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  14580. var node = this.startNode();
  14581. var meta = this.parseIdent(true);
  14582. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  14583. node.meta = meta;
  14584. var containsEsc = this.containsEsc;
  14585. node.property = this.parseIdent(true);
  14586. if (node.property.name !== "target")
  14587. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  14588. if (containsEsc)
  14589. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  14590. if (!this.inNonArrowFunction)
  14591. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  14592. return this.finishNode(node, "MetaProperty")
  14593. }
  14594. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  14595. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  14596. if (isImport && node.callee.type === "ImportExpression") {
  14597. this.raise(startPos, "Cannot use new with import()");
  14598. }
  14599. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  14600. else { node.arguments = empty$1; }
  14601. return this.finishNode(node, "NewExpression")
  14602. };
  14603. // Parse template expression.
  14604. pp$3.parseTemplateElement = function(ref) {
  14605. var isTagged = ref.isTagged;
  14606. var elem = this.startNode();
  14607. if (this.type === types.invalidTemplate) {
  14608. if (!isTagged) {
  14609. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  14610. }
  14611. elem.value = {
  14612. raw: this.value,
  14613. cooked: null
  14614. };
  14615. } else {
  14616. elem.value = {
  14617. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  14618. cooked: this.value
  14619. };
  14620. }
  14621. this.next();
  14622. elem.tail = this.type === types.backQuote;
  14623. return this.finishNode(elem, "TemplateElement")
  14624. };
  14625. pp$3.parseTemplate = function(ref) {
  14626. if ( ref === void 0 ) ref = {};
  14627. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  14628. var node = this.startNode();
  14629. this.next();
  14630. node.expressions = [];
  14631. var curElt = this.parseTemplateElement({isTagged: isTagged});
  14632. node.quasis = [curElt];
  14633. while (!curElt.tail) {
  14634. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  14635. this.expect(types.dollarBraceL);
  14636. node.expressions.push(this.parseExpression());
  14637. this.expect(types.braceR);
  14638. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  14639. }
  14640. this.next();
  14641. return this.finishNode(node, "TemplateLiteral")
  14642. };
  14643. pp$3.isAsyncProp = function(prop) {
  14644. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  14645. (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
  14646. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  14647. };
  14648. // Parse an object literal or binding pattern.
  14649. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  14650. var node = this.startNode(), first = true, propHash = {};
  14651. node.properties = [];
  14652. this.next();
  14653. while (!this.eat(types.braceR)) {
  14654. if (!first) {
  14655. this.expect(types.comma);
  14656. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  14657. } else { first = false; }
  14658. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  14659. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  14660. node.properties.push(prop);
  14661. }
  14662. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  14663. };
  14664. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  14665. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  14666. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  14667. if (isPattern) {
  14668. prop.argument = this.parseIdent(false);
  14669. if (this.type === types.comma) {
  14670. this.raise(this.start, "Comma is not permitted after the rest element");
  14671. }
  14672. return this.finishNode(prop, "RestElement")
  14673. }
  14674. // To disallow parenthesized identifier via `this.toAssignable()`.
  14675. if (this.type === types.parenL && refDestructuringErrors) {
  14676. if (refDestructuringErrors.parenthesizedAssign < 0) {
  14677. refDestructuringErrors.parenthesizedAssign = this.start;
  14678. }
  14679. if (refDestructuringErrors.parenthesizedBind < 0) {
  14680. refDestructuringErrors.parenthesizedBind = this.start;
  14681. }
  14682. }
  14683. // Parse argument.
  14684. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  14685. // To disallow trailing comma via `this.toAssignable()`.
  14686. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  14687. refDestructuringErrors.trailingComma = this.start;
  14688. }
  14689. // Finish
  14690. return this.finishNode(prop, "SpreadElement")
  14691. }
  14692. if (this.options.ecmaVersion >= 6) {
  14693. prop.method = false;
  14694. prop.shorthand = false;
  14695. if (isPattern || refDestructuringErrors) {
  14696. startPos = this.start;
  14697. startLoc = this.startLoc;
  14698. }
  14699. if (!isPattern)
  14700. { isGenerator = this.eat(types.star); }
  14701. }
  14702. var containsEsc = this.containsEsc;
  14703. this.parsePropertyName(prop);
  14704. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  14705. isAsync = true;
  14706. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  14707. this.parsePropertyName(prop, refDestructuringErrors);
  14708. } else {
  14709. isAsync = false;
  14710. }
  14711. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  14712. return this.finishNode(prop, "Property")
  14713. };
  14714. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  14715. if ((isGenerator || isAsync) && this.type === types.colon)
  14716. { this.unexpected(); }
  14717. if (this.eat(types.colon)) {
  14718. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  14719. prop.kind = "init";
  14720. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  14721. if (isPattern) { this.unexpected(); }
  14722. prop.kind = "init";
  14723. prop.method = true;
  14724. prop.value = this.parseMethod(isGenerator, isAsync);
  14725. } else if (!isPattern && !containsEsc &&
  14726. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  14727. (prop.key.name === "get" || prop.key.name === "set") &&
  14728. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  14729. if (isGenerator || isAsync) { this.unexpected(); }
  14730. prop.kind = prop.key.name;
  14731. this.parsePropertyName(prop);
  14732. prop.value = this.parseMethod(false);
  14733. var paramCount = prop.kind === "get" ? 0 : 1;
  14734. if (prop.value.params.length !== paramCount) {
  14735. var start = prop.value.start;
  14736. if (prop.kind === "get")
  14737. { this.raiseRecoverable(start, "getter should have no params"); }
  14738. else
  14739. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  14740. } else {
  14741. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  14742. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  14743. }
  14744. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  14745. if (isGenerator || isAsync) { this.unexpected(); }
  14746. this.checkUnreserved(prop.key);
  14747. if (prop.key.name === "await" && !this.awaitIdentPos)
  14748. { this.awaitIdentPos = startPos; }
  14749. prop.kind = "init";
  14750. if (isPattern) {
  14751. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14752. } else if (this.type === types.eq && refDestructuringErrors) {
  14753. if (refDestructuringErrors.shorthandAssign < 0)
  14754. { refDestructuringErrors.shorthandAssign = this.start; }
  14755. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  14756. } else {
  14757. prop.value = this.copyNode(prop.key);
  14758. }
  14759. prop.shorthand = true;
  14760. } else { this.unexpected(); }
  14761. };
  14762. pp$3.parsePropertyName = function(prop) {
  14763. if (this.options.ecmaVersion >= 6) {
  14764. if (this.eat(types.bracketL)) {
  14765. prop.computed = true;
  14766. prop.key = this.parseMaybeAssign();
  14767. this.expect(types.bracketR);
  14768. return prop.key
  14769. } else {
  14770. prop.computed = false;
  14771. }
  14772. }
  14773. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  14774. };
  14775. // Initialize empty function node.
  14776. pp$3.initFunction = function(node) {
  14777. node.id = null;
  14778. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  14779. if (this.options.ecmaVersion >= 8) { node.async = false; }
  14780. };
  14781. // Parse object or class method.
  14782. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  14783. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14784. this.initFunction(node);
  14785. if (this.options.ecmaVersion >= 6)
  14786. { node.generator = isGenerator; }
  14787. if (this.options.ecmaVersion >= 8)
  14788. { node.async = !!isAsync; }
  14789. this.yieldPos = 0;
  14790. this.awaitPos = 0;
  14791. this.awaitIdentPos = 0;
  14792. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  14793. this.expect(types.parenL);
  14794. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  14795. this.checkYieldAwaitInDefaultParams();
  14796. this.parseFunctionBody(node, false, true);
  14797. this.yieldPos = oldYieldPos;
  14798. this.awaitPos = oldAwaitPos;
  14799. this.awaitIdentPos = oldAwaitIdentPos;
  14800. return this.finishNode(node, "FunctionExpression")
  14801. };
  14802. // Parse arrow function expression with given parameters.
  14803. pp$3.parseArrowExpression = function(node, params, isAsync) {
  14804. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14805. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  14806. this.initFunction(node);
  14807. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  14808. this.yieldPos = 0;
  14809. this.awaitPos = 0;
  14810. this.awaitIdentPos = 0;
  14811. node.params = this.toAssignableList(params, true);
  14812. this.parseFunctionBody(node, true, false);
  14813. this.yieldPos = oldYieldPos;
  14814. this.awaitPos = oldAwaitPos;
  14815. this.awaitIdentPos = oldAwaitIdentPos;
  14816. return this.finishNode(node, "ArrowFunctionExpression")
  14817. };
  14818. // Parse function body and check parameters.
  14819. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  14820. var isExpression = isArrowFunction && this.type !== types.braceL;
  14821. var oldStrict = this.strict, useStrict = false;
  14822. if (isExpression) {
  14823. node.body = this.parseMaybeAssign();
  14824. node.expression = true;
  14825. this.checkParams(node, false);
  14826. } else {
  14827. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  14828. if (!oldStrict || nonSimple) {
  14829. useStrict = this.strictDirective(this.end);
  14830. // If this is a strict mode function, verify that argument names
  14831. // are not repeated, and it does not try to bind the words `eval`
  14832. // or `arguments`.
  14833. if (useStrict && nonSimple)
  14834. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  14835. }
  14836. // Start a new scope with regard to labels and the `inFunction`
  14837. // flag (restore them to their old value afterwards).
  14838. var oldLabels = this.labels;
  14839. this.labels = [];
  14840. if (useStrict) { this.strict = true; }
  14841. // Add the params to varDeclaredNames to ensure that an error is thrown
  14842. // if a let/const declaration in the function clashes with one of the params.
  14843. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  14844. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  14845. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  14846. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  14847. node.expression = false;
  14848. this.adaptDirectivePrologue(node.body.body);
  14849. this.labels = oldLabels;
  14850. }
  14851. this.exitScope();
  14852. };
  14853. pp$3.isSimpleParamList = function(params) {
  14854. for (var i = 0, list = params; i < list.length; i += 1)
  14855. {
  14856. var param = list[i];
  14857. if (param.type !== "Identifier") { return false
  14858. } }
  14859. return true
  14860. };
  14861. // Checks function params for various disallowed patterns such as using "eval"
  14862. // or "arguments" and duplicate parameters.
  14863. pp$3.checkParams = function(node, allowDuplicates) {
  14864. var nameHash = Object.create(null);
  14865. for (var i = 0, list = node.params; i < list.length; i += 1)
  14866. {
  14867. var param = list[i];
  14868. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  14869. }
  14870. };
  14871. // Parses a comma-separated list of expressions, and returns them as
  14872. // an array. `close` is the token type that ends the list, and
  14873. // `allowEmpty` can be turned on to allow subsequent commas with
  14874. // nothing in between them to be parsed as `null` (which is needed
  14875. // for array literals).
  14876. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  14877. var elts = [], first = true;
  14878. while (!this.eat(close)) {
  14879. if (!first) {
  14880. this.expect(types.comma);
  14881. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  14882. } else { first = false; }
  14883. var elt = (void 0);
  14884. if (allowEmpty && this.type === types.comma)
  14885. { elt = null; }
  14886. else if (this.type === types.ellipsis) {
  14887. elt = this.parseSpread(refDestructuringErrors);
  14888. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  14889. { refDestructuringErrors.trailingComma = this.start; }
  14890. } else {
  14891. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  14892. }
  14893. elts.push(elt);
  14894. }
  14895. return elts
  14896. };
  14897. pp$3.checkUnreserved = function(ref) {
  14898. var start = ref.start;
  14899. var end = ref.end;
  14900. var name = ref.name;
  14901. if (this.inGenerator && name === "yield")
  14902. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  14903. if (this.inAsync && name === "await")
  14904. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  14905. if (this.keywords.test(name))
  14906. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  14907. if (this.options.ecmaVersion < 6 &&
  14908. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  14909. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  14910. if (re.test(name)) {
  14911. if (!this.inAsync && name === "await")
  14912. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  14913. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  14914. }
  14915. };
  14916. // Parse the next token as an identifier. If `liberal` is true (used
  14917. // when parsing properties), it will also convert keywords into
  14918. // identifiers.
  14919. pp$3.parseIdent = function(liberal, isBinding) {
  14920. var node = this.startNode();
  14921. if (this.type === types.name) {
  14922. node.name = this.value;
  14923. } else if (this.type.keyword) {
  14924. node.name = this.type.keyword;
  14925. // To fix https://github.com/acornjs/acorn/issues/575
  14926. // `class` and `function` keywords push new context into this.context.
  14927. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  14928. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  14929. if ((node.name === "class" || node.name === "function") &&
  14930. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  14931. this.context.pop();
  14932. }
  14933. } else {
  14934. this.unexpected();
  14935. }
  14936. this.next(!!liberal);
  14937. this.finishNode(node, "Identifier");
  14938. if (!liberal) {
  14939. this.checkUnreserved(node);
  14940. if (node.name === "await" && !this.awaitIdentPos)
  14941. { this.awaitIdentPos = node.start; }
  14942. }
  14943. return node
  14944. };
  14945. // Parses yield expression inside generator.
  14946. pp$3.parseYield = function(noIn) {
  14947. if (!this.yieldPos) { this.yieldPos = this.start; }
  14948. var node = this.startNode();
  14949. this.next();
  14950. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  14951. node.delegate = false;
  14952. node.argument = null;
  14953. } else {
  14954. node.delegate = this.eat(types.star);
  14955. node.argument = this.parseMaybeAssign(noIn);
  14956. }
  14957. return this.finishNode(node, "YieldExpression")
  14958. };
  14959. pp$3.parseAwait = function() {
  14960. if (!this.awaitPos) { this.awaitPos = this.start; }
  14961. var node = this.startNode();
  14962. this.next();
  14963. node.argument = this.parseMaybeUnary(null, true);
  14964. return this.finishNode(node, "AwaitExpression")
  14965. };
  14966. var pp$4 = Parser.prototype;
  14967. // This function is used to raise exceptions on parse errors. It
  14968. // takes an offset integer (into the current `input`) to indicate
  14969. // the location of the error, attaches the position to the end
  14970. // of the error message, and then raises a `SyntaxError` with that
  14971. // message.
  14972. pp$4.raise = function(pos, message) {
  14973. var loc = getLineInfo(this.input, pos);
  14974. message += " (" + loc.line + ":" + loc.column + ")";
  14975. var err = new SyntaxError(message);
  14976. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  14977. throw err
  14978. };
  14979. pp$4.raiseRecoverable = pp$4.raise;
  14980. pp$4.curPosition = function() {
  14981. if (this.options.locations) {
  14982. return new Position(this.curLine, this.pos - this.lineStart)
  14983. }
  14984. };
  14985. var pp$5 = Parser.prototype;
  14986. var Scope = function Scope(flags) {
  14987. this.flags = flags;
  14988. // A list of var-declared names in the current lexical scope
  14989. this.var = [];
  14990. // A list of lexically-declared names in the current lexical scope
  14991. this.lexical = [];
  14992. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  14993. this.functions = [];
  14994. };
  14995. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  14996. pp$5.enterScope = function(flags) {
  14997. this.scopeStack.push(new Scope(flags));
  14998. };
  14999. pp$5.exitScope = function() {
  15000. this.scopeStack.pop();
  15001. };
  15002. // The spec says:
  15003. // > At the top level of a function, or script, function declarations are
  15004. // > treated like var declarations rather than like lexical declarations.
  15005. pp$5.treatFunctionsAsVarInScope = function(scope) {
  15006. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  15007. };
  15008. pp$5.declareName = function(name, bindingType, pos) {
  15009. var redeclared = false;
  15010. if (bindingType === BIND_LEXICAL) {
  15011. var scope = this.currentScope();
  15012. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  15013. scope.lexical.push(name);
  15014. if (this.inModule && (scope.flags & SCOPE_TOP))
  15015. { delete this.undefinedExports[name]; }
  15016. } else if (bindingType === BIND_SIMPLE_CATCH) {
  15017. var scope$1 = this.currentScope();
  15018. scope$1.lexical.push(name);
  15019. } else if (bindingType === BIND_FUNCTION) {
  15020. var scope$2 = this.currentScope();
  15021. if (this.treatFunctionsAsVar)
  15022. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  15023. else
  15024. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  15025. scope$2.functions.push(name);
  15026. } else {
  15027. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  15028. var scope$3 = this.scopeStack[i];
  15029. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  15030. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  15031. redeclared = true;
  15032. break
  15033. }
  15034. scope$3.var.push(name);
  15035. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  15036. { delete this.undefinedExports[name]; }
  15037. if (scope$3.flags & SCOPE_VAR) { break }
  15038. }
  15039. }
  15040. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  15041. };
  15042. pp$5.checkLocalExport = function(id) {
  15043. // scope.functions must be empty as Module code is always strict.
  15044. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  15045. this.scopeStack[0].var.indexOf(id.name) === -1) {
  15046. this.undefinedExports[id.name] = id;
  15047. }
  15048. };
  15049. pp$5.currentScope = function() {
  15050. return this.scopeStack[this.scopeStack.length - 1]
  15051. };
  15052. pp$5.currentVarScope = function() {
  15053. for (var i = this.scopeStack.length - 1;; i--) {
  15054. var scope = this.scopeStack[i];
  15055. if (scope.flags & SCOPE_VAR) { return scope }
  15056. }
  15057. };
  15058. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  15059. pp$5.currentThisScope = function() {
  15060. for (var i = this.scopeStack.length - 1;; i--) {
  15061. var scope = this.scopeStack[i];
  15062. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  15063. }
  15064. };
  15065. var Node = function Node(parser, pos, loc) {
  15066. this.type = "";
  15067. this.start = pos;
  15068. this.end = 0;
  15069. if (parser.options.locations)
  15070. { this.loc = new SourceLocation(parser, loc); }
  15071. if (parser.options.directSourceFile)
  15072. { this.sourceFile = parser.options.directSourceFile; }
  15073. if (parser.options.ranges)
  15074. { this.range = [pos, 0]; }
  15075. };
  15076. // Start an AST node, attaching a start offset.
  15077. var pp$6 = Parser.prototype;
  15078. pp$6.startNode = function() {
  15079. return new Node(this, this.start, this.startLoc)
  15080. };
  15081. pp$6.startNodeAt = function(pos, loc) {
  15082. return new Node(this, pos, loc)
  15083. };
  15084. // Finish an AST node, adding `type` and `end` properties.
  15085. function finishNodeAt(node, type, pos, loc) {
  15086. node.type = type;
  15087. node.end = pos;
  15088. if (this.options.locations)
  15089. { node.loc.end = loc; }
  15090. if (this.options.ranges)
  15091. { node.range[1] = pos; }
  15092. return node
  15093. }
  15094. pp$6.finishNode = function(node, type) {
  15095. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  15096. };
  15097. // Finish node at given position
  15098. pp$6.finishNodeAt = function(node, type, pos, loc) {
  15099. return finishNodeAt.call(this, node, type, pos, loc)
  15100. };
  15101. pp$6.copyNode = function(node) {
  15102. var newNode = new Node(this, node.start, this.startLoc);
  15103. for (var prop in node) { newNode[prop] = node[prop]; }
  15104. return newNode
  15105. };
  15106. // The algorithm used to determine whether a regexp can appear at a
  15107. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  15108. this.token = token;
  15109. this.isExpr = !!isExpr;
  15110. this.preserveSpace = !!preserveSpace;
  15111. this.override = override;
  15112. this.generator = !!generator;
  15113. };
  15114. var types$1 = {
  15115. b_stat: new TokContext("{", false),
  15116. b_expr: new TokContext("{", true),
  15117. b_tmpl: new TokContext("${", false),
  15118. p_stat: new TokContext("(", false),
  15119. p_expr: new TokContext("(", true),
  15120. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  15121. f_stat: new TokContext("function", false),
  15122. f_expr: new TokContext("function", true),
  15123. f_expr_gen: new TokContext("function", true, false, null, true),
  15124. f_gen: new TokContext("function", false, false, null, true)
  15125. };
  15126. var pp$7 = Parser.prototype;
  15127. pp$7.initialContext = function() {
  15128. return [types$1.b_stat]
  15129. };
  15130. pp$7.braceIsBlock = function(prevType) {
  15131. var parent = this.curContext();
  15132. if (parent === types$1.f_expr || parent === types$1.f_stat)
  15133. { return true }
  15134. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  15135. { return !parent.isExpr }
  15136. // The check for `tt.name && exprAllowed` detects whether we are
  15137. // after a `yield` or `of` construct. See the `updateContext` for
  15138. // `tt.name`.
  15139. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  15140. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  15141. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  15142. { return true }
  15143. if (prevType === types.braceL)
  15144. { return parent === types$1.b_stat }
  15145. if (prevType === types._var || prevType === types._const || prevType === types.name)
  15146. { return false }
  15147. return !this.exprAllowed
  15148. };
  15149. pp$7.inGeneratorContext = function() {
  15150. for (var i = this.context.length - 1; i >= 1; i--) {
  15151. var context = this.context[i];
  15152. if (context.token === "function")
  15153. { return context.generator }
  15154. }
  15155. return false
  15156. };
  15157. pp$7.updateContext = function(prevType) {
  15158. var update, type = this.type;
  15159. if (type.keyword && prevType === types.dot)
  15160. { this.exprAllowed = false; }
  15161. else if (update = type.updateContext)
  15162. { update.call(this, prevType); }
  15163. else
  15164. { this.exprAllowed = type.beforeExpr; }
  15165. };
  15166. // Token-specific context update code
  15167. types.parenR.updateContext = types.braceR.updateContext = function() {
  15168. if (this.context.length === 1) {
  15169. this.exprAllowed = true;
  15170. return
  15171. }
  15172. var out = this.context.pop();
  15173. if (out === types$1.b_stat && this.curContext().token === "function") {
  15174. out = this.context.pop();
  15175. }
  15176. this.exprAllowed = !out.isExpr;
  15177. };
  15178. types.braceL.updateContext = function(prevType) {
  15179. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  15180. this.exprAllowed = true;
  15181. };
  15182. types.dollarBraceL.updateContext = function() {
  15183. this.context.push(types$1.b_tmpl);
  15184. this.exprAllowed = true;
  15185. };
  15186. types.parenL.updateContext = function(prevType) {
  15187. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  15188. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  15189. this.exprAllowed = true;
  15190. };
  15191. types.incDec.updateContext = function() {
  15192. // tokExprAllowed stays unchanged
  15193. };
  15194. types._function.updateContext = types._class.updateContext = function(prevType) {
  15195. if (prevType.beforeExpr && prevType !== types._else &&
  15196. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  15197. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  15198. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  15199. { this.context.push(types$1.f_expr); }
  15200. else
  15201. { this.context.push(types$1.f_stat); }
  15202. this.exprAllowed = false;
  15203. };
  15204. types.backQuote.updateContext = function() {
  15205. if (this.curContext() === types$1.q_tmpl)
  15206. { this.context.pop(); }
  15207. else
  15208. { this.context.push(types$1.q_tmpl); }
  15209. this.exprAllowed = false;
  15210. };
  15211. types.star.updateContext = function(prevType) {
  15212. if (prevType === types._function) {
  15213. var index = this.context.length - 1;
  15214. if (this.context[index] === types$1.f_expr)
  15215. { this.context[index] = types$1.f_expr_gen; }
  15216. else
  15217. { this.context[index] = types$1.f_gen; }
  15218. }
  15219. this.exprAllowed = true;
  15220. };
  15221. types.name.updateContext = function(prevType) {
  15222. var allowed = false;
  15223. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  15224. if (this.value === "of" && !this.exprAllowed ||
  15225. this.value === "yield" && this.inGeneratorContext())
  15226. { allowed = true; }
  15227. }
  15228. this.exprAllowed = allowed;
  15229. };
  15230. // This file contains Unicode properties extracted from the ECMAScript
  15231. // specification. The lists are extracted like so:
  15232. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  15233. // #table-binary-unicode-properties
  15234. 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";
  15235. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  15236. var ecma11BinaryProperties = ecma10BinaryProperties;
  15237. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  15238. var unicodeBinaryProperties = {
  15239. 9: ecma9BinaryProperties,
  15240. 10: ecma10BinaryProperties,
  15241. 11: ecma11BinaryProperties,
  15242. 12: ecma12BinaryProperties
  15243. };
  15244. // #table-unicode-general-category-values
  15245. 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";
  15246. // #table-unicode-script-values
  15247. var ecma9ScriptValues = "Adlam Adlm Ahom 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 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";
  15248. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  15249. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  15250. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  15251. var unicodeScriptValues = {
  15252. 9: ecma9ScriptValues,
  15253. 10: ecma10ScriptValues,
  15254. 11: ecma11ScriptValues,
  15255. 12: ecma12ScriptValues
  15256. };
  15257. var data = {};
  15258. function buildUnicodeData(ecmaVersion) {
  15259. var d = data[ecmaVersion] = {
  15260. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  15261. nonBinary: {
  15262. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  15263. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  15264. }
  15265. };
  15266. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  15267. d.nonBinary.gc = d.nonBinary.General_Category;
  15268. d.nonBinary.sc = d.nonBinary.Script;
  15269. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  15270. }
  15271. buildUnicodeData(9);
  15272. buildUnicodeData(10);
  15273. buildUnicodeData(11);
  15274. buildUnicodeData(12);
  15275. var pp$8 = Parser.prototype;
  15276. var RegExpValidationState = function RegExpValidationState(parser) {
  15277. this.parser = parser;
  15278. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
  15279. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  15280. this.source = "";
  15281. this.flags = "";
  15282. this.start = 0;
  15283. this.switchU = false;
  15284. this.switchN = false;
  15285. this.pos = 0;
  15286. this.lastIntValue = 0;
  15287. this.lastStringValue = "";
  15288. this.lastAssertionIsQuantifiable = false;
  15289. this.numCapturingParens = 0;
  15290. this.maxBackReference = 0;
  15291. this.groupNames = [];
  15292. this.backReferenceNames = [];
  15293. };
  15294. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  15295. var unicode = flags.indexOf("u") !== -1;
  15296. this.start = start | 0;
  15297. this.source = pattern + "";
  15298. this.flags = flags;
  15299. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  15300. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  15301. };
  15302. RegExpValidationState.prototype.raise = function raise (message) {
  15303. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  15304. };
  15305. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  15306. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  15307. RegExpValidationState.prototype.at = function at (i, forceU) {
  15308. if ( forceU === void 0 ) forceU = false;
  15309. var s = this.source;
  15310. var l = s.length;
  15311. if (i >= l) {
  15312. return -1
  15313. }
  15314. var c = s.charCodeAt(i);
  15315. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  15316. return c
  15317. }
  15318. var next = s.charCodeAt(i + 1);
  15319. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  15320. };
  15321. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  15322. if ( forceU === void 0 ) forceU = false;
  15323. var s = this.source;
  15324. var l = s.length;
  15325. if (i >= l) {
  15326. return l
  15327. }
  15328. var c = s.charCodeAt(i), next;
  15329. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  15330. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  15331. return i + 1
  15332. }
  15333. return i + 2
  15334. };
  15335. RegExpValidationState.prototype.current = function current (forceU) {
  15336. if ( forceU === void 0 ) forceU = false;
  15337. return this.at(this.pos, forceU)
  15338. };
  15339. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  15340. if ( forceU === void 0 ) forceU = false;
  15341. return this.at(this.nextIndex(this.pos, forceU), forceU)
  15342. };
  15343. RegExpValidationState.prototype.advance = function advance (forceU) {
  15344. if ( forceU === void 0 ) forceU = false;
  15345. this.pos = this.nextIndex(this.pos, forceU);
  15346. };
  15347. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  15348. if ( forceU === void 0 ) forceU = false;
  15349. if (this.current(forceU) === ch) {
  15350. this.advance(forceU);
  15351. return true
  15352. }
  15353. return false
  15354. };
  15355. function codePointToString(ch) {
  15356. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  15357. ch -= 0x10000;
  15358. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  15359. }
  15360. /**
  15361. * Validate the flags part of a given RegExpLiteral.
  15362. *
  15363. * @param {RegExpValidationState} state The state to validate RegExp.
  15364. * @returns {void}
  15365. */
  15366. pp$8.validateRegExpFlags = function(state) {
  15367. var validFlags = state.validFlags;
  15368. var flags = state.flags;
  15369. for (var i = 0; i < flags.length; i++) {
  15370. var flag = flags.charAt(i);
  15371. if (validFlags.indexOf(flag) === -1) {
  15372. this.raise(state.start, "Invalid regular expression flag");
  15373. }
  15374. if (flags.indexOf(flag, i + 1) > -1) {
  15375. this.raise(state.start, "Duplicate regular expression flag");
  15376. }
  15377. }
  15378. };
  15379. /**
  15380. * Validate the pattern part of a given RegExpLiteral.
  15381. *
  15382. * @param {RegExpValidationState} state The state to validate RegExp.
  15383. * @returns {void}
  15384. */
  15385. pp$8.validateRegExpPattern = function(state) {
  15386. this.regexp_pattern(state);
  15387. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  15388. // parsing contains a |GroupName|, reparse with the goal symbol
  15389. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  15390. // exception if _P_ did not conform to the grammar, if any elements of _P_
  15391. // were not matched by the parse, or if any Early Error conditions exist.
  15392. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  15393. state.switchN = true;
  15394. this.regexp_pattern(state);
  15395. }
  15396. };
  15397. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  15398. pp$8.regexp_pattern = function(state) {
  15399. state.pos = 0;
  15400. state.lastIntValue = 0;
  15401. state.lastStringValue = "";
  15402. state.lastAssertionIsQuantifiable = false;
  15403. state.numCapturingParens = 0;
  15404. state.maxBackReference = 0;
  15405. state.groupNames.length = 0;
  15406. state.backReferenceNames.length = 0;
  15407. this.regexp_disjunction(state);
  15408. if (state.pos !== state.source.length) {
  15409. // Make the same messages as V8.
  15410. if (state.eat(0x29 /* ) */)) {
  15411. state.raise("Unmatched ')'");
  15412. }
  15413. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  15414. state.raise("Lone quantifier brackets");
  15415. }
  15416. }
  15417. if (state.maxBackReference > state.numCapturingParens) {
  15418. state.raise("Invalid escape");
  15419. }
  15420. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  15421. var name = list[i];
  15422. if (state.groupNames.indexOf(name) === -1) {
  15423. state.raise("Invalid named capture referenced");
  15424. }
  15425. }
  15426. };
  15427. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  15428. pp$8.regexp_disjunction = function(state) {
  15429. this.regexp_alternative(state);
  15430. while (state.eat(0x7C /* | */)) {
  15431. this.regexp_alternative(state);
  15432. }
  15433. // Make the same message as V8.
  15434. if (this.regexp_eatQuantifier(state, true)) {
  15435. state.raise("Nothing to repeat");
  15436. }
  15437. if (state.eat(0x7B /* { */)) {
  15438. state.raise("Lone quantifier brackets");
  15439. }
  15440. };
  15441. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  15442. pp$8.regexp_alternative = function(state) {
  15443. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  15444. { }
  15445. };
  15446. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  15447. pp$8.regexp_eatTerm = function(state) {
  15448. if (this.regexp_eatAssertion(state)) {
  15449. // Handle `QuantifiableAssertion Quantifier` alternative.
  15450. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  15451. // is a QuantifiableAssertion.
  15452. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  15453. // Make the same message as V8.
  15454. if (state.switchU) {
  15455. state.raise("Invalid quantifier");
  15456. }
  15457. }
  15458. return true
  15459. }
  15460. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  15461. this.regexp_eatQuantifier(state);
  15462. return true
  15463. }
  15464. return false
  15465. };
  15466. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  15467. pp$8.regexp_eatAssertion = function(state) {
  15468. var start = state.pos;
  15469. state.lastAssertionIsQuantifiable = false;
  15470. // ^, $
  15471. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  15472. return true
  15473. }
  15474. // \b \B
  15475. if (state.eat(0x5C /* \ */)) {
  15476. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  15477. return true
  15478. }
  15479. state.pos = start;
  15480. }
  15481. // Lookahead / Lookbehind
  15482. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  15483. var lookbehind = false;
  15484. if (this.options.ecmaVersion >= 9) {
  15485. lookbehind = state.eat(0x3C /* < */);
  15486. }
  15487. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  15488. this.regexp_disjunction(state);
  15489. if (!state.eat(0x29 /* ) */)) {
  15490. state.raise("Unterminated group");
  15491. }
  15492. state.lastAssertionIsQuantifiable = !lookbehind;
  15493. return true
  15494. }
  15495. }
  15496. state.pos = start;
  15497. return false
  15498. };
  15499. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  15500. pp$8.regexp_eatQuantifier = function(state, noError) {
  15501. if ( noError === void 0 ) noError = false;
  15502. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  15503. state.eat(0x3F /* ? */);
  15504. return true
  15505. }
  15506. return false
  15507. };
  15508. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  15509. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  15510. return (
  15511. state.eat(0x2A /* * */) ||
  15512. state.eat(0x2B /* + */) ||
  15513. state.eat(0x3F /* ? */) ||
  15514. this.regexp_eatBracedQuantifier(state, noError)
  15515. )
  15516. };
  15517. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  15518. var start = state.pos;
  15519. if (state.eat(0x7B /* { */)) {
  15520. var min = 0, max = -1;
  15521. if (this.regexp_eatDecimalDigits(state)) {
  15522. min = state.lastIntValue;
  15523. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  15524. max = state.lastIntValue;
  15525. }
  15526. if (state.eat(0x7D /* } */)) {
  15527. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  15528. if (max !== -1 && max < min && !noError) {
  15529. state.raise("numbers out of order in {} quantifier");
  15530. }
  15531. return true
  15532. }
  15533. }
  15534. if (state.switchU && !noError) {
  15535. state.raise("Incomplete quantifier");
  15536. }
  15537. state.pos = start;
  15538. }
  15539. return false
  15540. };
  15541. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  15542. pp$8.regexp_eatAtom = function(state) {
  15543. return (
  15544. this.regexp_eatPatternCharacters(state) ||
  15545. state.eat(0x2E /* . */) ||
  15546. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15547. this.regexp_eatCharacterClass(state) ||
  15548. this.regexp_eatUncapturingGroup(state) ||
  15549. this.regexp_eatCapturingGroup(state)
  15550. )
  15551. };
  15552. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  15553. var start = state.pos;
  15554. if (state.eat(0x5C /* \ */)) {
  15555. if (this.regexp_eatAtomEscape(state)) {
  15556. return true
  15557. }
  15558. state.pos = start;
  15559. }
  15560. return false
  15561. };
  15562. pp$8.regexp_eatUncapturingGroup = function(state) {
  15563. var start = state.pos;
  15564. if (state.eat(0x28 /* ( */)) {
  15565. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  15566. this.regexp_disjunction(state);
  15567. if (state.eat(0x29 /* ) */)) {
  15568. return true
  15569. }
  15570. state.raise("Unterminated group");
  15571. }
  15572. state.pos = start;
  15573. }
  15574. return false
  15575. };
  15576. pp$8.regexp_eatCapturingGroup = function(state) {
  15577. if (state.eat(0x28 /* ( */)) {
  15578. if (this.options.ecmaVersion >= 9) {
  15579. this.regexp_groupSpecifier(state);
  15580. } else if (state.current() === 0x3F /* ? */) {
  15581. state.raise("Invalid group");
  15582. }
  15583. this.regexp_disjunction(state);
  15584. if (state.eat(0x29 /* ) */)) {
  15585. state.numCapturingParens += 1;
  15586. return true
  15587. }
  15588. state.raise("Unterminated group");
  15589. }
  15590. return false
  15591. };
  15592. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  15593. pp$8.regexp_eatExtendedAtom = function(state) {
  15594. return (
  15595. state.eat(0x2E /* . */) ||
  15596. this.regexp_eatReverseSolidusAtomEscape(state) ||
  15597. this.regexp_eatCharacterClass(state) ||
  15598. this.regexp_eatUncapturingGroup(state) ||
  15599. this.regexp_eatCapturingGroup(state) ||
  15600. this.regexp_eatInvalidBracedQuantifier(state) ||
  15601. this.regexp_eatExtendedPatternCharacter(state)
  15602. )
  15603. };
  15604. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  15605. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  15606. if (this.regexp_eatBracedQuantifier(state, true)) {
  15607. state.raise("Nothing to repeat");
  15608. }
  15609. return false
  15610. };
  15611. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  15612. pp$8.regexp_eatSyntaxCharacter = function(state) {
  15613. var ch = state.current();
  15614. if (isSyntaxCharacter(ch)) {
  15615. state.lastIntValue = ch;
  15616. state.advance();
  15617. return true
  15618. }
  15619. return false
  15620. };
  15621. function isSyntaxCharacter(ch) {
  15622. return (
  15623. ch === 0x24 /* $ */ ||
  15624. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  15625. ch === 0x2E /* . */ ||
  15626. ch === 0x3F /* ? */ ||
  15627. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  15628. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  15629. )
  15630. }
  15631. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  15632. // But eat eager.
  15633. pp$8.regexp_eatPatternCharacters = function(state) {
  15634. var start = state.pos;
  15635. var ch = 0;
  15636. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  15637. state.advance();
  15638. }
  15639. return state.pos !== start
  15640. };
  15641. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  15642. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  15643. var ch = state.current();
  15644. if (
  15645. ch !== -1 &&
  15646. ch !== 0x24 /* $ */ &&
  15647. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  15648. ch !== 0x2E /* . */ &&
  15649. ch !== 0x3F /* ? */ &&
  15650. ch !== 0x5B /* [ */ &&
  15651. ch !== 0x5E /* ^ */ &&
  15652. ch !== 0x7C /* | */
  15653. ) {
  15654. state.advance();
  15655. return true
  15656. }
  15657. return false
  15658. };
  15659. // GroupSpecifier ::
  15660. // [empty]
  15661. // `?` GroupName
  15662. pp$8.regexp_groupSpecifier = function(state) {
  15663. if (state.eat(0x3F /* ? */)) {
  15664. if (this.regexp_eatGroupName(state)) {
  15665. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  15666. state.raise("Duplicate capture group name");
  15667. }
  15668. state.groupNames.push(state.lastStringValue);
  15669. return
  15670. }
  15671. state.raise("Invalid group");
  15672. }
  15673. };
  15674. // GroupName ::
  15675. // `<` RegExpIdentifierName `>`
  15676. // Note: this updates `state.lastStringValue` property with the eaten name.
  15677. pp$8.regexp_eatGroupName = function(state) {
  15678. state.lastStringValue = "";
  15679. if (state.eat(0x3C /* < */)) {
  15680. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  15681. return true
  15682. }
  15683. state.raise("Invalid capture group name");
  15684. }
  15685. return false
  15686. };
  15687. // RegExpIdentifierName ::
  15688. // RegExpIdentifierStart
  15689. // RegExpIdentifierName RegExpIdentifierPart
  15690. // Note: this updates `state.lastStringValue` property with the eaten name.
  15691. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  15692. state.lastStringValue = "";
  15693. if (this.regexp_eatRegExpIdentifierStart(state)) {
  15694. state.lastStringValue += codePointToString(state.lastIntValue);
  15695. while (this.regexp_eatRegExpIdentifierPart(state)) {
  15696. state.lastStringValue += codePointToString(state.lastIntValue);
  15697. }
  15698. return true
  15699. }
  15700. return false
  15701. };
  15702. // RegExpIdentifierStart ::
  15703. // UnicodeIDStart
  15704. // `$`
  15705. // `_`
  15706. // `\` RegExpUnicodeEscapeSequence[+U]
  15707. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  15708. var start = state.pos;
  15709. var forceU = this.options.ecmaVersion >= 11;
  15710. var ch = state.current(forceU);
  15711. state.advance(forceU);
  15712. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15713. ch = state.lastIntValue;
  15714. }
  15715. if (isRegExpIdentifierStart(ch)) {
  15716. state.lastIntValue = ch;
  15717. return true
  15718. }
  15719. state.pos = start;
  15720. return false
  15721. };
  15722. function isRegExpIdentifierStart(ch) {
  15723. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  15724. }
  15725. // RegExpIdentifierPart ::
  15726. // UnicodeIDContinue
  15727. // `$`
  15728. // `_`
  15729. // `\` RegExpUnicodeEscapeSequence[+U]
  15730. // <ZWNJ>
  15731. // <ZWJ>
  15732. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  15733. var start = state.pos;
  15734. var forceU = this.options.ecmaVersion >= 11;
  15735. var ch = state.current(forceU);
  15736. state.advance(forceU);
  15737. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  15738. ch = state.lastIntValue;
  15739. }
  15740. if (isRegExpIdentifierPart(ch)) {
  15741. state.lastIntValue = ch;
  15742. return true
  15743. }
  15744. state.pos = start;
  15745. return false
  15746. };
  15747. function isRegExpIdentifierPart(ch) {
  15748. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  15749. }
  15750. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  15751. pp$8.regexp_eatAtomEscape = function(state) {
  15752. if (
  15753. this.regexp_eatBackReference(state) ||
  15754. this.regexp_eatCharacterClassEscape(state) ||
  15755. this.regexp_eatCharacterEscape(state) ||
  15756. (state.switchN && this.regexp_eatKGroupName(state))
  15757. ) {
  15758. return true
  15759. }
  15760. if (state.switchU) {
  15761. // Make the same message as V8.
  15762. if (state.current() === 0x63 /* c */) {
  15763. state.raise("Invalid unicode escape");
  15764. }
  15765. state.raise("Invalid escape");
  15766. }
  15767. return false
  15768. };
  15769. pp$8.regexp_eatBackReference = function(state) {
  15770. var start = state.pos;
  15771. if (this.regexp_eatDecimalEscape(state)) {
  15772. var n = state.lastIntValue;
  15773. if (state.switchU) {
  15774. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  15775. if (n > state.maxBackReference) {
  15776. state.maxBackReference = n;
  15777. }
  15778. return true
  15779. }
  15780. if (n <= state.numCapturingParens) {
  15781. return true
  15782. }
  15783. state.pos = start;
  15784. }
  15785. return false
  15786. };
  15787. pp$8.regexp_eatKGroupName = function(state) {
  15788. if (state.eat(0x6B /* k */)) {
  15789. if (this.regexp_eatGroupName(state)) {
  15790. state.backReferenceNames.push(state.lastStringValue);
  15791. return true
  15792. }
  15793. state.raise("Invalid named reference");
  15794. }
  15795. return false
  15796. };
  15797. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  15798. pp$8.regexp_eatCharacterEscape = function(state) {
  15799. return (
  15800. this.regexp_eatControlEscape(state) ||
  15801. this.regexp_eatCControlLetter(state) ||
  15802. this.regexp_eatZero(state) ||
  15803. this.regexp_eatHexEscapeSequence(state) ||
  15804. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  15805. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  15806. this.regexp_eatIdentityEscape(state)
  15807. )
  15808. };
  15809. pp$8.regexp_eatCControlLetter = function(state) {
  15810. var start = state.pos;
  15811. if (state.eat(0x63 /* c */)) {
  15812. if (this.regexp_eatControlLetter(state)) {
  15813. return true
  15814. }
  15815. state.pos = start;
  15816. }
  15817. return false
  15818. };
  15819. pp$8.regexp_eatZero = function(state) {
  15820. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  15821. state.lastIntValue = 0;
  15822. state.advance();
  15823. return true
  15824. }
  15825. return false
  15826. };
  15827. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  15828. pp$8.regexp_eatControlEscape = function(state) {
  15829. var ch = state.current();
  15830. if (ch === 0x74 /* t */) {
  15831. state.lastIntValue = 0x09; /* \t */
  15832. state.advance();
  15833. return true
  15834. }
  15835. if (ch === 0x6E /* n */) {
  15836. state.lastIntValue = 0x0A; /* \n */
  15837. state.advance();
  15838. return true
  15839. }
  15840. if (ch === 0x76 /* v */) {
  15841. state.lastIntValue = 0x0B; /* \v */
  15842. state.advance();
  15843. return true
  15844. }
  15845. if (ch === 0x66 /* f */) {
  15846. state.lastIntValue = 0x0C; /* \f */
  15847. state.advance();
  15848. return true
  15849. }
  15850. if (ch === 0x72 /* r */) {
  15851. state.lastIntValue = 0x0D; /* \r */
  15852. state.advance();
  15853. return true
  15854. }
  15855. return false
  15856. };
  15857. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  15858. pp$8.regexp_eatControlLetter = function(state) {
  15859. var ch = state.current();
  15860. if (isControlLetter(ch)) {
  15861. state.lastIntValue = ch % 0x20;
  15862. state.advance();
  15863. return true
  15864. }
  15865. return false
  15866. };
  15867. function isControlLetter(ch) {
  15868. return (
  15869. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  15870. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  15871. )
  15872. }
  15873. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  15874. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  15875. if ( forceU === void 0 ) forceU = false;
  15876. var start = state.pos;
  15877. var switchU = forceU || state.switchU;
  15878. if (state.eat(0x75 /* u */)) {
  15879. if (this.regexp_eatFixedHexDigits(state, 4)) {
  15880. var lead = state.lastIntValue;
  15881. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  15882. var leadSurrogateEnd = state.pos;
  15883. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  15884. var trail = state.lastIntValue;
  15885. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  15886. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  15887. return true
  15888. }
  15889. }
  15890. state.pos = leadSurrogateEnd;
  15891. state.lastIntValue = lead;
  15892. }
  15893. return true
  15894. }
  15895. if (
  15896. switchU &&
  15897. state.eat(0x7B /* { */) &&
  15898. this.regexp_eatHexDigits(state) &&
  15899. state.eat(0x7D /* } */) &&
  15900. isValidUnicode(state.lastIntValue)
  15901. ) {
  15902. return true
  15903. }
  15904. if (switchU) {
  15905. state.raise("Invalid unicode escape");
  15906. }
  15907. state.pos = start;
  15908. }
  15909. return false
  15910. };
  15911. function isValidUnicode(ch) {
  15912. return ch >= 0 && ch <= 0x10FFFF
  15913. }
  15914. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  15915. pp$8.regexp_eatIdentityEscape = function(state) {
  15916. if (state.switchU) {
  15917. if (this.regexp_eatSyntaxCharacter(state)) {
  15918. return true
  15919. }
  15920. if (state.eat(0x2F /* / */)) {
  15921. state.lastIntValue = 0x2F; /* / */
  15922. return true
  15923. }
  15924. return false
  15925. }
  15926. var ch = state.current();
  15927. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  15928. state.lastIntValue = ch;
  15929. state.advance();
  15930. return true
  15931. }
  15932. return false
  15933. };
  15934. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  15935. pp$8.regexp_eatDecimalEscape = function(state) {
  15936. state.lastIntValue = 0;
  15937. var ch = state.current();
  15938. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  15939. do {
  15940. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  15941. state.advance();
  15942. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  15943. return true
  15944. }
  15945. return false
  15946. };
  15947. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  15948. pp$8.regexp_eatCharacterClassEscape = function(state) {
  15949. var ch = state.current();
  15950. if (isCharacterClassEscape(ch)) {
  15951. state.lastIntValue = -1;
  15952. state.advance();
  15953. return true
  15954. }
  15955. if (
  15956. state.switchU &&
  15957. this.options.ecmaVersion >= 9 &&
  15958. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  15959. ) {
  15960. state.lastIntValue = -1;
  15961. state.advance();
  15962. if (
  15963. state.eat(0x7B /* { */) &&
  15964. this.regexp_eatUnicodePropertyValueExpression(state) &&
  15965. state.eat(0x7D /* } */)
  15966. ) {
  15967. return true
  15968. }
  15969. state.raise("Invalid property name");
  15970. }
  15971. return false
  15972. };
  15973. function isCharacterClassEscape(ch) {
  15974. return (
  15975. ch === 0x64 /* d */ ||
  15976. ch === 0x44 /* D */ ||
  15977. ch === 0x73 /* s */ ||
  15978. ch === 0x53 /* S */ ||
  15979. ch === 0x77 /* w */ ||
  15980. ch === 0x57 /* W */
  15981. )
  15982. }
  15983. // UnicodePropertyValueExpression ::
  15984. // UnicodePropertyName `=` UnicodePropertyValue
  15985. // LoneUnicodePropertyNameOrValue
  15986. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  15987. var start = state.pos;
  15988. // UnicodePropertyName `=` UnicodePropertyValue
  15989. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  15990. var name = state.lastStringValue;
  15991. if (this.regexp_eatUnicodePropertyValue(state)) {
  15992. var value = state.lastStringValue;
  15993. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  15994. return true
  15995. }
  15996. }
  15997. state.pos = start;
  15998. // LoneUnicodePropertyNameOrValue
  15999. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  16000. var nameOrValue = state.lastStringValue;
  16001. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  16002. return true
  16003. }
  16004. return false
  16005. };
  16006. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  16007. if (!has(state.unicodeProperties.nonBinary, name))
  16008. { state.raise("Invalid property name"); }
  16009. if (!state.unicodeProperties.nonBinary[name].test(value))
  16010. { state.raise("Invalid property value"); }
  16011. };
  16012. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  16013. if (!state.unicodeProperties.binary.test(nameOrValue))
  16014. { state.raise("Invalid property name"); }
  16015. };
  16016. // UnicodePropertyName ::
  16017. // UnicodePropertyNameCharacters
  16018. pp$8.regexp_eatUnicodePropertyName = function(state) {
  16019. var ch = 0;
  16020. state.lastStringValue = "";
  16021. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  16022. state.lastStringValue += codePointToString(ch);
  16023. state.advance();
  16024. }
  16025. return state.lastStringValue !== ""
  16026. };
  16027. function isUnicodePropertyNameCharacter(ch) {
  16028. return isControlLetter(ch) || ch === 0x5F /* _ */
  16029. }
  16030. // UnicodePropertyValue ::
  16031. // UnicodePropertyValueCharacters
  16032. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  16033. var ch = 0;
  16034. state.lastStringValue = "";
  16035. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  16036. state.lastStringValue += codePointToString(ch);
  16037. state.advance();
  16038. }
  16039. return state.lastStringValue !== ""
  16040. };
  16041. function isUnicodePropertyValueCharacter(ch) {
  16042. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  16043. }
  16044. // LoneUnicodePropertyNameOrValue ::
  16045. // UnicodePropertyValueCharacters
  16046. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  16047. return this.regexp_eatUnicodePropertyValue(state)
  16048. };
  16049. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  16050. pp$8.regexp_eatCharacterClass = function(state) {
  16051. if (state.eat(0x5B /* [ */)) {
  16052. state.eat(0x5E /* ^ */);
  16053. this.regexp_classRanges(state);
  16054. if (state.eat(0x5D /* ] */)) {
  16055. return true
  16056. }
  16057. // Unreachable since it threw "unterminated regular expression" error before.
  16058. state.raise("Unterminated character class");
  16059. }
  16060. return false
  16061. };
  16062. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  16063. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  16064. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  16065. pp$8.regexp_classRanges = function(state) {
  16066. while (this.regexp_eatClassAtom(state)) {
  16067. var left = state.lastIntValue;
  16068. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  16069. var right = state.lastIntValue;
  16070. if (state.switchU && (left === -1 || right === -1)) {
  16071. state.raise("Invalid character class");
  16072. }
  16073. if (left !== -1 && right !== -1 && left > right) {
  16074. state.raise("Range out of order in character class");
  16075. }
  16076. }
  16077. }
  16078. };
  16079. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  16080. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  16081. pp$8.regexp_eatClassAtom = function(state) {
  16082. var start = state.pos;
  16083. if (state.eat(0x5C /* \ */)) {
  16084. if (this.regexp_eatClassEscape(state)) {
  16085. return true
  16086. }
  16087. if (state.switchU) {
  16088. // Make the same message as V8.
  16089. var ch$1 = state.current();
  16090. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  16091. state.raise("Invalid class escape");
  16092. }
  16093. state.raise("Invalid escape");
  16094. }
  16095. state.pos = start;
  16096. }
  16097. var ch = state.current();
  16098. if (ch !== 0x5D /* ] */) {
  16099. state.lastIntValue = ch;
  16100. state.advance();
  16101. return true
  16102. }
  16103. return false
  16104. };
  16105. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  16106. pp$8.regexp_eatClassEscape = function(state) {
  16107. var start = state.pos;
  16108. if (state.eat(0x62 /* b */)) {
  16109. state.lastIntValue = 0x08; /* <BS> */
  16110. return true
  16111. }
  16112. if (state.switchU && state.eat(0x2D /* - */)) {
  16113. state.lastIntValue = 0x2D; /* - */
  16114. return true
  16115. }
  16116. if (!state.switchU && state.eat(0x63 /* c */)) {
  16117. if (this.regexp_eatClassControlLetter(state)) {
  16118. return true
  16119. }
  16120. state.pos = start;
  16121. }
  16122. return (
  16123. this.regexp_eatCharacterClassEscape(state) ||
  16124. this.regexp_eatCharacterEscape(state)
  16125. )
  16126. };
  16127. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  16128. pp$8.regexp_eatClassControlLetter = function(state) {
  16129. var ch = state.current();
  16130. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  16131. state.lastIntValue = ch % 0x20;
  16132. state.advance();
  16133. return true
  16134. }
  16135. return false
  16136. };
  16137. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  16138. pp$8.regexp_eatHexEscapeSequence = function(state) {
  16139. var start = state.pos;
  16140. if (state.eat(0x78 /* x */)) {
  16141. if (this.regexp_eatFixedHexDigits(state, 2)) {
  16142. return true
  16143. }
  16144. if (state.switchU) {
  16145. state.raise("Invalid escape");
  16146. }
  16147. state.pos = start;
  16148. }
  16149. return false
  16150. };
  16151. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  16152. pp$8.regexp_eatDecimalDigits = function(state) {
  16153. var start = state.pos;
  16154. var ch = 0;
  16155. state.lastIntValue = 0;
  16156. while (isDecimalDigit(ch = state.current())) {
  16157. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  16158. state.advance();
  16159. }
  16160. return state.pos !== start
  16161. };
  16162. function isDecimalDigit(ch) {
  16163. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  16164. }
  16165. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  16166. pp$8.regexp_eatHexDigits = function(state) {
  16167. var start = state.pos;
  16168. var ch = 0;
  16169. state.lastIntValue = 0;
  16170. while (isHexDigit(ch = state.current())) {
  16171. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  16172. state.advance();
  16173. }
  16174. return state.pos !== start
  16175. };
  16176. function isHexDigit(ch) {
  16177. return (
  16178. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  16179. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  16180. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  16181. )
  16182. }
  16183. function hexToInt(ch) {
  16184. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  16185. return 10 + (ch - 0x41 /* A */)
  16186. }
  16187. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  16188. return 10 + (ch - 0x61 /* a */)
  16189. }
  16190. return ch - 0x30 /* 0 */
  16191. }
  16192. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  16193. // Allows only 0-377(octal) i.e. 0-255(decimal).
  16194. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  16195. if (this.regexp_eatOctalDigit(state)) {
  16196. var n1 = state.lastIntValue;
  16197. if (this.regexp_eatOctalDigit(state)) {
  16198. var n2 = state.lastIntValue;
  16199. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  16200. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  16201. } else {
  16202. state.lastIntValue = n1 * 8 + n2;
  16203. }
  16204. } else {
  16205. state.lastIntValue = n1;
  16206. }
  16207. return true
  16208. }
  16209. return false
  16210. };
  16211. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  16212. pp$8.regexp_eatOctalDigit = function(state) {
  16213. var ch = state.current();
  16214. if (isOctalDigit(ch)) {
  16215. state.lastIntValue = ch - 0x30; /* 0 */
  16216. state.advance();
  16217. return true
  16218. }
  16219. state.lastIntValue = 0;
  16220. return false
  16221. };
  16222. function isOctalDigit(ch) {
  16223. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  16224. }
  16225. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  16226. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  16227. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  16228. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  16229. var start = state.pos;
  16230. state.lastIntValue = 0;
  16231. for (var i = 0; i < length; ++i) {
  16232. var ch = state.current();
  16233. if (!isHexDigit(ch)) {
  16234. state.pos = start;
  16235. return false
  16236. }
  16237. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  16238. state.advance();
  16239. }
  16240. return true
  16241. };
  16242. // Object type used to represent tokens. Note that normally, tokens
  16243. // simply exist as properties on the parser object. This is only
  16244. // used for the onToken callback and the external tokenizer.
  16245. var Token = function Token(p) {
  16246. this.type = p.type;
  16247. this.value = p.value;
  16248. this.start = p.start;
  16249. this.end = p.end;
  16250. if (p.options.locations)
  16251. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  16252. if (p.options.ranges)
  16253. { this.range = [p.start, p.end]; }
  16254. };
  16255. // ## Tokenizer
  16256. var pp$9 = Parser.prototype;
  16257. // Move to the next token
  16258. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  16259. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  16260. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  16261. if (this.options.onToken)
  16262. { this.options.onToken(new Token(this)); }
  16263. this.lastTokEnd = this.end;
  16264. this.lastTokStart = this.start;
  16265. this.lastTokEndLoc = this.endLoc;
  16266. this.lastTokStartLoc = this.startLoc;
  16267. this.nextToken();
  16268. };
  16269. pp$9.getToken = function() {
  16270. this.next();
  16271. return new Token(this)
  16272. };
  16273. // If we're in an ES6 environment, make parsers iterable
  16274. if (typeof Symbol !== "undefined")
  16275. { pp$9[Symbol.iterator] = function() {
  16276. var this$1 = this;
  16277. return {
  16278. next: function () {
  16279. var token = this$1.getToken();
  16280. return {
  16281. done: token.type === types.eof,
  16282. value: token
  16283. }
  16284. }
  16285. }
  16286. }; }
  16287. // Toggle strict mode. Re-reads the next number or string to please
  16288. // pedantic tests (`"use strict"; 010;` should fail).
  16289. pp$9.curContext = function() {
  16290. return this.context[this.context.length - 1]
  16291. };
  16292. // Read a single token, updating the parser object's token-related
  16293. // properties.
  16294. pp$9.nextToken = function() {
  16295. var curContext = this.curContext();
  16296. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  16297. this.start = this.pos;
  16298. if (this.options.locations) { this.startLoc = this.curPosition(); }
  16299. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  16300. if (curContext.override) { return curContext.override(this) }
  16301. else { this.readToken(this.fullCharCodeAtPos()); }
  16302. };
  16303. pp$9.readToken = function(code) {
  16304. // Identifier or keyword. '\uXXXX' sequences are allowed in
  16305. // identifiers, so '\' also dispatches to that.
  16306. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  16307. { return this.readWord() }
  16308. return this.getTokenFromCode(code)
  16309. };
  16310. pp$9.fullCharCodeAtPos = function() {
  16311. var code = this.input.charCodeAt(this.pos);
  16312. if (code <= 0xd7ff || code >= 0xe000) { return code }
  16313. var next = this.input.charCodeAt(this.pos + 1);
  16314. return (code << 10) + next - 0x35fdc00
  16315. };
  16316. pp$9.skipBlockComment = function() {
  16317. var startLoc = this.options.onComment && this.curPosition();
  16318. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  16319. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  16320. this.pos = end + 2;
  16321. if (this.options.locations) {
  16322. lineBreakG.lastIndex = start;
  16323. var match;
  16324. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  16325. ++this.curLine;
  16326. this.lineStart = match.index + match[0].length;
  16327. }
  16328. }
  16329. if (this.options.onComment)
  16330. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  16331. startLoc, this.curPosition()); }
  16332. };
  16333. pp$9.skipLineComment = function(startSkip) {
  16334. var start = this.pos;
  16335. var startLoc = this.options.onComment && this.curPosition();
  16336. var ch = this.input.charCodeAt(this.pos += startSkip);
  16337. while (this.pos < this.input.length && !isNewLine(ch)) {
  16338. ch = this.input.charCodeAt(++this.pos);
  16339. }
  16340. if (this.options.onComment)
  16341. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  16342. startLoc, this.curPosition()); }
  16343. };
  16344. // Called at the start of the parse and after every token. Skips
  16345. // whitespace and comments, and.
  16346. pp$9.skipSpace = function() {
  16347. loop: while (this.pos < this.input.length) {
  16348. var ch = this.input.charCodeAt(this.pos);
  16349. switch (ch) {
  16350. case 32: case 160: // ' '
  16351. ++this.pos;
  16352. break
  16353. case 13:
  16354. if (this.input.charCodeAt(this.pos + 1) === 10) {
  16355. ++this.pos;
  16356. }
  16357. case 10: case 8232: case 8233:
  16358. ++this.pos;
  16359. if (this.options.locations) {
  16360. ++this.curLine;
  16361. this.lineStart = this.pos;
  16362. }
  16363. break
  16364. case 47: // '/'
  16365. switch (this.input.charCodeAt(this.pos + 1)) {
  16366. case 42: // '*'
  16367. this.skipBlockComment();
  16368. break
  16369. case 47:
  16370. this.skipLineComment(2);
  16371. break
  16372. default:
  16373. break loop
  16374. }
  16375. break
  16376. default:
  16377. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  16378. ++this.pos;
  16379. } else {
  16380. break loop
  16381. }
  16382. }
  16383. }
  16384. };
  16385. // Called at the end of every token. Sets `end`, `val`, and
  16386. // maintains `context` and `exprAllowed`, and skips the space after
  16387. // the token, so that the next one's `start` will point at the
  16388. // right position.
  16389. pp$9.finishToken = function(type, val) {
  16390. this.end = this.pos;
  16391. if (this.options.locations) { this.endLoc = this.curPosition(); }
  16392. var prevType = this.type;
  16393. this.type = type;
  16394. this.value = val;
  16395. this.updateContext(prevType);
  16396. };
  16397. // ### Token reading
  16398. // This is the function that is called to fetch the next token. It
  16399. // is somewhat obscure, because it works in character codes rather
  16400. // than characters, and because operator parsing has been inlined
  16401. // into it.
  16402. //
  16403. // All in the name of speed.
  16404. //
  16405. pp$9.readToken_dot = function() {
  16406. var next = this.input.charCodeAt(this.pos + 1);
  16407. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  16408. var next2 = this.input.charCodeAt(this.pos + 2);
  16409. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  16410. this.pos += 3;
  16411. return this.finishToken(types.ellipsis)
  16412. } else {
  16413. ++this.pos;
  16414. return this.finishToken(types.dot)
  16415. }
  16416. };
  16417. pp$9.readToken_slash = function() { // '/'
  16418. var next = this.input.charCodeAt(this.pos + 1);
  16419. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  16420. if (next === 61) { return this.finishOp(types.assign, 2) }
  16421. return this.finishOp(types.slash, 1)
  16422. };
  16423. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  16424. var next = this.input.charCodeAt(this.pos + 1);
  16425. var size = 1;
  16426. var tokentype = code === 42 ? types.star : types.modulo;
  16427. // exponentiation operator ** and **=
  16428. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  16429. ++size;
  16430. tokentype = types.starstar;
  16431. next = this.input.charCodeAt(this.pos + 2);
  16432. }
  16433. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  16434. return this.finishOp(tokentype, size)
  16435. };
  16436. pp$9.readToken_pipe_amp = function(code) { // '|&'
  16437. var next = this.input.charCodeAt(this.pos + 1);
  16438. if (next === code) {
  16439. if (this.options.ecmaVersion >= 12) {
  16440. var next2 = this.input.charCodeAt(this.pos + 2);
  16441. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  16442. }
  16443. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  16444. }
  16445. if (next === 61) { return this.finishOp(types.assign, 2) }
  16446. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  16447. };
  16448. pp$9.readToken_caret = function() { // '^'
  16449. var next = this.input.charCodeAt(this.pos + 1);
  16450. if (next === 61) { return this.finishOp(types.assign, 2) }
  16451. return this.finishOp(types.bitwiseXOR, 1)
  16452. };
  16453. pp$9.readToken_plus_min = function(code) { // '+-'
  16454. var next = this.input.charCodeAt(this.pos + 1);
  16455. if (next === code) {
  16456. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  16457. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  16458. // A `-->` line comment
  16459. this.skipLineComment(3);
  16460. this.skipSpace();
  16461. return this.nextToken()
  16462. }
  16463. return this.finishOp(types.incDec, 2)
  16464. }
  16465. if (next === 61) { return this.finishOp(types.assign, 2) }
  16466. return this.finishOp(types.plusMin, 1)
  16467. };
  16468. pp$9.readToken_lt_gt = function(code) { // '<>'
  16469. var next = this.input.charCodeAt(this.pos + 1);
  16470. var size = 1;
  16471. if (next === code) {
  16472. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  16473. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  16474. return this.finishOp(types.bitShift, size)
  16475. }
  16476. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  16477. this.input.charCodeAt(this.pos + 3) === 45) {
  16478. // `<!--`, an XML-style comment that should be interpreted as a line comment
  16479. this.skipLineComment(4);
  16480. this.skipSpace();
  16481. return this.nextToken()
  16482. }
  16483. if (next === 61) { size = 2; }
  16484. return this.finishOp(types.relational, size)
  16485. };
  16486. pp$9.readToken_eq_excl = function(code) { // '=!'
  16487. var next = this.input.charCodeAt(this.pos + 1);
  16488. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  16489. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  16490. this.pos += 2;
  16491. return this.finishToken(types.arrow)
  16492. }
  16493. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  16494. };
  16495. pp$9.readToken_question = function() { // '?'
  16496. var ecmaVersion = this.options.ecmaVersion;
  16497. if (ecmaVersion >= 11) {
  16498. var next = this.input.charCodeAt(this.pos + 1);
  16499. if (next === 46) {
  16500. var next2 = this.input.charCodeAt(this.pos + 2);
  16501. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  16502. }
  16503. if (next === 63) {
  16504. if (ecmaVersion >= 12) {
  16505. var next2$1 = this.input.charCodeAt(this.pos + 2);
  16506. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  16507. }
  16508. return this.finishOp(types.coalesce, 2)
  16509. }
  16510. }
  16511. return this.finishOp(types.question, 1)
  16512. };
  16513. pp$9.getTokenFromCode = function(code) {
  16514. switch (code) {
  16515. // The interpretation of a dot depends on whether it is followed
  16516. // by a digit or another two dots.
  16517. case 46: // '.'
  16518. return this.readToken_dot()
  16519. // Punctuation tokens.
  16520. case 40: ++this.pos; return this.finishToken(types.parenL)
  16521. case 41: ++this.pos; return this.finishToken(types.parenR)
  16522. case 59: ++this.pos; return this.finishToken(types.semi)
  16523. case 44: ++this.pos; return this.finishToken(types.comma)
  16524. case 91: ++this.pos; return this.finishToken(types.bracketL)
  16525. case 93: ++this.pos; return this.finishToken(types.bracketR)
  16526. case 123: ++this.pos; return this.finishToken(types.braceL)
  16527. case 125: ++this.pos; return this.finishToken(types.braceR)
  16528. case 58: ++this.pos; return this.finishToken(types.colon)
  16529. case 96: // '`'
  16530. if (this.options.ecmaVersion < 6) { break }
  16531. ++this.pos;
  16532. return this.finishToken(types.backQuote)
  16533. case 48: // '0'
  16534. var next = this.input.charCodeAt(this.pos + 1);
  16535. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  16536. if (this.options.ecmaVersion >= 6) {
  16537. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  16538. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  16539. }
  16540. // Anything else beginning with a digit is an integer, octal
  16541. // number, or float.
  16542. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  16543. return this.readNumber(false)
  16544. // Quotes produce strings.
  16545. case 34: case 39: // '"', "'"
  16546. return this.readString(code)
  16547. // Operators are parsed inline in tiny state machines. '=' (61) is
  16548. // often referred to. `finishOp` simply skips the amount of
  16549. // characters it is given as second argument, and returns a token
  16550. // of the type given by its first argument.
  16551. case 47: // '/'
  16552. return this.readToken_slash()
  16553. case 37: case 42: // '%*'
  16554. return this.readToken_mult_modulo_exp(code)
  16555. case 124: case 38: // '|&'
  16556. return this.readToken_pipe_amp(code)
  16557. case 94: // '^'
  16558. return this.readToken_caret()
  16559. case 43: case 45: // '+-'
  16560. return this.readToken_plus_min(code)
  16561. case 60: case 62: // '<>'
  16562. return this.readToken_lt_gt(code)
  16563. case 61: case 33: // '=!'
  16564. return this.readToken_eq_excl(code)
  16565. case 63: // '?'
  16566. return this.readToken_question()
  16567. case 126: // '~'
  16568. return this.finishOp(types.prefix, 1)
  16569. }
  16570. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  16571. };
  16572. pp$9.finishOp = function(type, size) {
  16573. var str = this.input.slice(this.pos, this.pos + size);
  16574. this.pos += size;
  16575. return this.finishToken(type, str)
  16576. };
  16577. pp$9.readRegexp = function() {
  16578. var escaped, inClass, start = this.pos;
  16579. for (;;) {
  16580. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  16581. var ch = this.input.charAt(this.pos);
  16582. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  16583. if (!escaped) {
  16584. if (ch === "[") { inClass = true; }
  16585. else if (ch === "]" && inClass) { inClass = false; }
  16586. else if (ch === "/" && !inClass) { break }
  16587. escaped = ch === "\\";
  16588. } else { escaped = false; }
  16589. ++this.pos;
  16590. }
  16591. var pattern = this.input.slice(start, this.pos);
  16592. ++this.pos;
  16593. var flagsStart = this.pos;
  16594. var flags = this.readWord1();
  16595. if (this.containsEsc) { this.unexpected(flagsStart); }
  16596. // Validate pattern
  16597. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  16598. state.reset(start, pattern, flags);
  16599. this.validateRegExpFlags(state);
  16600. this.validateRegExpPattern(state);
  16601. // Create Literal#value property value.
  16602. var value = null;
  16603. try {
  16604. value = new RegExp(pattern, flags);
  16605. } catch (e) {
  16606. // ESTree requires null if it failed to instantiate RegExp object.
  16607. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  16608. }
  16609. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  16610. };
  16611. // Read an integer in the given radix. Return null if zero digits
  16612. // were read, the integer value otherwise. When `len` is given, this
  16613. // will return `null` unless the integer has exactly `len` digits.
  16614. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  16615. // `len` is used for character escape sequences. In that case, disallow separators.
  16616. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  16617. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  16618. // and isn't fraction part nor exponent part. In that case, if the first digit
  16619. // is zero then disallow separators.
  16620. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  16621. var start = this.pos, total = 0, lastCode = 0;
  16622. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  16623. var code = this.input.charCodeAt(this.pos), val = (void 0);
  16624. if (allowSeparators && code === 95) {
  16625. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  16626. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  16627. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  16628. lastCode = code;
  16629. continue
  16630. }
  16631. if (code >= 97) { val = code - 97 + 10; } // a
  16632. else if (code >= 65) { val = code - 65 + 10; } // A
  16633. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  16634. else { val = Infinity; }
  16635. if (val >= radix) { break }
  16636. lastCode = code;
  16637. total = total * radix + val;
  16638. }
  16639. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  16640. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  16641. return total
  16642. };
  16643. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  16644. if (isLegacyOctalNumericLiteral) {
  16645. return parseInt(str, 8)
  16646. }
  16647. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  16648. return parseFloat(str.replace(/_/g, ""))
  16649. }
  16650. function stringToBigInt(str) {
  16651. if (typeof BigInt !== "function") {
  16652. return null
  16653. }
  16654. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  16655. return BigInt(str.replace(/_/g, ""))
  16656. }
  16657. pp$9.readRadixNumber = function(radix) {
  16658. var start = this.pos;
  16659. this.pos += 2; // 0x
  16660. var val = this.readInt(radix);
  16661. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  16662. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  16663. val = stringToBigInt(this.input.slice(start, this.pos));
  16664. ++this.pos;
  16665. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16666. return this.finishToken(types.num, val)
  16667. };
  16668. // Read an integer, octal integer, or floating-point number.
  16669. pp$9.readNumber = function(startsWithDot) {
  16670. var start = this.pos;
  16671. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  16672. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  16673. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  16674. var next = this.input.charCodeAt(this.pos);
  16675. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  16676. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  16677. ++this.pos;
  16678. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16679. return this.finishToken(types.num, val$1)
  16680. }
  16681. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  16682. if (next === 46 && !octal) { // '.'
  16683. ++this.pos;
  16684. this.readInt(10);
  16685. next = this.input.charCodeAt(this.pos);
  16686. }
  16687. if ((next === 69 || next === 101) && !octal) { // 'eE'
  16688. next = this.input.charCodeAt(++this.pos);
  16689. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  16690. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  16691. }
  16692. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  16693. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  16694. return this.finishToken(types.num, val)
  16695. };
  16696. // Read a string value, interpreting backslash-escapes.
  16697. pp$9.readCodePoint = function() {
  16698. var ch = this.input.charCodeAt(this.pos), code;
  16699. if (ch === 123) { // '{'
  16700. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  16701. var codePos = ++this.pos;
  16702. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  16703. ++this.pos;
  16704. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  16705. } else {
  16706. code = this.readHexChar(4);
  16707. }
  16708. return code
  16709. };
  16710. function codePointToString$1(code) {
  16711. // UTF-16 Decoding
  16712. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  16713. code -= 0x10000;
  16714. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  16715. }
  16716. pp$9.readString = function(quote) {
  16717. var out = "", chunkStart = ++this.pos;
  16718. for (;;) {
  16719. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  16720. var ch = this.input.charCodeAt(this.pos);
  16721. if (ch === quote) { break }
  16722. if (ch === 92) { // '\'
  16723. out += this.input.slice(chunkStart, this.pos);
  16724. out += this.readEscapedChar(false);
  16725. chunkStart = this.pos;
  16726. } else {
  16727. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  16728. ++this.pos;
  16729. }
  16730. }
  16731. out += this.input.slice(chunkStart, this.pos++);
  16732. return this.finishToken(types.string, out)
  16733. };
  16734. // Reads template string tokens.
  16735. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  16736. pp$9.tryReadTemplateToken = function() {
  16737. this.inTemplateElement = true;
  16738. try {
  16739. this.readTmplToken();
  16740. } catch (err) {
  16741. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  16742. this.readInvalidTemplateToken();
  16743. } else {
  16744. throw err
  16745. }
  16746. }
  16747. this.inTemplateElement = false;
  16748. };
  16749. pp$9.invalidStringToken = function(position, message) {
  16750. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  16751. throw INVALID_TEMPLATE_ESCAPE_ERROR
  16752. } else {
  16753. this.raise(position, message);
  16754. }
  16755. };
  16756. pp$9.readTmplToken = function() {
  16757. var out = "", chunkStart = this.pos;
  16758. for (;;) {
  16759. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  16760. var ch = this.input.charCodeAt(this.pos);
  16761. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  16762. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  16763. if (ch === 36) {
  16764. this.pos += 2;
  16765. return this.finishToken(types.dollarBraceL)
  16766. } else {
  16767. ++this.pos;
  16768. return this.finishToken(types.backQuote)
  16769. }
  16770. }
  16771. out += this.input.slice(chunkStart, this.pos);
  16772. return this.finishToken(types.template, out)
  16773. }
  16774. if (ch === 92) { // '\'
  16775. out += this.input.slice(chunkStart, this.pos);
  16776. out += this.readEscapedChar(true);
  16777. chunkStart = this.pos;
  16778. } else if (isNewLine(ch)) {
  16779. out += this.input.slice(chunkStart, this.pos);
  16780. ++this.pos;
  16781. switch (ch) {
  16782. case 13:
  16783. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  16784. case 10:
  16785. out += "\n";
  16786. break
  16787. default:
  16788. out += String.fromCharCode(ch);
  16789. break
  16790. }
  16791. if (this.options.locations) {
  16792. ++this.curLine;
  16793. this.lineStart = this.pos;
  16794. }
  16795. chunkStart = this.pos;
  16796. } else {
  16797. ++this.pos;
  16798. }
  16799. }
  16800. };
  16801. // Reads a template token to search for the end, without validating any escape sequences
  16802. pp$9.readInvalidTemplateToken = function() {
  16803. for (; this.pos < this.input.length; this.pos++) {
  16804. switch (this.input[this.pos]) {
  16805. case "\\":
  16806. ++this.pos;
  16807. break
  16808. case "$":
  16809. if (this.input[this.pos + 1] !== "{") {
  16810. break
  16811. }
  16812. // falls through
  16813. case "`":
  16814. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  16815. // no default
  16816. }
  16817. }
  16818. this.raise(this.start, "Unterminated template");
  16819. };
  16820. // Used to read escaped characters
  16821. pp$9.readEscapedChar = function(inTemplate) {
  16822. var ch = this.input.charCodeAt(++this.pos);
  16823. ++this.pos;
  16824. switch (ch) {
  16825. case 110: return "\n" // 'n' -> '\n'
  16826. case 114: return "\r" // 'r' -> '\r'
  16827. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  16828. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  16829. case 116: return "\t" // 't' -> '\t'
  16830. case 98: return "\b" // 'b' -> '\b'
  16831. case 118: return "\u000b" // 'v' -> '\u000b'
  16832. case 102: return "\f" // 'f' -> '\f'
  16833. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  16834. case 10: // ' \n'
  16835. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  16836. return ""
  16837. case 56:
  16838. case 57:
  16839. if (this.strict) {
  16840. this.invalidStringToken(
  16841. this.pos - 1,
  16842. "Invalid escape sequence"
  16843. );
  16844. }
  16845. if (inTemplate) {
  16846. var codePos = this.pos - 1;
  16847. this.invalidStringToken(
  16848. codePos,
  16849. "Invalid escape sequence in template string"
  16850. );
  16851. return null
  16852. }
  16853. default:
  16854. if (ch >= 48 && ch <= 55) {
  16855. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  16856. var octal = parseInt(octalStr, 8);
  16857. if (octal > 255) {
  16858. octalStr = octalStr.slice(0, -1);
  16859. octal = parseInt(octalStr, 8);
  16860. }
  16861. this.pos += octalStr.length - 1;
  16862. ch = this.input.charCodeAt(this.pos);
  16863. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  16864. this.invalidStringToken(
  16865. this.pos - 1 - octalStr.length,
  16866. inTemplate
  16867. ? "Octal literal in template string"
  16868. : "Octal literal in strict mode"
  16869. );
  16870. }
  16871. return String.fromCharCode(octal)
  16872. }
  16873. if (isNewLine(ch)) {
  16874. // Unicode new line characters after \ get removed from output in both
  16875. // template literals and strings
  16876. return ""
  16877. }
  16878. return String.fromCharCode(ch)
  16879. }
  16880. };
  16881. // Used to read character escape sequences ('\x', '\u', '\U').
  16882. pp$9.readHexChar = function(len) {
  16883. var codePos = this.pos;
  16884. var n = this.readInt(16, len);
  16885. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  16886. return n
  16887. };
  16888. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  16889. // to whether the word contained a '\u' escape.
  16890. //
  16891. // Incrementally adds only escaped chars, adding other chunks as-is
  16892. // as a micro-optimization.
  16893. pp$9.readWord1 = function() {
  16894. this.containsEsc = false;
  16895. var word = "", first = true, chunkStart = this.pos;
  16896. var astral = this.options.ecmaVersion >= 6;
  16897. while (this.pos < this.input.length) {
  16898. var ch = this.fullCharCodeAtPos();
  16899. if (isIdentifierChar(ch, astral)) {
  16900. this.pos += ch <= 0xffff ? 1 : 2;
  16901. } else if (ch === 92) { // "\"
  16902. this.containsEsc = true;
  16903. word += this.input.slice(chunkStart, this.pos);
  16904. var escStart = this.pos;
  16905. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  16906. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  16907. ++this.pos;
  16908. var esc = this.readCodePoint();
  16909. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  16910. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  16911. word += codePointToString$1(esc);
  16912. chunkStart = this.pos;
  16913. } else {
  16914. break
  16915. }
  16916. first = false;
  16917. }
  16918. return word + this.input.slice(chunkStart, this.pos)
  16919. };
  16920. // Read an identifier or keyword token. Will check for reserved
  16921. // words when necessary.
  16922. pp$9.readWord = function() {
  16923. var word = this.readWord1();
  16924. var type = types.name;
  16925. if (this.keywords.test(word)) {
  16926. type = keywords$1[word];
  16927. }
  16928. return this.finishToken(type, word)
  16929. };
  16930. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  16931. var version = "8.0.5";
  16932. Parser.acorn = {
  16933. Parser: Parser,
  16934. version: version,
  16935. defaultOptions: defaultOptions,
  16936. Position: Position,
  16937. SourceLocation: SourceLocation,
  16938. getLineInfo: getLineInfo,
  16939. Node: Node,
  16940. TokenType: TokenType,
  16941. tokTypes: types,
  16942. keywordTypes: keywords$1,
  16943. TokContext: TokContext,
  16944. tokContexts: types$1,
  16945. isIdentifierChar: isIdentifierChar,
  16946. isIdentifierStart: isIdentifierStart,
  16947. Token: Token,
  16948. isNewLine: isNewLine,
  16949. lineBreak: lineBreak,
  16950. lineBreakG: lineBreakG,
  16951. nonASCIIwhitespace: nonASCIIwhitespace
  16952. };
  16953. // The main exported interface (under `self.acorn` when in the
  16954. // browser) is a `parse` function that takes a code string and
  16955. // returns an abstract syntax tree as specified by [Mozilla parser
  16956. // API][api].
  16957. //
  16958. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  16959. function parse(input, options) {
  16960. return Parser.parse(input, options)
  16961. }
  16962. // This function tries to parse a single expression at a given
  16963. // offset in a string. Useful for parsing mixed-language formats
  16964. // that embed JavaScript expressions.
  16965. function parseExpressionAt(input, pos, options) {
  16966. return Parser.parseExpressionAt(input, pos, options)
  16967. }
  16968. // Acorn is organized as a tokenizer and a recursive-descent parser.
  16969. // The `tokenizer` export provides an interface to the tokenizer.
  16970. function tokenizer(input, options) {
  16971. return Parser.tokenizer(input, options)
  16972. }
  16973. var acorn = {
  16974. __proto__: null,
  16975. Node: Node,
  16976. Parser: Parser,
  16977. Position: Position,
  16978. SourceLocation: SourceLocation,
  16979. TokContext: TokContext,
  16980. Token: Token,
  16981. TokenType: TokenType,
  16982. defaultOptions: defaultOptions,
  16983. getLineInfo: getLineInfo,
  16984. isIdentifierChar: isIdentifierChar,
  16985. isIdentifierStart: isIdentifierStart,
  16986. isNewLine: isNewLine,
  16987. keywordTypes: keywords$1,
  16988. lineBreak: lineBreak,
  16989. lineBreakG: lineBreakG,
  16990. nonASCIIwhitespace: nonASCIIwhitespace,
  16991. parse: parse,
  16992. parseExpressionAt: parseExpressionAt,
  16993. tokContexts: types$1,
  16994. tokTypes: types,
  16995. tokenizer: tokenizer,
  16996. version: version
  16997. };
  16998. class GlobalScope extends Scope$1 {
  16999. constructor() {
  17000. super();
  17001. this.variables.set('undefined', new UndefinedVariable());
  17002. }
  17003. findVariable(name) {
  17004. let variable = this.variables.get(name);
  17005. if (!variable) {
  17006. variable = new GlobalVariable(name);
  17007. this.variables.set(name, variable);
  17008. }
  17009. return variable;
  17010. }
  17011. }
  17012. const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  17013. function mkdirpath(path$1) {
  17014. const dir = path.dirname(path$1);
  17015. try {
  17016. fs.readdirSync(dir);
  17017. }
  17018. catch (err) {
  17019. mkdirpath(dir);
  17020. try {
  17021. fs.mkdirSync(dir);
  17022. }
  17023. catch (err2) {
  17024. if (err2.code !== 'EEXIST') {
  17025. throw err2;
  17026. }
  17027. }
  17028. }
  17029. }
  17030. function writeFile(dest, data) {
  17031. return new Promise((fulfil, reject) => {
  17032. mkdirpath(dest);
  17033. fs.writeFile(dest, data, err => {
  17034. if (err) {
  17035. reject(err);
  17036. }
  17037. else {
  17038. fulfil();
  17039. }
  17040. });
  17041. });
  17042. }
  17043. async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
  17044. const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
  17045. if (pluginResult != null)
  17046. return pluginResult;
  17047. // external modules (non-entry modules that start with neither '.' or '/')
  17048. // are skipped at this stage.
  17049. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  17050. return null;
  17051. // `resolve` processes paths from right to left, prepending them until an
  17052. // absolute path is created. Absolute importees therefore shortcircuit the
  17053. // resolve call and require no special handing on our part.
  17054. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  17055. return addJsExtensionIfNecessary(importer ? path.resolve(path.dirname(importer), source) : path.resolve(source), preserveSymlinks);
  17056. }
  17057. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  17058. let found = findFile(file, preserveSymlinks);
  17059. if (found)
  17060. return found;
  17061. found = findFile(file + '.mjs', preserveSymlinks);
  17062. if (found)
  17063. return found;
  17064. found = findFile(file + '.js', preserveSymlinks);
  17065. return found;
  17066. }
  17067. function findFile(file, preserveSymlinks) {
  17068. try {
  17069. const stats = fs.lstatSync(file);
  17070. if (!preserveSymlinks && stats.isSymbolicLink())
  17071. return findFile(fs.realpathSync(file), preserveSymlinks);
  17072. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  17073. // check case
  17074. const name = path.basename(file);
  17075. const files = fs.readdirSync(path.dirname(file));
  17076. if (files.indexOf(name) !== -1)
  17077. return file;
  17078. }
  17079. }
  17080. catch (_a) {
  17081. // suppress
  17082. }
  17083. }
  17084. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  17085. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  17086. function throwPluginError(err, plugin, { hook, id } = {}) {
  17087. if (typeof err === 'string')
  17088. err = { message: err };
  17089. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  17090. err.pluginCode = err.code;
  17091. }
  17092. err.code = Errors.PLUGIN_ERROR;
  17093. err.plugin = plugin;
  17094. if (hook) {
  17095. err.hook = hook;
  17096. }
  17097. if (id) {
  17098. err.id = id;
  17099. }
  17100. return error(err);
  17101. }
  17102. const deprecatedHooks = [
  17103. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  17104. ];
  17105. function warnDeprecatedHooks(plugins, options) {
  17106. for (const { active, deprecated, replacement } of deprecatedHooks) {
  17107. for (const plugin of plugins) {
  17108. if (deprecated in plugin) {
  17109. warnDeprecation({
  17110. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  17111. plugin: plugin.name
  17112. }, active, options);
  17113. }
  17114. }
  17115. }
  17116. }
  17117. function createPluginCache(cache) {
  17118. return {
  17119. has(id) {
  17120. const item = cache[id];
  17121. if (!item)
  17122. return false;
  17123. item[0] = 0;
  17124. return true;
  17125. },
  17126. get(id) {
  17127. const item = cache[id];
  17128. if (!item)
  17129. return undefined;
  17130. item[0] = 0;
  17131. return item[1];
  17132. },
  17133. set(id, value) {
  17134. cache[id] = [0, value];
  17135. },
  17136. delete(id) {
  17137. return delete cache[id];
  17138. }
  17139. };
  17140. }
  17141. function getTrackedPluginCache(pluginCache, onUse) {
  17142. return {
  17143. has(id) {
  17144. onUse();
  17145. return pluginCache.has(id);
  17146. },
  17147. get(id) {
  17148. onUse();
  17149. return pluginCache.get(id);
  17150. },
  17151. set(id, value) {
  17152. onUse();
  17153. return pluginCache.set(id, value);
  17154. },
  17155. delete(id) {
  17156. onUse();
  17157. return pluginCache.delete(id);
  17158. }
  17159. };
  17160. }
  17161. const NO_CACHE = {
  17162. has() {
  17163. return false;
  17164. },
  17165. get() {
  17166. return undefined;
  17167. },
  17168. set() { },
  17169. delete() {
  17170. return false;
  17171. }
  17172. };
  17173. function uncacheablePluginError(pluginName) {
  17174. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17175. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  17176. return error({
  17177. code: 'ANONYMOUS_PLUGIN_CACHE',
  17178. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  17179. });
  17180. }
  17181. return error({
  17182. code: 'DUPLICATE_PLUGIN_NAME',
  17183. 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).`
  17184. });
  17185. }
  17186. function getCacheForUncacheablePlugin(pluginName) {
  17187. return {
  17188. has() {
  17189. return uncacheablePluginError(pluginName);
  17190. },
  17191. get() {
  17192. return uncacheablePluginError(pluginName);
  17193. },
  17194. set() {
  17195. return uncacheablePluginError(pluginName);
  17196. },
  17197. delete() {
  17198. return uncacheablePluginError(pluginName);
  17199. }
  17200. };
  17201. }
  17202. function transform(source, module, pluginDriver, warn) {
  17203. const id = module.id;
  17204. const sourcemapChain = [];
  17205. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  17206. const originalCode = source.code;
  17207. let ast = source.ast;
  17208. const transformDependencies = [];
  17209. const emittedFiles = [];
  17210. let customTransformCache = false;
  17211. const useCustomTransformCache = () => (customTransformCache = true);
  17212. let curPlugin;
  17213. const curSource = source.code;
  17214. function transformReducer(previousCode, result, plugin) {
  17215. let code;
  17216. let map;
  17217. if (typeof result === 'string') {
  17218. code = result;
  17219. }
  17220. else if (result && typeof result === 'object') {
  17221. module.updateOptions(result);
  17222. if (result.code == null) {
  17223. if (result.map || result.ast) {
  17224. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  17225. }
  17226. return previousCode;
  17227. }
  17228. ({ code, map, ast } = result);
  17229. }
  17230. else {
  17231. return previousCode;
  17232. }
  17233. // strict null check allows 'null' maps to not be pushed to the chain,
  17234. // while 'undefined' gets the missing map warning
  17235. if (map !== null) {
  17236. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  17237. missing: true,
  17238. plugin: plugin.name
  17239. });
  17240. }
  17241. return code;
  17242. }
  17243. return pluginDriver
  17244. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  17245. curPlugin = plugin;
  17246. return {
  17247. ...pluginContext,
  17248. cache: customTransformCache
  17249. ? pluginContext.cache
  17250. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  17251. warn(warning, pos) {
  17252. if (typeof warning === 'string')
  17253. warning = { message: warning };
  17254. if (pos)
  17255. augmentCodeLocation(warning, pos, curSource, id);
  17256. warning.id = id;
  17257. warning.hook = 'transform';
  17258. pluginContext.warn(warning);
  17259. },
  17260. error(err, pos) {
  17261. if (typeof err === 'string')
  17262. err = { message: err };
  17263. if (pos)
  17264. augmentCodeLocation(err, pos, curSource, id);
  17265. err.id = id;
  17266. err.hook = 'transform';
  17267. return pluginContext.error(err);
  17268. },
  17269. emitAsset(name, source) {
  17270. emittedFiles.push({ type: 'asset', name, source });
  17271. return pluginContext.emitAsset(name, source);
  17272. },
  17273. emitChunk(id, options) {
  17274. emittedFiles.push({ type: 'chunk', id, name: options && options.name });
  17275. return pluginContext.emitChunk(id, options);
  17276. },
  17277. emitFile(emittedFile) {
  17278. emittedFiles.push(emittedFile);
  17279. return pluginDriver.emitFile(emittedFile);
  17280. },
  17281. addWatchFile(id) {
  17282. transformDependencies.push(id);
  17283. pluginContext.addWatchFile(id);
  17284. },
  17285. setAssetSource() {
  17286. return this.error({
  17287. code: 'INVALID_SETASSETSOURCE',
  17288. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  17289. });
  17290. },
  17291. getCombinedSourcemap() {
  17292. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  17293. if (!combinedMap) {
  17294. const magicString = new MagicString(originalCode);
  17295. return magicString.generateMap({ includeContent: true, hires: true, source: id });
  17296. }
  17297. if (originalSourcemap !== combinedMap) {
  17298. originalSourcemap = combinedMap;
  17299. sourcemapChain.length = 0;
  17300. }
  17301. return new SourceMap({
  17302. ...combinedMap,
  17303. file: null,
  17304. sourcesContent: combinedMap.sourcesContent
  17305. });
  17306. }
  17307. };
  17308. })
  17309. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  17310. .then(code => {
  17311. if (!customTransformCache) {
  17312. // files emitted by a transform hook need to be emitted again if the hook is skipped
  17313. if (emittedFiles.length)
  17314. module.transformFiles = emittedFiles;
  17315. }
  17316. return {
  17317. ast,
  17318. code,
  17319. customTransformCache,
  17320. meta: module.info.meta,
  17321. originalCode,
  17322. originalSourcemap,
  17323. sourcemapChain,
  17324. transformDependencies
  17325. };
  17326. });
  17327. }
  17328. class ModuleLoader {
  17329. constructor(graph, modulesById, options, pluginDriver) {
  17330. this.graph = graph;
  17331. this.modulesById = modulesById;
  17332. this.options = options;
  17333. this.pluginDriver = pluginDriver;
  17334. this.implicitEntryModules = new Set();
  17335. this.indexedEntryModules = [];
  17336. this.latestLoadModulesPromise = Promise.resolve();
  17337. this.nextEntryModuleIndex = 0;
  17338. this.hasModuleSideEffects = options.treeshake
  17339. ? options.treeshake.moduleSideEffects
  17340. : () => true;
  17341. }
  17342. async addAdditionalModules(unresolvedModules) {
  17343. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  17344. await this.awaitLoadModulesPromise();
  17345. return result;
  17346. }
  17347. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  17348. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  17349. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  17350. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  17351. let moduleIndex = firstEntryModuleIndex;
  17352. for (let index = 0; index < entryModules.length; index++) {
  17353. const entryModule = entryModules[index];
  17354. entryModule.isUserDefinedEntryPoint =
  17355. entryModule.isUserDefinedEntryPoint || isUserDefined;
  17356. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
  17357. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  17358. if (!existingIndexedModule) {
  17359. this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
  17360. }
  17361. else {
  17362. existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
  17363. }
  17364. moduleIndex++;
  17365. }
  17366. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  17367. return entryModules;
  17368. }));
  17369. await this.awaitLoadModulesPromise();
  17370. return {
  17371. entryModules: this.indexedEntryModules.map(({ module }) => module),
  17372. implicitEntryModules: [...this.implicitEntryModules],
  17373. newEntryModules
  17374. };
  17375. }
  17376. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  17377. const unresolvedModule = {
  17378. fileName: fileName || null,
  17379. id,
  17380. importer,
  17381. name: name || null
  17382. };
  17383. const module = implicitlyLoadedAfterOneOf
  17384. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  17385. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  17386. if (preserveSignature != null) {
  17387. module.preserveSignature = preserveSignature;
  17388. }
  17389. return module;
  17390. }
  17391. async resolveId(source, importer, customOptions, skip = null) {
  17392. return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  17393. ? false
  17394. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
  17395. }
  17396. addDefaultsToResolvedId(resolvedId) {
  17397. var _a, _b;
  17398. if (!resolvedId) {
  17399. return null;
  17400. }
  17401. const external = resolvedId.external || false;
  17402. return {
  17403. external,
  17404. id: resolvedId.id,
  17405. meta: resolvedId.meta || EMPTY_OBJECT,
  17406. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
  17407. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  17408. };
  17409. }
  17410. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  17411. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  17412. addChunkNamesToModule(entryModule, unresolvedModule, false);
  17413. if (!entryModule.info.isEntry) {
  17414. this.implicitEntryModules.add(entryModule);
  17415. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  17416. for (const module of implicitlyLoadedAfterModules) {
  17417. entryModule.implicitlyLoadedAfter.add(module);
  17418. }
  17419. for (const dependant of entryModule.implicitlyLoadedAfter) {
  17420. dependant.implicitlyLoadedBefore.add(entryModule);
  17421. }
  17422. }
  17423. return entryModule;
  17424. }));
  17425. }
  17426. async addModuleSource(id, importer, module) {
  17427. var _a;
  17428. timeStart('load modules', 3);
  17429. let source;
  17430. try {
  17431. source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
  17432. }
  17433. catch (err) {
  17434. timeEnd('load modules', 3);
  17435. let msg = `Could not load ${id}`;
  17436. if (importer)
  17437. msg += ` (imported by ${relativeId(importer)})`;
  17438. msg += `: ${err.message}`;
  17439. err.message = msg;
  17440. throw err;
  17441. }
  17442. timeEnd('load modules', 3);
  17443. const sourceDescription = typeof source === 'string'
  17444. ? { code: source }
  17445. : typeof source === 'object' && typeof source.code === 'string'
  17446. ? source
  17447. : error(errBadLoader(id));
  17448. const cachedModule = this.graph.cachedModules.get(id);
  17449. if (cachedModule &&
  17450. !cachedModule.customTransformCache &&
  17451. cachedModule.originalCode === sourceDescription.code) {
  17452. if (cachedModule.transformFiles) {
  17453. for (const emittedFile of cachedModule.transformFiles)
  17454. this.pluginDriver.emitFile(emittedFile);
  17455. }
  17456. module.setSource(cachedModule);
  17457. }
  17458. else {
  17459. module.updateOptions(sourceDescription);
  17460. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  17461. }
  17462. }
  17463. async awaitLoadModulesPromise() {
  17464. let startingPromise;
  17465. do {
  17466. startingPromise = this.latestLoadModulesPromise;
  17467. await startingPromise;
  17468. } while (startingPromise !== this.latestLoadModulesPromise);
  17469. }
  17470. extendLoadModulesPromise(loadNewModulesPromise) {
  17471. this.latestLoadModulesPromise = Promise.all([
  17472. loadNewModulesPromise,
  17473. this.latestLoadModulesPromise
  17474. ]);
  17475. this.latestLoadModulesPromise.catch(() => {
  17476. /* Avoid unhandled Promise rejections */
  17477. });
  17478. return loadNewModulesPromise;
  17479. }
  17480. async fetchDynamicDependencies(module) {
  17481. const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
  17482. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  17483. ? dynamicImport.argument
  17484. : dynamicImport.argument.esTreeNode, module.id);
  17485. if (resolvedId === null)
  17486. return null;
  17487. if (typeof resolvedId === 'string') {
  17488. dynamicImport.resolution = resolvedId;
  17489. return null;
  17490. }
  17491. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  17492. }));
  17493. for (const dependency of dependencies) {
  17494. if (dependency) {
  17495. module.dynamicDependencies.add(dependency);
  17496. dependency.dynamicImporters.push(module.id);
  17497. }
  17498. }
  17499. }
  17500. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
  17501. const existingModule = this.modulesById.get(id);
  17502. if (existingModule instanceof Module) {
  17503. if (isEntry) {
  17504. existingModule.info.isEntry = true;
  17505. this.implicitEntryModules.delete(existingModule);
  17506. for (const dependant of existingModule.implicitlyLoadedAfter) {
  17507. dependant.implicitlyLoadedBefore.delete(existingModule);
  17508. }
  17509. existingModule.implicitlyLoadedAfter.clear();
  17510. }
  17511. return existingModule;
  17512. }
  17513. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  17514. this.modulesById.set(id, module);
  17515. this.graph.watchFiles[id] = true;
  17516. await this.addModuleSource(id, importer, module);
  17517. await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
  17518. await Promise.all([
  17519. this.fetchStaticDependencies(module),
  17520. this.fetchDynamicDependencies(module)
  17521. ]);
  17522. module.linkImports();
  17523. return module;
  17524. }
  17525. fetchResolvedDependency(source, importer, resolvedId) {
  17526. if (resolvedId.external) {
  17527. if (!this.modulesById.has(resolvedId.id)) {
  17528. this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
  17529. }
  17530. const externalModule = this.modulesById.get(resolvedId.id);
  17531. if (!(externalModule instanceof ExternalModule)) {
  17532. return error(errInternalIdCannotBeExternal(source, importer));
  17533. }
  17534. return Promise.resolve(externalModule);
  17535. }
  17536. else {
  17537. return this.fetchModule(resolvedId, importer, false);
  17538. }
  17539. }
  17540. async fetchStaticDependencies(module) {
  17541. for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
  17542. module.resolvedIds[source] ||
  17543. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
  17544. module.dependencies.add(dependency);
  17545. dependency.importers.push(module.id);
  17546. }
  17547. }
  17548. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  17549. if (resolveIdResult) {
  17550. if (typeof resolveIdResult === 'object') {
  17551. return {
  17552. ...resolveIdResult,
  17553. external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
  17554. };
  17555. }
  17556. const external = this.options.external(resolveIdResult, importer, true);
  17557. return {
  17558. external,
  17559. id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
  17560. };
  17561. }
  17562. const id = normalizeRelativeExternalId(source, importer);
  17563. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  17564. return null;
  17565. }
  17566. return {
  17567. external: true,
  17568. id
  17569. };
  17570. }
  17571. handleResolveId(resolvedId, source, importer) {
  17572. if (resolvedId === null) {
  17573. if (isRelative(source)) {
  17574. return error(errUnresolvedImport(source, importer));
  17575. }
  17576. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  17577. return {
  17578. external: true,
  17579. id: source,
  17580. meta: EMPTY_OBJECT,
  17581. moduleSideEffects: this.hasModuleSideEffects(source, true),
  17582. syntheticNamedExports: false
  17583. };
  17584. }
  17585. else {
  17586. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  17587. this.options.onwarn(errExternalSyntheticExports(source, importer));
  17588. }
  17589. }
  17590. return resolvedId;
  17591. }
  17592. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  17593. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
  17594. if (resolveIdResult == null) {
  17595. return error(implicitlyLoadedBefore === null
  17596. ? errUnresolvedEntry(unresolvedId)
  17597. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  17598. }
  17599. if (resolveIdResult === false ||
  17600. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  17601. return error(implicitlyLoadedBefore === null
  17602. ? errEntryCannotBeExternal(unresolvedId)
  17603. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  17604. }
  17605. return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
  17606. }
  17607. async resolveDynamicImport(module, specifier, importer) {
  17608. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  17609. specifier,
  17610. importer
  17611. ]);
  17612. if (typeof specifier !== 'string') {
  17613. if (typeof resolution === 'string') {
  17614. return resolution;
  17615. }
  17616. if (!resolution) {
  17617. return null;
  17618. }
  17619. return {
  17620. external: false,
  17621. moduleSideEffects: true,
  17622. ...resolution
  17623. };
  17624. }
  17625. if (resolution == null) {
  17626. return (module.resolvedIds[specifier] =
  17627. module.resolvedIds[specifier] ||
  17628. this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
  17629. }
  17630. return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  17631. }
  17632. }
  17633. function normalizeRelativeExternalId(source, importer) {
  17634. return isRelative(source)
  17635. ? importer
  17636. ? path.resolve(importer, '..', source)
  17637. : path.resolve(source)
  17638. : source;
  17639. }
  17640. function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
  17641. if (fileName !== null) {
  17642. module.chunkFileNames.add(fileName);
  17643. }
  17644. else if (name !== null) {
  17645. if (module.chunkName === null) {
  17646. module.chunkName = name;
  17647. }
  17648. if (isUserDefined) {
  17649. module.userChunkNames.add(name);
  17650. }
  17651. }
  17652. }
  17653. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  17654. let deprecationWarningShown = false;
  17655. return ((...args) => {
  17656. if (!deprecationWarningShown) {
  17657. deprecationWarningShown = true;
  17658. warnDeprecation({
  17659. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  17660. plugin: pluginName
  17661. }, activeDeprecation, options);
  17662. }
  17663. return handler(...args);
  17664. });
  17665. }
  17666. function getPluginContexts(pluginCache, graph, options, fileEmitter) {
  17667. const existingPluginNames = new Set();
  17668. return (plugin, pidx) => {
  17669. let cacheable = true;
  17670. if (typeof plugin.cacheKey !== 'string') {
  17671. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  17672. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  17673. existingPluginNames.has(plugin.name)) {
  17674. cacheable = false;
  17675. }
  17676. else {
  17677. existingPluginNames.add(plugin.name);
  17678. }
  17679. }
  17680. let cacheInstance;
  17681. if (!pluginCache) {
  17682. cacheInstance = NO_CACHE;
  17683. }
  17684. else if (cacheable) {
  17685. const cacheKey = plugin.cacheKey || plugin.name;
  17686. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  17687. }
  17688. else {
  17689. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  17690. }
  17691. const context = {
  17692. addWatchFile(id) {
  17693. if (graph.phase >= BuildPhase.GENERATE) {
  17694. return this.error(errInvalidRollupPhaseForAddWatchFile());
  17695. }
  17696. graph.watchFiles[id] = true;
  17697. },
  17698. cache: cacheInstance,
  17699. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
  17700. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
  17701. emitFile: fileEmitter.emitFile,
  17702. error(err) {
  17703. return throwPluginError(err, plugin.name);
  17704. },
  17705. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  17706. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  17707. getFileName: fileEmitter.getFileName,
  17708. getModuleIds: () => graph.modulesById.keys(),
  17709. getModuleInfo: graph.getModuleInfo,
  17710. getWatchFiles: () => Object.keys(graph.watchFiles),
  17711. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  17712. meta: {
  17713. rollupVersion: version$1,
  17714. watchMode: graph.watchMode
  17715. },
  17716. get moduleIds() {
  17717. function* wrappedModuleIds() {
  17718. warnDeprecation({
  17719. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  17720. plugin: plugin.name
  17721. }, false, options);
  17722. yield* moduleIds;
  17723. }
  17724. const moduleIds = graph.modulesById.keys();
  17725. return wrappedModuleIds();
  17726. },
  17727. parse: graph.contextParse,
  17728. resolve(source, importer, { custom, skipSelf } = BLANK) {
  17729. return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
  17730. },
  17731. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  17732. .resolveId(source, importer, BLANK)
  17733. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  17734. setAssetSource: fileEmitter.setAssetSource,
  17735. warn(warning) {
  17736. if (typeof warning === 'string')
  17737. warning = { message: warning };
  17738. if (warning.code)
  17739. warning.pluginCode = warning.code;
  17740. warning.code = 'PLUGIN_WARNING';
  17741. warning.plugin = plugin.name;
  17742. options.onwarn(warning);
  17743. }
  17744. };
  17745. return context;
  17746. };
  17747. }
  17748. const inputHookNames = {
  17749. buildEnd: 1,
  17750. buildStart: 1,
  17751. closeBundle: 1,
  17752. closeWatcher: 1,
  17753. load: 1,
  17754. moduleParsed: 1,
  17755. options: 1,
  17756. resolveDynamicImport: 1,
  17757. resolveId: 1,
  17758. transform: 1,
  17759. watchChange: 1
  17760. };
  17761. const inputHooks = Object.keys(inputHookNames);
  17762. function throwInvalidHookError(hookName, pluginName) {
  17763. return error({
  17764. code: 'INVALID_PLUGIN_HOOK',
  17765. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  17766. });
  17767. }
  17768. class PluginDriver {
  17769. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  17770. this.graph = graph;
  17771. this.options = options;
  17772. warnDeprecatedHooks(userPlugins, options);
  17773. this.pluginCache = pluginCache;
  17774. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  17775. this.emitFile = this.fileEmitter.emitFile;
  17776. this.getFileName = this.fileEmitter.getFileName;
  17777. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
  17778. this.setOutputBundle = this.fileEmitter.setOutputBundle;
  17779. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  17780. this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
  17781. if (basePluginDriver) {
  17782. for (const plugin of userPlugins) {
  17783. for (const hook of inputHooks) {
  17784. if (hook in plugin) {
  17785. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  17786. }
  17787. }
  17788. }
  17789. }
  17790. }
  17791. createOutputPluginDriver(plugins) {
  17792. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  17793. }
  17794. // chains, first non-null result stops and returns
  17795. hookFirst(hookName, args, replaceContext, skip) {
  17796. let promise = Promise.resolve(undefined);
  17797. for (let i = 0; i < this.plugins.length; i++) {
  17798. if (skip === i)
  17799. continue;
  17800. promise = promise.then(result => {
  17801. if (result != null)
  17802. return result;
  17803. return this.runHook(hookName, args, i, false, replaceContext);
  17804. });
  17805. }
  17806. return promise;
  17807. }
  17808. // chains synchronously, first non-null result stops and returns
  17809. hookFirstSync(hookName, args, replaceContext) {
  17810. for (let i = 0; i < this.plugins.length; i++) {
  17811. const result = this.runHookSync(hookName, args, i, replaceContext);
  17812. if (result != null)
  17813. return result;
  17814. }
  17815. return null;
  17816. }
  17817. // parallel, ignores returns
  17818. hookParallel(hookName, args, replaceContext) {
  17819. const promises = [];
  17820. for (let i = 0; i < this.plugins.length; i++) {
  17821. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17822. if (!hookPromise)
  17823. continue;
  17824. promises.push(hookPromise);
  17825. }
  17826. return Promise.all(promises).then(() => { });
  17827. }
  17828. // chains, reduces returned value, handling the reduced value as the first hook argument
  17829. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  17830. let promise = Promise.resolve(arg0);
  17831. for (let i = 0; i < this.plugins.length; i++) {
  17832. promise = promise.then(arg0 => {
  17833. const args = [arg0, ...rest];
  17834. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  17835. if (!hookPromise)
  17836. return arg0;
  17837. return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
  17838. });
  17839. }
  17840. return promise;
  17841. }
  17842. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  17843. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  17844. for (let i = 0; i < this.plugins.length; i++) {
  17845. const args = [arg0, ...rest];
  17846. const result = this.runHookSync(hookName, args, i, replaceContext);
  17847. arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
  17848. }
  17849. return arg0;
  17850. }
  17851. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17852. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  17853. let promise = Promise.resolve(initialValue);
  17854. for (let i = 0; i < this.plugins.length; i++) {
  17855. promise = promise.then(value => {
  17856. const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
  17857. if (!hookPromise)
  17858. return value;
  17859. return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
  17860. });
  17861. }
  17862. return promise;
  17863. }
  17864. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  17865. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  17866. let acc = initialValue;
  17867. for (let i = 0; i < this.plugins.length; i++) {
  17868. const result = this.runHookSync(hookName, args, i, replaceContext);
  17869. acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
  17870. }
  17871. return acc;
  17872. }
  17873. // chains, ignores returns
  17874. hookSeq(hookName, args, replaceContext) {
  17875. let promise = Promise.resolve();
  17876. for (let i = 0; i < this.plugins.length; i++) {
  17877. promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
  17878. }
  17879. return promise;
  17880. }
  17881. // chains synchronously, ignores returns
  17882. hookSeqSync(hookName, args, replaceContext) {
  17883. for (let i = 0; i < this.plugins.length; i++) {
  17884. this.runHookSync(hookName, args, i, replaceContext);
  17885. }
  17886. }
  17887. runHook(hookName, args, pluginIndex, permitValues, hookContext) {
  17888. const plugin = this.plugins[pluginIndex];
  17889. const hook = plugin[hookName];
  17890. if (!hook)
  17891. return undefined;
  17892. let context = this.pluginContexts[pluginIndex];
  17893. if (hookContext) {
  17894. context = hookContext(context, plugin);
  17895. }
  17896. return Promise.resolve()
  17897. .then(() => {
  17898. // permit values allows values to be returned instead of a functional hook
  17899. if (typeof hook !== 'function') {
  17900. if (permitValues)
  17901. return hook;
  17902. return throwInvalidHookError(hookName, plugin.name);
  17903. }
  17904. return hook.apply(context, args);
  17905. })
  17906. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  17907. }
  17908. /**
  17909. * Run a sync plugin hook and return the result.
  17910. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  17911. * @param args Arguments passed to the plugin hook.
  17912. * @param pluginIndex Index of the plugin inside `this.plugins[]`.
  17913. * @param hookContext When passed, the plugin context can be overridden.
  17914. */
  17915. runHookSync(hookName, args, pluginIndex, hookContext) {
  17916. const plugin = this.plugins[pluginIndex];
  17917. const hook = plugin[hookName];
  17918. if (!hook)
  17919. return undefined;
  17920. let context = this.pluginContexts[pluginIndex];
  17921. if (hookContext) {
  17922. context = hookContext(context, plugin);
  17923. }
  17924. try {
  17925. // permit values allows values to be returned instead of a functional hook
  17926. if (typeof hook !== 'function') {
  17927. return throwInvalidHookError(hookName, plugin.name);
  17928. }
  17929. return hook.apply(context, args);
  17930. }
  17931. catch (err) {
  17932. return throwPluginError(err, plugin.name, { hook: hookName });
  17933. }
  17934. }
  17935. }
  17936. function normalizeEntryModules(entryModules) {
  17937. if (Array.isArray(entryModules)) {
  17938. return entryModules.map(id => ({
  17939. fileName: null,
  17940. id,
  17941. implicitlyLoadedAfter: [],
  17942. importer: undefined,
  17943. name: null
  17944. }));
  17945. }
  17946. return Object.keys(entryModules).map(name => ({
  17947. fileName: null,
  17948. id: entryModules[name],
  17949. implicitlyLoadedAfter: [],
  17950. importer: undefined,
  17951. name
  17952. }));
  17953. }
  17954. class Graph {
  17955. constructor(options, watcher) {
  17956. var _a, _b;
  17957. this.options = options;
  17958. this.entryModules = [];
  17959. this.modulesById = new Map();
  17960. this.needsTreeshakingPass = false;
  17961. this.phase = BuildPhase.LOAD_AND_PARSE;
  17962. this.watchFiles = Object.create(null);
  17963. this.watchMode = false;
  17964. this.externalModules = [];
  17965. this.implicitEntryModules = [];
  17966. this.modules = [];
  17967. this.getModuleInfo = (moduleId) => {
  17968. const foundModule = this.modulesById.get(moduleId);
  17969. if (!foundModule)
  17970. return null;
  17971. return foundModule.info;
  17972. };
  17973. this.deoptimizationTracker = new PathTracker();
  17974. this.cachedModules = new Map();
  17975. if (options.cache !== false) {
  17976. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  17977. for (const module of options.cache.modules)
  17978. this.cachedModules.set(module.id, module);
  17979. }
  17980. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  17981. // increment access counter
  17982. for (const name in this.pluginCache) {
  17983. const cache = this.pluginCache[name];
  17984. for (const key of Object.keys(cache))
  17985. cache[key][0]++;
  17986. }
  17987. }
  17988. this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
  17989. ...this.options.acorn,
  17990. ...options
  17991. });
  17992. if (watcher) {
  17993. this.watchMode = true;
  17994. const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
  17995. const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
  17996. watcher.on('change', handleChange);
  17997. watcher.on('close', handleClose);
  17998. watcher.once('restart', () => {
  17999. watcher.removeListener('change', handleChange);
  18000. watcher.removeListener('close', handleClose);
  18001. });
  18002. }
  18003. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  18004. this.scope = new GlobalScope();
  18005. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  18006. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  18007. }
  18008. async build() {
  18009. timeStart('generate module graph', 2);
  18010. await this.generateModuleGraph();
  18011. timeEnd('generate module graph', 2);
  18012. timeStart('sort modules', 2);
  18013. this.phase = BuildPhase.ANALYSE;
  18014. this.sortModules();
  18015. timeEnd('sort modules', 2);
  18016. timeStart('mark included statements', 2);
  18017. this.includeStatements();
  18018. timeEnd('mark included statements', 2);
  18019. this.phase = BuildPhase.GENERATE;
  18020. }
  18021. getCache() {
  18022. // handle plugin cache eviction
  18023. for (const name in this.pluginCache) {
  18024. const cache = this.pluginCache[name];
  18025. let allDeleted = true;
  18026. for (const key of Object.keys(cache)) {
  18027. if (cache[key][0] >= this.options.experimentalCacheExpiry)
  18028. delete cache[key];
  18029. else
  18030. allDeleted = false;
  18031. }
  18032. if (allDeleted)
  18033. delete this.pluginCache[name];
  18034. }
  18035. return {
  18036. modules: this.modules.map(module => module.toJSON()),
  18037. plugins: this.pluginCache
  18038. };
  18039. }
  18040. async generateModuleGraph() {
  18041. ({
  18042. entryModules: this.entryModules,
  18043. implicitEntryModules: this.implicitEntryModules
  18044. } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  18045. if (this.entryModules.length === 0) {
  18046. throw new Error('You must supply options.input to rollup');
  18047. }
  18048. for (const module of this.modulesById.values()) {
  18049. if (module instanceof Module) {
  18050. this.modules.push(module);
  18051. }
  18052. else {
  18053. this.externalModules.push(module);
  18054. }
  18055. }
  18056. }
  18057. includeStatements() {
  18058. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  18059. if (module.preserveSignature !== false) {
  18060. module.includeAllExports(false);
  18061. }
  18062. else {
  18063. markModuleAndImpureDependenciesAsExecuted(module);
  18064. }
  18065. }
  18066. if (this.options.treeshake) {
  18067. let treeshakingPass = 1;
  18068. do {
  18069. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  18070. this.needsTreeshakingPass = false;
  18071. for (const module of this.modules) {
  18072. if (module.isExecuted) {
  18073. if (module.info.hasModuleSideEffects === 'no-treeshake') {
  18074. module.includeAllInBundle();
  18075. }
  18076. else {
  18077. module.include();
  18078. }
  18079. }
  18080. }
  18081. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  18082. } while (this.needsTreeshakingPass);
  18083. }
  18084. else {
  18085. for (const module of this.modules)
  18086. module.includeAllInBundle();
  18087. }
  18088. for (const externalModule of this.externalModules)
  18089. externalModule.warnUnusedImports();
  18090. for (const module of this.implicitEntryModules) {
  18091. for (const dependant of module.implicitlyLoadedAfter) {
  18092. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  18093. error(errImplicitDependantIsNotIncluded(dependant));
  18094. }
  18095. }
  18096. }
  18097. }
  18098. sortModules() {
  18099. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  18100. for (const cyclePath of cyclePaths) {
  18101. this.options.onwarn({
  18102. code: 'CIRCULAR_DEPENDENCY',
  18103. cycle: cyclePath,
  18104. importer: cyclePath[0],
  18105. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  18106. });
  18107. }
  18108. this.modules = orderedModules;
  18109. for (const module of this.modules) {
  18110. module.bindReferences();
  18111. }
  18112. this.warnForMissingExports();
  18113. }
  18114. warnForMissingExports() {
  18115. for (const module of this.modules) {
  18116. for (const importName of Object.keys(module.importDescriptions)) {
  18117. const importDescription = module.importDescriptions[importName];
  18118. if (importDescription.name !== '*' &&
  18119. !importDescription.module.getVariableForExportName(importDescription.name)) {
  18120. module.warn({
  18121. code: 'NON_EXISTENT_EXPORT',
  18122. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  18123. name: importDescription.name,
  18124. source: importDescription.module.id
  18125. }, importDescription.start);
  18126. }
  18127. }
  18128. }
  18129. }
  18130. }
  18131. var require$$1 = /*@__PURE__*/getAugmentedNamespace(acorn);
  18132. const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
  18133. const getAcorn$1 = Parser => {
  18134. if (Parser.acorn) return Parser.acorn
  18135. const acorn = require$$1;
  18136. if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
  18137. throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
  18138. }
  18139. // Make sure `Parser` comes from the same acorn as we `require`d,
  18140. // otherwise the comparisons fail.
  18141. for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
  18142. if (cur !== acorn.Parser) {
  18143. throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
  18144. }
  18145. }
  18146. return acorn
  18147. };
  18148. var acornPrivateClassElements = function(Parser) {
  18149. // Only load this plugin once.
  18150. if (Parser.prototype.parsePrivateName) {
  18151. return Parser
  18152. }
  18153. const acorn = getAcorn$1(Parser);
  18154. Parser = class extends Parser {
  18155. _branch() {
  18156. this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
  18157. this.__branch.end = this.end;
  18158. this.__branch.pos = this.pos;
  18159. this.__branch.type = this.type;
  18160. this.__branch.value = this.value;
  18161. this.__branch.containsEsc = this.containsEsc;
  18162. return this.__branch
  18163. }
  18164. parsePrivateClassElementName(element) {
  18165. element.computed = false;
  18166. element.key = this.parsePrivateName();
  18167. if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
  18168. const accept = {get: "set", set: "get"}[element.kind];
  18169. const privateBoundNames = this._privateBoundNames;
  18170. if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
  18171. this.raise(element.start, "Duplicate private element");
  18172. }
  18173. privateBoundNames[element.key.name] = element.kind || true;
  18174. delete this._unresolvedPrivateNames[element.key.name];
  18175. return element.key
  18176. }
  18177. parsePrivateName() {
  18178. const node = this.startNode();
  18179. node.name = this.value;
  18180. this.next();
  18181. this.finishNode(node, "PrivateIdentifier");
  18182. if (this.options.allowReserved == "never") this.checkUnreserved(node);
  18183. return node
  18184. }
  18185. // Parse # token
  18186. getTokenFromCode(code) {
  18187. if (code === 35) {
  18188. ++this.pos;
  18189. const word = this.readWord1();
  18190. return this.finishToken(this.privateIdentifierToken, word)
  18191. }
  18192. return super.getTokenFromCode(code)
  18193. }
  18194. // Manage stacks and check for undeclared private names
  18195. parseClass(node, isStatement) {
  18196. const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
  18197. this._outerPrivateBoundNames = this._privateBoundNames;
  18198. this._privateBoundNames = Object.create(this._privateBoundNames || null);
  18199. const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18200. this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
  18201. this._unresolvedPrivateNames = Object.create(null);
  18202. const _return = super.parseClass(node, isStatement);
  18203. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  18204. this._privateBoundNames = this._outerPrivateBoundNames;
  18205. this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
  18206. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18207. this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
  18208. if (!this._unresolvedPrivateNames) {
  18209. const names = Object.keys(unresolvedPrivateNames);
  18210. if (names.length) {
  18211. names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
  18212. this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
  18213. }
  18214. } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
  18215. return _return
  18216. }
  18217. // Class heritage is evaluated with outer private environment
  18218. parseClassSuper(node) {
  18219. const privateBoundNames = this._privateBoundNames;
  18220. this._privateBoundNames = this._outerPrivateBoundNames;
  18221. const unresolvedPrivateNames = this._unresolvedPrivateNames;
  18222. this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
  18223. const _return = super.parseClassSuper(node);
  18224. this._privateBoundNames = privateBoundNames;
  18225. this._unresolvedPrivateNames = unresolvedPrivateNames;
  18226. return _return
  18227. }
  18228. // Parse private element access
  18229. parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
  18230. const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
  18231. const branch = this._branch();
  18232. if (!(
  18233. (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
  18234. branch.type == this.privateIdentifierToken
  18235. )) {
  18236. return super.parseSubscript.apply(this, arguments)
  18237. }
  18238. let optional = false;
  18239. if (!this.eat(acorn.tokTypes.dot)) {
  18240. this.expect(acorn.tokTypes.questionDot);
  18241. optional = true;
  18242. }
  18243. let node = this.startNodeAt(startPos, startLoc);
  18244. node.object = base;
  18245. node.computed = false;
  18246. if (optionalSupported) {
  18247. node.optional = optional;
  18248. }
  18249. if (this.type == this.privateIdentifierToken) {
  18250. if (base.type == "Super") {
  18251. this.raise(this.start, "Cannot access private element on super");
  18252. }
  18253. node.property = this.parsePrivateName();
  18254. if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
  18255. if (!this._unresolvedPrivateNames) {
  18256. this.raise(node.property.start, "Usage of undeclared private name");
  18257. }
  18258. this._unresolvedPrivateNames[node.property.name] = node.property.start;
  18259. }
  18260. } else {
  18261. node.property = this.parseIdent(true);
  18262. }
  18263. return this.finishNode(node, "MemberExpression")
  18264. }
  18265. // Prohibit delete of private class elements
  18266. parseMaybeUnary(refDestructuringErrors, sawUnary) {
  18267. const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
  18268. if (_return.operator == "delete") {
  18269. if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
  18270. this.raise(_return.start, "Private elements may not be deleted");
  18271. }
  18272. }
  18273. return _return
  18274. }
  18275. };
  18276. Parser.prototype.privateIdentifierToken = new acorn.TokenType("privateIdentifier");
  18277. return Parser
  18278. };
  18279. const privateClassElements$1 = acornPrivateClassElements;
  18280. var acornClassFields = function(Parser) {
  18281. const acorn = Parser.acorn || require$$1;
  18282. const tt = acorn.tokTypes;
  18283. Parser = privateClassElements$1(Parser);
  18284. return class extends Parser {
  18285. _maybeParseFieldValue(field) {
  18286. if (this.eat(tt.eq)) {
  18287. const oldInFieldValue = this._inFieldValue;
  18288. this._inFieldValue = true;
  18289. if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
  18290. field.value = this.parseAwait();
  18291. } else field.value = this.parseExpression();
  18292. this._inFieldValue = oldInFieldValue;
  18293. } else field.value = null;
  18294. }
  18295. // Parse fields
  18296. parseClassElement(_constructorAllowsSuper) {
  18297. if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
  18298. const branch = this._branch();
  18299. if (branch.type == tt.bracketL) {
  18300. let count = 0;
  18301. do {
  18302. if (branch.eat(tt.bracketL)) ++count;
  18303. else if (branch.eat(tt.bracketR)) --count;
  18304. else branch.next();
  18305. } while (count > 0)
  18306. } else branch.next(true);
  18307. let isField = branch.type == tt.eq || branch.type == tt.semi;
  18308. if (!isField && branch.canInsertSemicolon()) {
  18309. isField = branch.type != tt.parenL;
  18310. }
  18311. if (isField) {
  18312. const node = this.startNode();
  18313. if (this.type == this.privateIdentifierToken) {
  18314. this.parsePrivateClassElementName(node);
  18315. } else {
  18316. this.parsePropertyName(node);
  18317. }
  18318. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  18319. (node.key.type === "Literal" && node.key.value === "constructor")) {
  18320. this.raise(node.key.start, "Classes may not have a field called constructor");
  18321. }
  18322. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  18323. this._maybeParseFieldValue(node);
  18324. this.exitScope();
  18325. this.finishNode(node, "PropertyDefinition");
  18326. this.semicolon();
  18327. return node
  18328. }
  18329. }
  18330. return super.parseClassElement.apply(this, arguments)
  18331. }
  18332. // Prohibit arguments in class field initializers
  18333. parseIdent(liberal, isBinding) {
  18334. const ident = super.parseIdent(liberal, isBinding);
  18335. if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
  18336. return ident
  18337. }
  18338. }
  18339. };
  18340. const privateClassElements = acornPrivateClassElements;
  18341. var acornStaticClassFeatures = function(Parser) {
  18342. const ExtendedParser = privateClassElements(Parser);
  18343. const acorn = Parser.acorn || require$$1;
  18344. const tt = acorn.tokTypes;
  18345. return class extends ExtendedParser {
  18346. _maybeParseFieldValue(field) {
  18347. if (this.eat(tt.eq)) {
  18348. const oldInFieldValue = this._inStaticFieldScope;
  18349. this._inStaticFieldScope = this.currentThisScope();
  18350. field.value = this.parseExpression();
  18351. this._inStaticFieldScope = oldInFieldValue;
  18352. } else field.value = null;
  18353. }
  18354. // Parse fields
  18355. parseClassElement(_constructorAllowsSuper) {
  18356. if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
  18357. return super.parseClassElement.apply(this, arguments)
  18358. }
  18359. const branch = this._branch();
  18360. branch.next();
  18361. if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateIdentifierToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
  18362. return super.parseClassElement.apply(this, arguments)
  18363. }
  18364. if (branch.type == tt.bracketL) {
  18365. let count = 0;
  18366. do {
  18367. if (branch.eat(tt.bracketL)) ++count;
  18368. else if (branch.eat(tt.bracketR)) --count;
  18369. else branch.next();
  18370. } while (count > 0)
  18371. } else branch.next();
  18372. if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
  18373. return super.parseClassElement.apply(this, arguments)
  18374. }
  18375. const node = this.startNode();
  18376. node.static = this.eatContextual("static");
  18377. if (this.type == this.privateIdentifierToken) {
  18378. this.parsePrivateClassElementName(node);
  18379. } else {
  18380. this.parsePropertyName(node);
  18381. }
  18382. if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
  18383. (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
  18384. this.raise(node.key.start, "Classes may not have a field called constructor");
  18385. }
  18386. if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
  18387. this.raise(node.key.start, "Classes may not have a static property named prototype");
  18388. }
  18389. this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
  18390. this._maybeParseFieldValue(node);
  18391. this.exitScope();
  18392. this.finishNode(node, "PropertyDefinition");
  18393. this.semicolon();
  18394. return node
  18395. }
  18396. // Parse private static methods
  18397. parsePropertyName(prop) {
  18398. if (prop.static && this.type == this.privateIdentifierToken) {
  18399. this.parsePrivateClassElementName(prop);
  18400. } else {
  18401. super.parsePropertyName(prop);
  18402. }
  18403. }
  18404. // Prohibit arguments in class field initializers
  18405. parseIdent(liberal, isBinding) {
  18406. const ident = super.parseIdent(liberal, isBinding);
  18407. if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
  18408. this.raise(ident.start, "A static class field initializer may not contain arguments");
  18409. }
  18410. return ident
  18411. }
  18412. }
  18413. };
  18414. function normalizeInputOptions(config) {
  18415. var _a, _b;
  18416. // These are options that may trigger special warnings or behaviour later
  18417. // if the user did not select an explicit value
  18418. const unsetOptions = new Set();
  18419. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  18420. const onwarn = getOnwarn(config);
  18421. const strictDeprecations = config.strictDeprecations || false;
  18422. const options = {
  18423. acorn: getAcorn(config),
  18424. acornInjectPlugins: getAcornInjectPlugins(config),
  18425. cache: getCache(config),
  18426. context,
  18427. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  18428. external: getIdMatcher(config.external),
  18429. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  18430. input: getInput(config),
  18431. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  18432. moduleContext: getModuleContext(config, context),
  18433. onwarn,
  18434. perf: config.perf || false,
  18435. plugins: ensureArray(config.plugins),
  18436. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  18437. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  18438. preserveSymlinks: config.preserveSymlinks || false,
  18439. shimMissingExports: config.shimMissingExports || false,
  18440. strictDeprecations,
  18441. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  18442. };
  18443. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  18444. return { options, unsetOptions };
  18445. }
  18446. const getOnwarn = (config) => {
  18447. return config.onwarn
  18448. ? warning => {
  18449. warning.toString = () => {
  18450. let str = '';
  18451. if (warning.plugin)
  18452. str += `(${warning.plugin} plugin) `;
  18453. if (warning.loc)
  18454. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  18455. str += warning.message;
  18456. return str;
  18457. };
  18458. config.onwarn(warning, defaultOnWarn);
  18459. }
  18460. : defaultOnWarn;
  18461. };
  18462. const getAcorn = (config) => ({
  18463. allowAwaitOutsideFunction: true,
  18464. ecmaVersion: 'latest',
  18465. preserveParens: false,
  18466. sourceType: 'module',
  18467. ...config.acorn
  18468. });
  18469. const getAcornInjectPlugins = (config) => [
  18470. acornClassFields,
  18471. acornStaticClassFeatures,
  18472. ...ensureArray(config.acornInjectPlugins)
  18473. ];
  18474. const getCache = (config) => {
  18475. var _a;
  18476. return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
  18477. };
  18478. const getIdMatcher = (option) => {
  18479. if (option === true) {
  18480. return () => true;
  18481. }
  18482. if (typeof option === 'function') {
  18483. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  18484. }
  18485. if (option) {
  18486. const ids = new Set();
  18487. const matchers = [];
  18488. for (const value of ensureArray(option)) {
  18489. if (value instanceof RegExp) {
  18490. matchers.push(value);
  18491. }
  18492. else {
  18493. ids.add(value);
  18494. }
  18495. }
  18496. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  18497. }
  18498. return () => false;
  18499. };
  18500. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  18501. const configInlineDynamicImports = config.inlineDynamicImports;
  18502. if (configInlineDynamicImports) {
  18503. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  18504. }
  18505. return configInlineDynamicImports;
  18506. };
  18507. const getInput = (config) => {
  18508. const configInput = config.input;
  18509. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  18510. };
  18511. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  18512. const configManualChunks = config.manualChunks;
  18513. if (configManualChunks) {
  18514. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  18515. }
  18516. return configManualChunks;
  18517. };
  18518. const getModuleContext = (config, context) => {
  18519. const configModuleContext = config.moduleContext;
  18520. if (typeof configModuleContext === 'function') {
  18521. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  18522. }
  18523. if (configModuleContext) {
  18524. const contextByModuleId = Object.create(null);
  18525. for (const key of Object.keys(configModuleContext)) {
  18526. contextByModuleId[path.resolve(key)] = configModuleContext[key];
  18527. }
  18528. return id => contextByModuleId[id] || context;
  18529. }
  18530. return () => context;
  18531. };
  18532. const getPreserveEntrySignatures = (config, unsetOptions) => {
  18533. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  18534. if (configPreserveEntrySignatures == null) {
  18535. unsetOptions.add('preserveEntrySignatures');
  18536. }
  18537. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  18538. };
  18539. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  18540. const configPreserveModules = config.preserveModules;
  18541. if (configPreserveModules) {
  18542. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  18543. }
  18544. return configPreserveModules;
  18545. };
  18546. const getTreeshake = (config, warn, strictDeprecations) => {
  18547. const configTreeshake = config.treeshake;
  18548. if (configTreeshake === false) {
  18549. return false;
  18550. }
  18551. if (configTreeshake && configTreeshake !== true) {
  18552. if (typeof configTreeshake.pureExternalModules !== 'undefined') {
  18553. 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);
  18554. }
  18555. return {
  18556. annotations: configTreeshake.annotations !== false,
  18557. moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
  18558. propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
  18559. tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
  18560. unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
  18561. };
  18562. }
  18563. return {
  18564. annotations: true,
  18565. moduleSideEffects: () => true,
  18566. propertyReadSideEffects: true,
  18567. tryCatchDeoptimization: true,
  18568. unknownGlobalSideEffects: true
  18569. };
  18570. };
  18571. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
  18572. if (typeof moduleSideEffectsOption === 'boolean') {
  18573. return () => moduleSideEffectsOption;
  18574. }
  18575. if (moduleSideEffectsOption === 'no-external') {
  18576. return (_id, external) => !external;
  18577. }
  18578. if (typeof moduleSideEffectsOption === 'function') {
  18579. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  18580. }
  18581. if (Array.isArray(moduleSideEffectsOption)) {
  18582. const ids = new Set(moduleSideEffectsOption);
  18583. return id => ids.has(id);
  18584. }
  18585. if (moduleSideEffectsOption) {
  18586. warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  18587. }
  18588. const isPureExternalModule = getIdMatcher(pureExternalModules);
  18589. return (id, external) => !(external && isPureExternalModule(id));
  18590. };
  18591. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  18592. var _a, _b, _c, _d, _e, _f, _g;
  18593. // These are options that may trigger special warnings or behaviour later
  18594. // if the user did not select an explicit value
  18595. const unsetOptions = new Set(unsetInputOptions);
  18596. const compact = config.compact || false;
  18597. const format = getFormat(config);
  18598. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  18599. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  18600. const file = getFile(config, preserveModules, inputOptions);
  18601. const outputOptions = {
  18602. amd: getAmd(config),
  18603. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  18604. banner: getAddon(config, 'banner'),
  18605. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  18606. compact,
  18607. dir: getDir(config, file),
  18608. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  18609. entryFileNames: getEntryFileNames(config, unsetOptions),
  18610. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  18611. exports: getExports(config, unsetOptions),
  18612. extend: config.extend || false,
  18613. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  18614. file,
  18615. footer: getAddon(config, 'footer'),
  18616. format,
  18617. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  18618. globals: config.globals || {},
  18619. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  18620. indent: getIndent(config, compact),
  18621. inlineDynamicImports,
  18622. interop: getInterop(config, inputOptions),
  18623. intro: getAddon(config, 'intro'),
  18624. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  18625. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  18626. name: config.name,
  18627. namespaceToStringTag: config.namespaceToStringTag || false,
  18628. noConflict: config.noConflict || false,
  18629. outro: getAddon(config, 'outro'),
  18630. paths: config.paths || {},
  18631. plugins: ensureArray(config.plugins),
  18632. preferConst: config.preferConst || false,
  18633. preserveModules,
  18634. preserveModulesRoot: getPreserveModulesRoot(config),
  18635. sourcemap: config.sourcemap || false,
  18636. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  18637. sourcemapFile: config.sourcemapFile,
  18638. sourcemapPathTransform: config.sourcemapPathTransform,
  18639. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  18640. systemNullSetters: config.systemNullSetters || false,
  18641. validate: config.validate || false
  18642. };
  18643. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  18644. return { options: outputOptions, unsetOptions };
  18645. }
  18646. const getFile = (config, preserveModules, inputOptions) => {
  18647. const file = config.file;
  18648. if (typeof file === 'string') {
  18649. if (preserveModules) {
  18650. return error({
  18651. code: 'INVALID_OPTION',
  18652. message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
  18653. });
  18654. }
  18655. if (!Array.isArray(inputOptions.input))
  18656. return error({
  18657. code: 'INVALID_OPTION',
  18658. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  18659. });
  18660. }
  18661. return file;
  18662. };
  18663. const getFormat = (config) => {
  18664. const configFormat = config.format;
  18665. switch (configFormat) {
  18666. case undefined:
  18667. case 'es':
  18668. case 'esm':
  18669. case 'module':
  18670. return 'es';
  18671. case 'cjs':
  18672. case 'commonjs':
  18673. return 'cjs';
  18674. case 'system':
  18675. case 'systemjs':
  18676. return 'system';
  18677. case 'amd':
  18678. case 'iife':
  18679. case 'umd':
  18680. return configFormat;
  18681. default:
  18682. return error({
  18683. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  18684. url: `https://rollupjs.org/guide/en/#outputformat`
  18685. });
  18686. }
  18687. };
  18688. const getInlineDynamicImports = (config, inputOptions) => {
  18689. var _a;
  18690. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
  18691. false;
  18692. const { input } = inputOptions;
  18693. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  18694. return error({
  18695. code: 'INVALID_OPTION',
  18696. message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
  18697. });
  18698. }
  18699. return inlineDynamicImports;
  18700. };
  18701. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  18702. var _a;
  18703. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  18704. if (preserveModules) {
  18705. if (inlineDynamicImports) {
  18706. return error({
  18707. code: 'INVALID_OPTION',
  18708. message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
  18709. });
  18710. }
  18711. if (inputOptions.preserveEntrySignatures === false) {
  18712. return error({
  18713. code: 'INVALID_OPTION',
  18714. message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
  18715. });
  18716. }
  18717. }
  18718. return preserveModules;
  18719. };
  18720. const getPreserveModulesRoot = (config) => {
  18721. const preserveModulesRoot = config.preserveModulesRoot;
  18722. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  18723. return undefined;
  18724. }
  18725. return path.resolve(preserveModulesRoot);
  18726. };
  18727. const getAmd = (config) => {
  18728. const collection = {
  18729. autoId: false,
  18730. basePath: '',
  18731. define: 'define',
  18732. ...config.amd
  18733. };
  18734. if ((collection.autoId || collection.basePath) && collection.id) {
  18735. return error({
  18736. code: 'INVALID_OPTION',
  18737. message: '"output.amd.autoId"/"output.amd.basePath" and "output.amd.id" cannot be used together.'
  18738. });
  18739. }
  18740. if (collection.basePath && !collection.autoId) {
  18741. return error({
  18742. code: 'INVALID_OPTION',
  18743. message: '"output.amd.basePath" only works with "output.amd.autoId".'
  18744. });
  18745. }
  18746. let normalized;
  18747. if (collection.autoId) {
  18748. normalized = {
  18749. autoId: true,
  18750. basePath: collection.basePath,
  18751. define: collection.define
  18752. };
  18753. }
  18754. else {
  18755. normalized = {
  18756. autoId: false,
  18757. define: collection.define,
  18758. id: collection.id
  18759. };
  18760. }
  18761. return normalized;
  18762. };
  18763. const getAddon = (config, name) => {
  18764. const configAddon = config[name];
  18765. if (typeof configAddon === 'function') {
  18766. return configAddon;
  18767. }
  18768. return () => configAddon || '';
  18769. };
  18770. const getDir = (config, file) => {
  18771. const dir = config.dir;
  18772. if (typeof dir === 'string' && typeof file === 'string') {
  18773. return error({
  18774. code: 'INVALID_OPTION',
  18775. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  18776. });
  18777. }
  18778. return dir;
  18779. };
  18780. const getDynamicImportFunction = (config, inputOptions) => {
  18781. const configDynamicImportFunction = config.dynamicImportFunction;
  18782. if (configDynamicImportFunction) {
  18783. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  18784. }
  18785. return configDynamicImportFunction;
  18786. };
  18787. const getEntryFileNames = (config, unsetOptions) => {
  18788. const configEntryFileNames = config.entryFileNames;
  18789. if (configEntryFileNames == null) {
  18790. unsetOptions.add('entryFileNames');
  18791. }
  18792. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  18793. };
  18794. function getExports(config, unsetOptions) {
  18795. const configExports = config.exports;
  18796. if (configExports == null) {
  18797. unsetOptions.add('exports');
  18798. }
  18799. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  18800. return error(errInvalidExportOptionValue(configExports));
  18801. }
  18802. return configExports || 'auto';
  18803. }
  18804. const getIndent = (config, compact) => {
  18805. if (compact) {
  18806. return '';
  18807. }
  18808. const configIndent = config.indent;
  18809. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  18810. };
  18811. const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
  18812. const getInterop = (config, inputOptions) => {
  18813. const configInterop = config.interop;
  18814. const validatedInteropTypes = new Set();
  18815. const validateInterop = (interop) => {
  18816. if (!validatedInteropTypes.has(interop)) {
  18817. validatedInteropTypes.add(interop);
  18818. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  18819. return error({
  18820. code: 'INVALID_OPTION',
  18821. message: `The value ${JSON.stringify(interop)} is not supported for "output.interop". Use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value => JSON.stringify(value)).join(', ')} instead.`,
  18822. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18823. });
  18824. }
  18825. if (typeof interop === 'boolean') {
  18826. warnDeprecation({
  18827. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  18828. url: 'https://rollupjs.org/guide/en/#outputinterop'
  18829. }, false, inputOptions);
  18830. }
  18831. }
  18832. return interop;
  18833. };
  18834. if (typeof configInterop === 'function') {
  18835. const interopPerId = Object.create(null);
  18836. let defaultInterop = null;
  18837. return id => id === null
  18838. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  18839. : id in interopPerId
  18840. ? interopPerId[id]
  18841. : validateInterop((interopPerId[id] = configInterop(id)));
  18842. }
  18843. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  18844. };
  18845. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  18846. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  18847. if (configManualChunks) {
  18848. if (inlineDynamicImports) {
  18849. return error({
  18850. code: 'INVALID_OPTION',
  18851. message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
  18852. });
  18853. }
  18854. if (preserveModules) {
  18855. return error({
  18856. code: 'INVALID_OPTION',
  18857. message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
  18858. });
  18859. }
  18860. }
  18861. return configManualChunks || {};
  18862. };
  18863. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  18864. function rollup(rawInputOptions) {
  18865. return rollupInternal(rawInputOptions, null);
  18866. }
  18867. async function rollupInternal(rawInputOptions, watcher) {
  18868. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  18869. initialiseTimers(inputOptions);
  18870. const graph = new Graph(inputOptions, watcher);
  18871. // remove the cache option from the memory after graph creation (cache is not used anymore)
  18872. const useCache = rawInputOptions.cache !== false;
  18873. delete inputOptions.cache;
  18874. delete rawInputOptions.cache;
  18875. timeStart('BUILD', 1);
  18876. try {
  18877. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  18878. await graph.build();
  18879. }
  18880. catch (err) {
  18881. const watchFiles = Object.keys(graph.watchFiles);
  18882. if (watchFiles.length > 0) {
  18883. err.watchFiles = watchFiles;
  18884. }
  18885. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  18886. await graph.pluginDriver.hookParallel('closeBundle', []);
  18887. throw err;
  18888. }
  18889. await graph.pluginDriver.hookParallel('buildEnd', []);
  18890. timeEnd('BUILD', 1);
  18891. const result = {
  18892. cache: useCache ? graph.getCache() : undefined,
  18893. closed: false,
  18894. async close() {
  18895. if (result.closed)
  18896. return;
  18897. result.closed = true;
  18898. await graph.pluginDriver.hookParallel('closeBundle', []);
  18899. },
  18900. async generate(rawOutputOptions) {
  18901. if (result.closed)
  18902. return error(errAlreadyClosed());
  18903. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18904. },
  18905. watchFiles: Object.keys(graph.watchFiles),
  18906. async write(rawOutputOptions) {
  18907. if (result.closed)
  18908. return error(errAlreadyClosed());
  18909. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  18910. }
  18911. };
  18912. if (inputOptions.perf)
  18913. result.getTimings = getTimings;
  18914. return result;
  18915. }
  18916. async function getInputOptions(rawInputOptions, watchMode) {
  18917. if (!rawInputOptions) {
  18918. throw new Error('You must supply an options object to rollup');
  18919. }
  18920. const rawPlugins = ensureArray(rawInputOptions.plugins);
  18921. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  18922. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  18923. return { options, unsetOptions };
  18924. }
  18925. function applyOptionHook(watchMode) {
  18926. return async (inputOptions, plugin) => {
  18927. if (plugin.options)
  18928. return (plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions) || inputOptions);
  18929. return inputOptions;
  18930. };
  18931. }
  18932. function normalizePlugins(plugins, anonymousPrefix) {
  18933. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  18934. const plugin = plugins[pluginIndex];
  18935. if (!plugin.name) {
  18936. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  18937. }
  18938. }
  18939. }
  18940. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  18941. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  18942. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  18943. const generated = await bundle.generate(isWrite);
  18944. if (isWrite) {
  18945. if (!outputOptions.dir && !outputOptions.file) {
  18946. return error({
  18947. code: 'MISSING_OPTION',
  18948. message: 'You must specify "output.file" or "output.dir" for the build.'
  18949. });
  18950. }
  18951. await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
  18952. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  18953. }
  18954. return createOutput(generated);
  18955. }
  18956. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  18957. if (!rawOutputOptions) {
  18958. throw new Error('You must supply an options object');
  18959. }
  18960. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  18961. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  18962. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  18963. return {
  18964. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  18965. outputPluginDriver
  18966. };
  18967. }
  18968. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  18969. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  18970. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  18971. return {
  18972. ...pluginContext,
  18973. emitFile: emitError,
  18974. setAssetSource: emitError
  18975. };
  18976. }), inputOptions, unsetInputOptions);
  18977. }
  18978. function createOutput(outputBundle) {
  18979. return {
  18980. output: Object.keys(outputBundle)
  18981. .map(fileName => outputBundle[fileName])
  18982. .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  18983. const fileTypeA = getSortingFileType(outputFileA);
  18984. const fileTypeB = getSortingFileType(outputFileB);
  18985. if (fileTypeA === fileTypeB)
  18986. return 0;
  18987. return fileTypeA < fileTypeB ? -1 : 1;
  18988. })
  18989. };
  18990. }
  18991. var SortingFileType;
  18992. (function (SortingFileType) {
  18993. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  18994. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  18995. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  18996. })(SortingFileType || (SortingFileType = {}));
  18997. function getSortingFileType(file) {
  18998. if (file.type === 'asset') {
  18999. return SortingFileType.ASSET;
  19000. }
  19001. if (file.isEntry) {
  19002. return SortingFileType.ENTRY_CHUNK;
  19003. }
  19004. return SortingFileType.SECONDARY_CHUNK;
  19005. }
  19006. function writeOutputFile(outputFile, outputOptions) {
  19007. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  19008. let writeSourceMapPromise;
  19009. let source;
  19010. if (outputFile.type === 'asset') {
  19011. source = outputFile.source;
  19012. }
  19013. else {
  19014. source = outputFile.code;
  19015. if (outputOptions.sourcemap && outputFile.map) {
  19016. let url;
  19017. if (outputOptions.sourcemap === 'inline') {
  19018. url = outputFile.map.toUrl();
  19019. }
  19020. else {
  19021. url = `${path.basename(outputFile.fileName)}.map`;
  19022. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  19023. }
  19024. if (outputOptions.sourcemap !== 'hidden') {
  19025. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19026. }
  19027. }
  19028. }
  19029. return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
  19030. }
  19031. class WatchEmitter extends require$$0.EventEmitter {
  19032. constructor() {
  19033. super();
  19034. // Allows more than 10 bundles to be watched without
  19035. // showing the `MaxListenersExceededWarning` to the user.
  19036. this.setMaxListeners(Infinity);
  19037. }
  19038. close() { }
  19039. }
  19040. function watch(configs) {
  19041. const emitter = new WatchEmitter();
  19042. const configArray = ensureArray(configs);
  19043. const watchConfigs = configArray.filter(config => config.watch !== false);
  19044. if (watchConfigs.length === 0) {
  19045. throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
  19046. }
  19047. loadFsEvents()
  19048. .then(() => Promise.resolve().then(function () { return require('./watch.js'); }))
  19049. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  19050. return emitter;
  19051. }
  19052. exports.defaultOnWarn = defaultOnWarn;
  19053. exports.ensureArray = ensureArray;
  19054. exports.error = error;
  19055. exports.fseventsImporter = fseventsImporter;
  19056. exports.getAliasName = getAliasName;
  19057. exports.getAugmentedNamespace = getAugmentedNamespace;
  19058. exports.getOrCreate = getOrCreate;
  19059. exports.loadFsEvents = loadFsEvents;
  19060. exports.relativeId = relativeId;
  19061. exports.rollup = rollup;
  19062. exports.rollupInternal = rollupInternal;
  19063. exports.version = version$1;
  19064. exports.warnUnknownOptions = warnUnknownOptions;
  19065. exports.watch = watch;
  19066. //# sourceMappingURL=rollup.js.map